repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/cookie_store/src/cookie_path.rs
crates/cookie_store/src/cookie_path.rs
use std::cmp::max; use std::ops::Deref; use serde_derive::{Deserialize, Serialize}; use url::Url; /// Returns true if `request_url` path-matches `path` per /// [IETF RFC6265 Section 5.1.4](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4) pub fn is_match(path: &str, request_url: &Url) -> bool { CookiePath::parse(path).map_or(false, |cp| cp.matches(request_url)) } /// The path of a `Cookie` #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, Hash, PartialOrd, Ord)] pub struct CookiePath(String, bool); impl CookiePath { /// Determine if `request_url` path-matches this `CookiePath` per /// [IETF RFC6265 Section 5.1.4](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4) pub fn matches(&self, request_url: &Url) -> bool { if request_url.cannot_be_a_base() { false } else { let request_path = request_url.path(); let cookie_path = &*self.0; // o The cookie-path and the request-path are identical. cookie_path == request_path || (request_path.starts_with(cookie_path) && (cookie_path.ends_with('/') || &request_path[cookie_path.len()..=cookie_path.len()] == "/")) } } /// Returns true if this `CookiePath` was set from a Path attribute; this allows us to /// distinguish from the case where Path was explicitly set to "/" pub fn is_from_path_attr(&self) -> bool { self.1 } // The user agent MUST use an algorithm equivalent to the following // algorithm to compute the default-path of a cookie: // // 1. Let uri-path be the path portion of the request-uri if such a // portion exists (and empty otherwise). For example, if the // request-uri contains just a path (and optional query string), // then the uri-path is that path (without the %x3F ("?") character // or query string), and if the request-uri contains a full // absoluteURI, the uri-path is the path component of that URI. // // 2. If the uri-path is empty or if the first character of the uri- // path is not a %x2F ("/") character, output %x2F ("/") and skip // the remaining steps. // // 3. If the uri-path contains no more than one %x2F ("/") character, // output %x2F ("/") and skip the remaining step. // // 4. Output the characters of the uri-path from the first character up // to, but not including, the right-most %x2F ("/"). /// Determine the default-path of `request_url` per /// [IETF RFC6265 Section 5.1.4](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4) pub fn default_path(request_url: &Url) -> CookiePath { let cp = if request_url.cannot_be_a_base() { // non-relative path scheme, default to "/" (uri-path "empty", case 2) "/".into() } else { let path = request_url.path(); match path.rfind('/') { None => "/".into(), // no "/" in string, default to "/" (case 2) Some(i) => path[0..max(i, 1)].into(), // case 4 (subsumes case 3) } }; CookiePath(cp, false) } /// Attempt to parse `path` as a `CookiePath`; if unsuccessful, the default-path of /// `request_url` will be returned as the `CookiePath`. pub fn new(path: &str, request_url: &Url) -> CookiePath { match CookiePath::parse(path) { Some(cp) => cp, None => CookiePath::default_path(request_url), } } /// Attempt to parse `path` as a `CookiePath`. If `path` does not have a leading "/", /// `None` is returned. pub fn parse(path: &str) -> Option<CookiePath> { if path.starts_with('/') { Some(CookiePath(String::from(path), true)) } else { None } } } impl AsRef<str> for CookiePath { fn as_ref(&self) -> &str { &self.0 } } impl Deref for CookiePath { type Target = str; fn deref(&self) -> &Self::Target { &self.0 } } impl<'a> From<&'a CookiePath> for String { fn from(cp: &CookiePath) -> String { cp.0.clone() } } impl From<CookiePath> for String { fn from(cp: CookiePath) -> String { cp.0 } } #[cfg(test)] mod tests { use url::Url; use super::CookiePath; #[test] fn default_path() { fn get_path(url: &str) -> String { CookiePath::default_path(&Url::parse(url).expect("unable to parse url in default_path")) .into() } assert_eq!(get_path("data:foobusbar"), "/"); assert_eq!(get_path("http://example.com"), "/"); assert_eq!(get_path("http://example.com/"), "/"); assert_eq!(get_path("http://example.com/foo"), "/"); assert_eq!(get_path("http://example.com/foo/"), "/foo"); assert_eq!(get_path("http://example.com//foo/"), "//foo"); assert_eq!(get_path("http://example.com/foo//"), "/foo/"); assert_eq!(get_path("http://example.com/foo/bus/bar"), "/foo/bus"); assert_eq!(get_path("http://example.com/foo//bus/bar"), "/foo//bus"); assert_eq!(get_path("http://example.com/foo/bus/bar/"), "/foo/bus/bar"); } fn do_match(exp: bool, cp: &str, rp: &str) { let url = Url::parse(&format!("http://example.com{}", rp)) .expect("unable to parse url in do_match"); let cp = CookiePath::parse(cp).expect("unable to parse CookiePath in do_match"); assert!( exp == cp.matches(&url), "\n>> {:?}\nshould{}match\n>> {:?}\n>> {:?}\n", cp, if exp { " " } else { " NOT " }, url, url.path() ); } fn is_match(cp: &str, rp: &str) { do_match(true, cp, rp); } fn is_mismatch(cp: &str, rp: &str) { do_match(false, cp, rp); } #[test] fn bad_paths() { assert!(CookiePath::parse("").is_none()); assert!(CookiePath::parse("a/foo").is_none()); } #[test] fn bad_path_defaults() { fn get_path(cp: &str, url: &str) -> String { CookiePath::new( cp, &Url::parse(url).expect("unable to parse url in bad_path_defaults"), ) .into() } assert_eq!(get_path("", "http://example.com/"), "/"); assert_eq!(get_path("a/foo", "http://example.com/"), "/"); assert_eq!(get_path("", "http://example.com/foo/bar"), "/foo"); assert_eq!(get_path("a/foo", "http://example.com/foo/bar"), "/foo"); assert_eq!(get_path("", "http://example.com/foo/bar/"), "/foo/bar"); assert_eq!(get_path("a/foo", "http://example.com/foo/bar/"), "/foo/bar"); } #[test] fn shortest_path() { is_match("/", "/"); } // A request-path path-matches a given cookie-path if at least one of // the following conditions holds: #[test] fn identical_paths() { // o The cookie-path and the request-path are identical. is_match("/foo/bus", "/foo/bus"); // identical is_mismatch("/foo/bus", "/foo/buss"); // trailing character is_mismatch("/foo/bus", "/zoo/bus"); // character mismatch is_mismatch("/foo/bus", "/zfoo/bus"); // leading character } #[test] fn cookie_path_prefix1() { // o The cookie-path is a prefix of the request-path, and the last // character of the cookie-path is %x2F ("/"). is_match("/foo/", "/foo/bus"); // cookie-path a prefix and ends in "/" is_mismatch("/bar", "/foo/bus"); // cookie-path not a prefix of request-path is_mismatch("/foo/bus/bar", "/foo/bus"); // cookie-path not a prefix of request-path is_mismatch("/fo", "/foo/bus"); // cookie-path a prefix, but last char != "/" and first char in request-path ("o") after prefix != "/" } #[test] fn cookie_path_prefix2() { // o The cookie-path is a prefix of the request-path, and the first // character of the request-path that is not included in the cookie- // path is a %x2F ("/") character. is_match("/foo", "/foo/bus"); // cookie-path a prefix of request-path, and next char in request-path = "/" is_mismatch("/bar", "/foo/bus"); // cookie-path not a prefix of request-path is_mismatch("/foo/bus/bar", "/foo/bus"); // cookie-path not a prefix of request-path is_mismatch("/fo", "/foo/bus"); // cookie-path a prefix, but next char in request-path ("o") != "/" } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_json_tree/src/node.rs
crates/egui_json_tree/src/node.rs
use std::collections::{HashMap, HashSet}; use egui::{ collapsing_header::CollapsingState, text::LayoutJob, util::cache::{ComputerMut, FrameCache}, Color32, FontId, Id, Label, Response, Sense, TextFormat, Ui, }; use crate::{ delimiters::{ARRAY_DELIMITERS, OBJECT_DELIMITERS}, response::JsonTreeResponse, search::SearchTerm, style::JsonTreeStyle, tree::JsonTreeConfig, value::{BaseValueType, ExpandableType, JsonTreeValue, ToJsonTreeValue}, DefaultExpand, }; pub struct JsonTreeNode<'a> { id: Id, value: &'a dyn ToJsonTreeValue, parent: Option<Parent>, } impl<'a> JsonTreeNode<'a> { pub(crate) fn new(id: Id, value: &'a dyn ToJsonTreeValue) -> Self { Self { id, value, parent: None, } } pub(crate) fn show_with_config(self, ui: &mut Ui, config: JsonTreeConfig) -> JsonTreeResponse { let persistent_id = ui.id(); let tree_id = self.id; let make_persistent_id = |path_segments: &Vec<String>| persistent_id.with(tree_id.with(path_segments)); let mut path_id_map = HashMap::new(); let (default_expand, search_term) = match config.default_expand { DefaultExpand::All => (InnerExpand::All, None), DefaultExpand::None => (InnerExpand::None, None), DefaultExpand::ToLevel(l) => (InnerExpand::ToLevel(l), None), DefaultExpand::SearchResults(search_str) => { // If searching, the entire path_id_map must be populated. populate_path_id_map(self.value, &mut path_id_map, &make_persistent_id); let search_term = SearchTerm::parse(search_str); let paths = search_term .as_ref() .map(|search_term| { search_term.find_matching_paths_in(self.value, config.abbreviate_root) }) .unwrap_or_default(); (InnerExpand::Paths(paths), search_term) } }; let node_config = JsonTreeNodeConfig { style: config.style, default_expand, abbreviate_root: config.abbreviate_root, search_term, }; let response_callback = &mut config .response_callback .unwrap_or_else(|| Box::new(|_, _| {})); // Wrap in a vertical layout in case this tree is placed directly in a horizontal layout, // which does not allow indent layouts as direct children. ui.vertical(|ui| { // Centres the collapsing header icon. ui.spacing_mut().interact_size.y = node_config.style.font_id(ui).size; self.show_impl( ui, &mut vec![], &mut path_id_map, response_callback, &make_persistent_id, &node_config, ); }); JsonTreeResponse { collapsing_state_ids: path_id_map.into_values().collect(), } } fn show_impl( self, ui: &mut Ui, path_segments: &mut Vec<String>, path_id_map: &mut PathIdMap, response_callback: &mut dyn FnMut(Response, &String), make_persistent_id: &dyn Fn(&Vec<String>) -> Id, config: &JsonTreeNodeConfig, ) { let JsonTreeNodeConfig { style, search_term, .. } = config; let pointer_string = &get_pointer_string(path_segments); match self.value.to_json_tree_value() { JsonTreeValue::Base(value_str, value_type) => { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 0.0; if let Some(parent) = &self.parent { let key_response = render_key(ui, style, parent, search_term.as_ref()); response_callback(key_response, pointer_string); } let value_response = render_value( ui, style, &value_str.to_string(), &value_type, search_term.as_ref(), ); response_callback(value_response, pointer_string); }); } JsonTreeValue::Expandable(entries, expandable_type) => { let expandable = Expandable { id: self.id, entries, expandable_type, parent: self.parent, }; show_expandable( ui, path_segments, path_id_map, expandable, response_callback, &make_persistent_id, config, ); } }; } } #[derive(Default)] struct ValueLayoutJobCreator; impl ValueLayoutJobCreator { fn create( &self, style: &JsonTreeStyle, value_str: &str, value_type: &BaseValueType, search_term: Option<&SearchTerm>, font_id: &FontId, ) -> LayoutJob { let color = style.get_color(value_type); let add_quote_if_string = |job: &mut LayoutJob| { if *value_type == BaseValueType::String { append(job, "\"", color, None, font_id) }; }; let mut job = LayoutJob::default(); add_quote_if_string(&mut job); add_text_with_highlighting( &mut job, value_str, color, search_term, style.highlight_color, font_id, ); add_quote_if_string(&mut job); job } } impl ComputerMut< ( &JsonTreeStyle, &str, &BaseValueType, Option<&SearchTerm>, &FontId, ), LayoutJob, > for ValueLayoutJobCreator { fn compute( &mut self, (style, value_str, value_type, search_term, font_id): ( &JsonTreeStyle, &str, &BaseValueType, Option<&SearchTerm>, &FontId, ), ) -> LayoutJob { self.create(style, value_str, value_type, search_term, font_id) } } type ValueLayoutJobCreatorCache = FrameCache<LayoutJob, ValueLayoutJobCreator>; fn render_value( ui: &mut Ui, style: &JsonTreeStyle, value_str: &str, value_type: &BaseValueType, search_term: Option<&SearchTerm>, ) -> Response { let job = ui.ctx().memory_mut(|mem| { mem.caches.cache::<ValueLayoutJobCreatorCache>().get(( style, value_str, value_type, search_term, &style.font_id(ui), )) }); render_job(ui, job) } fn show_expandable( ui: &mut Ui, path_segments: &mut Vec<String>, path_id_map: &mut PathIdMap, expandable: Expandable, response_callback: &mut dyn FnMut(Response, &String), make_persistent_id: &dyn Fn(&Vec<String>) -> Id, config: &JsonTreeNodeConfig, ) { let JsonTreeNodeConfig { default_expand, style, abbreviate_root, search_term, } = config; let pointer_string = &get_pointer_string(path_segments); let delimiters = match expandable.expandable_type { ExpandableType::Array => &ARRAY_DELIMITERS, ExpandableType::Object => &OBJECT_DELIMITERS, }; let default_open = match &default_expand { InnerExpand::All => true, InnerExpand::None => false, InnerExpand::ToLevel(num_levels_open) => (path_segments.len() as u8) <= *num_levels_open, InnerExpand::Paths(paths) => paths.contains(path_segments), }; let id_source = *path_id_map .entry(path_segments.to_vec()) .or_insert_with(|| make_persistent_id(path_segments)); let state = CollapsingState::load_with_default_open(ui.ctx(), id_source, default_open); let is_expanded = state.is_open(); let font_id = style.font_id(ui); state .show_header(ui, |ui| { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 0.0; if path_segments.is_empty() && !is_expanded { if *abbreviate_root { response_callback( render_punc( ui, delimiters.collapsed, style.punctuation_color, None, &font_id, ), pointer_string, ); return; } render_punc( ui, delimiters.opening, style.punctuation_color, None, &font_id, ); render_punc(ui, " ", style.punctuation_color, None, &font_id); let entries_len = expandable.entries.len(); for (idx, (key, elem)) in expandable.entries.iter().enumerate() { // Don't show array indices when the array is collapsed. if matches!(expandable.expandable_type, ExpandableType::Object) { let key_response = render_key( ui, style, &Parent::new(key.to_owned(), expandable.expandable_type), search_term.as_ref(), ); response_callback(key_response, pointer_string); } match elem.to_json_tree_value() { JsonTreeValue::Base(value_str, value_type) => { let value_response = render_value( ui, style, &value_str.to_string(), &value_type, search_term.as_ref(), ); response_callback(value_response, pointer_string); } JsonTreeValue::Expandable(entries, expandable_type) => { let nested_delimiters = match expandable_type { ExpandableType::Array => &ARRAY_DELIMITERS, ExpandableType::Object => &OBJECT_DELIMITERS, }; let delimiter = if entries.is_empty() { nested_delimiters.collapsed_empty } else { nested_delimiters.collapsed }; let collapsed_expandable_response = render_punc( ui, delimiter, style.punctuation_color, None, &font_id, ); response_callback(collapsed_expandable_response, pointer_string); } }; let spacing_str = if idx == entries_len - 1 { " " } else { ", " }; render_punc(ui, spacing_str, style.punctuation_color, None, &font_id); } render_punc( ui, delimiters.closing, style.punctuation_color, None, &font_id, ); } else { if let Some(parent) = &expandable.parent { let key_response = render_key(ui, style, parent, search_term.as_ref()); response_callback(key_response, pointer_string); } if is_expanded { render_punc( ui, delimiters.opening, style.punctuation_color, None, &font_id, ); } else { let delimiter = if expandable.entries.is_empty() { delimiters.collapsed_empty } else { delimiters.collapsed }; let collapsed_expandable_response = render_punc(ui, delimiter, style.punctuation_color, None, &font_id); response_callback(collapsed_expandable_response, pointer_string); } } }); }) .body(|ui| { for (key, elem) in expandable.entries { let is_expandable = elem.is_expandable(); path_segments.push(key.clone()); let add_nested_tree = |ui: &mut Ui| { let nested_tree = JsonTreeNode { id: expandable.id, value: elem, parent: Some(Parent::new(key, expandable.expandable_type)), }; nested_tree.show_impl( ui, path_segments, path_id_map, response_callback, make_persistent_id, config, ); }; if is_expandable { add_nested_tree(ui); } else { ui.scope(|ui| { ui.visuals_mut().indent_has_left_vline = false; ui.spacing_mut().indent = ui.spacing().icon_width + ui.spacing().icon_spacing; ui.indent(id_source, add_nested_tree); }); } path_segments.pop(); } }); if is_expanded { ui.horizontal_wrapped(|ui| { let indent = ui.spacing().icon_width / 2.0; ui.add_space(indent); render_punc( ui, delimiters.closing, style.punctuation_color, None, &font_id, ); }); } } #[derive(Default)] struct KeyLayoutJobCreator; impl KeyLayoutJobCreator { fn create( &self, style: &JsonTreeStyle, parent: &Parent, search_term: Option<&SearchTerm>, font_id: &FontId, ) -> LayoutJob { let mut job = LayoutJob::default(); match parent { Parent { key, expandable_type: ExpandableType::Array, } => add_array_idx( &mut job, key, style.array_idx_color, style.punctuation_color, font_id, ), Parent { key, expandable_type: ExpandableType::Object, } => add_object_key( &mut job, key, style.object_key_color, style.punctuation_color, search_term, style.highlight_color, font_id, ), }; job } } impl ComputerMut<(&JsonTreeStyle, &Parent, Option<&SearchTerm>, &FontId), LayoutJob> for KeyLayoutJobCreator { fn compute( &mut self, (style, parent, search_term, font_id): ( &JsonTreeStyle, &Parent, Option<&SearchTerm>, &FontId, ), ) -> LayoutJob { self.create(style, parent, search_term, font_id) } } type KeyLayoutJobCreatorCache = FrameCache<LayoutJob, KeyLayoutJobCreator>; fn render_key( ui: &mut Ui, style: &JsonTreeStyle, parent: &Parent, search_term: Option<&SearchTerm>, ) -> Response { let job = ui.ctx().memory_mut(|mem| { mem.caches.cache::<KeyLayoutJobCreatorCache>().get(( style, parent, search_term, &style.font_id(ui), )) }); render_job(ui, job) } fn add_object_key( job: &mut LayoutJob, key_str: &str, color: Color32, punctuation_color: Color32, search_term: Option<&SearchTerm>, highlight_color: Color32, font_id: &FontId, ) { append(job, "\"", color, None, font_id); add_text_with_highlighting(job, key_str, color, search_term, highlight_color, font_id); append(job, "\"", color, None, font_id); append(job, ": ", punctuation_color, None, font_id); } fn add_array_idx( job: &mut LayoutJob, idx_str: &str, color: Color32, punctuation_color: Color32, font_id: &FontId, ) { append(job, idx_str, color, None, font_id); append(job, ": ", punctuation_color, None, font_id); } fn add_text_with_highlighting( job: &mut LayoutJob, text_str: &str, text_color: Color32, search_term: Option<&SearchTerm>, highlight_color: Color32, font_id: &FontId, ) { if let Some(search_term) = search_term { let matches = search_term.find_match_indices_in(text_str); if !matches.is_empty() { let mut start = 0; for match_idx in matches { append(job, &text_str[start..match_idx], text_color, None, font_id); let highlight_end_idx = match_idx + search_term.len(); append( job, &text_str[match_idx..highlight_end_idx], text_color, Some(highlight_color), font_id, ); start = highlight_end_idx; } append(job, &text_str[start..], text_color, None, font_id); return; } } append(job, text_str, text_color, None, font_id); } fn append( job: &mut LayoutJob, text_str: &str, color: Color32, background_color: Option<Color32>, font_id: &FontId, ) { let mut text_format = TextFormat { color, font_id: font_id.clone(), ..Default::default() }; if let Some(background_color) = background_color { text_format.background = background_color; } job.append(text_str, 0.0, text_format); } fn render_punc( ui: &mut Ui, punc_str: &str, color: Color32, background_color: Option<Color32>, font_id: &FontId, ) -> Response { let mut job = LayoutJob::default(); append(&mut job, punc_str, color, background_color, font_id); render_job(ui, job) } fn render_job(ui: &mut Ui, job: LayoutJob) -> Response { ui.add(Label::new(job).sense(Sense::click_and_drag())) } struct JsonTreeNodeConfig { style: JsonTreeStyle, default_expand: InnerExpand, abbreviate_root: bool, search_term: Option<SearchTerm>, } #[derive(Debug, Clone)] enum InnerExpand { All, None, ToLevel(u8), Paths(HashSet<Vec<String>>), } struct Expandable<'a> { id: Id, entries: Vec<(String, &'a dyn ToJsonTreeValue)>, expandable_type: ExpandableType, parent: Option<Parent>, } #[derive(Hash)] struct Parent { key: String, expandable_type: ExpandableType, } impl Parent { fn new(key: String, expandable_type: ExpandableType) -> Self { Self { key, expandable_type, } } } fn get_pointer_string(path_segments: &[String]) -> String { if path_segments.is_empty() { "".to_string() } else { format!("/{}", path_segments.join("/")) } } type PathIdMap = HashMap<Vec<String>, Id>; fn populate_path_id_map( value: &dyn ToJsonTreeValue, path_id_map: &mut PathIdMap, make_persistent_id: &dyn Fn(&Vec<String>) -> Id, ) { populate_path_id_map_impl(value, &mut vec![], path_id_map, make_persistent_id); } fn populate_path_id_map_impl( value: &dyn ToJsonTreeValue, path_segments: &mut Vec<String>, path_id_map: &mut PathIdMap, make_persistent_id: &dyn Fn(&Vec<String>) -> Id, ) { if let JsonTreeValue::Expandable(entries, _) = value.to_json_tree_value() { for (key, val) in entries { let id = make_persistent_id(path_segments); path_id_map.insert(path_segments.clone(), id); path_segments.push(key.to_owned()); populate_path_id_map_impl(val, path_segments, path_id_map, make_persistent_id); path_segments.pop(); } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_json_tree/src/delimiters.rs
crates/egui_json_tree/src/delimiters.rs
pub struct Delimiters { pub collapsed: &'static str, pub collapsed_empty: &'static str, pub opening: &'static str, pub closing: &'static str, } pub const ARRAY_DELIMITERS: Delimiters = Delimiters { collapsed: "[...]", collapsed_empty: "[]", opening: "[", closing: "]", }; pub const OBJECT_DELIMITERS: Delimiters = Delimiters { collapsed: "{...}", collapsed_empty: "{}", opening: "{", closing: "}", };
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_json_tree/src/lib.rs
crates/egui_json_tree/src/lib.rs
//! An interactive JSON tree visualiser for `egui`, with search and highlight functionality. //! //! ``` //! use egui::{Color32}; //! use egui_json_tree::{DefaultExpand, JsonTree, JsonTreeStyle}; //! //! # egui::__run_test_ui(|ui| { //! let value = serde_json::json!({ "foo": "bar", "fizz": [1, 2, 3]}); //! //! // Simple: //! JsonTree::new("simple-tree", &value).show(ui); //! //! // Customised: //! let response = JsonTree::new("customised-tree", &value) //! .style(JsonTreeStyle { //! bool_color: Color32::YELLOW, //! ..Default::default() //! }) //! .default_expand(DefaultExpand::All) //! .response_callback(|response, json_pointer_string| { //! // Handle interactions within the JsonTree. //! }) //! .abbreviate_root(true) // Show {...} when the root object is collapsed. //! .show(ui); //! //! // Reset the expanded state of all arrays/objects to respect the `default_expand` setting. //! response.reset_expanded(ui); //! # }); //! ``` //! [`JsonTree`] can visualise any type that implements [`ToJsonTreeValue`](trait@value::ToJsonTreeValue). //! An implementation to support [`serde_json::Value`](serde_json::Value) is provided with this crate. //! If you wish to use a different JSON type, see the [`value`](mod@value) module, //! and disable default features in your `Cargo.toml` if you do not need the [`serde_json`](serde_json) dependency. mod default_expand; mod delimiters; mod node; mod response; mod search; mod style; mod tree; pub use response::JsonTreeResponse; pub use style::JsonTreeStyle; pub mod value; pub use default_expand::DefaultExpand; pub use tree::JsonTree;
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_json_tree/src/response.rs
crates/egui_json_tree/src/response.rs
use std::collections::HashSet; use egui::{collapsing_header::CollapsingState, Id, Ui}; /// The response from showing a [`JsonTree`](crate::JsonTree). pub struct JsonTreeResponse { pub(crate) collapsing_state_ids: HashSet<Id>, } impl JsonTreeResponse { /// For the [`JsonTree`](crate::JsonTree) that provided this response, /// resets the expanded state for all of its arrays/objects to respect the `default_expand` setting. /// /// Call this whenever the `default_expand` setting changes, /// and/or you when wish to reset any manually collapsed/expanded arrays and objects to respect this setting. pub fn reset_expanded(&self, ui: &mut Ui) { for id in self.collapsing_state_ids.iter() { if let Some(state) = CollapsingState::load(ui.ctx(), *id) { state.remove(ui.ctx()); } } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_json_tree/src/value.rs
crates/egui_json_tree/src/value.rs
//! Representation of JSON values for presentation purposes. //! //! Write your own [`ToJsonTreeValue`] implementation which converts to [`JsonTreeValue`] if you wish to visualise a custom JSON type with a [`JsonTree`](crate::JsonTree), //! and disable default features in your `Cargo.toml` if you do not need the [`serde_json`](serde_json) dependency. //! //! See the [`impl ToJsonTreeValue for serde_json::Value `](../../src/egui_json_tree/value.rs.html#43-77) implementation for reference. /// Representation of JSON values for presentation purposes. pub enum JsonTreeValue<'a> { /// Representation for a non-recursive JSON value: /// - A value that can be converted to a `String` to represent the base value, e.g. `"true"` for the boolean value `true`. /// - The type of the base value. Base(&'a dyn ToString, BaseValueType), /// Representation for a recursive JSON value: /// - A `Vec` of key-value pairs. The order *must always* be the same. /// - For arrays, the key should be the index of each element. /// - For objects, the key should be the key of each object entry, without quotes. /// - The type of the recursive value, i.e. array or object. Expandable(Vec<(String, &'a dyn ToJsonTreeValue)>, ExpandableType), } /// The type of a non-recursive JSON value. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum BaseValueType { Null, Bool, Number, String, } /// The type of a recursive JSON value. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ExpandableType { Array, Object, } pub trait ToJsonTreeValue { fn to_json_tree_value(&self) -> JsonTreeValue; fn is_expandable(&self) -> bool; } const NULL_STR: &str = "null"; const TRUE_STR: &str = "true"; const FALSE_STR: &str = "false"; #[cfg(feature = "serde_json")] impl ToJsonTreeValue for serde_json::Value { fn to_json_tree_value(&self) -> JsonTreeValue { match self { serde_json::Value::Null => JsonTreeValue::Base(&NULL_STR, BaseValueType::Null), serde_json::Value::Bool(b) => { JsonTreeValue::Base(if *b { &TRUE_STR } else { &FALSE_STR }, BaseValueType::Bool) } serde_json::Value::Number(n) => JsonTreeValue::Base(n, BaseValueType::Number), serde_json::Value::String(s) => JsonTreeValue::Base(s, BaseValueType::String), serde_json::Value::Array(arr) => JsonTreeValue::Expandable( arr.iter() .enumerate() .map(|(idx, elem)| (idx.to_string(), elem as &dyn ToJsonTreeValue)) .collect(), ExpandableType::Array, ), serde_json::Value::Object(obj) => JsonTreeValue::Expandable( obj.iter() .map(|(key, val)| (key.to_owned(), val as &dyn ToJsonTreeValue)) .collect(), ExpandableType::Object, ), } } fn is_expandable(&self) -> bool { matches!( self, serde_json::Value::Array(_) | serde_json::Value::Object(_) ) } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_json_tree/src/search.rs
crates/egui_json_tree/src/search.rs
use std::collections::HashSet; use crate::value::{ExpandableType, JsonTreeValue, ToJsonTreeValue}; #[derive(Debug, Clone, Hash)] pub struct SearchTerm(String); impl SearchTerm { pub fn parse(search_str: &str) -> Option<Self> { SearchTerm::is_valid(search_str).then_some(Self(search_str.to_ascii_lowercase())) } fn is_valid(search_str: &str) -> bool { !search_str.is_empty() } pub fn find_match_indices_in(&self, other: &str) -> Vec<usize> { other .to_ascii_lowercase() .match_indices(&self.0) .map(|(idx, _)| idx) .collect() } pub fn len(&self) -> usize { self.0.len() } pub fn find_matching_paths_in( &self, value: &dyn ToJsonTreeValue, abbreviate_root: bool, ) -> HashSet<Vec<String>> { let mut matching_paths = HashSet::new(); search_impl(value, self, &mut vec![], &mut matching_paths); if !abbreviate_root && matching_paths.len() == 1 { // The only match was a top level key or value - no need to expand anything. matching_paths.clear(); } matching_paths } fn matches<V: ToString + ?Sized>(&self, other: &V) -> bool { other.to_string().to_ascii_lowercase().contains(&self.0) } } fn search_impl( value: &dyn ToJsonTreeValue, search_term: &SearchTerm, path_segments: &mut Vec<String>, matching_paths: &mut HashSet<Vec<String>>, ) { match value.to_json_tree_value() { JsonTreeValue::Base(value_str, _) => { if search_term.matches(value_str) { update_matches(path_segments, matching_paths); } } JsonTreeValue::Expandable(entries, expandable_type) => { for (key, val) in entries.iter() { path_segments.push(key.to_string()); // Ignore matches for indices in an array. if expandable_type == ExpandableType::Object && search_term.matches(key) { update_matches(path_segments, matching_paths); } search_impl(*val, search_term, path_segments, matching_paths); path_segments.pop(); } } }; } fn update_matches(path_segments: &[String], matching_paths: &mut HashSet<Vec<String>>) { for i in 0..path_segments.len() { matching_paths.insert(path_segments[0..i].to_vec()); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_json_tree/src/tree.rs
crates/egui_json_tree/src/tree.rs
use crate::{ node::JsonTreeNode, value::ToJsonTreeValue, DefaultExpand, JsonTreeResponse, JsonTreeStyle, }; use egui::{Id, Response, Ui}; use std::hash::Hash; type ResponseCallback<'a> = dyn FnMut(Response, &String) + 'a; #[derive(Default)] pub struct JsonTreeConfig<'a> { pub(crate) style: JsonTreeStyle, pub(crate) default_expand: DefaultExpand<'a>, pub(crate) response_callback: Option<Box<ResponseCallback<'a>>>, pub(crate) abbreviate_root: bool, } /// An interactive JSON tree visualiser. #[must_use = "You should call .show()"] pub struct JsonTree<'a> { id: Id, value: &'a dyn ToJsonTreeValue, config: JsonTreeConfig<'a>, } impl<'a> JsonTree<'a> { /// Creates a new [`JsonTree`]. /// `id` must be a globally unique identifier. pub fn new(id: impl Hash, value: &'a impl ToJsonTreeValue) -> Self { Self { id: Id::new(id), value, config: JsonTreeConfig::default(), } } /// Override colors for JSON syntax highlighting, and search match highlighting. pub fn style(mut self, style: JsonTreeStyle) -> Self { self.config.style = style; self } /// Override how the [`JsonTree`] expands arrays/objects by default. pub fn default_expand(mut self, default_expand: DefaultExpand<'a>) -> Self { self.config.default_expand = default_expand; self } /// Register a callback to handle interactions within a [`JsonTree`]. /// - `Response`: The `Response` from rendering an array index, object key or value. /// - `&String`: A JSON pointer string. pub fn response_callback( mut self, response_callback: impl FnMut(Response, &String) + 'a, ) -> Self { self.config.response_callback = Some(Box::new(response_callback)); self } /// Override whether a root array/object should show direct child elements when collapsed. /// /// If called with `true`, a collapsed root object would render as: `{...}`. /// /// Otherwise, a collapsed root object would render as: `{ "foo": "bar", "baz": {...} }`. pub fn abbreviate_root(mut self, abbreviate_root: bool) -> Self { self.config.abbreviate_root = abbreviate_root; self } /// Show the JSON tree visualisation within the `Ui`. pub fn show(self, ui: &mut Ui) -> JsonTreeResponse { JsonTreeNode::new(self.id, self.value).show_with_config(ui, self.config) } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_json_tree/src/default_expand.rs
crates/egui_json_tree/src/default_expand.rs
#[derive(Default, Debug, Clone)] /// Configuration for how a [`JsonTree`](crate::JsonTree) should expand arrays and objects by default. pub enum DefaultExpand<'a> { /// Expand all arrays and objects. All, /// Collapse all arrays and objects. #[default] None, /// Expand arrays and objects according to how many levels deep they are nested: /// - `0` would expand a top-level array/object only, /// - `1` would expand a top-level array/object and any array/object that is a direct child, /// - `2` ... /// /// And so on. ToLevel(u8), /// Expand arrays and objects to display object keys and values, /// and array elements, that match the search term. Letter case is ignored. The matches are highlighted. /// If the search term is empty, nothing will be expanded by default. SearchResults(&'a str), }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_json_tree/src/style.rs
crates/egui_json_tree/src/style.rs
use egui::{Color32, FontId, TextStyle, Ui}; use crate::value::BaseValueType; /// Contains coloring parameters for JSON syntax highlighting, and search match highlighting. #[derive(Debug, Clone, Hash)] pub struct JsonTreeStyle { pub object_key_color: Color32, pub array_idx_color: Color32, pub null_color: Color32, pub bool_color: Color32, pub number_color: Color32, pub string_color: Color32, pub highlight_color: Color32, /// The text color for array brackets, object braces, colons and commas. pub punctuation_color: Color32, /// The font to use. Defaults to `TextStyle::Monospace.resolve(ui.style())`. pub font_id: Option<FontId>, } impl Default for JsonTreeStyle { fn default() -> Self { Self { object_key_color: Color32::from_rgb(161, 206, 235), array_idx_color: Color32::from_rgb(96, 103, 168), null_color: Color32::from_rgb(103, 154, 209), bool_color: Color32::from_rgb(103, 154, 209), number_color: Color32::from_rgb(181, 199, 166), string_color: Color32::from_rgb(194, 146, 122), highlight_color: Color32::from_rgba_premultiplied(72, 72, 72, 50), punctuation_color: Color32::from_gray(140), font_id: None, } } } impl JsonTreeStyle { pub fn get_color(&self, base_value_type: &BaseValueType) -> Color32 { match base_value_type { BaseValueType::Null => self.null_color, BaseValueType::Bool => self.bool_color, BaseValueType::Number => self.number_color, BaseValueType::String => self.string_color, } } pub(crate) fn font_id(&self, ui: &Ui) -> FontId { if let Some(font_id) = &self.font_id { font_id.clone() } else { TextStyle::Monospace.resolve(ui.style()) } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_test_runner/src/main.rs
crates/netpurr_test_runner/src/main.rs
use std::cell::RefCell; use std::ops::Deref; use std::process::exit; use std::rc::Rc; use std::sync::{Arc, RwLock}; use std::time::Duration; use clap::Parser; use futures_util::future::join_all; use reqwest::Client; use netpurr_core::data::collections::{CollectionFolder, CollectionFolderOnlyRead, Testcase}; use netpurr_core::data::test::TestStatus; use netpurr_core::data::workspace_data::WorkspaceData; use netpurr_core::runner; use netpurr_core::runner::test::ResultTreeFolder; use netpurr_core::runner::TestGroupRunResults; #[derive(Parser, Debug)] #[command(version, about, long_about = None)] struct Args { #[arg(short, long)] workspace_name: String, #[arg(short, long)] collection_name: String, } fn main() { //let args = Args::parse(); let args=Args{ workspace_name: "aiproject".to_string(), collection_name: "百炼".to_string(), }; let client = Client::builder() .trust_dns(true) .tcp_nodelay(true) .timeout(Duration::from_secs(60)) .build() .unwrap_or_default(); let mut workspace_data = WorkspaceData::default(); workspace_data.load_all(args.workspace_name.clone()); let test_group_run_results = Arc::new(RwLock::new(TestGroupRunResults::default())); let collection_op = workspace_data.get_collection_by_name(args.collection_name.clone()); match collection_op { None => { println!("{}", "collection is not exist") } Some(collection) => run_test_group( client, workspace_data, test_group_run_results, args.collection_name.clone(), collection.folder.borrow().get_path(), None, collection.folder.clone(), ), } } fn run_test_group( client: Client, workspace_data: WorkspaceData, test_group_run_result: Arc<RwLock<TestGroupRunResults>>, collection_name: String, collection_path: String, parent_testcase: Option<Testcase>, folder: Rc<RefCell<CollectionFolder>>, ) { let envs = workspace_data.get_build_envs(workspace_data.get_collection(Some(collection_name.clone()))); let script_tree = workspace_data.get_script_tree(collection_path.clone()); let folder_only_read = CollectionFolderOnlyRead::from(folder.clone()); let run_request_infos = runner::Runner::get_test_group_jobs( envs.clone(), script_tree.clone(), collection_path.clone(), parent_testcase, folder_only_read.clone(), ); runner::Runner::run_test_group_jobs(client,run_request_infos,test_group_run_result.clone(),true); let result_tree = ResultTreeFolder::create( folder.clone(), vec![], test_group_run_result.read().unwrap().deref().clone(), ); let json = serde_yaml::to_string(&result_tree).expect("yaml error"); println!("{}", json); if result_tree.status == TestStatus::PASS { println!("{}", "Test Success"); exit(0); } else { println!("{}", "Test Error"); exit(1); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui-toast/src/lib.rs
crates/egui-toast/src/lib.rs
//! This crate provides a convenient interface for showing toast notifications with //! the [egui](https://github.com/emilk/egui) library. //! //! For a complete example, see <https://github.com/urholaukkarinen/egui-toast/tree/main/demo>. //! //! # Usage //! //! To get started, create a `Toasts` instance in your rendering code and specify the anchor position and //! direction for the notifications. Toast notifications will show up starting from the specified //! anchor position and stack up in the specified direction. //! ``` //! # use std::time::Duration; //! use egui::Align2; //! # use egui_toast::{Toasts, ToastKind, ToastOptions, Toast}; //! # egui_toast::__run_test_ui(|ui, ctx| { //! let mut toasts = Toasts::new() //! .anchor(Align2::LEFT_TOP, (10.0, 10.0)) //! .direction(egui::Direction::TopDown); //! //! toasts.add(Toast { //! text: "Hello, World".into(), //! kind: ToastKind::Info, //! options: ToastOptions::default() //! .duration_in_seconds(3.0) //! .show_progress(true) //! .show_icon(true) //! }); //! //! // Show all toasts //! toasts.show(ctx); //! # }) //! ``` //! //! Look of the notifications can be fully customized by specifying a custom rendering function for a specific toast kind //! with [`Toasts::custom_contents`]. [`ToastKind::Custom`] can be used if the default kinds are not sufficient. //! //! ``` //! # use std::time::Duration; //! # use std::sync::Arc; //! # use egui_toast::{Toast, ToastKind, ToastOptions, Toasts}; //! # egui_toast::__run_test_ui(|ui, ctx| { //! const MY_CUSTOM_TOAST: u32 = 0; //! //! fn custom_toast_contents(ui: &mut egui::Ui, toast: &mut Toast) -> egui::Response { //! egui::Frame::window(ui.style()).show(ui, |ui| { //! ui.label(toast.text.clone()); //! }).response //! } //! //! let mut toasts = Toasts::new() //! .custom_contents(MY_CUSTOM_TOAST, custom_toast_contents); //! //! // Add a custom toast that never expires //! toasts.add(Toast { //! text: "Hello, World".into(), //! kind: ToastKind::Custom(MY_CUSTOM_TOAST), //! options: ToastOptions::default(), //! }); //! //! # }) //! ``` //! #![deny(clippy::all)] mod toast; pub use toast::*; use std::collections::HashMap; use std::sync::Arc; use std::time::Duration; use egui::epaint::RectShape; use egui::{ Align2, Area, Color32, Context, Direction, Frame, Id, Order, Pos2, Response, RichText, Rounding, Shape, Stroke, Ui, }; pub const INFO_COLOR: Color32 = Color32::from_rgb(0, 155, 255); pub const WARNING_COLOR: Color32 = Color32::from_rgb(255, 212, 0); pub const ERROR_COLOR: Color32 = Color32::from_rgb(255, 32, 0); pub const SUCCESS_COLOR: Color32 = Color32::from_rgb(0, 255, 32); pub type ToastContents = dyn Fn(&mut Ui, &mut Toast) -> Response + Send + Sync; pub struct Toasts { id: Id, align: Align2, offset: Pos2, direction: Direction, custom_toast_contents: HashMap<ToastKind, Arc<ToastContents>>, /// Toasts added since the last draw call. These are moved to the /// egui context's memory, so you are free to recreate the [`Toasts`] instance every frame. added_toasts: Vec<Toast>, } impl Default for Toasts { fn default() -> Self { Self { id: Id::new("__toasts"), align: Align2::LEFT_TOP, offset: Pos2::new(10.0, 10.0), direction: Direction::TopDown, custom_toast_contents: HashMap::new(), added_toasts: Vec::new(), } } } impl Toasts { pub fn new() -> Self { Self::default() } /// Position where the toasts show up. /// /// The toasts will start from this position and stack up /// in the direction specified with [`Self::direction`]. pub fn position(mut self, position: impl Into<Pos2>) -> Self { self.offset = position.into(); self } /// Anchor for the toasts. /// /// For instance, if you set this to (10.0, 10.0) and [`Align2::LEFT_TOP`], /// then (10.0, 10.0) will be the top-left corner of the first toast. pub fn anchor(mut self, anchor: Align2, offset: impl Into<Pos2>) -> Self { self.align = anchor; self.offset = offset.into(); self } /// Direction where the toasts stack up pub fn direction(mut self, direction: impl Into<Direction>) -> Self { self.direction = direction.into(); self } /// Can be used to specify a custom rendering function for toasts for given kind pub fn custom_contents( mut self, kind: impl Into<ToastKind>, add_contents: impl Fn(&mut Ui, &mut Toast) -> Response + Send + Sync + 'static, ) -> Self { self.custom_toast_contents .insert(kind.into(), Arc::new(add_contents)); self } /// Add a new toast pub fn add(&mut self, toast: Toast) -> &mut Self { self.added_toasts.push(toast); self } /// Show and update all toasts pub fn show(&mut self, ctx: &Context) { let Self { id, align, mut offset, direction, .. } = *self; let dt = ctx.input(|i| i.unstable_dt) as f64; let mut toasts: Vec<Toast> = ctx.data_mut(|d| d.get_temp(id).unwrap_or_default()); toasts.extend(std::mem::take(&mut self.added_toasts)); toasts.retain(|toast| toast.options.ttl_sec > 0.0); for (i, toast) in toasts.iter_mut().enumerate() { let response = Area::new(id.with("toast").with(i)) .anchor(align, offset.to_vec2()) .order(Order::Foreground) .interactable(true) .show(ctx, |ui| { if let Some(add_contents) = self.custom_toast_contents.get_mut(&toast.kind) { add_contents(ui, toast) } else { default_toast_contents(ui, toast) }; }) .response; if !response.hovered() { toast.options.ttl_sec -= dt; if toast.options.ttl_sec.is_finite() { ctx.request_repaint_after(Duration::from_secs_f64( toast.options.ttl_sec.max(0.0), )); } } if toast.options.show_progress { ctx.request_repaint(); } match direction { Direction::LeftToRight => { offset.x += response.rect.width() + 10.0; } Direction::RightToLeft => { offset.x -= response.rect.width() + 10.0; } Direction::TopDown => { offset.y += response.rect.height() + 10.0; } Direction::BottomUp => { offset.y -= response.rect.height() + 10.0; } } } ctx.data_mut(|d| d.insert_temp(id, toasts)); } } fn default_toast_contents(ui: &mut Ui, toast: &mut Toast) -> Response { let inner_margin = 10.0; let frame = Frame::window(ui.style()); let response = frame .inner_margin(inner_margin) .stroke(Stroke::NONE) .show(ui, |ui| { ui.horizontal(|ui| { let (icon, color) = match toast.kind { ToastKind::Warning => ("⚠", WARNING_COLOR), ToastKind::Error => ("❗", ERROR_COLOR), ToastKind::Success => ("✔", SUCCESS_COLOR), _ => ("ℹ", INFO_COLOR), }; let a = |ui: &mut Ui, toast: &mut Toast| { if toast.options.show_icon { ui.label(RichText::new(icon).color(color)); } }; let b = |ui: &mut Ui, toast: &mut Toast| ui.label(toast.text.clone()); let c = |ui: &mut Ui, toast: &mut Toast| { if ui.button("🗙").clicked() { toast.close(); } }; // Draw the contents in the reverse order on right-to-left layouts // to keep the same look. if ui.layout().prefer_right_to_left() { c(ui, toast); b(ui, toast); a(ui, toast); } else { a(ui, toast); b(ui, toast); c(ui, toast); } }) }) .response; if toast.options.show_progress { progress_bar(ui, &response, toast); } // Draw the frame's stroke last let frame_shape = Shape::Rect(RectShape::stroke( response.rect, frame.rounding, ui.visuals().window_stroke, )); ui.painter().add(frame_shape); response } fn progress_bar(ui: &mut Ui, response: &Response, toast: &Toast) { let rounding = Rounding { nw: 0.0, ne: 0.0, ..ui.visuals().window_rounding }; let mut clip_rect = response.rect; clip_rect.set_top(clip_rect.bottom() - 2.0); clip_rect.set_right(clip_rect.left() + clip_rect.width() * toast.options.progress() as f32); ui.painter().with_clip_rect(clip_rect).rect_filled( response.rect, rounding, ui.visuals().text_color(), ); } pub fn __run_test_ui(mut add_contents: impl FnMut(&mut Ui, &Context)) { let ctx = Context::default(); let _ = ctx.run(Default::default(), |ctx| { egui::CentralPanel::default().show(ctx, |ui| { add_contents(ui, ctx); }); }); } pub fn __run_test_ui_with_toasts(mut add_contents: impl FnMut(&mut Ui, &mut Toasts)) { let ctx = Context::default(); let _ = ctx.run(Default::default(), |ctx| { egui::CentralPanel::default().show(ctx, |ui| { let mut toasts = Toasts::new(); add_contents(ui, &mut toasts); }); }); }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui-toast/src/toast.rs
crates/egui-toast/src/toast.rs
use egui::WidgetText; use std::time::Duration; #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] pub enum ToastKind { Info, Warning, Error, Success, Custom(u32), } impl From<u32> for ToastKind { fn from(value: u32) -> ToastKind { ToastKind::Custom(value) } } #[derive(Clone)] pub struct Toast { pub kind: ToastKind, pub text: WidgetText, pub options: ToastOptions, } impl Toast { /// Close the toast immediately pub fn close(&mut self) { self.options.ttl_sec = 0.0; } } #[derive(Copy, Clone)] pub struct ToastOptions { /// Whether the toast should include an icon. pub show_icon: bool, /// Whether the toast should visualize the remaining time pub show_progress: bool, /// The toast is removed when this reaches zero. pub(crate) ttl_sec: f64, /// Initial value of ttl_sec, used for progress pub(crate) initial_ttl_sec: f64, } impl Default for ToastOptions { fn default() -> Self { Self { show_icon: true, show_progress: true, ttl_sec: f64::INFINITY, initial_ttl_sec: f64::INFINITY, } } } impl ToastOptions { /// Set duration of the toast. [None] duration means the toast never expires. pub fn duration(mut self, duration: impl Into<Option<Duration>>) -> Self { self.ttl_sec = duration .into() .map_or(f64::INFINITY, |duration| duration.as_secs_f64()); self.initial_ttl_sec = self.ttl_sec; self } /// Set duration of the toast in milliseconds. pub fn duration_in_millis(self, millis: u64) -> Self { self.duration(Duration::from_millis(millis)) } /// Set duration of the toast in seconds. pub fn duration_in_seconds(self, secs: f64) -> Self { self.duration(Duration::from_secs_f64(secs)) } /// Visualize remaining time using a progress bar. pub fn show_progress(mut self, show_progress: bool) -> Self { self.show_progress = show_progress; self } /// Show type icon in the toast. pub fn show_icon(mut self, show_icon: bool) -> Self { self.show_icon = show_icon; self } /// Remaining time of the toast between 1..0 pub fn progress(self) -> f64 { if self.ttl_sec.is_finite() && self.initial_ttl_sec > 0.0 { self.ttl_sec / self.initial_ttl_sec } else { 0.0 } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui-phosphor/src/lib.rs
crates/egui-phosphor/src/lib.rs
pub mod variants; pub use variants::*; pub fn add_to_fonts(fonts: &mut egui::FontDefinitions, variant: Variant) { fonts .font_data .insert("phosphor".into(), variant.font_data()); if let Some(font_keys) = fonts.families.get_mut(&egui::FontFamily::Proportional) { font_keys.push("phosphor".into()); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui-phosphor/src/variants/light.rs
crates/egui-phosphor/src/variants/light.rs
#![allow(unused)] pub const ADDRESS_BOOK: &str = "\u{E900}"; pub const AIRPLANE_IN_FLIGHT: &str = "\u{E901}"; pub const AIRPLANE_LANDING: &str = "\u{E902}"; pub const AIRPLANE: &str = "\u{E903}"; pub const AIRPLANE_TAKEOFF: &str = "\u{E904}"; pub const AIRPLANE_TILT: &str = "\u{E905}"; pub const AIRPLAY: &str = "\u{E906}"; pub const AIR_TRAFFIC_CONTROL: &str = "\u{E907}"; pub const ALARM: &str = "\u{E908}"; pub const ALIEN: &str = "\u{E909}"; pub const ALIGN_BOTTOM: &str = "\u{E90A}"; pub const ALIGN_BOTTOM_SIMPLE: &str = "\u{E90B}"; pub const ALIGN_CENTER_HORIZONTAL: &str = "\u{E90C}"; pub const ALIGN_CENTER_HORIZONTAL_SIMPLE: &str = "\u{E90D}"; pub const ALIGN_CENTER_VERTICAL: &str = "\u{E90E}"; pub const ALIGN_CENTER_VERTICAL_SIMPLE: &str = "\u{E90F}"; pub const ALIGN_LEFT: &str = "\u{E910}"; pub const ALIGN_LEFT_SIMPLE: &str = "\u{E911}"; pub const ALIGN_RIGHT: &str = "\u{E912}"; pub const ALIGN_RIGHT_SIMPLE: &str = "\u{E913}"; pub const ALIGN_TOP: &str = "\u{E914}"; pub const ALIGN_TOP_SIMPLE: &str = "\u{E915}"; pub const AMAZON_LOGO: &str = "\u{E916}"; pub const ANCHOR: &str = "\u{E917}"; pub const ANCHOR_SIMPLE: &str = "\u{E918}"; pub const ANDROID_LOGO: &str = "\u{E919}"; pub const ANGULAR_LOGO: &str = "\u{E91A}"; pub const APERTURE: &str = "\u{E91B}"; pub const APPLE_LOGO: &str = "\u{E91C}"; pub const APPLE_PODCASTS_LOGO: &str = "\u{E91D}"; pub const APP_STORE_LOGO: &str = "\u{E91E}"; pub const APP_WINDOW: &str = "\u{E91F}"; pub const ARCHIVE_BOX: &str = "\u{E920}"; pub const ARCHIVE: &str = "\u{E921}"; pub const ARCHIVE_TRAY: &str = "\u{E922}"; pub const ARMCHAIR: &str = "\u{E923}"; pub const ARROW_ARC_LEFT: &str = "\u{E924}"; pub const ARROW_ARC_RIGHT: &str = "\u{E925}"; pub const ARROW_BEND_DOUBLE_UP_LEFT: &str = "\u{E926}"; pub const ARROW_BEND_DOUBLE_UP_RIGHT: &str = "\u{E927}"; pub const ARROW_BEND_DOWN_LEFT: &str = "\u{E928}"; pub const ARROW_BEND_DOWN_RIGHT: &str = "\u{E929}"; pub const ARROW_BEND_LEFT_DOWN: &str = "\u{E92A}"; pub const ARROW_BEND_LEFT_UP: &str = "\u{E92B}"; pub const ARROW_BEND_RIGHT_DOWN: &str = "\u{E92C}"; pub const ARROW_BEND_RIGHT_UP: &str = "\u{E92D}"; pub const ARROW_BEND_UP_LEFT: &str = "\u{E92E}"; pub const ARROW_BEND_UP_RIGHT: &str = "\u{E92F}"; pub const ARROW_CIRCLE_DOWN_LEFT: &str = "\u{E930}"; pub const ARROW_CIRCLE_DOWN: &str = "\u{E931}"; pub const ARROW_CIRCLE_DOWN_RIGHT: &str = "\u{E932}"; pub const ARROW_CIRCLE_LEFT: &str = "\u{E933}"; pub const ARROW_CIRCLE_RIGHT: &str = "\u{E934}"; pub const ARROW_CIRCLE_UP_LEFT: &str = "\u{E935}"; pub const ARROW_CIRCLE_UP: &str = "\u{E936}"; pub const ARROW_CIRCLE_UP_RIGHT: &str = "\u{E937}"; pub const ARROW_CLOCKWISE: &str = "\u{E938}"; pub const ARROW_COUNTER_CLOCKWISE: &str = "\u{E939}"; pub const ARROW_DOWN_LEFT: &str = "\u{E93A}"; pub const ARROW_DOWN: &str = "\u{E93B}"; pub const ARROW_DOWN_RIGHT: &str = "\u{E93C}"; pub const ARROW_ELBOW_DOWN_LEFT: &str = "\u{E93D}"; pub const ARROW_ELBOW_DOWN_RIGHT: &str = "\u{E93E}"; pub const ARROW_ELBOW_LEFT_DOWN: &str = "\u{E93F}"; pub const ARROW_ELBOW_LEFT: &str = "\u{E940}"; pub const ARROW_ELBOW_LEFT_UP: &str = "\u{E941}"; pub const ARROW_ELBOW_RIGHT_DOWN: &str = "\u{E942}"; pub const ARROW_ELBOW_RIGHT: &str = "\u{E943}"; pub const ARROW_ELBOW_RIGHT_UP: &str = "\u{E944}"; pub const ARROW_ELBOW_UP_LEFT: &str = "\u{E945}"; pub const ARROW_ELBOW_UP_RIGHT: &str = "\u{E946}"; pub const ARROW_FAT_DOWN: &str = "\u{E947}"; pub const ARROW_FAT_LEFT: &str = "\u{E948}"; pub const ARROW_FAT_LINE_DOWN: &str = "\u{E949}"; pub const ARROW_FAT_LINE_LEFT: &str = "\u{E94A}"; pub const ARROW_FAT_LINE_RIGHT: &str = "\u{E94B}"; pub const ARROW_FAT_LINES_DOWN: &str = "\u{E94C}"; pub const ARROW_FAT_LINES_LEFT: &str = "\u{E94D}"; pub const ARROW_FAT_LINES_RIGHT: &str = "\u{E94E}"; pub const ARROW_FAT_LINES_UP: &str = "\u{E94F}"; pub const ARROW_FAT_LINE_UP: &str = "\u{E950}"; pub const ARROW_FAT_RIGHT: &str = "\u{E951}"; pub const ARROW_FAT_UP: &str = "\u{E952}"; pub const ARROW_LEFT: &str = "\u{E953}"; pub const ARROW_LINE_DOWN_LEFT: &str = "\u{E954}"; pub const ARROW_LINE_DOWN: &str = "\u{E955}"; pub const ARROW_LINE_DOWN_RIGHT: &str = "\u{E956}"; pub const ARROW_LINE_LEFT: &str = "\u{E957}"; pub const ARROW_LINE_RIGHT: &str = "\u{E958}"; pub const ARROW_LINE_UP_LEFT: &str = "\u{E959}"; pub const ARROW_LINE_UP: &str = "\u{E95A}"; pub const ARROW_LINE_UP_RIGHT: &str = "\u{E95B}"; pub const ARROW_RIGHT: &str = "\u{E95C}"; pub const ARROWS_CLOCKWISE: &str = "\u{E95D}"; pub const ARROWS_COUNTER_CLOCKWISE: &str = "\u{E95E}"; pub const ARROWS_DOWN_UP: &str = "\u{E95F}"; pub const ARROWS_HORIZONTAL: &str = "\u{E960}"; pub const ARROWS_IN_CARDINAL: &str = "\u{E961}"; pub const ARROWS_IN: &str = "\u{E962}"; pub const ARROWS_IN_LINE_HORIZONTAL: &str = "\u{E963}"; pub const ARROWS_IN_LINE_VERTICAL: &str = "\u{E964}"; pub const ARROWS_IN_SIMPLE: &str = "\u{E965}"; pub const ARROWS_LEFT_RIGHT: &str = "\u{E966}"; pub const ARROWS_MERGE: &str = "\u{E967}"; pub const ARROWS_OUT_CARDINAL: &str = "\u{E968}"; pub const ARROWS_OUT: &str = "\u{E969}"; pub const ARROWS_OUT_LINE_HORIZONTAL: &str = "\u{E96A}"; pub const ARROWS_OUT_LINE_VERTICAL: &str = "\u{E96B}"; pub const ARROWS_OUT_SIMPLE: &str = "\u{E96C}"; pub const ARROW_SQUARE_DOWN_LEFT: &str = "\u{E96D}"; pub const ARROW_SQUARE_DOWN: &str = "\u{E96E}"; pub const ARROW_SQUARE_DOWN_RIGHT: &str = "\u{E96F}"; pub const ARROW_SQUARE_IN: &str = "\u{E970}"; pub const ARROW_SQUARE_LEFT: &str = "\u{E971}"; pub const ARROW_SQUARE_OUT: &str = "\u{E972}"; pub const ARROW_SQUARE_RIGHT: &str = "\u{E973}"; pub const ARROW_SQUARE_UP_LEFT: &str = "\u{E974}"; pub const ARROW_SQUARE_UP: &str = "\u{E975}"; pub const ARROW_SQUARE_UP_RIGHT: &str = "\u{E976}"; pub const ARROWS_SPLIT: &str = "\u{E977}"; pub const ARROWS_VERTICAL: &str = "\u{E978}"; pub const ARROW_U_DOWN_LEFT: &str = "\u{E979}"; pub const ARROW_U_DOWN_RIGHT: &str = "\u{E97A}"; pub const ARROW_U_LEFT_DOWN: &str = "\u{E97B}"; pub const ARROW_U_LEFT_UP: &str = "\u{E97C}"; pub const ARROW_UP_LEFT: &str = "\u{E97D}"; pub const ARROW_UP: &str = "\u{E97E}"; pub const ARROW_UP_RIGHT: &str = "\u{E97F}"; pub const ARROW_U_RIGHT_DOWN: &str = "\u{E980}"; pub const ARROW_U_RIGHT_UP: &str = "\u{E981}"; pub const ARROW_U_UP_LEFT: &str = "\u{E982}"; pub const ARROW_U_UP_RIGHT: &str = "\u{E983}"; pub const ARTICLE: &str = "\u{E984}"; pub const ARTICLE_MEDIUM: &str = "\u{E985}"; pub const ARTICLE_NY_TIMES: &str = "\u{E986}"; pub const ASTERISK: &str = "\u{E987}"; pub const ASTERISK_SIMPLE: &str = "\u{E988}"; pub const AT: &str = "\u{E989}"; pub const ATOM: &str = "\u{E98A}"; pub const BABY: &str = "\u{E98B}"; pub const BACKPACK: &str = "\u{E98C}"; pub const BACKSPACE: &str = "\u{E98D}"; pub const BAG: &str = "\u{E98E}"; pub const BAG_SIMPLE: &str = "\u{E98F}"; pub const BALLOON: &str = "\u{E990}"; pub const BANDAIDS: &str = "\u{E991}"; pub const BANK: &str = "\u{E992}"; pub const BARBELL: &str = "\u{E993}"; pub const BARCODE: &str = "\u{E994}"; pub const BARRICADE: &str = "\u{E995}"; pub const BASEBALL_CAP: &str = "\u{E996}"; pub const BASEBALL: &str = "\u{E997}"; pub const BASKETBALL: &str = "\u{E998}"; pub const BASKET: &str = "\u{E999}"; pub const BATHTUB: &str = "\u{E99A}"; pub const BATTERY_CHARGING: &str = "\u{E99B}"; pub const BATTERY_CHARGING_VERTICAL: &str = "\u{E99C}"; pub const BATTERY_EMPTY: &str = "\u{E99D}"; pub const BATTERY_FULL: &str = "\u{E99E}"; pub const BATTERY_HIGH: &str = "\u{E99F}"; pub const BATTERY_LOW: &str = "\u{E9A0}"; pub const BATTERY_MEDIUM: &str = "\u{E9A1}"; pub const BATTERY_PLUS: &str = "\u{E9A2}"; pub const BATTERY_PLUS_VERTICAL: &str = "\u{E9A3}"; pub const BATTERY_VERTICAL_EMPTY: &str = "\u{E9A4}"; pub const BATTERY_VERTICAL_FULL: &str = "\u{E9A5}"; pub const BATTERY_VERTICAL_HIGH: &str = "\u{E9A6}"; pub const BATTERY_VERTICAL_LOW: &str = "\u{E9A7}"; pub const BATTERY_VERTICAL_MEDIUM: &str = "\u{E9A8}"; pub const BATTERY_WARNING: &str = "\u{E9A9}"; pub const BATTERY_WARNING_VERTICAL: &str = "\u{E9AA}"; pub const BED: &str = "\u{E9AB}"; pub const BEER_BOTTLE: &str = "\u{E9AC}"; pub const BEER_STEIN: &str = "\u{E9AD}"; pub const BEHANCE_LOGO: &str = "\u{E9AE}"; pub const BELL: &str = "\u{E9AF}"; pub const BELL_RINGING: &str = "\u{E9B0}"; pub const BELL_SIMPLE: &str = "\u{E9B1}"; pub const BELL_SIMPLE_RINGING: &str = "\u{E9B2}"; pub const BELL_SIMPLE_SLASH: &str = "\u{E9B3}"; pub const BELL_SIMPLE_Z: &str = "\u{E9B4}"; pub const BELL_SLASH: &str = "\u{E9B5}"; pub const BELL_Z: &str = "\u{E9B6}"; pub const BEZIER_CURVE: &str = "\u{E9B7}"; pub const BICYCLE: &str = "\u{E9B8}"; pub const BINOCULARS: &str = "\u{E9B9}"; pub const BIRD: &str = "\u{E9BA}"; pub const BLUETOOTH_CONNECTED: &str = "\u{E9BB}"; pub const BLUETOOTH: &str = "\u{E9BC}"; pub const BLUETOOTH_SLASH: &str = "\u{E9BD}"; pub const BLUETOOTH_X: &str = "\u{E9BE}"; pub const BOAT: &str = "\u{E9BF}"; pub const BONE: &str = "\u{E9C0}"; pub const BOOK_BOOKMARK: &str = "\u{E9C1}"; pub const BOOK: &str = "\u{E9C2}"; pub const BOOKMARK: &str = "\u{E9C3}"; pub const BOOKMARK_SIMPLE: &str = "\u{E9C4}"; pub const BOOKMARKS: &str = "\u{E9C5}"; pub const BOOKMARKS_SIMPLE: &str = "\u{E9C6}"; pub const BOOK_OPEN: &str = "\u{E9C7}"; pub const BOOK_OPEN_TEXT: &str = "\u{E9C8}"; pub const BOOKS: &str = "\u{E9C9}"; pub const BOOT: &str = "\u{E9CA}"; pub const BOUNDING_BOX: &str = "\u{E9CB}"; pub const BOWL_FOOD: &str = "\u{E9CC}"; pub const BRACKETS_ANGLE: &str = "\u{E9CD}"; pub const BRACKETS_CURLY: &str = "\u{E9CE}"; pub const BRACKETS_ROUND: &str = "\u{E9CF}"; pub const BRACKETS_SQUARE: &str = "\u{E9D0}"; pub const BRAIN: &str = "\u{E9D1}"; pub const BRANDY: &str = "\u{E9D2}"; pub const BRIDGE: &str = "\u{E9D3}"; pub const BRIEFCASE: &str = "\u{E9D4}"; pub const BRIEFCASE_METAL: &str = "\u{E9D5}"; pub const BROADCAST: &str = "\u{E9D6}"; pub const BROOM: &str = "\u{E9D7}"; pub const BROWSER: &str = "\u{E9D8}"; pub const BROWSERS: &str = "\u{E9D9}"; pub const BUG_BEETLE: &str = "\u{E9DA}"; pub const BUG_DROID: &str = "\u{E9DB}"; pub const BUG: &str = "\u{E9DC}"; pub const BUILDINGS: &str = "\u{E9DD}"; pub const BUS: &str = "\u{E9DE}"; pub const BUTTERFLY: &str = "\u{E9DF}"; pub const CACTUS: &str = "\u{E9E0}"; pub const CAKE: &str = "\u{E9E1}"; pub const CALCULATOR: &str = "\u{E9E2}"; pub const CALENDAR_BLANK: &str = "\u{E9E3}"; pub const CALENDAR_CHECK: &str = "\u{E9E4}"; pub const CALENDAR: &str = "\u{E9E5}"; pub const CALENDAR_PLUS: &str = "\u{E9E6}"; pub const CALENDAR_X: &str = "\u{E9E7}"; pub const CALL_BELL: &str = "\u{E9E8}"; pub const CAMERA: &str = "\u{E9E9}"; pub const CAMERA_PLUS: &str = "\u{E9EA}"; pub const CAMERA_ROTATE: &str = "\u{E9EB}"; pub const CAMERA_SLASH: &str = "\u{E9EC}"; pub const CAMPFIRE: &str = "\u{E9ED}"; pub const CARDHOLDER: &str = "\u{E9EE}"; pub const CARDS: &str = "\u{E9EF}"; pub const CARET_CIRCLE_DOUBLE_DOWN: &str = "\u{E9F0}"; pub const CARET_CIRCLE_DOUBLE_LEFT: &str = "\u{E9F1}"; pub const CARET_CIRCLE_DOUBLE_RIGHT: &str = "\u{E9F2}"; pub const CARET_CIRCLE_DOUBLE_UP: &str = "\u{E9F3}"; pub const CARET_CIRCLE_DOWN: &str = "\u{E9F4}"; pub const CARET_CIRCLE_LEFT: &str = "\u{E9F5}"; pub const CARET_CIRCLE_RIGHT: &str = "\u{E9F6}"; pub const CARET_CIRCLE_UP_DOWN: &str = "\u{E9F7}"; pub const CARET_CIRCLE_UP: &str = "\u{E9F8}"; pub const CARET_DOUBLE_DOWN: &str = "\u{E9F9}"; pub const CARET_DOUBLE_LEFT: &str = "\u{E9FA}"; pub const CARET_DOUBLE_RIGHT: &str = "\u{E9FB}"; pub const CARET_DOUBLE_UP: &str = "\u{E9FC}"; pub const CARET_DOWN: &str = "\u{E9FD}"; pub const CARET_LEFT: &str = "\u{E9FE}"; pub const CARET_RIGHT: &str = "\u{E9FF}"; pub const CARET_UP_DOWN: &str = "\u{EA00}"; pub const CARET_UP: &str = "\u{EA01}"; pub const CAR: &str = "\u{EA02}"; pub const CAR_PROFILE: &str = "\u{EA03}"; pub const CARROT: &str = "\u{EA04}"; pub const CAR_SIMPLE: &str = "\u{EA05}"; pub const CASSETTE_TAPE: &str = "\u{EA06}"; pub const CASTLE_TURRET: &str = "\u{EA07}"; pub const CAT: &str = "\u{EA08}"; pub const CELL_SIGNAL_FULL: &str = "\u{EA09}"; pub const CELL_SIGNAL_HIGH: &str = "\u{EA0A}"; pub const CELL_SIGNAL_LOW: &str = "\u{EA0B}"; pub const CELL_SIGNAL_MEDIUM: &str = "\u{EA0C}"; pub const CELL_SIGNAL_NONE: &str = "\u{EA0D}"; pub const CELL_SIGNAL_SLASH: &str = "\u{EA0E}"; pub const CELL_SIGNAL_X: &str = "\u{EA0F}"; pub const CERTIFICATE: &str = "\u{EA10}"; pub const CHAIR: &str = "\u{EA11}"; pub const CHALKBOARD: &str = "\u{EA12}"; pub const CHALKBOARD_SIMPLE: &str = "\u{EA13}"; pub const CHALKBOARD_TEACHER: &str = "\u{EA14}"; pub const CHAMPAGNE: &str = "\u{EA15}"; pub const CHARGING_STATION: &str = "\u{EA16}"; pub const CHART_BAR_HORIZONTAL: &str = "\u{EA17}"; pub const CHART_BAR: &str = "\u{EA18}"; pub const CHART_DONUT: &str = "\u{EA19}"; pub const CHART_LINE_DOWN: &str = "\u{EA1A}"; pub const CHART_LINE: &str = "\u{EA1B}"; pub const CHART_LINE_UP: &str = "\u{EA1C}"; pub const CHART_PIE: &str = "\u{EA1D}"; pub const CHART_PIE_SLICE: &str = "\u{EA1E}"; pub const CHART_POLAR: &str = "\u{EA1F}"; pub const CHART_SCATTER: &str = "\u{EA20}"; pub const CHAT_CENTERED_DOTS: &str = "\u{EA21}"; pub const CHAT_CENTERED: &str = "\u{EA22}"; pub const CHAT_CENTERED_TEXT: &str = "\u{EA23}"; pub const CHAT_CIRCLE_DOTS: &str = "\u{EA24}"; pub const CHAT_CIRCLE: &str = "\u{EA25}"; pub const CHAT_CIRCLE_TEXT: &str = "\u{EA26}"; pub const CHAT_DOTS: &str = "\u{EA27}"; pub const CHAT: &str = "\u{EA28}"; pub const CHATS_CIRCLE: &str = "\u{EA29}"; pub const CHATS: &str = "\u{EA2A}"; pub const CHATS_TEARDROP: &str = "\u{EA2B}"; pub const CHAT_TEARDROP_DOTS: &str = "\u{EA2C}"; pub const CHAT_TEARDROP: &str = "\u{EA2D}"; pub const CHAT_TEARDROP_TEXT: &str = "\u{EA2E}"; pub const CHAT_TEXT: &str = "\u{EA2F}"; pub const CHECK_CIRCLE: &str = "\u{EA30}"; pub const CHECK_FAT: &str = "\u{EA31}"; pub const CHECK: &str = "\u{EA32}"; pub const CHECKS: &str = "\u{EA33}"; pub const CHECK_SQUARE: &str = "\u{EA34}"; pub const CHECK_SQUARE_OFFSET: &str = "\u{EA35}"; pub const CHURCH: &str = "\u{EA36}"; pub const CIRCLE_DASHED: &str = "\u{EA37}"; pub const CIRCLE_HALF: &str = "\u{EA38}"; pub const CIRCLE_HALF_TILT: &str = "\u{EA39}"; pub const CIRCLE: &str = "\u{EA3A}"; pub const CIRCLE_NOTCH: &str = "\u{EA3B}"; pub const CIRCLES_FOUR: &str = "\u{EA3C}"; pub const CIRCLES_THREE: &str = "\u{EA3D}"; pub const CIRCLES_THREE_PLUS: &str = "\u{EA3E}"; pub const CIRCUITRY: &str = "\u{EA3F}"; pub const CLIPBOARD: &str = "\u{EA40}"; pub const CLIPBOARD_TEXT: &str = "\u{EA41}"; pub const CLOCK_AFTERNOON: &str = "\u{EA42}"; pub const CLOCK_CLOCKWISE: &str = "\u{EA43}"; pub const CLOCK_COUNTDOWN: &str = "\u{EA44}"; pub const CLOCK_COUNTER_CLOCKWISE: &str = "\u{EA45}"; pub const CLOCK: &str = "\u{EA46}"; pub const CLOSED_CAPTIONING: &str = "\u{EA47}"; pub const CLOUD_ARROW_DOWN: &str = "\u{EA48}"; pub const CLOUD_ARROW_UP: &str = "\u{EA49}"; pub const CLOUD_CHECK: &str = "\u{EA4A}"; pub const CLOUD_FOG: &str = "\u{EA4B}"; pub const CLOUD: &str = "\u{EA4C}"; pub const CLOUD_LIGHTNING: &str = "\u{EA4D}"; pub const CLOUD_MOON: &str = "\u{EA4E}"; pub const CLOUD_RAIN: &str = "\u{EA4F}"; pub const CLOUD_SLASH: &str = "\u{EA50}"; pub const CLOUD_SNOW: &str = "\u{EA51}"; pub const CLOUD_SUN: &str = "\u{EA52}"; pub const CLOUD_WARNING: &str = "\u{EA53}"; pub const CLOUD_X: &str = "\u{EA54}"; pub const CLUB: &str = "\u{EA55}"; pub const COAT_HANGER: &str = "\u{EA56}"; pub const CODA_LOGO: &str = "\u{EA57}"; pub const CODE_BLOCK: &str = "\u{EA58}"; pub const CODE: &str = "\u{EA59}"; pub const CODEPEN_LOGO: &str = "\u{EA5A}"; pub const CODESANDBOX_LOGO: &str = "\u{EA5B}"; pub const CODE_SIMPLE: &str = "\u{EA5C}"; pub const COFFEE: &str = "\u{EA5D}"; pub const COIN: &str = "\u{EA5E}"; pub const COINS: &str = "\u{EA5F}"; pub const COIN_VERTICAL: &str = "\u{EA60}"; pub const COLUMNS: &str = "\u{EA61}"; pub const COMMAND: &str = "\u{EA62}"; pub const COMPASS: &str = "\u{EA63}"; pub const COMPASS_TOOL: &str = "\u{EA64}"; pub const COMPUTER_TOWER: &str = "\u{EA65}"; pub const CONFETTI: &str = "\u{EA66}"; pub const CONTACTLESS_PAYMENT: &str = "\u{EA67}"; pub const CONTROL: &str = "\u{EA68}"; pub const COOKIE: &str = "\u{EA69}"; pub const COOKING_POT: &str = "\u{EA6A}"; pub const COPYLEFT: &str = "\u{EA6B}"; pub const COPY: &str = "\u{EA6C}"; pub const COPYRIGHT: &str = "\u{EA6D}"; pub const COPY_SIMPLE: &str = "\u{EA6E}"; pub const CORNERS_IN: &str = "\u{EA6F}"; pub const CORNERS_OUT: &str = "\u{EA70}"; pub const COUCH: &str = "\u{EA71}"; pub const CPU: &str = "\u{EA72}"; pub const CREDIT_CARD: &str = "\u{EA73}"; pub const CROP: &str = "\u{EA74}"; pub const CROSSHAIR: &str = "\u{EA75}"; pub const CROSSHAIR_SIMPLE: &str = "\u{EA76}"; pub const CROSS: &str = "\u{EA77}"; pub const CROWN: &str = "\u{EA78}"; pub const CROWN_SIMPLE: &str = "\u{EA79}"; pub const CUBE_FOCUS: &str = "\u{EA7A}"; pub const CUBE: &str = "\u{EA7B}"; pub const CUBE_TRANSPARENT: &str = "\u{EA7C}"; pub const CURRENCY_BTC: &str = "\u{EA7D}"; pub const CURRENCY_CIRCLE_DOLLAR: &str = "\u{EA7E}"; pub const CURRENCY_CNY: &str = "\u{EA7F}"; pub const CURRENCY_DOLLAR: &str = "\u{EA80}"; pub const CURRENCY_DOLLAR_SIMPLE: &str = "\u{EA81}"; pub const CURRENCY_ETH: &str = "\u{EA82}"; pub const CURRENCY_EUR: &str = "\u{EA83}"; pub const CURRENCY_GBP: &str = "\u{EA84}"; pub const CURRENCY_INR: &str = "\u{EA85}"; pub const CURRENCY_JPY: &str = "\u{EA86}"; pub const CURRENCY_KRW: &str = "\u{EA87}"; pub const CURRENCY_KZT: &str = "\u{EA88}"; pub const CURRENCY_NGN: &str = "\u{EA89}"; pub const CURRENCY_RUB: &str = "\u{EA8A}"; pub const CURSOR_CLICK: &str = "\u{EA8B}"; pub const CURSOR: &str = "\u{EA8C}"; pub const CURSOR_TEXT: &str = "\u{EA8D}"; pub const CYLINDER: &str = "\u{EA8E}"; pub const DATABASE: &str = "\u{EA8F}"; pub const DESKTOP: &str = "\u{EA90}"; pub const DESKTOP_TOWER: &str = "\u{EA91}"; pub const DETECTIVE: &str = "\u{EA92}"; pub const DEVICE_MOBILE_CAMERA: &str = "\u{EA93}"; pub const DEVICE_MOBILE: &str = "\u{EA94}"; pub const DEVICE_MOBILE_SPEAKER: &str = "\u{EA95}"; pub const DEVICES: &str = "\u{EA96}"; pub const DEVICE_TABLET_CAMERA: &str = "\u{EA97}"; pub const DEVICE_TABLET: &str = "\u{EA98}"; pub const DEVICE_TABLET_SPEAKER: &str = "\u{EA99}"; pub const DEV_TO_LOGO: &str = "\u{EA9A}"; pub const DIAMOND: &str = "\u{EA9B}"; pub const DIAMONDS_FOUR: &str = "\u{EA9C}"; pub const DICE_FIVE: &str = "\u{EA9D}"; pub const DICE_FOUR: &str = "\u{EA9E}"; pub const DICE_ONE: &str = "\u{EA9F}"; pub const DICE_SIX: &str = "\u{EAA0}"; pub const DICE_THREE: &str = "\u{EAA1}"; pub const DICE_TWO: &str = "\u{EAA2}"; pub const DISC: &str = "\u{EAA3}"; pub const DISCORD_LOGO: &str = "\u{EAA4}"; pub const DIVIDE: &str = "\u{EAA5}"; pub const DNA: &str = "\u{EAA6}"; pub const DOG: &str = "\u{EAA7}"; pub const DOOR: &str = "\u{EAA8}"; pub const DOOR_OPEN: &str = "\u{EAA9}"; pub const DOT: &str = "\u{EAAA}"; pub const DOT_OUTLINE: &str = "\u{EAAB}"; pub const DOTS_NINE: &str = "\u{EAAC}"; pub const DOTS_SIX: &str = "\u{EAAD}"; pub const DOTS_SIX_VERTICAL: &str = "\u{EAAE}"; pub const DOTS_THREE_CIRCLE: &str = "\u{EAAF}"; pub const DOTS_THREE_CIRCLE_VERTICAL: &str = "\u{EAB0}"; pub const DOTS_THREE: &str = "\u{EAB1}"; pub const DOTS_THREE_OUTLINE: &str = "\u{EAB2}"; pub const DOTS_THREE_OUTLINE_VERTICAL: &str = "\u{EAB3}"; pub const DOTS_THREE_VERTICAL: &str = "\u{EAB4}"; pub const DOWNLOAD: &str = "\u{EAB5}"; pub const DOWNLOAD_SIMPLE: &str = "\u{EAB6}"; pub const DRESS: &str = "\u{EAB7}"; pub const DRIBBBLE_LOGO: &str = "\u{EAB8}"; pub const DROPBOX_LOGO: &str = "\u{EAB9}"; pub const DROP_HALF_BOTTOM: &str = "\u{EABA}"; pub const DROP_HALF: &str = "\u{EABB}"; pub const DROP: &str = "\u{EABC}"; pub const EAR: &str = "\u{EABD}"; pub const EAR_SLASH: &str = "\u{EABE}"; pub const EGG_CRACK: &str = "\u{EABF}"; pub const EGG: &str = "\u{EAC0}"; pub const EJECT: &str = "\u{EAC1}"; pub const EJECT_SIMPLE: &str = "\u{EAC2}"; pub const ELEVATOR: &str = "\u{EAC3}"; pub const ENGINE: &str = "\u{EAC4}"; pub const ENVELOPE: &str = "\u{EAC5}"; pub const ENVELOPE_OPEN: &str = "\u{EAC6}"; pub const ENVELOPE_SIMPLE: &str = "\u{EAC7}"; pub const ENVELOPE_SIMPLE_OPEN: &str = "\u{EAC8}"; pub const EQUALIZER: &str = "\u{EAC9}"; pub const EQUALS: &str = "\u{EACA}"; pub const ERASER: &str = "\u{EACB}"; pub const ESCALATOR_DOWN: &str = "\u{EACC}"; pub const ESCALATOR_UP: &str = "\u{EACD}"; pub const EXAM: &str = "\u{EACE}"; pub const EXCLUDE: &str = "\u{EACF}"; pub const EXCLUDE_SQUARE: &str = "\u{EAD0}"; pub const EXPORT: &str = "\u{EAD1}"; pub const EYE_CLOSED: &str = "\u{EAD2}"; pub const EYEDROPPER: &str = "\u{EAD3}"; pub const EYEDROPPER_SAMPLE: &str = "\u{EAD4}"; pub const EYEGLASSES: &str = "\u{EAD5}"; pub const EYE: &str = "\u{EAD6}"; pub const EYE_SLASH: &str = "\u{EAD7}"; pub const FACEBOOK_LOGO: &str = "\u{EAD8}"; pub const FACE_MASK: &str = "\u{EAD9}"; pub const FACTORY: &str = "\u{EADA}"; pub const FADERS_HORIZONTAL: &str = "\u{EADB}"; pub const FADERS: &str = "\u{EADC}"; pub const FAN: &str = "\u{EADD}"; pub const FAST_FORWARD_CIRCLE: &str = "\u{EADE}"; pub const FAST_FORWARD: &str = "\u{EADF}"; pub const FEATHER: &str = "\u{EAE0}"; pub const FIGMA_LOGO: &str = "\u{EAE1}"; pub const FILE_ARCHIVE: &str = "\u{EAE2}"; pub const FILE_ARROW_DOWN: &str = "\u{EAE3}"; pub const FILE_ARROW_UP: &str = "\u{EAE4}"; pub const FILE_AUDIO: &str = "\u{EAE5}"; pub const FILE_CLOUD: &str = "\u{EAE6}"; pub const FILE_CODE: &str = "\u{EAE7}"; pub const FILE_CSS: &str = "\u{EAE8}"; pub const FILE_CSV: &str = "\u{EAE9}"; pub const FILE_DASHED: &str = "\u{EAEA}"; pub const FILE_DOTTED: &str = "\u{EAEA}"; pub const FILE_DOC: &str = "\u{EAEB}"; pub const FILE_HTML: &str = "\u{EAEC}"; pub const FILE_IMAGE: &str = "\u{EAED}"; pub const FILE_JPG: &str = "\u{EAEE}"; pub const FILE_JS: &str = "\u{EAEF}"; pub const FILE_JSX: &str = "\u{EAF0}"; pub const FILE: &str = "\u{EAF1}"; pub const FILE_LOCK: &str = "\u{EAF2}"; pub const FILE_MAGNIFYING_GLASS: &str = "\u{EAF3}"; pub const FILE_SEARCH: &str = "\u{EAF3}"; pub const FILE_MINUS: &str = "\u{EAF4}"; pub const FILE_PDF: &str = "\u{EAF5}"; pub const FILE_PLUS: &str = "\u{EAF6}"; pub const FILE_PNG: &str = "\u{EAF7}"; pub const FILE_PPT: &str = "\u{EAF8}"; pub const FILE_RS: &str = "\u{EAF9}"; pub const FILES: &str = "\u{EAFA}"; pub const FILE_SQL: &str = "\u{EAFB}"; pub const FILE_SVG: &str = "\u{EAFC}"; pub const FILE_TEXT: &str = "\u{EAFD}"; pub const FILE_TS: &str = "\u{EAFE}"; pub const FILE_TSX: &str = "\u{EAFF}"; pub const FILE_VIDEO: &str = "\u{EB00}"; pub const FILE_VUE: &str = "\u{EB01}"; pub const FILE_X: &str = "\u{EB02}"; pub const FILE_XLS: &str = "\u{EB03}"; pub const FILE_ZIP: &str = "\u{EB04}"; pub const FILM_REEL: &str = "\u{EB05}"; pub const FILM_SCRIPT: &str = "\u{EB06}"; pub const FILM_SLATE: &str = "\u{EB07}"; pub const FILM_STRIP: &str = "\u{EB08}"; pub const FINGERPRINT: &str = "\u{EB09}"; pub const FINGERPRINT_SIMPLE: &str = "\u{EB0A}"; pub const FINN_THE_HUMAN: &str = "\u{EB0B}"; pub const FIRE_EXTINGUISHER: &str = "\u{EB0C}"; pub const FIRE: &str = "\u{EB0D}"; pub const FIRE_SIMPLE: &str = "\u{EB0E}"; pub const FIRST_AID_KIT: &str = "\u{EB0F}"; pub const FIRST_AID: &str = "\u{EB10}"; pub const FISH: &str = "\u{EB11}"; pub const FISH_SIMPLE: &str = "\u{EB12}"; pub const FLAG_BANNER: &str = "\u{EB13}"; pub const FLAG_CHECKERED: &str = "\u{EB14}"; pub const FLAG: &str = "\u{EB15}"; pub const FLAG_PENNANT: &str = "\u{EB16}"; pub const FLAME: &str = "\u{EB17}"; pub const FLASHLIGHT: &str = "\u{EB18}"; pub const FLASK: &str = "\u{EB19}"; pub const FLOPPY_DISK_BACK: &str = "\u{EB1A}"; pub const FLOPPY_DISK: &str = "\u{EB1B}"; pub const FLOW_ARROW: &str = "\u{EB1C}"; pub const FLOWER: &str = "\u{EB1D}"; pub const FLOWER_LOTUS: &str = "\u{EB1E}"; pub const FLOWER_TULIP: &str = "\u{EB1F}"; pub const FLYING_SAUCER: &str = "\u{EB20}"; pub const FOLDER_DASHED: &str = "\u{EB21}"; pub const FOLDER_DOTTED: &str = "\u{EB21}"; pub const FOLDER: &str = "\u{EB22}"; pub const FOLDER_LOCK: &str = "\u{EB23}"; pub const FOLDER_MINUS: &str = "\u{EB24}"; pub const FOLDER_NOTCH: &str = "\u{EB25}"; pub const FOLDER_NOTCH_MINUS: &str = "\u{EB26}"; pub const FOLDER_NOTCH_OPEN: &str = "\u{EB27}"; pub const FOLDER_NOTCH_PLUS: &str = "\u{EB28}"; pub const FOLDER_OPEN: &str = "\u{EB29}"; pub const FOLDER_PLUS: &str = "\u{EB2A}"; pub const FOLDER_SIMPLE_DASHED: &str = "\u{EB2B}"; pub const FOLDER_SIMPLE_DOTTED: &str = "\u{EB2B}"; pub const FOLDER_SIMPLE: &str = "\u{EB2C}"; pub const FOLDER_SIMPLE_LOCK: &str = "\u{EB2D}"; pub const FOLDER_SIMPLE_MINUS: &str = "\u{EB2E}"; pub const FOLDER_SIMPLE_PLUS: &str = "\u{EB2F}"; pub const FOLDER_SIMPLE_STAR: &str = "\u{EB30}"; pub const FOLDER_SIMPLE_USER: &str = "\u{EB31}"; pub const FOLDERS: &str = "\u{EB32}"; pub const FOLDER_STAR: &str = "\u{EB33}"; pub const FOLDER_USER: &str = "\u{EB34}"; pub const FOOTBALL: &str = "\u{EB35}"; pub const FOOTPRINTS: &str = "\u{EB36}"; pub const FORK_KNIFE: &str = "\u{EB37}"; pub const FRAME_CORNERS: &str = "\u{EB38}"; pub const FRAMER_LOGO: &str = "\u{EB39}"; pub const FUNCTION: &str = "\u{EB3A}"; pub const FUNNEL: &str = "\u{EB3B}"; pub const FUNNEL_SIMPLE: &str = "\u{EB3C}"; pub const GAME_CONTROLLER: &str = "\u{EB3D}"; pub const GARAGE: &str = "\u{EB3E}"; pub const GAS_CAN: &str = "\u{EB3F}"; pub const GAS_PUMP: &str = "\u{EB40}"; pub const GAUGE: &str = "\u{EB41}"; pub const GAVEL: &str = "\u{EB42}"; pub const GEAR_FINE: &str = "\u{EB43}"; pub const GEAR: &str = "\u{EB44}"; pub const GEAR_SIX: &str = "\u{EB45}"; pub const GENDER_FEMALE: &str = "\u{EB46}"; pub const GENDER_INTERSEX: &str = "\u{EB47}"; pub const GENDER_MALE: &str = "\u{EB48}"; pub const GENDER_NEUTER: &str = "\u{EB49}"; pub const GENDER_NONBINARY: &str = "\u{EB4A}"; pub const GENDER_TRANSGENDER: &str = "\u{EB4B}"; pub const GHOST: &str = "\u{EB4C}"; pub const GIF: &str = "\u{EB4D}"; pub const GIFT: &str = "\u{EB4E}"; pub const GIT_BRANCH: &str = "\u{EB4F}"; pub const GIT_COMMIT: &str = "\u{EB50}"; pub const GIT_DIFF: &str = "\u{EB51}"; pub const GIT_FORK: &str = "\u{EB52}"; pub const GITHUB_LOGO: &str = "\u{EB53}"; pub const GITLAB_LOGO: &str = "\u{EB54}"; pub const GITLAB_LOGO_SIMPLE: &str = "\u{EB55}"; pub const GIT_MERGE: &str = "\u{EB56}"; pub const GIT_PULL_REQUEST: &str = "\u{EB57}"; pub const GLOBE_HEMISPHERE_EAST: &str = "\u{EB58}"; pub const GLOBE_HEMISPHERE_WEST: &str = "\u{EB59}"; pub const GLOBE: &str = "\u{EB5A}"; pub const GLOBE_SIMPLE: &str = "\u{EB5B}"; pub const GLOBE_STAND: &str = "\u{EB5C}"; pub const GOGGLES: &str = "\u{EB5D}"; pub const GOODREADS_LOGO: &str = "\u{EB5E}"; pub const GOOGLE_CARDBOARD_LOGO: &str = "\u{EB5F}"; pub const GOOGLE_CHROME_LOGO: &str = "\u{EB60}"; pub const GOOGLE_DRIVE_LOGO: &str = "\u{EB61}"; pub const GOOGLE_LOGO: &str = "\u{EB62}"; pub const GOOGLE_PHOTOS_LOGO: &str = "\u{EB63}"; pub const GOOGLE_PLAY_LOGO: &str = "\u{EB64}"; pub const GOOGLE_PODCASTS_LOGO: &str = "\u{EB65}"; pub const GRADIENT: &str = "\u{EB66}"; pub const GRADUATION_CAP: &str = "\u{EB67}"; pub const GRAINS: &str = "\u{EB68}"; pub const GRAINS_SLASH: &str = "\u{EB69}"; pub const GRAPH: &str = "\u{EB6A}"; pub const GRID_FOUR: &str = "\u{EB6B}"; pub const GRID_NINE: &str = "\u{EB6C}"; pub const GUITAR: &str = "\u{EB6D}"; pub const HAMBURGER: &str = "\u{EB6E}"; pub const HAMMER: &str = "\u{EB6F}"; pub const HANDBAG: &str = "\u{EB70}"; pub const HANDBAG_SIMPLE: &str = "\u{EB71}"; pub const HAND_COINS: &str = "\u{EB72}"; pub const HAND_EYE: &str = "\u{EB73}"; pub const HAND_FIST: &str = "\u{EB74}"; pub const HAND_GRABBING: &str = "\u{EB75}"; pub const HAND_HEART: &str = "\u{EB76}"; pub const HAND: &str = "\u{EB77}"; pub const HAND_PALM: &str = "\u{EB78}"; pub const HAND_POINTING: &str = "\u{EB79}"; pub const HANDS_CLAPPING: &str = "\u{EB7A}"; pub const HANDSHAKE: &str = "\u{EB7B}"; pub const HAND_SOAP: &str = "\u{EB7C}"; pub const HANDS_PRAYING: &str = "\u{EB7D}"; pub const HAND_SWIPE_LEFT: &str = "\u{EB7E}"; pub const HAND_SWIPE_RIGHT: &str = "\u{EB7F}"; pub const HAND_TAP: &str = "\u{EB80}"; pub const HAND_WAVING: &str = "\u{EB81}"; pub const HARD_DRIVE: &str = "\u{EB82}"; pub const HARD_DRIVES: &str = "\u{EB83}"; pub const HASH: &str = "\u{EB84}"; pub const HASH_STRAIGHT: &str = "\u{EB85}"; pub const HEADLIGHTS: &str = "\u{EB86}"; pub const HEADPHONES: &str = "\u{EB87}"; pub const HEADSET: &str = "\u{EB88}"; pub const HEARTBEAT: &str = "\u{EB89}"; pub const HEART_BREAK: &str = "\u{EB8A}"; pub const HEART_HALF: &str = "\u{EB8B}"; pub const HEART: &str = "\u{EB8C}"; pub const HEART_STRAIGHT_BREAK: &str = "\u{EB8D}"; pub const HEART_STRAIGHT: &str = "\u{EB8E}"; pub const HEXAGON: &str = "\u{EB8F}"; pub const HIGH_HEEL: &str = "\u{EB90}"; pub const HIGHLIGHTER_CIRCLE: &str = "\u{EB91}"; pub const HOODIE: &str = "\u{EB92}"; pub const HORSE: &str = "\u{EB93}"; pub const HOURGLASS_HIGH: &str = "\u{EB94}"; pub const HOURGLASS: &str = "\u{EB95}"; pub const HOURGLASS_LOW: &str = "\u{EB96}"; pub const HOURGLASS_MEDIUM: &str = "\u{EB97}"; pub const HOURGLASS_SIMPLE_HIGH: &str = "\u{EB98}"; pub const HOURGLASS_SIMPLE: &str = "\u{EB99}"; pub const HOURGLASS_SIMPLE_LOW: &str = "\u{EB9A}"; pub const HOURGLASS_SIMPLE_MEDIUM: &str = "\u{EB9B}"; pub const HOUSE: &str = "\u{EB9C}"; pub const HOUSE_LINE: &str = "\u{EB9D}"; pub const HOUSE_SIMPLE: &str = "\u{EB9E}"; pub const ICE_CREAM: &str = "\u{EB9F}"; pub const IDENTIFICATION_BADGE: &str = "\u{EBA0}"; pub const IDENTIFICATION_CARD: &str = "\u{EBA1}"; pub const IMAGE: &str = "\u{EBA2}"; pub const IMAGES: &str = "\u{EBA3}"; pub const IMAGE_SQUARE: &str = "\u{EBA4}"; pub const IMAGES_SQUARE: &str = "\u{EBA5}"; pub const INFINITY: &str = "\u{EBA6}"; pub const INFO: &str = "\u{EBA7}"; pub const INSTAGRAM_LOGO: &str = "\u{EBA8}"; pub const INTERSECT: &str = "\u{EBA9}"; pub const INTERSECT_SQUARE: &str = "\u{EBAA}"; pub const INTERSECT_THREE: &str = "\u{EBAB}"; pub const JEEP: &str = "\u{EBAC}"; pub const KANBAN: &str = "\u{EBAD}"; pub const KEYBOARD: &str = "\u{EBAE}"; pub const KEYHOLE: &str = "\u{EBAF}"; pub const KEY: &str = "\u{EBB0}"; pub const KEY_RETURN: &str = "\u{EBB1}"; pub const KNIFE: &str = "\u{EBB2}"; pub const LADDER: &str = "\u{EBB3}"; pub const LADDER_SIMPLE: &str = "\u{EBB4}"; pub const LAMP: &str = "\u{EBB5}"; pub const LAPTOP: &str = "\u{EBB6}"; pub const LAYOUT: &str = "\u{EBB7}"; pub const LEAF: &str = "\u{EBB8}"; pub const LIFEBUOY: &str = "\u{EBB9}"; pub const LIGHTBULB_FILAMENT: &str = "\u{EBBA}"; pub const LIGHTBULB: &str = "\u{EBBB}"; pub const LIGHTHOUSE: &str = "\u{EBBC}"; pub const LIGHTNING_A: &str = "\u{EBBD}"; pub const LIGHTNING: &str = "\u{EBBE}"; pub const LIGHTNING_SLASH: &str = "\u{EBBF}"; pub const LINE_SEGMENT: &str = "\u{EBC0}"; pub const LINE_SEGMENTS: &str = "\u{EBC1}"; pub const LINK_BREAK: &str = "\u{EBC2}"; pub const LINKEDIN_LOGO: &str = "\u{EBC3}"; pub const LINK: &str = "\u{EBC4}"; pub const LINK_SIMPLE_BREAK: &str = "\u{EBC5}"; pub const LINK_SIMPLE_HORIZONTAL_BREAK: &str = "\u{EBC6}"; pub const LINK_SIMPLE_HORIZONTAL: &str = "\u{EBC7}"; pub const LINK_SIMPLE: &str = "\u{EBC8}"; pub const LINUX_LOGO: &str = "\u{EBC9}"; pub const LIST_BULLETS: &str = "\u{EBCA}"; pub const LIST_CHECKS: &str = "\u{EBCB}"; pub const LIST_DASHES: &str = "\u{EBCC}"; pub const LIST: &str = "\u{EBCD}"; pub const LIST_MAGNIFYING_GLASS: &str = "\u{EBCE}"; pub const LIST_NUMBERS: &str = "\u{EBCF}"; pub const LIST_PLUS: &str = "\u{EBD0}"; pub const LOCKERS: &str = "\u{EBD1}"; pub const LOCK_KEY: &str = "\u{EBD2}"; pub const LOCK_KEY_OPEN: &str = "\u{EBD3}"; pub const LOCK_LAMINATED: &str = "\u{EBD4}"; pub const LOCK_LAMINATED_OPEN: &str = "\u{EBD5}"; pub const LOCK: &str = "\u{EBD6}"; pub const LOCK_OPEN: &str = "\u{EBD7}"; pub const LOCK_SIMPLE: &str = "\u{EBD8}"; pub const LOCK_SIMPLE_OPEN: &str = "\u{EBD9}"; pub const MAGIC_WAND: &str = "\u{EBDA}"; pub const MAGNET: &str = "\u{EBDB}"; pub const MAGNET_STRAIGHT: &str = "\u{EBDC}"; pub const MAGNIFYING_GLASS: &str = "\u{EBDD}"; pub const MAGNIFYING_GLASS_MINUS: &str = "\u{EBDE}"; pub const MAGNIFYING_GLASS_PLUS: &str = "\u{EBDF}"; pub const MAP_PIN: &str = "\u{EBE0}"; pub const MAP_PIN_LINE: &str = "\u{EBE1}"; pub const MAP_TRIFOLD: &str = "\u{EBE2}"; pub const MARKER_CIRCLE: &str = "\u{EBE3}"; pub const MARTINI: &str = "\u{EBE4}"; pub const MASK_HAPPY: &str = "\u{EBE5}"; pub const MASK_SAD: &str = "\u{EBE6}"; pub const MATH_OPERATIONS: &str = "\u{EBE7}"; pub const MEDAL: &str = "\u{EBE8}"; pub const MEDAL_MILITARY: &str = "\u{EBE9}"; pub const MEDIUM_LOGO: &str = "\u{EBEA}"; pub const MEGAPHONE: &str = "\u{EBEB}"; pub const MEGAPHONE_SIMPLE: &str = "\u{EBEC}"; pub const MESSENGER_LOGO: &str = "\u{EBED}"; pub const META_LOGO: &str = "\u{EBEE}"; pub const METRONOME: &str = "\u{EBEF}"; pub const MICROPHONE: &str = "\u{EBF0}"; pub const MICROPHONE_SLASH: &str = "\u{EBF1}"; pub const MICROPHONE_STAGE: &str = "\u{EBF2}"; pub const MICROSOFT_EXCEL_LOGO: &str = "\u{EBF3}";
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
true
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui-phosphor/src/variants/fill.rs
crates/egui-phosphor/src/variants/fill.rs
#![allow(unused)] pub const ADDRESS_BOOK: &str = "\u{E900}"; pub const AIRPLANE: &str = "\u{E901}"; pub const AIRPLANE_IN_FLIGHT: &str = "\u{E902}"; pub const AIRPLANE_LANDING: &str = "\u{E903}"; pub const AIRPLANE_TAKEOFF: &str = "\u{E904}"; pub const AIRPLANE_TILT: &str = "\u{E905}"; pub const AIRPLAY: &str = "\u{E906}"; pub const AIR_TRAFFIC_CONTROL: &str = "\u{E907}"; pub const ALARM: &str = "\u{E908}"; pub const ALIEN: &str = "\u{E909}"; pub const ALIGN_BOTTOM: &str = "\u{E90A}"; pub const ALIGN_BOTTOM_SIMPLE: &str = "\u{E90B}"; pub const ALIGN_CENTER_HORIZONTAL: &str = "\u{E90C}"; pub const ALIGN_CENTER_HORIZONTAL_SIMPLE: &str = "\u{E90D}"; pub const ALIGN_CENTER_VERTICAL: &str = "\u{E90E}"; pub const ALIGN_CENTER_VERTICAL_SIMPLE: &str = "\u{E90F}"; pub const ALIGN_LEFT: &str = "\u{E910}"; pub const ALIGN_LEFT_SIMPLE: &str = "\u{E911}"; pub const ALIGN_RIGHT: &str = "\u{E912}"; pub const ALIGN_RIGHT_SIMPLE: &str = "\u{E913}"; pub const ALIGN_TOP: &str = "\u{E914}"; pub const ALIGN_TOP_SIMPLE: &str = "\u{E915}"; pub const AMAZON_LOGO: &str = "\u{E916}"; pub const ANCHOR: &str = "\u{E917}"; pub const ANCHOR_SIMPLE: &str = "\u{E918}"; pub const ANDROID_LOGO: &str = "\u{E919}"; pub const ANGULAR_LOGO: &str = "\u{E91A}"; pub const APERTURE: &str = "\u{E91B}"; pub const APPLE_LOGO: &str = "\u{E91C}"; pub const APPLE_PODCASTS_LOGO: &str = "\u{E91D}"; pub const APP_STORE_LOGO: &str = "\u{E91E}"; pub const APP_WINDOW: &str = "\u{E91F}"; pub const ARCHIVE_BOX: &str = "\u{E920}"; pub const ARCHIVE: &str = "\u{E921}"; pub const ARCHIVE_TRAY: &str = "\u{E922}"; pub const ARMCHAIR: &str = "\u{E923}"; pub const ARROW_ARC_LEFT: &str = "\u{E924}"; pub const ARROW_ARC_RIGHT: &str = "\u{E925}"; pub const ARROW_BEND_DOUBLE_UP_LEFT: &str = "\u{E926}"; pub const ARROW_BEND_DOUBLE_UP_RIGHT: &str = "\u{E927}"; pub const ARROW_BEND_DOWN_LEFT: &str = "\u{E928}"; pub const ARROW_BEND_DOWN_RIGHT: &str = "\u{E929}"; pub const ARROW_BEND_LEFT_DOWN: &str = "\u{E92A}"; pub const ARROW_BEND_LEFT_UP: &str = "\u{E92B}"; pub const ARROW_BEND_RIGHT_DOWN: &str = "\u{E92C}"; pub const ARROW_BEND_RIGHT_UP: &str = "\u{E92D}"; pub const ARROW_BEND_UP_LEFT: &str = "\u{E92E}"; pub const ARROW_BEND_UP_RIGHT: &str = "\u{E92F}"; pub const ARROW_CIRCLE_DOWN: &str = "\u{E930}"; pub const ARROW_CIRCLE_DOWN_LEFT: &str = "\u{E931}"; pub const ARROW_CIRCLE_DOWN_RIGHT: &str = "\u{E932}"; pub const ARROW_CIRCLE_LEFT: &str = "\u{E933}"; pub const ARROW_CIRCLE_RIGHT: &str = "\u{E934}"; pub const ARROW_CIRCLE_UP: &str = "\u{E935}"; pub const ARROW_CIRCLE_UP_LEFT: &str = "\u{E936}"; pub const ARROW_CIRCLE_UP_RIGHT: &str = "\u{E937}"; pub const ARROW_CLOCKWISE: &str = "\u{E938}"; pub const ARROW_COUNTER_CLOCKWISE: &str = "\u{E939}"; pub const ARROW_DOWN: &str = "\u{E93A}"; pub const ARROW_DOWN_LEFT: &str = "\u{E93B}"; pub const ARROW_DOWN_RIGHT: &str = "\u{E93C}"; pub const ARROW_ELBOW_DOWN_LEFT: &str = "\u{E93D}"; pub const ARROW_ELBOW_DOWN_RIGHT: &str = "\u{E93E}"; pub const ARROW_ELBOW_LEFT_DOWN: &str = "\u{E93F}"; pub const ARROW_ELBOW_LEFT: &str = "\u{E940}"; pub const ARROW_ELBOW_LEFT_UP: &str = "\u{E941}"; pub const ARROW_ELBOW_RIGHT_DOWN: &str = "\u{E942}"; pub const ARROW_ELBOW_RIGHT: &str = "\u{E943}"; pub const ARROW_ELBOW_RIGHT_UP: &str = "\u{E944}"; pub const ARROW_ELBOW_UP_LEFT: &str = "\u{E945}"; pub const ARROW_ELBOW_UP_RIGHT: &str = "\u{E946}"; pub const ARROW_FAT_DOWN: &str = "\u{E947}"; pub const ARROW_FAT_LEFT: &str = "\u{E948}"; pub const ARROW_FAT_LINE_DOWN: &str = "\u{E949}"; pub const ARROW_FAT_LINE_LEFT: &str = "\u{E94A}"; pub const ARROW_FAT_LINE_RIGHT: &str = "\u{E94B}"; pub const ARROW_FAT_LINES_DOWN: &str = "\u{E94C}"; pub const ARROW_FAT_LINES_LEFT: &str = "\u{E94D}"; pub const ARROW_FAT_LINES_RIGHT: &str = "\u{E94E}"; pub const ARROW_FAT_LINES_UP: &str = "\u{E94F}"; pub const ARROW_FAT_LINE_UP: &str = "\u{E950}"; pub const ARROW_FAT_RIGHT: &str = "\u{E951}"; pub const ARROW_FAT_UP: &str = "\u{E952}"; pub const ARROW_LEFT: &str = "\u{E953}"; pub const ARROW_LINE_DOWN: &str = "\u{E954}"; pub const ARROW_LINE_DOWN_LEFT: &str = "\u{E955}"; pub const ARROW_LINE_DOWN_RIGHT: &str = "\u{E956}"; pub const ARROW_LINE_LEFT: &str = "\u{E957}"; pub const ARROW_LINE_RIGHT: &str = "\u{E958}"; pub const ARROW_LINE_UP: &str = "\u{E959}"; pub const ARROW_LINE_UP_LEFT: &str = "\u{E95A}"; pub const ARROW_LINE_UP_RIGHT: &str = "\u{E95B}"; pub const ARROW_RIGHT: &str = "\u{E95C}"; pub const ARROWS_CLOCKWISE: &str = "\u{E95D}"; pub const ARROWS_COUNTER_CLOCKWISE: &str = "\u{E95E}"; pub const ARROWS_DOWN_UP: &str = "\u{E95F}"; pub const ARROWS_HORIZONTAL: &str = "\u{E960}"; pub const ARROWS_IN_CARDINAL: &str = "\u{E961}"; pub const ARROWS_IN: &str = "\u{E962}"; pub const ARROWS_IN_LINE_HORIZONTAL: &str = "\u{E963}"; pub const ARROWS_IN_LINE_VERTICAL: &str = "\u{E964}"; pub const ARROWS_IN_SIMPLE: &str = "\u{E965}"; pub const ARROWS_LEFT_RIGHT: &str = "\u{E966}"; pub const ARROWS_MERGE: &str = "\u{E967}"; pub const ARROWS_OUT_CARDINAL: &str = "\u{E968}"; pub const ARROWS_OUT: &str = "\u{E969}"; pub const ARROWS_OUT_LINE_HORIZONTAL: &str = "\u{E96A}"; pub const ARROWS_OUT_LINE_VERTICAL: &str = "\u{E96B}"; pub const ARROWS_OUT_SIMPLE: &str = "\u{E96C}"; pub const ARROW_SQUARE_DOWN: &str = "\u{E96D}"; pub const ARROW_SQUARE_DOWN_LEFT: &str = "\u{E96E}"; pub const ARROW_SQUARE_DOWN_RIGHT: &str = "\u{E96F}"; pub const ARROW_SQUARE_IN: &str = "\u{E970}"; pub const ARROW_SQUARE_LEFT: &str = "\u{E971}"; pub const ARROW_SQUARE_OUT: &str = "\u{E972}"; pub const ARROW_SQUARE_RIGHT: &str = "\u{E973}"; pub const ARROW_SQUARE_UP: &str = "\u{E974}"; pub const ARROW_SQUARE_UP_LEFT: &str = "\u{E975}"; pub const ARROW_SQUARE_UP_RIGHT: &str = "\u{E976}"; pub const ARROWS_SPLIT: &str = "\u{E977}"; pub const ARROWS_VERTICAL: &str = "\u{E978}"; pub const ARROW_U_DOWN_LEFT: &str = "\u{E979}"; pub const ARROW_U_DOWN_RIGHT: &str = "\u{E97A}"; pub const ARROW_U_LEFT_DOWN: &str = "\u{E97B}"; pub const ARROW_U_LEFT_UP: &str = "\u{E97C}"; pub const ARROW_UP: &str = "\u{E97D}"; pub const ARROW_UP_LEFT: &str = "\u{E97E}"; pub const ARROW_UP_RIGHT: &str = "\u{E97F}"; pub const ARROW_U_RIGHT_DOWN: &str = "\u{E980}"; pub const ARROW_U_RIGHT_UP: &str = "\u{E981}"; pub const ARROW_U_UP_LEFT: &str = "\u{E982}"; pub const ARROW_U_UP_RIGHT: &str = "\u{E983}"; pub const ARTICLE: &str = "\u{E984}"; pub const ARTICLE_MEDIUM: &str = "\u{E985}"; pub const ARTICLE_NY_TIMES: &str = "\u{E986}"; pub const ASTERISK: &str = "\u{E987}"; pub const ASTERISK_SIMPLE: &str = "\u{E988}"; pub const AT: &str = "\u{E989}"; pub const ATOM: &str = "\u{E98A}"; pub const BABY: &str = "\u{E98B}"; pub const BACKPACK: &str = "\u{E98C}"; pub const BACKSPACE: &str = "\u{E98D}"; pub const BAG: &str = "\u{E98E}"; pub const BAG_SIMPLE: &str = "\u{E98F}"; pub const BALLOON: &str = "\u{E990}"; pub const BANDAIDS: &str = "\u{E991}"; pub const BANK: &str = "\u{E992}"; pub const BARBELL: &str = "\u{E993}"; pub const BARCODE: &str = "\u{E994}"; pub const BARRICADE: &str = "\u{E995}"; pub const BASEBALL_CAP: &str = "\u{E996}"; pub const BASEBALL: &str = "\u{E997}"; pub const BASKETBALL: &str = "\u{E998}"; pub const BASKET: &str = "\u{E999}"; pub const BATHTUB: &str = "\u{E99A}"; pub const BATTERY_CHARGING: &str = "\u{E99B}"; pub const BATTERY_CHARGING_VERTICAL: &str = "\u{E99C}"; pub const BATTERY_EMPTY: &str = "\u{E99D}"; pub const BATTERY_FULL: &str = "\u{E99E}"; pub const BATTERY_HIGH: &str = "\u{E99F}"; pub const BATTERY_LOW: &str = "\u{E9A0}"; pub const BATTERY_MEDIUM: &str = "\u{E9A1}"; pub const BATTERY_PLUS: &str = "\u{E9A2}"; pub const BATTERY_PLUS_VERTICAL: &str = "\u{E9A3}"; pub const BATTERY_VERTICAL_EMPTY: &str = "\u{E9A4}"; pub const BATTERY_VERTICAL_FULL: &str = "\u{E9A5}"; pub const BATTERY_VERTICAL_HIGH: &str = "\u{E9A6}"; pub const BATTERY_VERTICAL_LOW: &str = "\u{E9A7}"; pub const BATTERY_VERTICAL_MEDIUM: &str = "\u{E9A8}"; pub const BATTERY_WARNING: &str = "\u{E9A9}"; pub const BATTERY_WARNING_VERTICAL: &str = "\u{E9AA}"; pub const BED: &str = "\u{E9AB}"; pub const BEER_BOTTLE: &str = "\u{E9AC}"; pub const BEER_STEIN: &str = "\u{E9AD}"; pub const BEHANCE_LOGO: &str = "\u{E9AE}"; pub const BELL: &str = "\u{E9AF}"; pub const BELL_RINGING: &str = "\u{E9B0}"; pub const BELL_SIMPLE: &str = "\u{E9B1}"; pub const BELL_SIMPLE_RINGING: &str = "\u{E9B2}"; pub const BELL_SIMPLE_SLASH: &str = "\u{E9B3}"; pub const BELL_SIMPLE_Z: &str = "\u{E9B4}"; pub const BELL_SLASH: &str = "\u{E9B5}"; pub const BELL_Z: &str = "\u{E9B6}"; pub const BEZIER_CURVE: &str = "\u{E9B7}"; pub const BICYCLE: &str = "\u{E9B8}"; pub const BINOCULARS: &str = "\u{E9B9}"; pub const BIRD: &str = "\u{E9BA}"; pub const BLUETOOTH_CONNECTED: &str = "\u{E9BB}"; pub const BLUETOOTH: &str = "\u{E9BC}"; pub const BLUETOOTH_SLASH: &str = "\u{E9BD}"; pub const BLUETOOTH_X: &str = "\u{E9BE}"; pub const BOAT: &str = "\u{E9BF}"; pub const BONE: &str = "\u{E9C0}"; pub const BOOK_BOOKMARK: &str = "\u{E9C1}"; pub const BOOK: &str = "\u{E9C2}"; pub const BOOKMARK: &str = "\u{E9C3}"; pub const BOOKMARKS: &str = "\u{E9C4}"; pub const BOOKMARK_SIMPLE: &str = "\u{E9C5}"; pub const BOOKMARKS_SIMPLE: &str = "\u{E9C6}"; pub const BOOK_OPEN: &str = "\u{E9C7}"; pub const BOOK_OPEN_TEXT: &str = "\u{E9C8}"; pub const BOOKS: &str = "\u{E9C9}"; pub const BOOT: &str = "\u{E9CA}"; pub const BOUNDING_BOX: &str = "\u{E9CB}"; pub const BOWL_FOOD: &str = "\u{E9CC}"; pub const BRACKETS_ANGLE: &str = "\u{E9CD}"; pub const BRACKETS_CURLY: &str = "\u{E9CE}"; pub const BRACKETS_ROUND: &str = "\u{E9CF}"; pub const BRACKETS_SQUARE: &str = "\u{E9D0}"; pub const BRAIN: &str = "\u{E9D1}"; pub const BRANDY: &str = "\u{E9D2}"; pub const BRIDGE: &str = "\u{E9D3}"; pub const BRIEFCASE: &str = "\u{E9D4}"; pub const BRIEFCASE_METAL: &str = "\u{E9D5}"; pub const BROADCAST: &str = "\u{E9D6}"; pub const BROOM: &str = "\u{E9D7}"; pub const BROWSER: &str = "\u{E9D8}"; pub const BROWSERS: &str = "\u{E9D9}"; pub const BUG_BEETLE: &str = "\u{E9DA}"; pub const BUG_DROID: &str = "\u{E9DB}"; pub const BUG: &str = "\u{E9DC}"; pub const BUILDINGS: &str = "\u{E9DD}"; pub const BUS: &str = "\u{E9DE}"; pub const BUTTERFLY: &str = "\u{E9DF}"; pub const CACTUS: &str = "\u{E9E0}"; pub const CAKE: &str = "\u{E9E1}"; pub const CALCULATOR: &str = "\u{E9E2}"; pub const CALENDAR_BLANK: &str = "\u{E9E3}"; pub const CALENDAR_CHECK: &str = "\u{E9E4}"; pub const CALENDAR: &str = "\u{E9E5}"; pub const CALENDAR_PLUS: &str = "\u{E9E6}"; pub const CALENDAR_X: &str = "\u{E9E7}"; pub const CALL_BELL: &str = "\u{E9E8}"; pub const CAMERA: &str = "\u{E9E9}"; pub const CAMERA_PLUS: &str = "\u{E9EA}"; pub const CAMERA_ROTATE: &str = "\u{E9EB}"; pub const CAMERA_SLASH: &str = "\u{E9EC}"; pub const CAMPFIRE: &str = "\u{E9ED}"; pub const CARDHOLDER: &str = "\u{E9EE}"; pub const CARDS: &str = "\u{E9EF}"; pub const CARET_CIRCLE_DOUBLE_DOWN: &str = "\u{E9F0}"; pub const CARET_CIRCLE_DOUBLE_LEFT: &str = "\u{E9F1}"; pub const CARET_CIRCLE_DOUBLE_RIGHT: &str = "\u{E9F2}"; pub const CARET_CIRCLE_DOUBLE_UP: &str = "\u{E9F3}"; pub const CARET_CIRCLE_DOWN: &str = "\u{E9F4}"; pub const CARET_CIRCLE_LEFT: &str = "\u{E9F5}"; pub const CARET_CIRCLE_RIGHT: &str = "\u{E9F6}"; pub const CARET_CIRCLE_UP_DOWN: &str = "\u{E9F7}"; pub const CARET_CIRCLE_UP: &str = "\u{E9F8}"; pub const CARET_DOUBLE_DOWN: &str = "\u{E9F9}"; pub const CARET_DOUBLE_LEFT: &str = "\u{E9FA}"; pub const CARET_DOUBLE_RIGHT: &str = "\u{E9FB}"; pub const CARET_DOUBLE_UP: &str = "\u{E9FC}"; pub const CARET_DOWN: &str = "\u{E9FD}"; pub const CARET_LEFT: &str = "\u{E9FE}"; pub const CARET_RIGHT: &str = "\u{E9FF}"; pub const CARET_UP_DOWN: &str = "\u{EA00}"; pub const CARET_UP: &str = "\u{EA01}"; pub const CAR: &str = "\u{EA02}"; pub const CAR_PROFILE: &str = "\u{EA03}"; pub const CARROT: &str = "\u{EA04}"; pub const CAR_SIMPLE: &str = "\u{EA05}"; pub const CASSETTE_TAPE: &str = "\u{EA06}"; pub const CASTLE_TURRET: &str = "\u{EA07}"; pub const CAT: &str = "\u{EA08}"; pub const CELL_SIGNAL_FULL: &str = "\u{EA09}"; pub const CELL_SIGNAL_HIGH: &str = "\u{EA0A}"; pub const CELL_SIGNAL_LOW: &str = "\u{EA0B}"; pub const CELL_SIGNAL_MEDIUM: &str = "\u{EA0C}"; pub const CELL_SIGNAL_NONE: &str = "\u{EA0D}"; pub const CELL_SIGNAL_SLASH: &str = "\u{EA0E}"; pub const CELL_SIGNAL_X: &str = "\u{EA0F}"; pub const CERTIFICATE: &str = "\u{EA10}"; pub const CHAIR: &str = "\u{EA11}"; pub const CHALKBOARD: &str = "\u{EA12}"; pub const CHALKBOARD_SIMPLE: &str = "\u{EA13}"; pub const CHALKBOARD_TEACHER: &str = "\u{EA14}"; pub const CHAMPAGNE: &str = "\u{EA15}"; pub const CHARGING_STATION: &str = "\u{EA16}"; pub const CHART_BAR: &str = "\u{EA17}"; pub const CHART_BAR_HORIZONTAL: &str = "\u{EA18}"; pub const CHART_DONUT: &str = "\u{EA19}"; pub const CHART_LINE_DOWN: &str = "\u{EA1A}"; pub const CHART_LINE: &str = "\u{EA1B}"; pub const CHART_LINE_UP: &str = "\u{EA1C}"; pub const CHART_PIE: &str = "\u{EA1D}"; pub const CHART_PIE_SLICE: &str = "\u{EA1E}"; pub const CHART_POLAR: &str = "\u{EA1F}"; pub const CHART_SCATTER: &str = "\u{EA20}"; pub const CHAT_CENTERED_DOTS: &str = "\u{EA21}"; pub const CHAT_CENTERED: &str = "\u{EA22}"; pub const CHAT_CENTERED_TEXT: &str = "\u{EA23}"; pub const CHAT_CIRCLE_DOTS: &str = "\u{EA24}"; pub const CHAT_CIRCLE: &str = "\u{EA25}"; pub const CHAT_CIRCLE_TEXT: &str = "\u{EA26}"; pub const CHAT_DOTS: &str = "\u{EA27}"; pub const CHAT: &str = "\u{EA28}"; pub const CHATS_CIRCLE: &str = "\u{EA29}"; pub const CHATS: &str = "\u{EA2A}"; pub const CHATS_TEARDROP: &str = "\u{EA2B}"; pub const CHAT_TEARDROP_DOTS: &str = "\u{EA2C}"; pub const CHAT_TEARDROP: &str = "\u{EA2D}"; pub const CHAT_TEARDROP_TEXT: &str = "\u{EA2E}"; pub const CHAT_TEXT: &str = "\u{EA2F}"; pub const CHECK_CIRCLE: &str = "\u{EA30}"; pub const CHECK_FAT: &str = "\u{EA31}"; pub const CHECK: &str = "\u{EA32}"; pub const CHECKS: &str = "\u{EA33}"; pub const CHECK_SQUARE: &str = "\u{EA34}"; pub const CHECK_SQUARE_OFFSET: &str = "\u{EA35}"; pub const CHURCH: &str = "\u{EA36}"; pub const CIRCLE_DASHED: &str = "\u{EA37}"; pub const CIRCLE: &str = "\u{EA38}"; pub const CIRCLE_HALF: &str = "\u{EA39}"; pub const CIRCLE_HALF_TILT: &str = "\u{EA3A}"; pub const CIRCLE_NOTCH: &str = "\u{EA3B}"; pub const CIRCLES_FOUR: &str = "\u{EA3C}"; pub const CIRCLES_THREE: &str = "\u{EA3D}"; pub const CIRCLES_THREE_PLUS: &str = "\u{EA3E}"; pub const CIRCUITRY: &str = "\u{EA3F}"; pub const CLIPBOARD: &str = "\u{EA40}"; pub const CLIPBOARD_TEXT: &str = "\u{EA41}"; pub const CLOCK_AFTERNOON: &str = "\u{EA42}"; pub const CLOCK_CLOCKWISE: &str = "\u{EA43}"; pub const CLOCK_COUNTDOWN: &str = "\u{EA44}"; pub const CLOCK_COUNTER_CLOCKWISE: &str = "\u{EA45}"; pub const CLOCK: &str = "\u{EA46}"; pub const CLOSED_CAPTIONING: &str = "\u{EA47}"; pub const CLOUD_ARROW_DOWN: &str = "\u{EA48}"; pub const CLOUD_ARROW_UP: &str = "\u{EA49}"; pub const CLOUD_CHECK: &str = "\u{EA4A}"; pub const CLOUD: &str = "\u{EA4B}"; pub const CLOUD_FOG: &str = "\u{EA4C}"; pub const CLOUD_LIGHTNING: &str = "\u{EA4D}"; pub const CLOUD_MOON: &str = "\u{EA4E}"; pub const CLOUD_RAIN: &str = "\u{EA4F}"; pub const CLOUD_SLASH: &str = "\u{EA50}"; pub const CLOUD_SNOW: &str = "\u{EA51}"; pub const CLOUD_SUN: &str = "\u{EA52}"; pub const CLOUD_WARNING: &str = "\u{EA53}"; pub const CLOUD_X: &str = "\u{EA54}"; pub const CLUB: &str = "\u{EA55}"; pub const COAT_HANGER: &str = "\u{EA56}"; pub const CODA_LOGO: &str = "\u{EA57}"; pub const CODE_BLOCK: &str = "\u{EA58}"; pub const CODE: &str = "\u{EA59}"; pub const CODEPEN_LOGO: &str = "\u{EA5A}"; pub const CODESANDBOX_LOGO: &str = "\u{EA5B}"; pub const CODE_SIMPLE: &str = "\u{EA5C}"; pub const COFFEE: &str = "\u{EA5D}"; pub const COIN: &str = "\u{EA5E}"; pub const COINS: &str = "\u{EA5F}"; pub const COIN_VERTICAL: &str = "\u{EA60}"; pub const COLUMNS: &str = "\u{EA61}"; pub const COMMAND: &str = "\u{EA62}"; pub const COMPASS: &str = "\u{EA63}"; pub const COMPASS_TOOL: &str = "\u{EA64}"; pub const COMPUTER_TOWER: &str = "\u{EA65}"; pub const CONFETTI: &str = "\u{EA66}"; pub const CONTACTLESS_PAYMENT: &str = "\u{EA67}"; pub const CONTROL: &str = "\u{EA68}"; pub const COOKIE: &str = "\u{EA69}"; pub const COOKING_POT: &str = "\u{EA6A}"; pub const COPY: &str = "\u{EA6B}"; pub const COPYLEFT: &str = "\u{EA6C}"; pub const COPYRIGHT: &str = "\u{EA6D}"; pub const COPY_SIMPLE: &str = "\u{EA6E}"; pub const CORNERS_IN: &str = "\u{EA6F}"; pub const CORNERS_OUT: &str = "\u{EA70}"; pub const COUCH: &str = "\u{EA71}"; pub const CPU: &str = "\u{EA72}"; pub const CREDIT_CARD: &str = "\u{EA73}"; pub const CROP: &str = "\u{EA74}"; pub const CROSS: &str = "\u{EA75}"; pub const CROSSHAIR: &str = "\u{EA76}"; pub const CROSSHAIR_SIMPLE: &str = "\u{EA77}"; pub const CROWN: &str = "\u{EA78}"; pub const CROWN_SIMPLE: &str = "\u{EA79}"; pub const CUBE: &str = "\u{EA7A}"; pub const CUBE_FOCUS: &str = "\u{EA7B}"; pub const CUBE_TRANSPARENT: &str = "\u{EA7C}"; pub const CURRENCY_BTC: &str = "\u{EA7D}"; pub const CURRENCY_CIRCLE_DOLLAR: &str = "\u{EA7E}"; pub const CURRENCY_CNY: &str = "\u{EA7F}"; pub const CURRENCY_DOLLAR: &str = "\u{EA80}"; pub const CURRENCY_DOLLAR_SIMPLE: &str = "\u{EA81}"; pub const CURRENCY_ETH: &str = "\u{EA82}"; pub const CURRENCY_EUR: &str = "\u{EA83}"; pub const CURRENCY_GBP: &str = "\u{EA84}"; pub const CURRENCY_INR: &str = "\u{EA85}"; pub const CURRENCY_JPY: &str = "\u{EA86}"; pub const CURRENCY_KRW: &str = "\u{EA87}"; pub const CURRENCY_KZT: &str = "\u{EA88}"; pub const CURRENCY_NGN: &str = "\u{EA89}"; pub const CURRENCY_RUB: &str = "\u{EA8A}"; pub const CURSOR_CLICK: &str = "\u{EA8B}"; pub const CURSOR: &str = "\u{EA8C}"; pub const CURSOR_TEXT: &str = "\u{EA8D}"; pub const CYLINDER: &str = "\u{EA8E}"; pub const DATABASE: &str = "\u{EA8F}"; pub const DESKTOP: &str = "\u{EA90}"; pub const DESKTOP_TOWER: &str = "\u{EA91}"; pub const DETECTIVE: &str = "\u{EA92}"; pub const DEVICE_MOBILE_CAMERA: &str = "\u{EA93}"; pub const DEVICE_MOBILE: &str = "\u{EA94}"; pub const DEVICE_MOBILE_SPEAKER: &str = "\u{EA95}"; pub const DEVICES: &str = "\u{EA96}"; pub const DEVICE_TABLET_CAMERA: &str = "\u{EA97}"; pub const DEVICE_TABLET: &str = "\u{EA98}"; pub const DEVICE_TABLET_SPEAKER: &str = "\u{EA99}"; pub const DEV_TO_LOGO: &str = "\u{EA9A}"; pub const DIAMOND: &str = "\u{EA9B}"; pub const DIAMONDS_FOUR: &str = "\u{EA9C}"; pub const DICE_FIVE: &str = "\u{EA9D}"; pub const DICE_FOUR: &str = "\u{EA9E}"; pub const DICE_ONE: &str = "\u{EA9F}"; pub const DICE_SIX: &str = "\u{EAA0}"; pub const DICE_THREE: &str = "\u{EAA1}"; pub const DICE_TWO: &str = "\u{EAA2}"; pub const DISC: &str = "\u{EAA3}"; pub const DISCORD_LOGO: &str = "\u{EAA4}"; pub const DIVIDE: &str = "\u{EAA5}"; pub const DNA: &str = "\u{EAA6}"; pub const DOG: &str = "\u{EAA7}"; pub const DOOR: &str = "\u{EAA8}"; pub const DOOR_OPEN: &str = "\u{EAA9}"; pub const DOT: &str = "\u{EAAA}"; pub const DOT_OUTLINE: &str = "\u{EAAB}"; pub const DOTS_NINE: &str = "\u{EAAC}"; pub const DOTS_SIX: &str = "\u{EAAD}"; pub const DOTS_SIX_VERTICAL: &str = "\u{EAAE}"; pub const DOTS_THREE_CIRCLE: &str = "\u{EAAF}"; pub const DOTS_THREE_CIRCLE_VERTICAL: &str = "\u{EAB0}"; pub const DOTS_THREE: &str = "\u{EAB1}"; pub const DOTS_THREE_OUTLINE: &str = "\u{EAB2}"; pub const DOTS_THREE_OUTLINE_VERTICAL: &str = "\u{EAB3}"; pub const DOTS_THREE_VERTICAL: &str = "\u{EAB4}"; pub const DOWNLOAD: &str = "\u{EAB5}"; pub const DOWNLOAD_SIMPLE: &str = "\u{EAB6}"; pub const DRESS: &str = "\u{EAB7}"; pub const DRIBBBLE_LOGO: &str = "\u{EAB8}"; pub const DROPBOX_LOGO: &str = "\u{EAB9}"; pub const DROP: &str = "\u{EABA}"; pub const DROP_HALF_BOTTOM: &str = "\u{EABB}"; pub const DROP_HALF: &str = "\u{EABC}"; pub const EAR: &str = "\u{EABD}"; pub const EAR_SLASH: &str = "\u{EABE}"; pub const EGG_CRACK: &str = "\u{EABF}"; pub const EGG: &str = "\u{EAC0}"; pub const EJECT: &str = "\u{EAC1}"; pub const EJECT_SIMPLE: &str = "\u{EAC2}"; pub const ELEVATOR: &str = "\u{EAC3}"; pub const ENGINE: &str = "\u{EAC4}"; pub const ENVELOPE: &str = "\u{EAC5}"; pub const ENVELOPE_OPEN: &str = "\u{EAC6}"; pub const ENVELOPE_SIMPLE: &str = "\u{EAC7}"; pub const ENVELOPE_SIMPLE_OPEN: &str = "\u{EAC8}"; pub const EQUALIZER: &str = "\u{EAC9}"; pub const EQUALS: &str = "\u{EACA}"; pub const ERASER: &str = "\u{EACB}"; pub const ESCALATOR_DOWN: &str = "\u{EACC}"; pub const ESCALATOR_UP: &str = "\u{EACD}"; pub const EXAM: &str = "\u{EACE}"; pub const EXCLUDE: &str = "\u{EACF}"; pub const EXCLUDE_SQUARE: &str = "\u{EAD0}"; pub const EXPORT: &str = "\u{EAD1}"; pub const EYE_CLOSED: &str = "\u{EAD2}"; pub const EYEDROPPER: &str = "\u{EAD3}"; pub const EYEDROPPER_SAMPLE: &str = "\u{EAD4}"; pub const EYE: &str = "\u{EAD5}"; pub const EYEGLASSES: &str = "\u{EAD6}"; pub const EYE_SLASH: &str = "\u{EAD7}"; pub const FACEBOOK_LOGO: &str = "\u{EAD8}"; pub const FACE_MASK: &str = "\u{EAD9}"; pub const FACTORY: &str = "\u{EADA}"; pub const FADERS: &str = "\u{EADB}"; pub const FADERS_HORIZONTAL: &str = "\u{EADC}"; pub const FAN: &str = "\u{EADD}"; pub const FAST_FORWARD_CIRCLE: &str = "\u{EADE}"; pub const FAST_FORWARD: &str = "\u{EADF}"; pub const FEATHER: &str = "\u{EAE0}"; pub const FIGMA_LOGO: &str = "\u{EAE1}"; pub const FILE_ARCHIVE: &str = "\u{EAE2}"; pub const FILE_ARROW_DOWN: &str = "\u{EAE3}"; pub const FILE_ARROW_UP: &str = "\u{EAE4}"; pub const FILE_AUDIO: &str = "\u{EAE5}"; pub const FILE_CLOUD: &str = "\u{EAE6}"; pub const FILE_CODE: &str = "\u{EAE7}"; pub const FILE_CSS: &str = "\u{EAE8}"; pub const FILE_CSV: &str = "\u{EAE9}"; pub const FILE_DASHED: &str = "\u{EAEA}"; pub const FILE_DOTTED: &str = "\u{EAEA}"; pub const FILE_DOC: &str = "\u{EAEB}"; pub const FILE: &str = "\u{EAEC}"; pub const FILE_HTML: &str = "\u{EAED}"; pub const FILE_IMAGE: &str = "\u{EAEE}"; pub const FILE_JPG: &str = "\u{EAEF}"; pub const FILE_JS: &str = "\u{EAF0}"; pub const FILE_JSX: &str = "\u{EAF1}"; pub const FILE_LOCK: &str = "\u{EAF2}"; pub const FILE_MAGNIFYING_GLASS: &str = "\u{EAF3}"; pub const FILE_SEARCH: &str = "\u{EAF3}"; pub const FILE_MINUS: &str = "\u{EAF4}"; pub const FILE_PDF: &str = "\u{EAF5}"; pub const FILE_PLUS: &str = "\u{EAF6}"; pub const FILE_PNG: &str = "\u{EAF7}"; pub const FILE_PPT: &str = "\u{EAF8}"; pub const FILE_RS: &str = "\u{EAF9}"; pub const FILES: &str = "\u{EAFA}"; pub const FILE_SQL: &str = "\u{EAFB}"; pub const FILE_SVG: &str = "\u{EAFC}"; pub const FILE_TEXT: &str = "\u{EAFD}"; pub const FILE_TS: &str = "\u{EAFE}"; pub const FILE_TSX: &str = "\u{EAFF}"; pub const FILE_VIDEO: &str = "\u{EB00}"; pub const FILE_VUE: &str = "\u{EB01}"; pub const FILE_X: &str = "\u{EB02}"; pub const FILE_XLS: &str = "\u{EB03}"; pub const FILE_ZIP: &str = "\u{EB04}"; pub const FILM_REEL: &str = "\u{EB05}"; pub const FILM_SCRIPT: &str = "\u{EB06}"; pub const FILM_SLATE: &str = "\u{EB07}"; pub const FILM_STRIP: &str = "\u{EB08}"; pub const FINGERPRINT: &str = "\u{EB09}"; pub const FINGERPRINT_SIMPLE: &str = "\u{EB0A}"; pub const FINN_THE_HUMAN: &str = "\u{EB0B}"; pub const FIRE_EXTINGUISHER: &str = "\u{EB0C}"; pub const FIRE: &str = "\u{EB0D}"; pub const FIRE_SIMPLE: &str = "\u{EB0E}"; pub const FIRST_AID: &str = "\u{EB0F}"; pub const FIRST_AID_KIT: &str = "\u{EB10}"; pub const FISH: &str = "\u{EB11}"; pub const FISH_SIMPLE: &str = "\u{EB12}"; pub const FLAG_BANNER: &str = "\u{EB13}"; pub const FLAG_CHECKERED: &str = "\u{EB14}"; pub const FLAG: &str = "\u{EB15}"; pub const FLAG_PENNANT: &str = "\u{EB16}"; pub const FLAME: &str = "\u{EB17}"; pub const FLASHLIGHT: &str = "\u{EB18}"; pub const FLASK: &str = "\u{EB19}"; pub const FLOPPY_DISK_BACK: &str = "\u{EB1A}"; pub const FLOPPY_DISK: &str = "\u{EB1B}"; pub const FLOW_ARROW: &str = "\u{EB1C}"; pub const FLOWER: &str = "\u{EB1D}"; pub const FLOWER_LOTUS: &str = "\u{EB1E}"; pub const FLOWER_TULIP: &str = "\u{EB1F}"; pub const FLYING_SAUCER: &str = "\u{EB20}"; pub const FOLDER_DASHED: &str = "\u{EB21}"; pub const FOLDER_DOTTED: &str = "\u{EB21}"; pub const FOLDER: &str = "\u{EB22}"; pub const FOLDER_LOCK: &str = "\u{EB23}"; pub const FOLDER_MINUS: &str = "\u{EB24}"; pub const FOLDER_NOTCH: &str = "\u{EB25}"; pub const FOLDER_NOTCH_MINUS: &str = "\u{EB26}"; pub const FOLDER_NOTCH_OPEN: &str = "\u{EB27}"; pub const FOLDER_NOTCH_PLUS: &str = "\u{EB28}"; pub const FOLDER_OPEN: &str = "\u{EB29}"; pub const FOLDER_PLUS: &str = "\u{EB2A}"; pub const FOLDERS: &str = "\u{EB2B}"; pub const FOLDER_SIMPLE_DASHED: &str = "\u{EB2C}"; pub const FOLDER_SIMPLE_DOTTED: &str = "\u{EB2C}"; pub const FOLDER_SIMPLE: &str = "\u{EB2D}"; pub const FOLDER_SIMPLE_LOCK: &str = "\u{EB2E}"; pub const FOLDER_SIMPLE_MINUS: &str = "\u{EB2F}"; pub const FOLDER_SIMPLE_PLUS: &str = "\u{EB30}"; pub const FOLDER_SIMPLE_STAR: &str = "\u{EB31}"; pub const FOLDER_SIMPLE_USER: &str = "\u{EB32}"; pub const FOLDER_STAR: &str = "\u{EB33}"; pub const FOLDER_USER: &str = "\u{EB34}"; pub const FOOTBALL: &str = "\u{EB35}"; pub const FOOTPRINTS: &str = "\u{EB36}"; pub const FORK_KNIFE: &str = "\u{EB37}"; pub const FRAME_CORNERS: &str = "\u{EB38}"; pub const FRAMER_LOGO: &str = "\u{EB39}"; pub const FUNCTION: &str = "\u{EB3A}"; pub const FUNNEL: &str = "\u{EB3B}"; pub const FUNNEL_SIMPLE: &str = "\u{EB3C}"; pub const GAME_CONTROLLER: &str = "\u{EB3D}"; pub const GARAGE: &str = "\u{EB3E}"; pub const GAS_CAN: &str = "\u{EB3F}"; pub const GAS_PUMP: &str = "\u{EB40}"; pub const GAUGE: &str = "\u{EB41}"; pub const GAVEL: &str = "\u{EB42}"; pub const GEAR: &str = "\u{EB43}"; pub const GEAR_FINE: &str = "\u{EB44}"; pub const GEAR_SIX: &str = "\u{EB45}"; pub const GENDER_FEMALE: &str = "\u{EB46}"; pub const GENDER_INTERSEX: &str = "\u{EB47}"; pub const GENDER_MALE: &str = "\u{EB48}"; pub const GENDER_NEUTER: &str = "\u{EB49}"; pub const GENDER_NONBINARY: &str = "\u{EB4A}"; pub const GENDER_TRANSGENDER: &str = "\u{EB4B}"; pub const GHOST: &str = "\u{EB4C}"; pub const GIF: &str = "\u{EB4D}"; pub const GIFT: &str = "\u{EB4E}"; pub const GIT_BRANCH: &str = "\u{EB4F}"; pub const GIT_COMMIT: &str = "\u{EB50}"; pub const GIT_DIFF: &str = "\u{EB51}"; pub const GIT_FORK: &str = "\u{EB52}"; pub const GITHUB_LOGO: &str = "\u{EB53}"; pub const GITLAB_LOGO: &str = "\u{EB54}"; pub const GITLAB_LOGO_SIMPLE: &str = "\u{EB55}"; pub const GIT_MERGE: &str = "\u{EB56}"; pub const GIT_PULL_REQUEST: &str = "\u{EB57}"; pub const GLOBE: &str = "\u{EB58}"; pub const GLOBE_HEMISPHERE_EAST: &str = "\u{EB59}"; pub const GLOBE_HEMISPHERE_WEST: &str = "\u{EB5A}"; pub const GLOBE_SIMPLE: &str = "\u{EB5B}"; pub const GLOBE_STAND: &str = "\u{EB5C}"; pub const GOGGLES: &str = "\u{EB5D}"; pub const GOODREADS_LOGO: &str = "\u{EB5E}"; pub const GOOGLE_CARDBOARD_LOGO: &str = "\u{EB5F}"; pub const GOOGLE_CHROME_LOGO: &str = "\u{EB60}"; pub const GOOGLE_DRIVE_LOGO: &str = "\u{EB61}"; pub const GOOGLE_LOGO: &str = "\u{EB62}"; pub const GOOGLE_PHOTOS_LOGO: &str = "\u{EB63}"; pub const GOOGLE_PLAY_LOGO: &str = "\u{EB64}"; pub const GOOGLE_PODCASTS_LOGO: &str = "\u{EB65}"; pub const GRADIENT: &str = "\u{EB66}"; pub const GRADUATION_CAP: &str = "\u{EB67}"; pub const GRAINS: &str = "\u{EB68}"; pub const GRAINS_SLASH: &str = "\u{EB69}"; pub const GRAPH: &str = "\u{EB6A}"; pub const GRID_FOUR: &str = "\u{EB6B}"; pub const GRID_NINE: &str = "\u{EB6C}"; pub const GUITAR: &str = "\u{EB6D}"; pub const HAMBURGER: &str = "\u{EB6E}"; pub const HAMMER: &str = "\u{EB6F}"; pub const HANDBAG: &str = "\u{EB70}"; pub const HANDBAG_SIMPLE: &str = "\u{EB71}"; pub const HAND_COINS: &str = "\u{EB72}"; pub const HAND_EYE: &str = "\u{EB73}"; pub const HAND: &str = "\u{EB74}"; pub const HAND_FIST: &str = "\u{EB75}"; pub const HAND_GRABBING: &str = "\u{EB76}"; pub const HAND_HEART: &str = "\u{EB77}"; pub const HAND_PALM: &str = "\u{EB78}"; pub const HAND_POINTING: &str = "\u{EB79}"; pub const HANDS_CLAPPING: &str = "\u{EB7A}"; pub const HANDSHAKE: &str = "\u{EB7B}"; pub const HAND_SOAP: &str = "\u{EB7C}"; pub const HANDS_PRAYING: &str = "\u{EB7D}"; pub const HAND_SWIPE_LEFT: &str = "\u{EB7E}"; pub const HAND_SWIPE_RIGHT: &str = "\u{EB7F}"; pub const HAND_TAP: &str = "\u{EB80}"; pub const HAND_WAVING: &str = "\u{EB81}"; pub const HARD_DRIVE: &str = "\u{EB82}"; pub const HARD_DRIVES: &str = "\u{EB83}"; pub const HASH: &str = "\u{EB84}"; pub const HASH_STRAIGHT: &str = "\u{EB85}"; pub const HEADLIGHTS: &str = "\u{EB86}"; pub const HEADPHONES: &str = "\u{EB87}"; pub const HEADSET: &str = "\u{EB88}"; pub const HEARTBEAT: &str = "\u{EB89}"; pub const HEART_BREAK: &str = "\u{EB8A}"; pub const HEART: &str = "\u{EB8B}"; pub const HEART_HALF: &str = "\u{EB8C}"; pub const HEART_STRAIGHT_BREAK: &str = "\u{EB8D}"; pub const HEART_STRAIGHT: &str = "\u{EB8E}"; pub const HEXAGON: &str = "\u{EB8F}"; pub const HIGH_HEEL: &str = "\u{EB90}"; pub const HIGHLIGHTER_CIRCLE: &str = "\u{EB91}"; pub const HOODIE: &str = "\u{EB92}"; pub const HORSE: &str = "\u{EB93}"; pub const HOURGLASS: &str = "\u{EB94}"; pub const HOURGLASS_HIGH: &str = "\u{EB95}"; pub const HOURGLASS_LOW: &str = "\u{EB96}"; pub const HOURGLASS_MEDIUM: &str = "\u{EB97}"; pub const HOURGLASS_SIMPLE: &str = "\u{EB98}"; pub const HOURGLASS_SIMPLE_HIGH: &str = "\u{EB99}"; pub const HOURGLASS_SIMPLE_LOW: &str = "\u{EB9A}"; pub const HOURGLASS_SIMPLE_MEDIUM: &str = "\u{EB9B}"; pub const HOUSE: &str = "\u{EB9C}"; pub const HOUSE_LINE: &str = "\u{EB9D}"; pub const HOUSE_SIMPLE: &str = "\u{EB9E}"; pub const ICE_CREAM: &str = "\u{EB9F}"; pub const IDENTIFICATION_BADGE: &str = "\u{EBA0}"; pub const IDENTIFICATION_CARD: &str = "\u{EBA1}"; pub const IMAGE: &str = "\u{EBA2}"; pub const IMAGES: &str = "\u{EBA3}"; pub const IMAGE_SQUARE: &str = "\u{EBA4}"; pub const IMAGES_SQUARE: &str = "\u{EBA5}"; pub const INFINITY: &str = "\u{EBA6}"; pub const INFO: &str = "\u{EBA7}"; pub const INSTAGRAM_LOGO: &str = "\u{EBA8}"; pub const INTERSECT: &str = "\u{EBA9}"; pub const INTERSECT_SQUARE: &str = "\u{EBAA}"; pub const INTERSECT_THREE: &str = "\u{EBAB}"; pub const JEEP: &str = "\u{EBAC}"; pub const KANBAN: &str = "\u{EBAD}"; pub const KEYBOARD: &str = "\u{EBAE}"; pub const KEY: &str = "\u{EBAF}"; pub const KEYHOLE: &str = "\u{EBB0}"; pub const KEY_RETURN: &str = "\u{EBB1}"; pub const KNIFE: &str = "\u{EBB2}"; pub const LADDER: &str = "\u{EBB3}"; pub const LADDER_SIMPLE: &str = "\u{EBB4}"; pub const LAMP: &str = "\u{EBB5}"; pub const LAPTOP: &str = "\u{EBB6}"; pub const LAYOUT: &str = "\u{EBB7}"; pub const LEAF: &str = "\u{EBB8}"; pub const LIFEBUOY: &str = "\u{EBB9}"; pub const LIGHTBULB_FILAMENT: &str = "\u{EBBA}"; pub const LIGHTBULB: &str = "\u{EBBB}"; pub const LIGHTHOUSE: &str = "\u{EBBC}"; pub const LIGHTNING_A: &str = "\u{EBBD}"; pub const LIGHTNING: &str = "\u{EBBE}"; pub const LIGHTNING_SLASH: &str = "\u{EBBF}"; pub const LINE_SEGMENT: &str = "\u{EBC0}"; pub const LINE_SEGMENTS: &str = "\u{EBC1}"; pub const LINK_BREAK: &str = "\u{EBC2}"; pub const LINKEDIN_LOGO: &str = "\u{EBC3}"; pub const LINK: &str = "\u{EBC4}"; pub const LINK_SIMPLE_BREAK: &str = "\u{EBC5}"; pub const LINK_SIMPLE: &str = "\u{EBC6}"; pub const LINK_SIMPLE_HORIZONTAL_BREAK: &str = "\u{EBC7}"; pub const LINK_SIMPLE_HORIZONTAL: &str = "\u{EBC8}"; pub const LINUX_LOGO: &str = "\u{EBC9}"; pub const LIST_BULLETS: &str = "\u{EBCA}"; pub const LIST_CHECKS: &str = "\u{EBCB}"; pub const LIST_DASHES: &str = "\u{EBCC}"; pub const LIST: &str = "\u{EBCD}"; pub const LIST_MAGNIFYING_GLASS: &str = "\u{EBCE}"; pub const LIST_NUMBERS: &str = "\u{EBCF}"; pub const LIST_PLUS: &str = "\u{EBD0}"; pub const LOCKERS: &str = "\u{EBD1}"; pub const LOCK: &str = "\u{EBD2}"; pub const LOCK_KEY: &str = "\u{EBD3}"; pub const LOCK_KEY_OPEN: &str = "\u{EBD4}"; pub const LOCK_LAMINATED: &str = "\u{EBD5}"; pub const LOCK_LAMINATED_OPEN: &str = "\u{EBD6}"; pub const LOCK_OPEN: &str = "\u{EBD7}"; pub const LOCK_SIMPLE: &str = "\u{EBD8}"; pub const LOCK_SIMPLE_OPEN: &str = "\u{EBD9}"; pub const MAGIC_WAND: &str = "\u{EBDA}"; pub const MAGNET: &str = "\u{EBDB}"; pub const MAGNET_STRAIGHT: &str = "\u{EBDC}"; pub const MAGNIFYING_GLASS: &str = "\u{EBDD}"; pub const MAGNIFYING_GLASS_MINUS: &str = "\u{EBDE}"; pub const MAGNIFYING_GLASS_PLUS: &str = "\u{EBDF}"; pub const MAP_PIN: &str = "\u{EBE0}"; pub const MAP_PIN_LINE: &str = "\u{EBE1}"; pub const MAP_TRIFOLD: &str = "\u{EBE2}"; pub const MARKER_CIRCLE: &str = "\u{EBE3}"; pub const MARTINI: &str = "\u{EBE4}"; pub const MASK_HAPPY: &str = "\u{EBE5}"; pub const MASK_SAD: &str = "\u{EBE6}"; pub const MATH_OPERATIONS: &str = "\u{EBE7}"; pub const MEDAL: &str = "\u{EBE8}"; pub const MEDAL_MILITARY: &str = "\u{EBE9}"; pub const MEDIUM_LOGO: &str = "\u{EBEA}"; pub const MEGAPHONE: &str = "\u{EBEB}"; pub const MEGAPHONE_SIMPLE: &str = "\u{EBEC}"; pub const MESSENGER_LOGO: &str = "\u{EBED}"; pub const META_LOGO: &str = "\u{EBEE}"; pub const METRONOME: &str = "\u{EBEF}"; pub const MICROPHONE: &str = "\u{EBF0}"; pub const MICROPHONE_SLASH: &str = "\u{EBF1}"; pub const MICROPHONE_STAGE: &str = "\u{EBF2}"; pub const MICROSOFT_EXCEL_LOGO: &str = "\u{EBF3}";
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
true
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui-phosphor/src/variants/regular.rs
crates/egui-phosphor/src/variants/regular.rs
#![allow(unused)] pub const ADDRESS_BOOK: &str = "\u{E900}"; pub const AIRPLANE: &str = "\u{E901}"; pub const AIRPLANE_IN_FLIGHT: &str = "\u{E902}"; pub const AIRPLANE_LANDING: &str = "\u{E903}"; pub const AIRPLANE_TAKEOFF: &str = "\u{E904}"; pub const AIRPLANE_TILT: &str = "\u{E905}"; pub const AIRPLAY: &str = "\u{E906}"; pub const AIR_TRAFFIC_CONTROL: &str = "\u{E907}"; pub const ALARM: &str = "\u{E908}"; pub const ALIEN: &str = "\u{E909}"; pub const ALIGN_BOTTOM: &str = "\u{E90A}"; pub const ALIGN_BOTTOM_SIMPLE: &str = "\u{E90B}"; pub const ALIGN_CENTER_HORIZONTAL: &str = "\u{E90C}"; pub const ALIGN_CENTER_HORIZONTAL_SIMPLE: &str = "\u{E90D}"; pub const ALIGN_CENTER_VERTICAL: &str = "\u{E90E}"; pub const ALIGN_CENTER_VERTICAL_SIMPLE: &str = "\u{E90F}"; pub const ALIGN_LEFT: &str = "\u{E910}"; pub const ALIGN_LEFT_SIMPLE: &str = "\u{E911}"; pub const ALIGN_RIGHT: &str = "\u{E912}"; pub const ALIGN_RIGHT_SIMPLE: &str = "\u{E913}"; pub const ALIGN_TOP: &str = "\u{E914}"; pub const ALIGN_TOP_SIMPLE: &str = "\u{E915}"; pub const AMAZON_LOGO: &str = "\u{E916}"; pub const ANCHOR: &str = "\u{E917}"; pub const ANCHOR_SIMPLE: &str = "\u{E918}"; pub const ANDROID_LOGO: &str = "\u{E919}"; pub const ANGULAR_LOGO: &str = "\u{E91A}"; pub const APERTURE: &str = "\u{E91B}"; pub const APPLE_LOGO: &str = "\u{E91C}"; pub const APPLE_PODCASTS_LOGO: &str = "\u{E91D}"; pub const APP_STORE_LOGO: &str = "\u{E91E}"; pub const APP_WINDOW: &str = "\u{E91F}"; pub const ARCHIVE: &str = "\u{E920}"; pub const ARCHIVE_BOX: &str = "\u{E921}"; pub const ARCHIVE_TRAY: &str = "\u{E922}"; pub const ARMCHAIR: &str = "\u{E923}"; pub const ARROW_ARC_LEFT: &str = "\u{E924}"; pub const ARROW_ARC_RIGHT: &str = "\u{E925}"; pub const ARROW_BEND_DOUBLE_UP_LEFT: &str = "\u{E926}"; pub const ARROW_BEND_DOUBLE_UP_RIGHT: &str = "\u{E927}"; pub const ARROW_BEND_DOWN_LEFT: &str = "\u{E928}"; pub const ARROW_BEND_DOWN_RIGHT: &str = "\u{E929}"; pub const ARROW_BEND_LEFT_DOWN: &str = "\u{E92A}"; pub const ARROW_BEND_LEFT_UP: &str = "\u{E92B}"; pub const ARROW_BEND_RIGHT_DOWN: &str = "\u{E92C}"; pub const ARROW_BEND_RIGHT_UP: &str = "\u{E92D}"; pub const ARROW_BEND_UP_LEFT: &str = "\u{E92E}"; pub const ARROW_BEND_UP_RIGHT: &str = "\u{E92F}"; pub const ARROW_CIRCLE_DOWN: &str = "\u{E930}"; pub const ARROW_CIRCLE_DOWN_LEFT: &str = "\u{E931}"; pub const ARROW_CIRCLE_DOWN_RIGHT: &str = "\u{E932}"; pub const ARROW_CIRCLE_LEFT: &str = "\u{E933}"; pub const ARROW_CIRCLE_RIGHT: &str = "\u{E934}"; pub const ARROW_CIRCLE_UP: &str = "\u{E935}"; pub const ARROW_CIRCLE_UP_LEFT: &str = "\u{E936}"; pub const ARROW_CIRCLE_UP_RIGHT: &str = "\u{E937}"; pub const ARROW_CLOCKWISE: &str = "\u{E938}"; pub const ARROW_COUNTER_CLOCKWISE: &str = "\u{E939}"; pub const ARROW_DOWN: &str = "\u{E93A}"; pub const ARROW_DOWN_LEFT: &str = "\u{E93B}"; pub const ARROW_DOWN_RIGHT: &str = "\u{E93C}"; pub const ARROW_ELBOW_DOWN_LEFT: &str = "\u{E93D}"; pub const ARROW_ELBOW_DOWN_RIGHT: &str = "\u{E93E}"; pub const ARROW_ELBOW_LEFT: &str = "\u{E93F}"; pub const ARROW_ELBOW_LEFT_DOWN: &str = "\u{E940}"; pub const ARROW_ELBOW_LEFT_UP: &str = "\u{E941}"; pub const ARROW_ELBOW_RIGHT: &str = "\u{E942}"; pub const ARROW_ELBOW_RIGHT_DOWN: &str = "\u{E943}"; pub const ARROW_ELBOW_RIGHT_UP: &str = "\u{E944}"; pub const ARROW_ELBOW_UP_LEFT: &str = "\u{E945}"; pub const ARROW_ELBOW_UP_RIGHT: &str = "\u{E946}"; pub const ARROW_FAT_DOWN: &str = "\u{E947}"; pub const ARROW_FAT_LEFT: &str = "\u{E948}"; pub const ARROW_FAT_LINE_DOWN: &str = "\u{E949}"; pub const ARROW_FAT_LINE_LEFT: &str = "\u{E94A}"; pub const ARROW_FAT_LINE_RIGHT: &str = "\u{E94B}"; pub const ARROW_FAT_LINES_DOWN: &str = "\u{E94C}"; pub const ARROW_FAT_LINES_LEFT: &str = "\u{E94D}"; pub const ARROW_FAT_LINES_RIGHT: &str = "\u{E94E}"; pub const ARROW_FAT_LINES_UP: &str = "\u{E94F}"; pub const ARROW_FAT_LINE_UP: &str = "\u{E950}"; pub const ARROW_FAT_RIGHT: &str = "\u{E951}"; pub const ARROW_FAT_UP: &str = "\u{E952}"; pub const ARROW_LEFT: &str = "\u{E953}"; pub const ARROW_LINE_DOWN: &str = "\u{E954}"; pub const ARROW_LINE_DOWN_LEFT: &str = "\u{E955}"; pub const ARROW_LINE_DOWN_RIGHT: &str = "\u{E956}"; pub const ARROW_LINE_LEFT: &str = "\u{E957}"; pub const ARROW_LINE_RIGHT: &str = "\u{E958}"; pub const ARROW_LINE_UP: &str = "\u{E959}"; pub const ARROW_LINE_UP_LEFT: &str = "\u{E95A}"; pub const ARROW_LINE_UP_RIGHT: &str = "\u{E95B}"; pub const ARROW_RIGHT: &str = "\u{E95C}"; pub const ARROWS_CLOCKWISE: &str = "\u{E95D}"; pub const ARROWS_COUNTER_CLOCKWISE: &str = "\u{E95E}"; pub const ARROWS_DOWN_UP: &str = "\u{E95F}"; pub const ARROWS_HORIZONTAL: &str = "\u{E960}"; pub const ARROWS_IN: &str = "\u{E961}"; pub const ARROWS_IN_CARDINAL: &str = "\u{E962}"; pub const ARROWS_IN_LINE_HORIZONTAL: &str = "\u{E963}"; pub const ARROWS_IN_LINE_VERTICAL: &str = "\u{E964}"; pub const ARROWS_IN_SIMPLE: &str = "\u{E965}"; pub const ARROWS_LEFT_RIGHT: &str = "\u{E966}"; pub const ARROWS_MERGE: &str = "\u{E967}"; pub const ARROWS_OUT: &str = "\u{E968}"; pub const ARROWS_OUT_CARDINAL: &str = "\u{E969}"; pub const ARROWS_OUT_LINE_HORIZONTAL: &str = "\u{E96A}"; pub const ARROWS_OUT_LINE_VERTICAL: &str = "\u{E96B}"; pub const ARROWS_OUT_SIMPLE: &str = "\u{E96C}"; pub const ARROW_SQUARE_DOWN: &str = "\u{E96D}"; pub const ARROW_SQUARE_DOWN_LEFT: &str = "\u{E96E}"; pub const ARROW_SQUARE_DOWN_RIGHT: &str = "\u{E96F}"; pub const ARROW_SQUARE_IN: &str = "\u{E970}"; pub const ARROW_SQUARE_LEFT: &str = "\u{E971}"; pub const ARROW_SQUARE_OUT: &str = "\u{E972}"; pub const ARROW_SQUARE_RIGHT: &str = "\u{E973}"; pub const ARROW_SQUARE_UP: &str = "\u{E974}"; pub const ARROW_SQUARE_UP_LEFT: &str = "\u{E975}"; pub const ARROW_SQUARE_UP_RIGHT: &str = "\u{E976}"; pub const ARROWS_SPLIT: &str = "\u{E977}"; pub const ARROWS_VERTICAL: &str = "\u{E978}"; pub const ARROW_U_DOWN_LEFT: &str = "\u{E979}"; pub const ARROW_U_DOWN_RIGHT: &str = "\u{E97A}"; pub const ARROW_U_LEFT_DOWN: &str = "\u{E97B}"; pub const ARROW_U_LEFT_UP: &str = "\u{E97C}"; pub const ARROW_UP: &str = "\u{E97D}"; pub const ARROW_UP_LEFT: &str = "\u{E97E}"; pub const ARROW_UP_RIGHT: &str = "\u{E97F}"; pub const ARROW_U_RIGHT_DOWN: &str = "\u{E980}"; pub const ARROW_U_RIGHT_UP: &str = "\u{E981}"; pub const ARROW_U_UP_LEFT: &str = "\u{E982}"; pub const ARROW_U_UP_RIGHT: &str = "\u{E983}"; pub const ARTICLE: &str = "\u{E984}"; pub const ARTICLE_MEDIUM: &str = "\u{E985}"; pub const ARTICLE_NY_TIMES: &str = "\u{E986}"; pub const ASTERISK: &str = "\u{E987}"; pub const ASTERISK_SIMPLE: &str = "\u{E988}"; pub const AT: &str = "\u{E989}"; pub const ATOM: &str = "\u{E98A}"; pub const BABY: &str = "\u{E98B}"; pub const BACKPACK: &str = "\u{E98C}"; pub const BACKSPACE: &str = "\u{E98D}"; pub const BAG: &str = "\u{E98E}"; pub const BAG_SIMPLE: &str = "\u{E98F}"; pub const BALLOON: &str = "\u{E990}"; pub const BANDAIDS: &str = "\u{E991}"; pub const BANK: &str = "\u{E992}"; pub const BARBELL: &str = "\u{E993}"; pub const BARCODE: &str = "\u{E994}"; pub const BARRICADE: &str = "\u{E995}"; pub const BASEBALL: &str = "\u{E996}"; pub const BASEBALL_CAP: &str = "\u{E997}"; pub const BASKET: &str = "\u{E998}"; pub const BASKETBALL: &str = "\u{E999}"; pub const BATHTUB: &str = "\u{E99A}"; pub const BATTERY_CHARGING: &str = "\u{E99B}"; pub const BATTERY_CHARGING_VERTICAL: &str = "\u{E99C}"; pub const BATTERY_EMPTY: &str = "\u{E99D}"; pub const BATTERY_FULL: &str = "\u{E99E}"; pub const BATTERY_HIGH: &str = "\u{E99F}"; pub const BATTERY_LOW: &str = "\u{E9A0}"; pub const BATTERY_MEDIUM: &str = "\u{E9A1}"; pub const BATTERY_PLUS: &str = "\u{E9A2}"; pub const BATTERY_PLUS_VERTICAL: &str = "\u{E9A3}"; pub const BATTERY_VERTICAL_EMPTY: &str = "\u{E9A4}"; pub const BATTERY_VERTICAL_FULL: &str = "\u{E9A5}"; pub const BATTERY_VERTICAL_HIGH: &str = "\u{E9A6}"; pub const BATTERY_VERTICAL_LOW: &str = "\u{E9A7}"; pub const BATTERY_VERTICAL_MEDIUM: &str = "\u{E9A8}"; pub const BATTERY_WARNING: &str = "\u{E9A9}"; pub const BATTERY_WARNING_VERTICAL: &str = "\u{E9AA}"; pub const BED: &str = "\u{E9AB}"; pub const BEER_BOTTLE: &str = "\u{E9AC}"; pub const BEER_STEIN: &str = "\u{E9AD}"; pub const BEHANCE_LOGO: &str = "\u{E9AE}"; pub const BELL: &str = "\u{E9AF}"; pub const BELL_RINGING: &str = "\u{E9B0}"; pub const BELL_SIMPLE: &str = "\u{E9B1}"; pub const BELL_SIMPLE_RINGING: &str = "\u{E9B2}"; pub const BELL_SIMPLE_SLASH: &str = "\u{E9B3}"; pub const BELL_SIMPLE_Z: &str = "\u{E9B4}"; pub const BELL_SLASH: &str = "\u{E9B5}"; pub const BELL_Z: &str = "\u{E9B6}"; pub const BEZIER_CURVE: &str = "\u{E9B7}"; pub const BICYCLE: &str = "\u{E9B8}"; pub const BINOCULARS: &str = "\u{E9B9}"; pub const BIRD: &str = "\u{E9BA}"; pub const BLUETOOTH: &str = "\u{E9BB}"; pub const BLUETOOTH_CONNECTED: &str = "\u{E9BC}"; pub const BLUETOOTH_SLASH: &str = "\u{E9BD}"; pub const BLUETOOTH_X: &str = "\u{E9BE}"; pub const BOAT: &str = "\u{E9BF}"; pub const BONE: &str = "\u{E9C0}"; pub const BOOK: &str = "\u{E9C1}"; pub const BOOK_BOOKMARK: &str = "\u{E9C2}"; pub const BOOKMARK: &str = "\u{E9C3}"; pub const BOOKMARKS: &str = "\u{E9C4}"; pub const BOOKMARK_SIMPLE: &str = "\u{E9C5}"; pub const BOOKMARKS_SIMPLE: &str = "\u{E9C6}"; pub const BOOK_OPEN: &str = "\u{E9C7}"; pub const BOOK_OPEN_TEXT: &str = "\u{E9C8}"; pub const BOOKS: &str = "\u{E9C9}"; pub const BOOT: &str = "\u{E9CA}"; pub const BOUNDING_BOX: &str = "\u{E9CB}"; pub const BOWL_FOOD: &str = "\u{E9CC}"; pub const BRACKETS_ANGLE: &str = "\u{E9CD}"; pub const BRACKETS_CURLY: &str = "\u{E9CE}"; pub const BRACKETS_ROUND: &str = "\u{E9CF}"; pub const BRACKETS_SQUARE: &str = "\u{E9D0}"; pub const BRAIN: &str = "\u{E9D1}"; pub const BRANDY: &str = "\u{E9D2}"; pub const BRIDGE: &str = "\u{E9D3}"; pub const BRIEFCASE: &str = "\u{E9D4}"; pub const BRIEFCASE_METAL: &str = "\u{E9D5}"; pub const BROADCAST: &str = "\u{E9D6}"; pub const BROOM: &str = "\u{E9D7}"; pub const BROWSER: &str = "\u{E9D8}"; pub const BROWSERS: &str = "\u{E9D9}"; pub const BUG: &str = "\u{E9DA}"; pub const BUG_BEETLE: &str = "\u{E9DB}"; pub const BUG_DROID: &str = "\u{E9DC}"; pub const BUILDINGS: &str = "\u{E9DD}"; pub const BUS: &str = "\u{E9DE}"; pub const BUTTERFLY: &str = "\u{E9DF}"; pub const CACTUS: &str = "\u{E9E0}"; pub const CAKE: &str = "\u{E9E1}"; pub const CALCULATOR: &str = "\u{E9E2}"; pub const CALENDAR: &str = "\u{E9E3}"; pub const CALENDAR_BLANK: &str = "\u{E9E4}"; pub const CALENDAR_CHECK: &str = "\u{E9E5}"; pub const CALENDAR_PLUS: &str = "\u{E9E6}"; pub const CALENDAR_X: &str = "\u{E9E7}"; pub const CALL_BELL: &str = "\u{E9E8}"; pub const CAMERA: &str = "\u{E9E9}"; pub const CAMERA_PLUS: &str = "\u{E9EA}"; pub const CAMERA_ROTATE: &str = "\u{E9EB}"; pub const CAMERA_SLASH: &str = "\u{E9EC}"; pub const CAMPFIRE: &str = "\u{E9ED}"; pub const CAR: &str = "\u{E9EE}"; pub const CARDHOLDER: &str = "\u{E9EF}"; pub const CARDS: &str = "\u{E9F0}"; pub const CARET_CIRCLE_DOUBLE_DOWN: &str = "\u{E9F1}"; pub const CARET_CIRCLE_DOUBLE_LEFT: &str = "\u{E9F2}"; pub const CARET_CIRCLE_DOUBLE_RIGHT: &str = "\u{E9F3}"; pub const CARET_CIRCLE_DOUBLE_UP: &str = "\u{E9F4}"; pub const CARET_CIRCLE_DOWN: &str = "\u{E9F5}"; pub const CARET_CIRCLE_LEFT: &str = "\u{E9F6}"; pub const CARET_CIRCLE_RIGHT: &str = "\u{E9F7}"; pub const CARET_CIRCLE_UP: &str = "\u{E9F8}"; pub const CARET_CIRCLE_UP_DOWN: &str = "\u{E9F9}"; pub const CARET_DOUBLE_DOWN: &str = "\u{E9FA}"; pub const CARET_DOUBLE_LEFT: &str = "\u{E9FB}"; pub const CARET_DOUBLE_RIGHT: &str = "\u{E9FC}"; pub const CARET_DOUBLE_UP: &str = "\u{E9FD}"; pub const CARET_DOWN: &str = "\u{E9FE}"; pub const CARET_LEFT: &str = "\u{E9FF}"; pub const CARET_RIGHT: &str = "\u{EA00}"; pub const CARET_UP: &str = "\u{EA01}"; pub const CARET_UP_DOWN: &str = "\u{EA02}"; pub const CAR_PROFILE: &str = "\u{EA03}"; pub const CARROT: &str = "\u{EA04}"; pub const CAR_SIMPLE: &str = "\u{EA05}"; pub const CASSETTE_TAPE: &str = "\u{EA06}"; pub const CASTLE_TURRET: &str = "\u{EA07}"; pub const CAT: &str = "\u{EA08}"; pub const CELL_SIGNAL_FULL: &str = "\u{EA09}"; pub const CELL_SIGNAL_HIGH: &str = "\u{EA0A}"; pub const CELL_SIGNAL_LOW: &str = "\u{EA0B}"; pub const CELL_SIGNAL_MEDIUM: &str = "\u{EA0C}"; pub const CELL_SIGNAL_NONE: &str = "\u{EA0D}"; pub const CELL_SIGNAL_SLASH: &str = "\u{EA0E}"; pub const CELL_SIGNAL_X: &str = "\u{EA0F}"; pub const CERTIFICATE: &str = "\u{EA10}"; pub const CHAIR: &str = "\u{EA11}"; pub const CHALKBOARD: &str = "\u{EA12}"; pub const CHALKBOARD_SIMPLE: &str = "\u{EA13}"; pub const CHALKBOARD_TEACHER: &str = "\u{EA14}"; pub const CHAMPAGNE: &str = "\u{EA15}"; pub const CHARGING_STATION: &str = "\u{EA16}"; pub const CHART_BAR: &str = "\u{EA17}"; pub const CHART_BAR_HORIZONTAL: &str = "\u{EA18}"; pub const CHART_DONUT: &str = "\u{EA19}"; pub const CHART_LINE: &str = "\u{EA1A}"; pub const CHART_LINE_DOWN: &str = "\u{EA1B}"; pub const CHART_LINE_UP: &str = "\u{EA1C}"; pub const CHART_PIE: &str = "\u{EA1D}"; pub const CHART_PIE_SLICE: &str = "\u{EA1E}"; pub const CHART_POLAR: &str = "\u{EA1F}"; pub const CHART_SCATTER: &str = "\u{EA20}"; pub const CHAT: &str = "\u{EA21}"; pub const CHAT_CENTERED: &str = "\u{EA22}"; pub const CHAT_CENTERED_DOTS: &str = "\u{EA23}"; pub const CHAT_CENTERED_TEXT: &str = "\u{EA24}"; pub const CHAT_CIRCLE: &str = "\u{EA25}"; pub const CHAT_CIRCLE_DOTS: &str = "\u{EA26}"; pub const CHAT_CIRCLE_TEXT: &str = "\u{EA27}"; pub const CHAT_DOTS: &str = "\u{EA28}"; pub const CHATS: &str = "\u{EA29}"; pub const CHATS_CIRCLE: &str = "\u{EA2A}"; pub const CHATS_TEARDROP: &str = "\u{EA2B}"; pub const CHAT_TEARDROP: &str = "\u{EA2C}"; pub const CHAT_TEARDROP_DOTS: &str = "\u{EA2D}"; pub const CHAT_TEARDROP_TEXT: &str = "\u{EA2E}"; pub const CHAT_TEXT: &str = "\u{EA2F}"; pub const CHECK: &str = "\u{EA30}"; pub const CHECK_CIRCLE: &str = "\u{EA31}"; pub const CHECK_FAT: &str = "\u{EA32}"; pub const CHECKS: &str = "\u{EA33}"; pub const CHECK_SQUARE: &str = "\u{EA34}"; pub const CHECK_SQUARE_OFFSET: &str = "\u{EA35}"; pub const CHURCH: &str = "\u{EA36}"; pub const CIRCLE: &str = "\u{EA37}"; pub const CIRCLE_DASHED: &str = "\u{EA38}"; pub const CIRCLE_HALF: &str = "\u{EA39}"; pub const CIRCLE_HALF_TILT: &str = "\u{EA3A}"; pub const CIRCLE_NOTCH: &str = "\u{EA3B}"; pub const CIRCLES_FOUR: &str = "\u{EA3C}"; pub const CIRCLES_THREE: &str = "\u{EA3D}"; pub const CIRCLES_THREE_PLUS: &str = "\u{EA3E}"; pub const CIRCUITRY: &str = "\u{EA3F}"; pub const CLIPBOARD: &str = "\u{EA40}"; pub const CLIPBOARD_TEXT: &str = "\u{EA41}"; pub const CLOCK: &str = "\u{EA42}"; pub const CLOCK_AFTERNOON: &str = "\u{EA43}"; pub const CLOCK_CLOCKWISE: &str = "\u{EA44}"; pub const CLOCK_COUNTDOWN: &str = "\u{EA45}"; pub const CLOCK_COUNTER_CLOCKWISE: &str = "\u{EA46}"; pub const CLOSED_CAPTIONING: &str = "\u{EA47}"; pub const CLOUD: &str = "\u{EA48}"; pub const CLOUD_ARROW_DOWN: &str = "\u{EA49}"; pub const CLOUD_ARROW_UP: &str = "\u{EA4A}"; pub const CLOUD_CHECK: &str = "\u{EA4B}"; pub const CLOUD_FOG: &str = "\u{EA4C}"; pub const CLOUD_LIGHTNING: &str = "\u{EA4D}"; pub const CLOUD_MOON: &str = "\u{EA4E}"; pub const CLOUD_RAIN: &str = "\u{EA4F}"; pub const CLOUD_SLASH: &str = "\u{EA50}"; pub const CLOUD_SNOW: &str = "\u{EA51}"; pub const CLOUD_SUN: &str = "\u{EA52}"; pub const CLOUD_WARNING: &str = "\u{EA53}"; pub const CLOUD_X: &str = "\u{EA54}"; pub const CLUB: &str = "\u{EA55}"; pub const COAT_HANGER: &str = "\u{EA56}"; pub const CODA_LOGO: &str = "\u{EA57}"; pub const CODE: &str = "\u{EA58}"; pub const CODE_BLOCK: &str = "\u{EA59}"; pub const CODEPEN_LOGO: &str = "\u{EA5A}"; pub const CODESANDBOX_LOGO: &str = "\u{EA5B}"; pub const CODE_SIMPLE: &str = "\u{EA5C}"; pub const COFFEE: &str = "\u{EA5D}"; pub const COIN: &str = "\u{EA5E}"; pub const COINS: &str = "\u{EA5F}"; pub const COIN_VERTICAL: &str = "\u{EA60}"; pub const COLUMNS: &str = "\u{EA61}"; pub const COMMAND: &str = "\u{EA62}"; pub const COMPASS: &str = "\u{EA63}"; pub const COMPASS_TOOL: &str = "\u{EA64}"; pub const COMPUTER_TOWER: &str = "\u{EA65}"; pub const CONFETTI: &str = "\u{EA66}"; pub const CONTACTLESS_PAYMENT: &str = "\u{EA67}"; pub const CONTROL: &str = "\u{EA68}"; pub const COOKIE: &str = "\u{EA69}"; pub const COOKING_POT: &str = "\u{EA6A}"; pub const COPY: &str = "\u{EA6B}"; pub const COPYLEFT: &str = "\u{EA6C}"; pub const COPYRIGHT: &str = "\u{EA6D}"; pub const COPY_SIMPLE: &str = "\u{EA6E}"; pub const CORNERS_IN: &str = "\u{EA6F}"; pub const CORNERS_OUT: &str = "\u{EA70}"; pub const COUCH: &str = "\u{EA71}"; pub const CPU: &str = "\u{EA72}"; pub const CREDIT_CARD: &str = "\u{EA73}"; pub const CROP: &str = "\u{EA74}"; pub const CROSS: &str = "\u{EA75}"; pub const CROSSHAIR: &str = "\u{EA76}"; pub const CROSSHAIR_SIMPLE: &str = "\u{EA77}"; pub const CROWN: &str = "\u{EA78}"; pub const CROWN_SIMPLE: &str = "\u{EA79}"; pub const CUBE: &str = "\u{EA7A}"; pub const CUBE_FOCUS: &str = "\u{EA7B}"; pub const CUBE_TRANSPARENT: &str = "\u{EA7C}"; pub const CURRENCY_BTC: &str = "\u{EA7D}"; pub const CURRENCY_CIRCLE_DOLLAR: &str = "\u{EA7E}"; pub const CURRENCY_CNY: &str = "\u{EA7F}"; pub const CURRENCY_DOLLAR: &str = "\u{EA80}"; pub const CURRENCY_DOLLAR_SIMPLE: &str = "\u{EA81}"; pub const CURRENCY_ETH: &str = "\u{EA82}"; pub const CURRENCY_EUR: &str = "\u{EA83}"; pub const CURRENCY_GBP: &str = "\u{EA84}"; pub const CURRENCY_INR: &str = "\u{EA85}"; pub const CURRENCY_JPY: &str = "\u{EA86}"; pub const CURRENCY_KRW: &str = "\u{EA87}"; pub const CURRENCY_KZT: &str = "\u{EA88}"; pub const CURRENCY_NGN: &str = "\u{EA89}"; pub const CURRENCY_RUB: &str = "\u{EA8A}"; pub const CURSOR: &str = "\u{EA8B}"; pub const CURSOR_CLICK: &str = "\u{EA8C}"; pub const CURSOR_TEXT: &str = "\u{EA8D}"; pub const CYLINDER: &str = "\u{EA8E}"; pub const DATABASE: &str = "\u{EA8F}"; pub const DESKTOP: &str = "\u{EA90}"; pub const DESKTOP_TOWER: &str = "\u{EA91}"; pub const DETECTIVE: &str = "\u{EA92}"; pub const DEVICE_MOBILE: &str = "\u{EA93}"; pub const DEVICE_MOBILE_CAMERA: &str = "\u{EA94}"; pub const DEVICE_MOBILE_SPEAKER: &str = "\u{EA95}"; pub const DEVICES: &str = "\u{EA96}"; pub const DEVICE_TABLET: &str = "\u{EA97}"; pub const DEVICE_TABLET_CAMERA: &str = "\u{EA98}"; pub const DEVICE_TABLET_SPEAKER: &str = "\u{EA99}"; pub const DEV_TO_LOGO: &str = "\u{EA9A}"; pub const DIAMOND: &str = "\u{EA9B}"; pub const DIAMONDS_FOUR: &str = "\u{EA9C}"; pub const DICE_FIVE: &str = "\u{EA9D}"; pub const DICE_FOUR: &str = "\u{EA9E}"; pub const DICE_ONE: &str = "\u{EA9F}"; pub const DICE_SIX: &str = "\u{EAA0}"; pub const DICE_THREE: &str = "\u{EAA1}"; pub const DICE_TWO: &str = "\u{EAA2}"; pub const DISC: &str = "\u{EAA3}"; pub const DISCORD_LOGO: &str = "\u{EAA4}"; pub const DIVIDE: &str = "\u{EAA5}"; pub const DNA: &str = "\u{EAA6}"; pub const DOG: &str = "\u{EAA7}"; pub const DOOR: &str = "\u{EAA8}"; pub const DOOR_OPEN: &str = "\u{EAA9}"; pub const DOT: &str = "\u{EAAA}"; pub const DOT_OUTLINE: &str = "\u{EAAB}"; pub const DOTS_NINE: &str = "\u{EAAC}"; pub const DOTS_SIX: &str = "\u{EAAD}"; pub const DOTS_SIX_VERTICAL: &str = "\u{EAAE}"; pub const DOTS_THREE: &str = "\u{EAAF}"; pub const DOTS_THREE_CIRCLE: &str = "\u{EAB0}"; pub const DOTS_THREE_CIRCLE_VERTICAL: &str = "\u{EAB1}"; pub const DOTS_THREE_OUTLINE: &str = "\u{EAB2}"; pub const DOTS_THREE_OUTLINE_VERTICAL: &str = "\u{EAB3}"; pub const DOTS_THREE_VERTICAL: &str = "\u{EAB4}"; pub const DOWNLOAD: &str = "\u{EAB5}"; pub const DOWNLOAD_SIMPLE: &str = "\u{EAB6}"; pub const DRESS: &str = "\u{EAB7}"; pub const DRIBBBLE_LOGO: &str = "\u{EAB8}"; pub const DROP: &str = "\u{EAB9}"; pub const DROPBOX_LOGO: &str = "\u{EABA}"; pub const DROP_HALF: &str = "\u{EABB}"; pub const DROP_HALF_BOTTOM: &str = "\u{EABC}"; pub const EAR: &str = "\u{EABD}"; pub const EAR_SLASH: &str = "\u{EABE}"; pub const EGG: &str = "\u{EABF}"; pub const EGG_CRACK: &str = "\u{EAC0}"; pub const EJECT: &str = "\u{EAC1}"; pub const EJECT_SIMPLE: &str = "\u{EAC2}"; pub const ELEVATOR: &str = "\u{EAC3}"; pub const ENGINE: &str = "\u{EAC4}"; pub const ENVELOPE: &str = "\u{EAC5}"; pub const ENVELOPE_OPEN: &str = "\u{EAC6}"; pub const ENVELOPE_SIMPLE: &str = "\u{EAC7}"; pub const ENVELOPE_SIMPLE_OPEN: &str = "\u{EAC8}"; pub const EQUALIZER: &str = "\u{EAC9}"; pub const EQUALS: &str = "\u{EACA}"; pub const ERASER: &str = "\u{EACB}"; pub const ESCALATOR_DOWN: &str = "\u{EACC}"; pub const ESCALATOR_UP: &str = "\u{EACD}"; pub const EXAM: &str = "\u{EACE}"; pub const EXCLUDE: &str = "\u{EACF}"; pub const EXCLUDE_SQUARE: &str = "\u{EAD0}"; pub const EXPORT: &str = "\u{EAD1}"; pub const EYE: &str = "\u{EAD2}"; pub const EYE_CLOSED: &str = "\u{EAD3}"; pub const EYEDROPPER: &str = "\u{EAD4}"; pub const EYEDROPPER_SAMPLE: &str = "\u{EAD5}"; pub const EYEGLASSES: &str = "\u{EAD6}"; pub const EYE_SLASH: &str = "\u{EAD7}"; pub const FACEBOOK_LOGO: &str = "\u{EAD8}"; pub const FACE_MASK: &str = "\u{EAD9}"; pub const FACTORY: &str = "\u{EADA}"; pub const FADERS: &str = "\u{EADB}"; pub const FADERS_HORIZONTAL: &str = "\u{EADC}"; pub const FAN: &str = "\u{EADD}"; pub const FAST_FORWARD: &str = "\u{EADE}"; pub const FAST_FORWARD_CIRCLE: &str = "\u{EADF}"; pub const FEATHER: &str = "\u{EAE0}"; pub const FIGMA_LOGO: &str = "\u{EAE1}"; pub const FILE: &str = "\u{EAE2}"; pub const FILE_ARCHIVE: &str = "\u{EAE3}"; pub const FILE_ARROW_DOWN: &str = "\u{EAE4}"; pub const FILE_ARROW_UP: &str = "\u{EAE5}"; pub const FILE_AUDIO: &str = "\u{EAE6}"; pub const FILE_CLOUD: &str = "\u{EAE7}"; pub const FILE_CODE: &str = "\u{EAE8}"; pub const FILE_CSS: &str = "\u{EAE9}"; pub const FILE_CSV: &str = "\u{EAEA}"; pub const FILE_DASHED: &str = "\u{EAEB}"; pub const FILE_DOTTED: &str = "\u{EAEB}"; pub const FILE_DOC: &str = "\u{EAEC}"; pub const FILE_HTML: &str = "\u{EAED}"; pub const FILE_IMAGE: &str = "\u{EAEE}"; pub const FILE_JPG: &str = "\u{EAEF}"; pub const FILE_JS: &str = "\u{EAF0}"; pub const FILE_JSX: &str = "\u{EAF1}"; pub const FILE_LOCK: &str = "\u{EAF2}"; pub const FILE_MAGNIFYING_GLASS: &str = "\u{EAF3}"; pub const FILE_SEARCH: &str = "\u{EAF3}"; pub const FILE_MINUS: &str = "\u{EAF4}"; pub const FILE_PDF: &str = "\u{EAF5}"; pub const FILE_PLUS: &str = "\u{EAF6}"; pub const FILE_PNG: &str = "\u{EAF7}"; pub const FILE_PPT: &str = "\u{EAF8}"; pub const FILE_RS: &str = "\u{EAF9}"; pub const FILES: &str = "\u{EAFA}"; pub const FILE_SQL: &str = "\u{EAFB}"; pub const FILE_SVG: &str = "\u{EAFC}"; pub const FILE_TEXT: &str = "\u{EAFD}"; pub const FILE_TS: &str = "\u{EAFE}"; pub const FILE_TSX: &str = "\u{EAFF}"; pub const FILE_VIDEO: &str = "\u{EB00}"; pub const FILE_VUE: &str = "\u{EB01}"; pub const FILE_X: &str = "\u{EB02}"; pub const FILE_XLS: &str = "\u{EB03}"; pub const FILE_ZIP: &str = "\u{EB04}"; pub const FILM_REEL: &str = "\u{EB05}"; pub const FILM_SCRIPT: &str = "\u{EB06}"; pub const FILM_SLATE: &str = "\u{EB07}"; pub const FILM_STRIP: &str = "\u{EB08}"; pub const FINGERPRINT: &str = "\u{EB09}"; pub const FINGERPRINT_SIMPLE: &str = "\u{EB0A}"; pub const FINN_THE_HUMAN: &str = "\u{EB0B}"; pub const FIRE: &str = "\u{EB0C}"; pub const FIRE_EXTINGUISHER: &str = "\u{EB0D}"; pub const FIRE_SIMPLE: &str = "\u{EB0E}"; pub const FIRST_AID: &str = "\u{EB0F}"; pub const FIRST_AID_KIT: &str = "\u{EB10}"; pub const FISH: &str = "\u{EB11}"; pub const FISH_SIMPLE: &str = "\u{EB12}"; pub const FLAG: &str = "\u{EB13}"; pub const FLAG_BANNER: &str = "\u{EB14}"; pub const FLAG_CHECKERED: &str = "\u{EB15}"; pub const FLAG_PENNANT: &str = "\u{EB16}"; pub const FLAME: &str = "\u{EB17}"; pub const FLASHLIGHT: &str = "\u{EB18}"; pub const FLASK: &str = "\u{EB19}"; pub const FLOPPY_DISK: &str = "\u{EB1A}"; pub const FLOPPY_DISK_BACK: &str = "\u{EB1B}"; pub const FLOW_ARROW: &str = "\u{EB1C}"; pub const FLOWER: &str = "\u{EB1D}"; pub const FLOWER_LOTUS: &str = "\u{EB1E}"; pub const FLOWER_TULIP: &str = "\u{EB1F}"; pub const FLYING_SAUCER: &str = "\u{EB20}"; pub const FOLDER: &str = "\u{EB21}"; pub const FOLDER_DASHED: &str = "\u{EB22}"; pub const FOLDER_DOTTED: &str = "\u{EB22}"; pub const FOLDER_LOCK: &str = "\u{EB23}"; pub const FOLDER_MINUS: &str = "\u{EB24}"; pub const FOLDER_NOTCH: &str = "\u{EB25}"; pub const FOLDER_NOTCH_MINUS: &str = "\u{EB26}"; pub const FOLDER_NOTCH_OPEN: &str = "\u{EB27}"; pub const FOLDER_NOTCH_PLUS: &str = "\u{EB28}"; pub const FOLDER_OPEN: &str = "\u{EB29}"; pub const FOLDER_PLUS: &str = "\u{EB2A}"; pub const FOLDERS: &str = "\u{EB2B}"; pub const FOLDER_SIMPLE: &str = "\u{EB2C}"; pub const FOLDER_SIMPLE_DASHED: &str = "\u{EB2D}"; pub const FOLDER_SIMPLE_DOTTED: &str = "\u{EB2D}"; pub const FOLDER_SIMPLE_LOCK: &str = "\u{EB2E}"; pub const FOLDER_SIMPLE_MINUS: &str = "\u{EB2F}"; pub const FOLDER_SIMPLE_PLUS: &str = "\u{EB30}"; pub const FOLDER_SIMPLE_STAR: &str = "\u{EB31}"; pub const FOLDER_SIMPLE_USER: &str = "\u{EB32}"; pub const FOLDER_STAR: &str = "\u{EB33}"; pub const FOLDER_USER: &str = "\u{EB34}"; pub const FOOTBALL: &str = "\u{EB35}"; pub const FOOTPRINTS: &str = "\u{EB36}"; pub const FORK_KNIFE: &str = "\u{EB37}"; pub const FRAME_CORNERS: &str = "\u{EB38}"; pub const FRAMER_LOGO: &str = "\u{EB39}"; pub const FUNCTION: &str = "\u{EB3A}"; pub const FUNNEL: &str = "\u{EB3B}"; pub const FUNNEL_SIMPLE: &str = "\u{EB3C}"; pub const GAME_CONTROLLER: &str = "\u{EB3D}"; pub const GARAGE: &str = "\u{EB3E}"; pub const GAS_CAN: &str = "\u{EB3F}"; pub const GAS_PUMP: &str = "\u{EB40}"; pub const GAUGE: &str = "\u{EB41}"; pub const GAVEL: &str = "\u{EB42}"; pub const GEAR: &str = "\u{EB43}"; pub const GEAR_FINE: &str = "\u{EB44}"; pub const GEAR_SIX: &str = "\u{EB45}"; pub const GENDER_FEMALE: &str = "\u{EB46}"; pub const GENDER_INTERSEX: &str = "\u{EB47}"; pub const GENDER_MALE: &str = "\u{EB48}"; pub const GENDER_NEUTER: &str = "\u{EB49}"; pub const GENDER_NONBINARY: &str = "\u{EB4A}"; pub const GENDER_TRANSGENDER: &str = "\u{EB4B}"; pub const GHOST: &str = "\u{EB4C}"; pub const GIF: &str = "\u{EB4D}"; pub const GIFT: &str = "\u{EB4E}"; pub const GIT_BRANCH: &str = "\u{EB4F}"; pub const GIT_COMMIT: &str = "\u{EB50}"; pub const GIT_DIFF: &str = "\u{EB51}"; pub const GIT_FORK: &str = "\u{EB52}"; pub const GITHUB_LOGO: &str = "\u{EB53}"; pub const GITLAB_LOGO: &str = "\u{EB54}"; pub const GITLAB_LOGO_SIMPLE: &str = "\u{EB55}"; pub const GIT_MERGE: &str = "\u{EB56}"; pub const GIT_PULL_REQUEST: &str = "\u{EB57}"; pub const GLOBE: &str = "\u{EB58}"; pub const GLOBE_HEMISPHERE_EAST: &str = "\u{EB59}"; pub const GLOBE_HEMISPHERE_WEST: &str = "\u{EB5A}"; pub const GLOBE_SIMPLE: &str = "\u{EB5B}"; pub const GLOBE_STAND: &str = "\u{EB5C}"; pub const GOGGLES: &str = "\u{EB5D}"; pub const GOODREADS_LOGO: &str = "\u{EB5E}"; pub const GOOGLE_CARDBOARD_LOGO: &str = "\u{EB5F}"; pub const GOOGLE_CHROME_LOGO: &str = "\u{EB60}"; pub const GOOGLE_DRIVE_LOGO: &str = "\u{EB61}"; pub const GOOGLE_LOGO: &str = "\u{EB62}"; pub const GOOGLE_PHOTOS_LOGO: &str = "\u{EB63}"; pub const GOOGLE_PLAY_LOGO: &str = "\u{EB64}"; pub const GOOGLE_PODCASTS_LOGO: &str = "\u{EB65}"; pub const GRADIENT: &str = "\u{EB66}"; pub const GRADUATION_CAP: &str = "\u{EB67}"; pub const GRAINS: &str = "\u{EB68}"; pub const GRAINS_SLASH: &str = "\u{EB69}"; pub const GRAPH: &str = "\u{EB6A}"; pub const GRID_FOUR: &str = "\u{EB6B}"; pub const GRID_NINE: &str = "\u{EB6C}"; pub const GUITAR: &str = "\u{EB6D}"; pub const HAMBURGER: &str = "\u{EB6E}"; pub const HAMMER: &str = "\u{EB6F}"; pub const HAND: &str = "\u{EB70}"; pub const HANDBAG: &str = "\u{EB71}"; pub const HANDBAG_SIMPLE: &str = "\u{EB72}"; pub const HAND_COINS: &str = "\u{EB73}"; pub const HAND_EYE: &str = "\u{EB74}"; pub const HAND_FIST: &str = "\u{EB75}"; pub const HAND_GRABBING: &str = "\u{EB76}"; pub const HAND_HEART: &str = "\u{EB77}"; pub const HAND_PALM: &str = "\u{EB78}"; pub const HAND_POINTING: &str = "\u{EB79}"; pub const HANDS_CLAPPING: &str = "\u{EB7A}"; pub const HANDSHAKE: &str = "\u{EB7B}"; pub const HAND_SOAP: &str = "\u{EB7C}"; pub const HANDS_PRAYING: &str = "\u{EB7D}"; pub const HAND_SWIPE_LEFT: &str = "\u{EB7E}"; pub const HAND_SWIPE_RIGHT: &str = "\u{EB7F}"; pub const HAND_TAP: &str = "\u{EB80}"; pub const HAND_WAVING: &str = "\u{EB81}"; pub const HARD_DRIVE: &str = "\u{EB82}"; pub const HARD_DRIVES: &str = "\u{EB83}"; pub const HASH: &str = "\u{EB84}"; pub const HASH_STRAIGHT: &str = "\u{EB85}"; pub const HEADLIGHTS: &str = "\u{EB86}"; pub const HEADPHONES: &str = "\u{EB87}"; pub const HEADSET: &str = "\u{EB88}"; pub const HEART: &str = "\u{EB89}"; pub const HEARTBEAT: &str = "\u{EB8A}"; pub const HEART_BREAK: &str = "\u{EB8B}"; pub const HEART_HALF: &str = "\u{EB8C}"; pub const HEART_STRAIGHT: &str = "\u{EB8D}"; pub const HEART_STRAIGHT_BREAK: &str = "\u{EB8E}"; pub const HEXAGON: &str = "\u{EB8F}"; pub const HIGH_HEEL: &str = "\u{EB90}"; pub const HIGHLIGHTER_CIRCLE: &str = "\u{EB91}"; pub const HOODIE: &str = "\u{EB92}"; pub const HORSE: &str = "\u{EB93}"; pub const HOURGLASS: &str = "\u{EB94}"; pub const HOURGLASS_HIGH: &str = "\u{EB95}"; pub const HOURGLASS_LOW: &str = "\u{EB96}"; pub const HOURGLASS_MEDIUM: &str = "\u{EB97}"; pub const HOURGLASS_SIMPLE: &str = "\u{EB98}"; pub const HOURGLASS_SIMPLE_HIGH: &str = "\u{EB99}"; pub const HOURGLASS_SIMPLE_LOW: &str = "\u{EB9A}"; pub const HOURGLASS_SIMPLE_MEDIUM: &str = "\u{EB9B}"; pub const HOUSE: &str = "\u{EB9C}"; pub const HOUSE_LINE: &str = "\u{EB9D}"; pub const HOUSE_SIMPLE: &str = "\u{EB9E}"; pub const ICE_CREAM: &str = "\u{EB9F}"; pub const IDENTIFICATION_BADGE: &str = "\u{EBA0}"; pub const IDENTIFICATION_CARD: &str = "\u{EBA1}"; pub const IMAGE: &str = "\u{EBA2}"; pub const IMAGES: &str = "\u{EBA3}"; pub const IMAGE_SQUARE: &str = "\u{EBA4}"; pub const IMAGES_SQUARE: &str = "\u{EBA5}"; pub const INFINITY: &str = "\u{EBA6}"; pub const INFO: &str = "\u{EBA7}"; pub const INSTAGRAM_LOGO: &str = "\u{EBA8}"; pub const INTERSECT: &str = "\u{EBA9}"; pub const INTERSECT_SQUARE: &str = "\u{EBAA}"; pub const INTERSECT_THREE: &str = "\u{EBAB}"; pub const JEEP: &str = "\u{EBAC}"; pub const KANBAN: &str = "\u{EBAD}"; pub const KEY: &str = "\u{EBAE}"; pub const KEYBOARD: &str = "\u{EBAF}"; pub const KEYHOLE: &str = "\u{EBB0}"; pub const KEY_RETURN: &str = "\u{EBB1}"; pub const KNIFE: &str = "\u{EBB2}"; pub const LADDER: &str = "\u{EBB3}"; pub const LADDER_SIMPLE: &str = "\u{EBB4}"; pub const LAMP: &str = "\u{EBB5}"; pub const LAPTOP: &str = "\u{EBB6}"; pub const LAYOUT: &str = "\u{EBB7}"; pub const LEAF: &str = "\u{EBB8}"; pub const LIFEBUOY: &str = "\u{EBB9}"; pub const LIGHTBULB: &str = "\u{EBBA}"; pub const LIGHTBULB_FILAMENT: &str = "\u{EBBB}"; pub const LIGHTHOUSE: &str = "\u{EBBC}"; pub const LIGHTNING: &str = "\u{EBBD}"; pub const LIGHTNING_A: &str = "\u{EBBE}"; pub const LIGHTNING_SLASH: &str = "\u{EBBF}"; pub const LINE_SEGMENT: &str = "\u{EBC0}"; pub const LINE_SEGMENTS: &str = "\u{EBC1}"; pub const LINK: &str = "\u{EBC2}"; pub const LINK_BREAK: &str = "\u{EBC3}"; pub const LINKEDIN_LOGO: &str = "\u{EBC4}"; pub const LINK_SIMPLE: &str = "\u{EBC5}"; pub const LINK_SIMPLE_BREAK: &str = "\u{EBC6}"; pub const LINK_SIMPLE_HORIZONTAL: &str = "\u{EBC7}"; pub const LINK_SIMPLE_HORIZONTAL_BREAK: &str = "\u{EBC8}"; pub const LINUX_LOGO: &str = "\u{EBC9}"; pub const LIST: &str = "\u{EBCA}"; pub const LIST_BULLETS: &str = "\u{EBCB}"; pub const LIST_CHECKS: &str = "\u{EBCC}"; pub const LIST_DASHES: &str = "\u{EBCD}"; pub const LIST_MAGNIFYING_GLASS: &str = "\u{EBCE}"; pub const LIST_NUMBERS: &str = "\u{EBCF}"; pub const LIST_PLUS: &str = "\u{EBD0}"; pub const LOCK: &str = "\u{EBD1}"; pub const LOCKERS: &str = "\u{EBD2}"; pub const LOCK_KEY: &str = "\u{EBD3}"; pub const LOCK_KEY_OPEN: &str = "\u{EBD4}"; pub const LOCK_LAMINATED: &str = "\u{EBD5}"; pub const LOCK_LAMINATED_OPEN: &str = "\u{EBD6}"; pub const LOCK_OPEN: &str = "\u{EBD7}"; pub const LOCK_SIMPLE: &str = "\u{EBD8}"; pub const LOCK_SIMPLE_OPEN: &str = "\u{EBD9}"; pub const MAGIC_WAND: &str = "\u{EBDA}"; pub const MAGNET: &str = "\u{EBDB}"; pub const MAGNET_STRAIGHT: &str = "\u{EBDC}"; pub const MAGNIFYING_GLASS: &str = "\u{EBDD}"; pub const MAGNIFYING_GLASS_MINUS: &str = "\u{EBDE}"; pub const MAGNIFYING_GLASS_PLUS: &str = "\u{EBDF}"; pub const MAP_PIN: &str = "\u{EBE0}"; pub const MAP_PIN_LINE: &str = "\u{EBE1}"; pub const MAP_TRIFOLD: &str = "\u{EBE2}"; pub const MARKER_CIRCLE: &str = "\u{EBE3}"; pub const MARTINI: &str = "\u{EBE4}"; pub const MASK_HAPPY: &str = "\u{EBE5}"; pub const MASK_SAD: &str = "\u{EBE6}"; pub const MATH_OPERATIONS: &str = "\u{EBE7}"; pub const MEDAL: &str = "\u{EBE8}"; pub const MEDAL_MILITARY: &str = "\u{EBE9}"; pub const MEDIUM_LOGO: &str = "\u{EBEA}"; pub const MEGAPHONE: &str = "\u{EBEB}"; pub const MEGAPHONE_SIMPLE: &str = "\u{EBEC}"; pub const MESSENGER_LOGO: &str = "\u{EBED}"; pub const META_LOGO: &str = "\u{EBEE}"; pub const METRONOME: &str = "\u{EBEF}"; pub const MICROPHONE: &str = "\u{EBF0}"; pub const MICROPHONE_SLASH: &str = "\u{EBF1}"; pub const MICROPHONE_STAGE: &str = "\u{EBF2}"; pub const MICROSOFT_EXCEL_LOGO: &str = "\u{EBF3}";
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
true
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui-phosphor/src/variants/bold.rs
crates/egui-phosphor/src/variants/bold.rs
#![allow(unused)] pub const ADDRESS_BOOK: &str = "\u{E900}"; pub const AIRPLANE: &str = "\u{E901}"; pub const AIRPLANE_IN_FLIGHT: &str = "\u{E902}"; pub const AIRPLANE_LANDING: &str = "\u{E903}"; pub const AIRPLANE_TAKEOFF: &str = "\u{E904}"; pub const AIRPLANE_TILT: &str = "\u{E905}"; pub const AIRPLAY: &str = "\u{E906}"; pub const AIR_TRAFFIC_CONTROL: &str = "\u{E907}"; pub const ALARM: &str = "\u{E908}"; pub const ALIEN: &str = "\u{E909}"; pub const ALIGN_BOTTOM: &str = "\u{E90A}"; pub const ALIGN_BOTTOM_SIMPLE: &str = "\u{E90B}"; pub const ALIGN_CENTER_HORIZONTAL: &str = "\u{E90C}"; pub const ALIGN_CENTER_HORIZONTAL_SIMPLE: &str = "\u{E90D}"; pub const ALIGN_CENTER_VERTICAL: &str = "\u{E90E}"; pub const ALIGN_CENTER_VERTICAL_SIMPLE: &str = "\u{E90F}"; pub const ALIGN_LEFT: &str = "\u{E910}"; pub const ALIGN_LEFT_SIMPLE: &str = "\u{E911}"; pub const ALIGN_RIGHT: &str = "\u{E912}"; pub const ALIGN_RIGHT_SIMPLE: &str = "\u{E913}"; pub const ALIGN_TOP: &str = "\u{E914}"; pub const ALIGN_TOP_SIMPLE: &str = "\u{E915}"; pub const AMAZON_LOGO: &str = "\u{E916}"; pub const ANCHOR: &str = "\u{E917}"; pub const ANCHOR_SIMPLE: &str = "\u{E918}"; pub const ANDROID_LOGO: &str = "\u{E919}"; pub const ANGULAR_LOGO: &str = "\u{E91A}"; pub const APERTURE: &str = "\u{E91B}"; pub const APPLE_LOGO: &str = "\u{E91C}"; pub const APPLE_PODCASTS_LOGO: &str = "\u{E91D}"; pub const APP_STORE_LOGO: &str = "\u{E91E}"; pub const APP_WINDOW: &str = "\u{E91F}"; pub const ARCHIVE: &str = "\u{E920}"; pub const ARCHIVE_BOX: &str = "\u{E921}"; pub const ARCHIVE_TRAY: &str = "\u{E922}"; pub const ARMCHAIR: &str = "\u{E923}"; pub const ARROW_ARC_LEFT: &str = "\u{E924}"; pub const ARROW_ARC_RIGHT: &str = "\u{E925}"; pub const ARROW_BEND_DOUBLE_UP_LEFT: &str = "\u{E926}"; pub const ARROW_BEND_DOUBLE_UP_RIGHT: &str = "\u{E927}"; pub const ARROW_BEND_DOWN_LEFT: &str = "\u{E928}"; pub const ARROW_BEND_DOWN_RIGHT: &str = "\u{E929}"; pub const ARROW_BEND_LEFT_DOWN: &str = "\u{E92A}"; pub const ARROW_BEND_LEFT_UP: &str = "\u{E92B}"; pub const ARROW_BEND_RIGHT_DOWN: &str = "\u{E92C}"; pub const ARROW_BEND_RIGHT_UP: &str = "\u{E92D}"; pub const ARROW_BEND_UP_LEFT: &str = "\u{E92E}"; pub const ARROW_BEND_UP_RIGHT: &str = "\u{E92F}"; pub const ARROW_CIRCLE_DOWN: &str = "\u{E930}"; pub const ARROW_CIRCLE_DOWN_LEFT: &str = "\u{E931}"; pub const ARROW_CIRCLE_DOWN_RIGHT: &str = "\u{E932}"; pub const ARROW_CIRCLE_LEFT: &str = "\u{E933}"; pub const ARROW_CIRCLE_RIGHT: &str = "\u{E934}"; pub const ARROW_CIRCLE_UP: &str = "\u{E935}"; pub const ARROW_CIRCLE_UP_LEFT: &str = "\u{E936}"; pub const ARROW_CIRCLE_UP_RIGHT: &str = "\u{E937}"; pub const ARROW_CLOCKWISE: &str = "\u{E938}"; pub const ARROW_COUNTER_CLOCKWISE: &str = "\u{E939}"; pub const ARROW_DOWN: &str = "\u{E93A}"; pub const ARROW_DOWN_LEFT: &str = "\u{E93B}"; pub const ARROW_DOWN_RIGHT: &str = "\u{E93C}"; pub const ARROW_ELBOW_DOWN_LEFT: &str = "\u{E93D}"; pub const ARROW_ELBOW_DOWN_RIGHT: &str = "\u{E93E}"; pub const ARROW_ELBOW_LEFT: &str = "\u{E93F}"; pub const ARROW_ELBOW_LEFT_DOWN: &str = "\u{E940}"; pub const ARROW_ELBOW_LEFT_UP: &str = "\u{E941}"; pub const ARROW_ELBOW_RIGHT: &str = "\u{E942}"; pub const ARROW_ELBOW_RIGHT_DOWN: &str = "\u{E943}"; pub const ARROW_ELBOW_RIGHT_UP: &str = "\u{E944}"; pub const ARROW_ELBOW_UP_LEFT: &str = "\u{E945}"; pub const ARROW_ELBOW_UP_RIGHT: &str = "\u{E946}"; pub const ARROW_FAT_DOWN: &str = "\u{E947}"; pub const ARROW_FAT_LEFT: &str = "\u{E948}"; pub const ARROW_FAT_LINE_DOWN: &str = "\u{E949}"; pub const ARROW_FAT_LINE_LEFT: &str = "\u{E94A}"; pub const ARROW_FAT_LINE_RIGHT: &str = "\u{E94B}"; pub const ARROW_FAT_LINES_DOWN: &str = "\u{E94C}"; pub const ARROW_FAT_LINES_LEFT: &str = "\u{E94D}"; pub const ARROW_FAT_LINES_RIGHT: &str = "\u{E94E}"; pub const ARROW_FAT_LINES_UP: &str = "\u{E94F}"; pub const ARROW_FAT_LINE_UP: &str = "\u{E950}"; pub const ARROW_FAT_RIGHT: &str = "\u{E951}"; pub const ARROW_FAT_UP: &str = "\u{E952}"; pub const ARROW_LEFT: &str = "\u{E953}"; pub const ARROW_LINE_DOWN: &str = "\u{E954}"; pub const ARROW_LINE_DOWN_LEFT: &str = "\u{E955}"; pub const ARROW_LINE_DOWN_RIGHT: &str = "\u{E956}"; pub const ARROW_LINE_LEFT: &str = "\u{E957}"; pub const ARROW_LINE_RIGHT: &str = "\u{E958}"; pub const ARROW_LINE_UP: &str = "\u{E959}"; pub const ARROW_LINE_UP_LEFT: &str = "\u{E95A}"; pub const ARROW_LINE_UP_RIGHT: &str = "\u{E95B}"; pub const ARROW_RIGHT: &str = "\u{E95C}"; pub const ARROWS_CLOCKWISE: &str = "\u{E95D}"; pub const ARROWS_COUNTER_CLOCKWISE: &str = "\u{E95E}"; pub const ARROWS_DOWN_UP: &str = "\u{E95F}"; pub const ARROWS_HORIZONTAL: &str = "\u{E960}"; pub const ARROWS_IN: &str = "\u{E961}"; pub const ARROWS_IN_CARDINAL: &str = "\u{E962}"; pub const ARROWS_IN_LINE_HORIZONTAL: &str = "\u{E963}"; pub const ARROWS_IN_LINE_VERTICAL: &str = "\u{E964}"; pub const ARROWS_IN_SIMPLE: &str = "\u{E965}"; pub const ARROWS_LEFT_RIGHT: &str = "\u{E966}"; pub const ARROWS_MERGE: &str = "\u{E967}"; pub const ARROWS_OUT: &str = "\u{E968}"; pub const ARROWS_OUT_CARDINAL: &str = "\u{E969}"; pub const ARROWS_OUT_LINE_HORIZONTAL: &str = "\u{E96A}"; pub const ARROWS_OUT_LINE_VERTICAL: &str = "\u{E96B}"; pub const ARROWS_OUT_SIMPLE: &str = "\u{E96C}"; pub const ARROW_SQUARE_DOWN: &str = "\u{E96D}"; pub const ARROW_SQUARE_DOWN_LEFT: &str = "\u{E96E}"; pub const ARROW_SQUARE_DOWN_RIGHT: &str = "\u{E96F}"; pub const ARROW_SQUARE_IN: &str = "\u{E970}"; pub const ARROW_SQUARE_LEFT: &str = "\u{E971}"; pub const ARROW_SQUARE_OUT: &str = "\u{E972}"; pub const ARROW_SQUARE_RIGHT: &str = "\u{E973}"; pub const ARROW_SQUARE_UP: &str = "\u{E974}"; pub const ARROW_SQUARE_UP_LEFT: &str = "\u{E975}"; pub const ARROW_SQUARE_UP_RIGHT: &str = "\u{E976}"; pub const ARROWS_SPLIT: &str = "\u{E977}"; pub const ARROWS_VERTICAL: &str = "\u{E978}"; pub const ARROW_U_DOWN_LEFT: &str = "\u{E979}"; pub const ARROW_U_DOWN_RIGHT: &str = "\u{E97A}"; pub const ARROW_U_LEFT_DOWN: &str = "\u{E97B}"; pub const ARROW_U_LEFT_UP: &str = "\u{E97C}"; pub const ARROW_UP: &str = "\u{E97D}"; pub const ARROW_UP_LEFT: &str = "\u{E97E}"; pub const ARROW_UP_RIGHT: &str = "\u{E97F}"; pub const ARROW_U_RIGHT_DOWN: &str = "\u{E980}"; pub const ARROW_U_RIGHT_UP: &str = "\u{E981}"; pub const ARROW_U_UP_LEFT: &str = "\u{E982}"; pub const ARROW_U_UP_RIGHT: &str = "\u{E983}"; pub const ARTICLE: &str = "\u{E984}"; pub const ARTICLE_MEDIUM: &str = "\u{E985}"; pub const ARTICLE_NY_TIMES: &str = "\u{E986}"; pub const ASTERISK: &str = "\u{E987}"; pub const ASTERISK_SIMPLE: &str = "\u{E988}"; pub const AT: &str = "\u{E989}"; pub const ATOM: &str = "\u{E98A}"; pub const BABY: &str = "\u{E98B}"; pub const BACKPACK: &str = "\u{E98C}"; pub const BACKSPACE: &str = "\u{E98D}"; pub const BAG: &str = "\u{E98E}"; pub const BAG_SIMPLE: &str = "\u{E98F}"; pub const BALLOON: &str = "\u{E990}"; pub const BANDAIDS: &str = "\u{E991}"; pub const BANK: &str = "\u{E992}"; pub const BARBELL: &str = "\u{E993}"; pub const BARCODE: &str = "\u{E994}"; pub const BARRICADE: &str = "\u{E995}"; pub const BASEBALL: &str = "\u{E996}"; pub const BASEBALL_CAP: &str = "\u{E997}"; pub const BASKETBALL: &str = "\u{E998}"; pub const BASKET: &str = "\u{E999}"; pub const BATHTUB: &str = "\u{E99A}"; pub const BATTERY_CHARGING: &str = "\u{E99B}"; pub const BATTERY_CHARGING_VERTICAL: &str = "\u{E99C}"; pub const BATTERY_EMPTY: &str = "\u{E99D}"; pub const BATTERY_FULL: &str = "\u{E99E}"; pub const BATTERY_HIGH: &str = "\u{E99F}"; pub const BATTERY_LOW: &str = "\u{E9A0}"; pub const BATTERY_MEDIUM: &str = "\u{E9A1}"; pub const BATTERY_PLUS: &str = "\u{E9A2}"; pub const BATTERY_PLUS_VERTICAL: &str = "\u{E9A3}"; pub const BATTERY_VERTICAL_EMPTY: &str = "\u{E9A4}"; pub const BATTERY_VERTICAL_FULL: &str = "\u{E9A5}"; pub const BATTERY_VERTICAL_HIGH: &str = "\u{E9A6}"; pub const BATTERY_VERTICAL_LOW: &str = "\u{E9A7}"; pub const BATTERY_VERTICAL_MEDIUM: &str = "\u{E9A8}"; pub const BATTERY_WARNING: &str = "\u{E9A9}"; pub const BATTERY_WARNING_VERTICAL: &str = "\u{E9AA}"; pub const BED: &str = "\u{E9AB}"; pub const BEER_BOTTLE: &str = "\u{E9AC}"; pub const BEER_STEIN: &str = "\u{E9AD}"; pub const BEHANCE_LOGO: &str = "\u{E9AE}"; pub const BELL: &str = "\u{E9AF}"; pub const BELL_RINGING: &str = "\u{E9B0}"; pub const BELL_SIMPLE: &str = "\u{E9B1}"; pub const BELL_SIMPLE_RINGING: &str = "\u{E9B2}"; pub const BELL_SIMPLE_SLASH: &str = "\u{E9B3}"; pub const BELL_SIMPLE_Z: &str = "\u{E9B4}"; pub const BELL_SLASH: &str = "\u{E9B5}"; pub const BELL_Z: &str = "\u{E9B6}"; pub const BEZIER_CURVE: &str = "\u{E9B7}"; pub const BICYCLE: &str = "\u{E9B8}"; pub const BINOCULARS: &str = "\u{E9B9}"; pub const BIRD: &str = "\u{E9BA}"; pub const BLUETOOTH: &str = "\u{E9BB}"; pub const BLUETOOTH_CONNECTED: &str = "\u{E9BC}"; pub const BLUETOOTH_SLASH: &str = "\u{E9BD}"; pub const BLUETOOTH_X: &str = "\u{E9BE}"; pub const BOAT: &str = "\u{E9BF}"; pub const BONE: &str = "\u{E9C0}"; pub const BOOK: &str = "\u{E9C1}"; pub const BOOK_BOOKMARK: &str = "\u{E9C2}"; pub const BOOKMARK: &str = "\u{E9C3}"; pub const BOOKMARKS: &str = "\u{E9C4}"; pub const BOOKMARK_SIMPLE: &str = "\u{E9C5}"; pub const BOOKMARKS_SIMPLE: &str = "\u{E9C6}"; pub const BOOK_OPEN: &str = "\u{E9C7}"; pub const BOOK_OPEN_TEXT: &str = "\u{E9C8}"; pub const BOOKS: &str = "\u{E9C9}"; pub const BOOT: &str = "\u{E9CA}"; pub const BOUNDING_BOX: &str = "\u{E9CB}"; pub const BOWL_FOOD: &str = "\u{E9CC}"; pub const BRACKETS_ANGLE: &str = "\u{E9CD}"; pub const BRACKETS_CURLY: &str = "\u{E9CE}"; pub const BRACKETS_ROUND: &str = "\u{E9CF}"; pub const BRACKETS_SQUARE: &str = "\u{E9D0}"; pub const BRAIN: &str = "\u{E9D1}"; pub const BRANDY: &str = "\u{E9D2}"; pub const BRIDGE: &str = "\u{E9D3}"; pub const BRIEFCASE: &str = "\u{E9D4}"; pub const BRIEFCASE_METAL: &str = "\u{E9D5}"; pub const BROADCAST: &str = "\u{E9D6}"; pub const BROOM: &str = "\u{E9D7}"; pub const BROWSER: &str = "\u{E9D8}"; pub const BROWSERS: &str = "\u{E9D9}"; pub const BUG_BEETLE: &str = "\u{E9DA}"; pub const BUG: &str = "\u{E9DB}"; pub const BUG_DROID: &str = "\u{E9DC}"; pub const BUILDINGS: &str = "\u{E9DD}"; pub const BUS: &str = "\u{E9DE}"; pub const BUTTERFLY: &str = "\u{E9DF}"; pub const CACTUS: &str = "\u{E9E0}"; pub const CAKE: &str = "\u{E9E1}"; pub const CALCULATOR: &str = "\u{E9E2}"; pub const CALENDAR_BLANK: &str = "\u{E9E3}"; pub const CALENDAR: &str = "\u{E9E4}"; pub const CALENDAR_CHECK: &str = "\u{E9E5}"; pub const CALENDAR_PLUS: &str = "\u{E9E6}"; pub const CALENDAR_X: &str = "\u{E9E7}"; pub const CALL_BELL: &str = "\u{E9E8}"; pub const CAMERA: &str = "\u{E9E9}"; pub const CAMERA_PLUS: &str = "\u{E9EA}"; pub const CAMERA_ROTATE: &str = "\u{E9EB}"; pub const CAMERA_SLASH: &str = "\u{E9EC}"; pub const CAMPFIRE: &str = "\u{E9ED}"; pub const CAR: &str = "\u{E9EE}"; pub const CARDHOLDER: &str = "\u{E9EF}"; pub const CARDS: &str = "\u{E9F0}"; pub const CARET_CIRCLE_DOUBLE_DOWN: &str = "\u{E9F1}"; pub const CARET_CIRCLE_DOUBLE_LEFT: &str = "\u{E9F2}"; pub const CARET_CIRCLE_DOUBLE_RIGHT: &str = "\u{E9F3}"; pub const CARET_CIRCLE_DOUBLE_UP: &str = "\u{E9F4}"; pub const CARET_CIRCLE_DOWN: &str = "\u{E9F5}"; pub const CARET_CIRCLE_LEFT: &str = "\u{E9F6}"; pub const CARET_CIRCLE_RIGHT: &str = "\u{E9F7}"; pub const CARET_CIRCLE_UP: &str = "\u{E9F8}"; pub const CARET_CIRCLE_UP_DOWN: &str = "\u{E9F9}"; pub const CARET_DOUBLE_DOWN: &str = "\u{E9FA}"; pub const CARET_DOUBLE_LEFT: &str = "\u{E9FB}"; pub const CARET_DOUBLE_RIGHT: &str = "\u{E9FC}"; pub const CARET_DOUBLE_UP: &str = "\u{E9FD}"; pub const CARET_DOWN: &str = "\u{E9FE}"; pub const CARET_LEFT: &str = "\u{E9FF}"; pub const CARET_RIGHT: &str = "\u{EA00}"; pub const CARET_UP: &str = "\u{EA01}"; pub const CARET_UP_DOWN: &str = "\u{EA02}"; pub const CAR_PROFILE: &str = "\u{EA03}"; pub const CARROT: &str = "\u{EA04}"; pub const CAR_SIMPLE: &str = "\u{EA05}"; pub const CASSETTE_TAPE: &str = "\u{EA06}"; pub const CASTLE_TURRET: &str = "\u{EA07}"; pub const CAT: &str = "\u{EA08}"; pub const CELL_SIGNAL_FULL: &str = "\u{EA09}"; pub const CELL_SIGNAL_HIGH: &str = "\u{EA0A}"; pub const CELL_SIGNAL_LOW: &str = "\u{EA0B}"; pub const CELL_SIGNAL_MEDIUM: &str = "\u{EA0C}"; pub const CELL_SIGNAL_NONE: &str = "\u{EA0D}"; pub const CELL_SIGNAL_SLASH: &str = "\u{EA0E}"; pub const CELL_SIGNAL_X: &str = "\u{EA0F}"; pub const CERTIFICATE: &str = "\u{EA10}"; pub const CHAIR: &str = "\u{EA11}"; pub const CHALKBOARD: &str = "\u{EA12}"; pub const CHALKBOARD_SIMPLE: &str = "\u{EA13}"; pub const CHALKBOARD_TEACHER: &str = "\u{EA14}"; pub const CHAMPAGNE: &str = "\u{EA15}"; pub const CHARGING_STATION: &str = "\u{EA16}"; pub const CHART_BAR: &str = "\u{EA17}"; pub const CHART_BAR_HORIZONTAL: &str = "\u{EA18}"; pub const CHART_DONUT: &str = "\u{EA19}"; pub const CHART_LINE: &str = "\u{EA1A}"; pub const CHART_LINE_DOWN: &str = "\u{EA1B}"; pub const CHART_LINE_UP: &str = "\u{EA1C}"; pub const CHART_PIE: &str = "\u{EA1D}"; pub const CHART_PIE_SLICE: &str = "\u{EA1E}"; pub const CHART_POLAR: &str = "\u{EA1F}"; pub const CHART_SCATTER: &str = "\u{EA20}"; pub const CHAT: &str = "\u{EA21}"; pub const CHAT_CENTERED: &str = "\u{EA22}"; pub const CHAT_CENTERED_DOTS: &str = "\u{EA23}"; pub const CHAT_CENTERED_TEXT: &str = "\u{EA24}"; pub const CHAT_CIRCLE: &str = "\u{EA25}"; pub const CHAT_CIRCLE_DOTS: &str = "\u{EA26}"; pub const CHAT_CIRCLE_TEXT: &str = "\u{EA27}"; pub const CHAT_DOTS: &str = "\u{EA28}"; pub const CHATS: &str = "\u{EA29}"; pub const CHATS_CIRCLE: &str = "\u{EA2A}"; pub const CHATS_TEARDROP: &str = "\u{EA2B}"; pub const CHAT_TEARDROP: &str = "\u{EA2C}"; pub const CHAT_TEARDROP_DOTS: &str = "\u{EA2D}"; pub const CHAT_TEARDROP_TEXT: &str = "\u{EA2E}"; pub const CHAT_TEXT: &str = "\u{EA2F}"; pub const CHECK: &str = "\u{EA30}"; pub const CHECK_CIRCLE: &str = "\u{EA31}"; pub const CHECK_FAT: &str = "\u{EA32}"; pub const CHECKS: &str = "\u{EA33}"; pub const CHECK_SQUARE: &str = "\u{EA34}"; pub const CHECK_SQUARE_OFFSET: &str = "\u{EA35}"; pub const CHURCH: &str = "\u{EA36}"; pub const CIRCLE: &str = "\u{EA37}"; pub const CIRCLE_DASHED: &str = "\u{EA38}"; pub const CIRCLE_HALF: &str = "\u{EA39}"; pub const CIRCLE_HALF_TILT: &str = "\u{EA3A}"; pub const CIRCLE_NOTCH: &str = "\u{EA3B}"; pub const CIRCLES_FOUR: &str = "\u{EA3C}"; pub const CIRCLES_THREE: &str = "\u{EA3D}"; pub const CIRCLES_THREE_PLUS: &str = "\u{EA3E}"; pub const CIRCUITRY: &str = "\u{EA3F}"; pub const CLIPBOARD: &str = "\u{EA40}"; pub const CLIPBOARD_TEXT: &str = "\u{EA41}"; pub const CLOCK_AFTERNOON: &str = "\u{EA42}"; pub const CLOCK: &str = "\u{EA43}"; pub const CLOCK_CLOCKWISE: &str = "\u{EA44}"; pub const CLOCK_COUNTDOWN: &str = "\u{EA45}"; pub const CLOCK_COUNTER_CLOCKWISE: &str = "\u{EA46}"; pub const CLOSED_CAPTIONING: &str = "\u{EA47}"; pub const CLOUD_ARROW_DOWN: &str = "\u{EA48}"; pub const CLOUD_ARROW_UP: &str = "\u{EA49}"; pub const CLOUD: &str = "\u{EA4A}"; pub const CLOUD_CHECK: &str = "\u{EA4B}"; pub const CLOUD_FOG: &str = "\u{EA4C}"; pub const CLOUD_LIGHTNING: &str = "\u{EA4D}"; pub const CLOUD_MOON: &str = "\u{EA4E}"; pub const CLOUD_RAIN: &str = "\u{EA4F}"; pub const CLOUD_SLASH: &str = "\u{EA50}"; pub const CLOUD_SNOW: &str = "\u{EA51}"; pub const CLOUD_SUN: &str = "\u{EA52}"; pub const CLOUD_WARNING: &str = "\u{EA53}"; pub const CLOUD_X: &str = "\u{EA54}"; pub const CLUB: &str = "\u{EA55}"; pub const COAT_HANGER: &str = "\u{EA56}"; pub const CODA_LOGO: &str = "\u{EA57}"; pub const CODE_BLOCK: &str = "\u{EA58}"; pub const CODE: &str = "\u{EA59}"; pub const CODEPEN_LOGO: &str = "\u{EA5A}"; pub const CODESANDBOX_LOGO: &str = "\u{EA5B}"; pub const CODE_SIMPLE: &str = "\u{EA5C}"; pub const COFFEE: &str = "\u{EA5D}"; pub const COIN: &str = "\u{EA5E}"; pub const COINS: &str = "\u{EA5F}"; pub const COIN_VERTICAL: &str = "\u{EA60}"; pub const COLUMNS: &str = "\u{EA61}"; pub const COMMAND: &str = "\u{EA62}"; pub const COMPASS: &str = "\u{EA63}"; pub const COMPASS_TOOL: &str = "\u{EA64}"; pub const COMPUTER_TOWER: &str = "\u{EA65}"; pub const CONFETTI: &str = "\u{EA66}"; pub const CONTACTLESS_PAYMENT: &str = "\u{EA67}"; pub const CONTROL: &str = "\u{EA68}"; pub const COOKIE: &str = "\u{EA69}"; pub const COOKING_POT: &str = "\u{EA6A}"; pub const COPY: &str = "\u{EA6B}"; pub const COPYLEFT: &str = "\u{EA6C}"; pub const COPYRIGHT: &str = "\u{EA6D}"; pub const COPY_SIMPLE: &str = "\u{EA6E}"; pub const CORNERS_IN: &str = "\u{EA6F}"; pub const CORNERS_OUT: &str = "\u{EA70}"; pub const COUCH: &str = "\u{EA71}"; pub const CPU: &str = "\u{EA72}"; pub const CREDIT_CARD: &str = "\u{EA73}"; pub const CROP: &str = "\u{EA74}"; pub const CROSS: &str = "\u{EA75}"; pub const CROSSHAIR: &str = "\u{EA76}"; pub const CROSSHAIR_SIMPLE: &str = "\u{EA77}"; pub const CROWN: &str = "\u{EA78}"; pub const CROWN_SIMPLE: &str = "\u{EA79}"; pub const CUBE: &str = "\u{EA7A}"; pub const CUBE_FOCUS: &str = "\u{EA7B}"; pub const CUBE_TRANSPARENT: &str = "\u{EA7C}"; pub const CURRENCY_BTC: &str = "\u{EA7D}"; pub const CURRENCY_CIRCLE_DOLLAR: &str = "\u{EA7E}"; pub const CURRENCY_CNY: &str = "\u{EA7F}"; pub const CURRENCY_DOLLAR: &str = "\u{EA80}"; pub const CURRENCY_DOLLAR_SIMPLE: &str = "\u{EA81}"; pub const CURRENCY_ETH: &str = "\u{EA82}"; pub const CURRENCY_EUR: &str = "\u{EA83}"; pub const CURRENCY_GBP: &str = "\u{EA84}"; pub const CURRENCY_INR: &str = "\u{EA85}"; pub const CURRENCY_JPY: &str = "\u{EA86}"; pub const CURRENCY_KRW: &str = "\u{EA87}"; pub const CURRENCY_KZT: &str = "\u{EA88}"; pub const CURRENCY_NGN: &str = "\u{EA89}"; pub const CURRENCY_RUB: &str = "\u{EA8A}"; pub const CURSOR: &str = "\u{EA8B}"; pub const CURSOR_CLICK: &str = "\u{EA8C}"; pub const CURSOR_TEXT: &str = "\u{EA8D}"; pub const CYLINDER: &str = "\u{EA8E}"; pub const DATABASE: &str = "\u{EA8F}"; pub const DESKTOP: &str = "\u{EA90}"; pub const DESKTOP_TOWER: &str = "\u{EA91}"; pub const DETECTIVE: &str = "\u{EA92}"; pub const DEVICE_MOBILE: &str = "\u{EA93}"; pub const DEVICE_MOBILE_CAMERA: &str = "\u{EA94}"; pub const DEVICE_MOBILE_SPEAKER: &str = "\u{EA95}"; pub const DEVICES: &str = "\u{EA96}"; pub const DEVICE_TABLET: &str = "\u{EA97}"; pub const DEVICE_TABLET_CAMERA: &str = "\u{EA98}"; pub const DEVICE_TABLET_SPEAKER: &str = "\u{EA99}"; pub const DEV_TO_LOGO: &str = "\u{EA9A}"; pub const DIAMOND: &str = "\u{EA9B}"; pub const DIAMONDS_FOUR: &str = "\u{EA9C}"; pub const DICE_FIVE: &str = "\u{EA9D}"; pub const DICE_FOUR: &str = "\u{EA9E}"; pub const DICE_ONE: &str = "\u{EA9F}"; pub const DICE_SIX: &str = "\u{EAA0}"; pub const DICE_THREE: &str = "\u{EAA1}"; pub const DICE_TWO: &str = "\u{EAA2}"; pub const DISC: &str = "\u{EAA3}"; pub const DISCORD_LOGO: &str = "\u{EAA4}"; pub const DIVIDE: &str = "\u{EAA5}"; pub const DNA: &str = "\u{EAA6}"; pub const DOG: &str = "\u{EAA7}"; pub const DOOR: &str = "\u{EAA8}"; pub const DOOR_OPEN: &str = "\u{EAA9}"; pub const DOT: &str = "\u{EAAA}"; pub const DOT_OUTLINE: &str = "\u{EAAB}"; pub const DOTS_NINE: &str = "\u{EAAC}"; pub const DOTS_SIX: &str = "\u{EAAD}"; pub const DOTS_SIX_VERTICAL: &str = "\u{EAAE}"; pub const DOTS_THREE: &str = "\u{EAAF}"; pub const DOTS_THREE_CIRCLE: &str = "\u{EAB0}"; pub const DOTS_THREE_CIRCLE_VERTICAL: &str = "\u{EAB1}"; pub const DOTS_THREE_OUTLINE: &str = "\u{EAB2}"; pub const DOTS_THREE_OUTLINE_VERTICAL: &str = "\u{EAB3}"; pub const DOTS_THREE_VERTICAL: &str = "\u{EAB4}"; pub const DOWNLOAD: &str = "\u{EAB5}"; pub const DOWNLOAD_SIMPLE: &str = "\u{EAB6}"; pub const DRESS: &str = "\u{EAB7}"; pub const DRIBBBLE_LOGO: &str = "\u{EAB8}"; pub const DROP: &str = "\u{EAB9}"; pub const DROPBOX_LOGO: &str = "\u{EABA}"; pub const DROP_HALF: &str = "\u{EABB}"; pub const DROP_HALF_BOTTOM: &str = "\u{EABC}"; pub const EAR: &str = "\u{EABD}"; pub const EAR_SLASH: &str = "\u{EABE}"; pub const EGG: &str = "\u{EABF}"; pub const EGG_CRACK: &str = "\u{EAC0}"; pub const EJECT: &str = "\u{EAC1}"; pub const EJECT_SIMPLE: &str = "\u{EAC2}"; pub const ELEVATOR: &str = "\u{EAC3}"; pub const ENGINE: &str = "\u{EAC4}"; pub const ENVELOPE: &str = "\u{EAC5}"; pub const ENVELOPE_OPEN: &str = "\u{EAC6}"; pub const ENVELOPE_SIMPLE: &str = "\u{EAC7}"; pub const ENVELOPE_SIMPLE_OPEN: &str = "\u{EAC8}"; pub const EQUALIZER: &str = "\u{EAC9}"; pub const EQUALS: &str = "\u{EACA}"; pub const ERASER: &str = "\u{EACB}"; pub const ESCALATOR_DOWN: &str = "\u{EACC}"; pub const ESCALATOR_UP: &str = "\u{EACD}"; pub const EXAM: &str = "\u{EACE}"; pub const EXCLUDE: &str = "\u{EACF}"; pub const EXCLUDE_SQUARE: &str = "\u{EAD0}"; pub const EXPORT: &str = "\u{EAD1}"; pub const EYE: &str = "\u{EAD2}"; pub const EYE_CLOSED: &str = "\u{EAD3}"; pub const EYEDROPPER: &str = "\u{EAD4}"; pub const EYEDROPPER_SAMPLE: &str = "\u{EAD5}"; pub const EYEGLASSES: &str = "\u{EAD6}"; pub const EYE_SLASH: &str = "\u{EAD7}"; pub const FACEBOOK_LOGO: &str = "\u{EAD8}"; pub const FACE_MASK: &str = "\u{EAD9}"; pub const FACTORY: &str = "\u{EADA}"; pub const FADERS: &str = "\u{EADB}"; pub const FADERS_HORIZONTAL: &str = "\u{EADC}"; pub const FAN: &str = "\u{EADD}"; pub const FAST_FORWARD: &str = "\u{EADE}"; pub const FAST_FORWARD_CIRCLE: &str = "\u{EADF}"; pub const FEATHER: &str = "\u{EAE0}"; pub const FIGMA_LOGO: &str = "\u{EAE1}"; pub const FILE_ARCHIVE: &str = "\u{EAE2}"; pub const FILE_ARROW_DOWN: &str = "\u{EAE3}"; pub const FILE_ARROW_UP: &str = "\u{EAE4}"; pub const FILE_AUDIO: &str = "\u{EAE5}"; pub const FILE: &str = "\u{EAE6}"; pub const FILE_CLOUD: &str = "\u{EAE7}"; pub const FILE_CODE: &str = "\u{EAE8}"; pub const FILE_CSS: &str = "\u{EAE9}"; pub const FILE_CSV: &str = "\u{EAEA}"; pub const FILE_DASHED: &str = "\u{EAEB}"; pub const FILE_DOTTED: &str = "\u{EAEB}"; pub const FILE_DOC: &str = "\u{EAEC}"; pub const FILE_HTML: &str = "\u{EAED}"; pub const FILE_IMAGE: &str = "\u{EAEE}"; pub const FILE_JPG: &str = "\u{EAEF}"; pub const FILE_JS: &str = "\u{EAF0}"; pub const FILE_JSX: &str = "\u{EAF1}"; pub const FILE_LOCK: &str = "\u{EAF2}"; pub const FILE_MAGNIFYING_GLASS: &str = "\u{EAF3}"; pub const FILE_SEARCH: &str = "\u{EAF3}"; pub const FILE_MINUS: &str = "\u{EAF4}"; pub const FILE_PDF: &str = "\u{EAF5}"; pub const FILE_PLUS: &str = "\u{EAF6}"; pub const FILE_PNG: &str = "\u{EAF7}"; pub const FILE_PPT: &str = "\u{EAF8}"; pub const FILE_RS: &str = "\u{EAF9}"; pub const FILES: &str = "\u{EAFA}"; pub const FILE_SQL: &str = "\u{EAFB}"; pub const FILE_SVG: &str = "\u{EAFC}"; pub const FILE_TEXT: &str = "\u{EAFD}"; pub const FILE_TS: &str = "\u{EAFE}"; pub const FILE_TSX: &str = "\u{EAFF}"; pub const FILE_VIDEO: &str = "\u{EB00}"; pub const FILE_VUE: &str = "\u{EB01}"; pub const FILE_X: &str = "\u{EB02}"; pub const FILE_XLS: &str = "\u{EB03}"; pub const FILE_ZIP: &str = "\u{EB04}"; pub const FILM_REEL: &str = "\u{EB05}"; pub const FILM_SCRIPT: &str = "\u{EB06}"; pub const FILM_SLATE: &str = "\u{EB07}"; pub const FILM_STRIP: &str = "\u{EB08}"; pub const FINGERPRINT: &str = "\u{EB09}"; pub const FINGERPRINT_SIMPLE: &str = "\u{EB0A}"; pub const FINN_THE_HUMAN: &str = "\u{EB0B}"; pub const FIRE: &str = "\u{EB0C}"; pub const FIRE_EXTINGUISHER: &str = "\u{EB0D}"; pub const FIRE_SIMPLE: &str = "\u{EB0E}"; pub const FIRST_AID: &str = "\u{EB0F}"; pub const FIRST_AID_KIT: &str = "\u{EB10}"; pub const FISH: &str = "\u{EB11}"; pub const FISH_SIMPLE: &str = "\u{EB12}"; pub const FLAG_BANNER: &str = "\u{EB13}"; pub const FLAG: &str = "\u{EB14}"; pub const FLAG_CHECKERED: &str = "\u{EB15}"; pub const FLAG_PENNANT: &str = "\u{EB16}"; pub const FLAME: &str = "\u{EB17}"; pub const FLASHLIGHT: &str = "\u{EB18}"; pub const FLASK: &str = "\u{EB19}"; pub const FLOPPY_DISK_BACK: &str = "\u{EB1A}"; pub const FLOPPY_DISK: &str = "\u{EB1B}"; pub const FLOW_ARROW: &str = "\u{EB1C}"; pub const FLOWER: &str = "\u{EB1D}"; pub const FLOWER_LOTUS: &str = "\u{EB1E}"; pub const FLOWER_TULIP: &str = "\u{EB1F}"; pub const FLYING_SAUCER: &str = "\u{EB20}"; pub const FOLDER: &str = "\u{EB21}"; pub const FOLDER_DASHED: &str = "\u{EB22}"; pub const FOLDER_DOTTED: &str = "\u{EB22}"; pub const FOLDER_LOCK: &str = "\u{EB23}"; pub const FOLDER_MINUS: &str = "\u{EB24}"; pub const FOLDER_NOTCH: &str = "\u{EB25}"; pub const FOLDER_NOTCH_MINUS: &str = "\u{EB26}"; pub const FOLDER_NOTCH_OPEN: &str = "\u{EB27}"; pub const FOLDER_NOTCH_PLUS: &str = "\u{EB28}"; pub const FOLDER_OPEN: &str = "\u{EB29}"; pub const FOLDER_PLUS: &str = "\u{EB2A}"; pub const FOLDERS: &str = "\u{EB2B}"; pub const FOLDER_SIMPLE: &str = "\u{EB2C}"; pub const FOLDER_SIMPLE_DASHED: &str = "\u{EB2D}"; pub const FOLDER_SIMPLE_DOTTED: &str = "\u{EB2D}"; pub const FOLDER_SIMPLE_LOCK: &str = "\u{EB2E}"; pub const FOLDER_SIMPLE_MINUS: &str = "\u{EB2F}"; pub const FOLDER_SIMPLE_PLUS: &str = "\u{EB30}"; pub const FOLDER_SIMPLE_STAR: &str = "\u{EB31}"; pub const FOLDER_SIMPLE_USER: &str = "\u{EB32}"; pub const FOLDER_STAR: &str = "\u{EB33}"; pub const FOLDER_USER: &str = "\u{EB34}"; pub const FOOTBALL: &str = "\u{EB35}"; pub const FOOTPRINTS: &str = "\u{EB36}"; pub const FORK_KNIFE: &str = "\u{EB37}"; pub const FRAME_CORNERS: &str = "\u{EB38}"; pub const FRAMER_LOGO: &str = "\u{EB39}"; pub const FUNCTION: &str = "\u{EB3A}"; pub const FUNNEL: &str = "\u{EB3B}"; pub const FUNNEL_SIMPLE: &str = "\u{EB3C}"; pub const GAME_CONTROLLER: &str = "\u{EB3D}"; pub const GARAGE: &str = "\u{EB3E}"; pub const GAS_CAN: &str = "\u{EB3F}"; pub const GAS_PUMP: &str = "\u{EB40}"; pub const GAUGE: &str = "\u{EB41}"; pub const GAVEL: &str = "\u{EB42}"; pub const GEAR: &str = "\u{EB43}"; pub const GEAR_FINE: &str = "\u{EB44}"; pub const GEAR_SIX: &str = "\u{EB45}"; pub const GENDER_FEMALE: &str = "\u{EB46}"; pub const GENDER_INTERSEX: &str = "\u{EB47}"; pub const GENDER_MALE: &str = "\u{EB48}"; pub const GENDER_NEUTER: &str = "\u{EB49}"; pub const GENDER_NONBINARY: &str = "\u{EB4A}"; pub const GENDER_TRANSGENDER: &str = "\u{EB4B}"; pub const GHOST: &str = "\u{EB4C}"; pub const GIF: &str = "\u{EB4D}"; pub const GIFT: &str = "\u{EB4E}"; pub const GIT_BRANCH: &str = "\u{EB4F}"; pub const GIT_COMMIT: &str = "\u{EB50}"; pub const GIT_DIFF: &str = "\u{EB51}"; pub const GIT_FORK: &str = "\u{EB52}"; pub const GITHUB_LOGO: &str = "\u{EB53}"; pub const GITLAB_LOGO: &str = "\u{EB54}"; pub const GITLAB_LOGO_SIMPLE: &str = "\u{EB55}"; pub const GIT_MERGE: &str = "\u{EB56}"; pub const GIT_PULL_REQUEST: &str = "\u{EB57}"; pub const GLOBE: &str = "\u{EB58}"; pub const GLOBE_HEMISPHERE_EAST: &str = "\u{EB59}"; pub const GLOBE_HEMISPHERE_WEST: &str = "\u{EB5A}"; pub const GLOBE_SIMPLE: &str = "\u{EB5B}"; pub const GLOBE_STAND: &str = "\u{EB5C}"; pub const GOGGLES: &str = "\u{EB5D}"; pub const GOODREADS_LOGO: &str = "\u{EB5E}"; pub const GOOGLE_CARDBOARD_LOGO: &str = "\u{EB5F}"; pub const GOOGLE_CHROME_LOGO: &str = "\u{EB60}"; pub const GOOGLE_DRIVE_LOGO: &str = "\u{EB61}"; pub const GOOGLE_LOGO: &str = "\u{EB62}"; pub const GOOGLE_PHOTOS_LOGO: &str = "\u{EB63}"; pub const GOOGLE_PLAY_LOGO: &str = "\u{EB64}"; pub const GOOGLE_PODCASTS_LOGO: &str = "\u{EB65}"; pub const GRADIENT: &str = "\u{EB66}"; pub const GRADUATION_CAP: &str = "\u{EB67}"; pub const GRAINS: &str = "\u{EB68}"; pub const GRAINS_SLASH: &str = "\u{EB69}"; pub const GRAPH: &str = "\u{EB6A}"; pub const GRID_FOUR: &str = "\u{EB6B}"; pub const GRID_NINE: &str = "\u{EB6C}"; pub const GUITAR: &str = "\u{EB6D}"; pub const HAMBURGER: &str = "\u{EB6E}"; pub const HAMMER: &str = "\u{EB6F}"; pub const HANDBAG: &str = "\u{EB70}"; pub const HANDBAG_SIMPLE: &str = "\u{EB71}"; pub const HAND: &str = "\u{EB72}"; pub const HAND_COINS: &str = "\u{EB73}"; pub const HAND_EYE: &str = "\u{EB74}"; pub const HAND_FIST: &str = "\u{EB75}"; pub const HAND_GRABBING: &str = "\u{EB76}"; pub const HAND_HEART: &str = "\u{EB77}"; pub const HAND_PALM: &str = "\u{EB78}"; pub const HAND_POINTING: &str = "\u{EB79}"; pub const HANDS_CLAPPING: &str = "\u{EB7A}"; pub const HANDSHAKE: &str = "\u{EB7B}"; pub const HAND_SOAP: &str = "\u{EB7C}"; pub const HANDS_PRAYING: &str = "\u{EB7D}"; pub const HAND_SWIPE_LEFT: &str = "\u{EB7E}"; pub const HAND_SWIPE_RIGHT: &str = "\u{EB7F}"; pub const HAND_TAP: &str = "\u{EB80}"; pub const HAND_WAVING: &str = "\u{EB81}"; pub const HARD_DRIVE: &str = "\u{EB82}"; pub const HARD_DRIVES: &str = "\u{EB83}"; pub const HASH: &str = "\u{EB84}"; pub const HASH_STRAIGHT: &str = "\u{EB85}"; pub const HEADLIGHTS: &str = "\u{EB86}"; pub const HEADPHONES: &str = "\u{EB87}"; pub const HEADSET: &str = "\u{EB88}"; pub const HEARTBEAT: &str = "\u{EB89}"; pub const HEART: &str = "\u{EB8A}"; pub const HEART_BREAK: &str = "\u{EB8B}"; pub const HEART_HALF: &str = "\u{EB8C}"; pub const HEART_STRAIGHT: &str = "\u{EB8D}"; pub const HEART_STRAIGHT_BREAK: &str = "\u{EB8E}"; pub const HEXAGON: &str = "\u{EB8F}"; pub const HIGH_HEEL: &str = "\u{EB90}"; pub const HIGHLIGHTER_CIRCLE: &str = "\u{EB91}"; pub const HOODIE: &str = "\u{EB92}"; pub const HORSE: &str = "\u{EB93}"; pub const HOURGLASS: &str = "\u{EB94}"; pub const HOURGLASS_HIGH: &str = "\u{EB95}"; pub const HOURGLASS_LOW: &str = "\u{EB96}"; pub const HOURGLASS_MEDIUM: &str = "\u{EB97}"; pub const HOURGLASS_SIMPLE: &str = "\u{EB98}"; pub const HOURGLASS_SIMPLE_HIGH: &str = "\u{EB99}"; pub const HOURGLASS_SIMPLE_LOW: &str = "\u{EB9A}"; pub const HOURGLASS_SIMPLE_MEDIUM: &str = "\u{EB9B}"; pub const HOUSE: &str = "\u{EB9C}"; pub const HOUSE_LINE: &str = "\u{EB9D}"; pub const HOUSE_SIMPLE: &str = "\u{EB9E}"; pub const ICE_CREAM: &str = "\u{EB9F}"; pub const IDENTIFICATION_BADGE: &str = "\u{EBA0}"; pub const IDENTIFICATION_CARD: &str = "\u{EBA1}"; pub const IMAGE: &str = "\u{EBA2}"; pub const IMAGES: &str = "\u{EBA3}"; pub const IMAGE_SQUARE: &str = "\u{EBA4}"; pub const IMAGES_SQUARE: &str = "\u{EBA5}"; pub const INFINITY: &str = "\u{EBA6}"; pub const INFO: &str = "\u{EBA7}"; pub const INSTAGRAM_LOGO: &str = "\u{EBA8}"; pub const INTERSECT: &str = "\u{EBA9}"; pub const INTERSECT_SQUARE: &str = "\u{EBAA}"; pub const INTERSECT_THREE: &str = "\u{EBAB}"; pub const JEEP: &str = "\u{EBAC}"; pub const KANBAN: &str = "\u{EBAD}"; pub const KEYBOARD: &str = "\u{EBAE}"; pub const KEY: &str = "\u{EBAF}"; pub const KEYHOLE: &str = "\u{EBB0}"; pub const KEY_RETURN: &str = "\u{EBB1}"; pub const KNIFE: &str = "\u{EBB2}"; pub const LADDER: &str = "\u{EBB3}"; pub const LADDER_SIMPLE: &str = "\u{EBB4}"; pub const LAMP: &str = "\u{EBB5}"; pub const LAPTOP: &str = "\u{EBB6}"; pub const LAYOUT: &str = "\u{EBB7}"; pub const LEAF: &str = "\u{EBB8}"; pub const LIFEBUOY: &str = "\u{EBB9}"; pub const LIGHTBULB: &str = "\u{EBBA}"; pub const LIGHTBULB_FILAMENT: &str = "\u{EBBB}"; pub const LIGHTHOUSE: &str = "\u{EBBC}"; pub const LIGHTNING_A: &str = "\u{EBBD}"; pub const LIGHTNING: &str = "\u{EBBE}"; pub const LIGHTNING_SLASH: &str = "\u{EBBF}"; pub const LINE_SEGMENT: &str = "\u{EBC0}"; pub const LINE_SEGMENTS: &str = "\u{EBC1}"; pub const LINK: &str = "\u{EBC2}"; pub const LINK_BREAK: &str = "\u{EBC3}"; pub const LINKEDIN_LOGO: &str = "\u{EBC4}"; pub const LINK_SIMPLE: &str = "\u{EBC5}"; pub const LINK_SIMPLE_BREAK: &str = "\u{EBC6}"; pub const LINK_SIMPLE_HORIZONTAL: &str = "\u{EBC7}"; pub const LINK_SIMPLE_HORIZONTAL_BREAK: &str = "\u{EBC8}"; pub const LINUX_LOGO: &str = "\u{EBC9}"; pub const LIST: &str = "\u{EBCA}"; pub const LIST_BULLETS: &str = "\u{EBCB}"; pub const LIST_CHECKS: &str = "\u{EBCC}"; pub const LIST_DASHES: &str = "\u{EBCD}"; pub const LIST_MAGNIFYING_GLASS: &str = "\u{EBCE}"; pub const LIST_NUMBERS: &str = "\u{EBCF}"; pub const LIST_PLUS: &str = "\u{EBD0}"; pub const LOCK: &str = "\u{EBD1}"; pub const LOCKERS: &str = "\u{EBD2}"; pub const LOCK_KEY: &str = "\u{EBD3}"; pub const LOCK_KEY_OPEN: &str = "\u{EBD4}"; pub const LOCK_LAMINATED: &str = "\u{EBD5}"; pub const LOCK_LAMINATED_OPEN: &str = "\u{EBD6}"; pub const LOCK_OPEN: &str = "\u{EBD7}"; pub const LOCK_SIMPLE: &str = "\u{EBD8}"; pub const LOCK_SIMPLE_OPEN: &str = "\u{EBD9}"; pub const MAGIC_WAND: &str = "\u{EBDA}"; pub const MAGNET: &str = "\u{EBDB}"; pub const MAGNET_STRAIGHT: &str = "\u{EBDC}"; pub const MAGNIFYING_GLASS: &str = "\u{EBDD}"; pub const MAGNIFYING_GLASS_MINUS: &str = "\u{EBDE}"; pub const MAGNIFYING_GLASS_PLUS: &str = "\u{EBDF}"; pub const MAP_PIN: &str = "\u{EBE0}"; pub const MAP_PIN_LINE: &str = "\u{EBE1}"; pub const MAP_TRIFOLD: &str = "\u{EBE2}"; pub const MARKER_CIRCLE: &str = "\u{EBE3}"; pub const MARTINI: &str = "\u{EBE4}"; pub const MASK_HAPPY: &str = "\u{EBE5}"; pub const MASK_SAD: &str = "\u{EBE6}"; pub const MATH_OPERATIONS: &str = "\u{EBE7}"; pub const MEDAL: &str = "\u{EBE8}"; pub const MEDAL_MILITARY: &str = "\u{EBE9}"; pub const MEDIUM_LOGO: &str = "\u{EBEA}"; pub const MEGAPHONE: &str = "\u{EBEB}"; pub const MEGAPHONE_SIMPLE: &str = "\u{EBEC}"; pub const MESSENGER_LOGO: &str = "\u{EBED}"; pub const META_LOGO: &str = "\u{EBEE}"; pub const METRONOME: &str = "\u{EBEF}"; pub const MICROPHONE: &str = "\u{EBF0}"; pub const MICROPHONE_SLASH: &str = "\u{EBF1}"; pub const MICROPHONE_STAGE: &str = "\u{EBF2}"; pub const MICROSOFT_EXCEL_LOGO: &str = "\u{EBF3}";
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
true
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui-phosphor/src/variants/mod.rs
crates/egui-phosphor/src/variants/mod.rs
#[cfg(feature = "bold")] pub mod bold; #[cfg(feature = "fill")] pub mod fill; #[cfg(feature = "light")] pub mod light; #[cfg(feature = "regular")] pub mod regular; #[cfg(feature = "thin")] pub mod thin; #[cfg(not(any( feature = "thin", feature = "light", feature = "regular", feature = "bold", feature = "fill", )))] compile_error!( "At least one font variant must be selected as a crate feature. When in doubt, use default features." ); #[derive(Debug, Clone, Copy)] pub enum Variant { #[cfg(feature = "thin")] Thin, #[cfg(feature = "light")] Light, #[cfg(feature = "regular")] Regular, #[cfg(feature = "bold")] Bold, #[cfg(feature = "fill")] Fill, } impl Variant { pub fn font_data(&self) -> egui::FontData { let mut font_data = egui::FontData::from_static(match self { #[cfg(feature = "thin")] Variant::Thin => include_bytes!("../../res/Phosphor-Thin.ttf"), #[cfg(feature = "light")] Variant::Light => include_bytes!("../../res/Phosphor-Light.ttf"), #[cfg(feature = "regular")] Variant::Regular => include_bytes!("../../res/Phosphor.ttf"), #[cfg(feature = "bold")] Variant::Bold => include_bytes!("../../res/Phosphor-Bold.ttf"), #[cfg(feature = "fill")] Variant::Fill => include_bytes!("../../res/Phosphor-Fill.ttf"), }); font_data.tweak.y_offset_factor = 0.1; font_data } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui-phosphor/src/variants/thin.rs
crates/egui-phosphor/src/variants/thin.rs
#![allow(unused)] pub const ADDRESS_BOOK: &str = "\u{E900}"; pub const AIRPLANE_IN_FLIGHT: &str = "\u{E901}"; pub const AIRPLANE_LANDING: &str = "\u{E902}"; pub const AIRPLANE_TAKEOFF: &str = "\u{E903}"; pub const AIRPLANE: &str = "\u{E904}"; pub const AIRPLANE_TILT: &str = "\u{E905}"; pub const AIRPLAY: &str = "\u{E906}"; pub const AIR_TRAFFIC_CONTROL: &str = "\u{E907}"; pub const ALARM: &str = "\u{E908}"; pub const ALIEN: &str = "\u{E909}"; pub const ALIGN_BOTTOM_SIMPLE: &str = "\u{E90A}"; pub const ALIGN_BOTTOM: &str = "\u{E90B}"; pub const ALIGN_CENTER_HORIZONTAL_SIMPLE: &str = "\u{E90C}"; pub const ALIGN_CENTER_HORIZONTAL: &str = "\u{E90D}"; pub const ALIGN_CENTER_VERTICAL_SIMPLE: &str = "\u{E90E}"; pub const ALIGN_CENTER_VERTICAL: &str = "\u{E90F}"; pub const ALIGN_LEFT_SIMPLE: &str = "\u{E910}"; pub const ALIGN_LEFT: &str = "\u{E911}"; pub const ALIGN_RIGHT_SIMPLE: &str = "\u{E912}"; pub const ALIGN_RIGHT: &str = "\u{E913}"; pub const ALIGN_TOP_SIMPLE: &str = "\u{E914}"; pub const ALIGN_TOP: &str = "\u{E915}"; pub const AMAZON_LOGO: &str = "\u{E916}"; pub const ANCHOR_SIMPLE: &str = "\u{E917}"; pub const ANCHOR: &str = "\u{E918}"; pub const ANDROID_LOGO: &str = "\u{E919}"; pub const ANGULAR_LOGO: &str = "\u{E91A}"; pub const APERTURE: &str = "\u{E91B}"; pub const APPLE_LOGO: &str = "\u{E91C}"; pub const APPLE_PODCASTS_LOGO: &str = "\u{E91D}"; pub const APP_STORE_LOGO: &str = "\u{E91E}"; pub const APP_WINDOW: &str = "\u{E91F}"; pub const ARCHIVE_BOX: &str = "\u{E920}"; pub const ARCHIVE: &str = "\u{E921}"; pub const ARCHIVE_TRAY: &str = "\u{E922}"; pub const ARMCHAIR: &str = "\u{E923}"; pub const ARROW_ARC_LEFT: &str = "\u{E924}"; pub const ARROW_ARC_RIGHT: &str = "\u{E925}"; pub const ARROW_BEND_DOUBLE_UP_LEFT: &str = "\u{E926}"; pub const ARROW_BEND_DOUBLE_UP_RIGHT: &str = "\u{E927}"; pub const ARROW_BEND_DOWN_LEFT: &str = "\u{E928}"; pub const ARROW_BEND_DOWN_RIGHT: &str = "\u{E929}"; pub const ARROW_BEND_LEFT_DOWN: &str = "\u{E92A}"; pub const ARROW_BEND_LEFT_UP: &str = "\u{E92B}"; pub const ARROW_BEND_RIGHT_DOWN: &str = "\u{E92C}"; pub const ARROW_BEND_RIGHT_UP: &str = "\u{E92D}"; pub const ARROW_BEND_UP_LEFT: &str = "\u{E92E}"; pub const ARROW_BEND_UP_RIGHT: &str = "\u{E92F}"; pub const ARROW_CIRCLE_DOWN_LEFT: &str = "\u{E930}"; pub const ARROW_CIRCLE_DOWN_RIGHT: &str = "\u{E931}"; pub const ARROW_CIRCLE_DOWN: &str = "\u{E932}"; pub const ARROW_CIRCLE_LEFT: &str = "\u{E933}"; pub const ARROW_CIRCLE_RIGHT: &str = "\u{E934}"; pub const ARROW_CIRCLE_UP_LEFT: &str = "\u{E935}"; pub const ARROW_CIRCLE_UP_RIGHT: &str = "\u{E936}"; pub const ARROW_CIRCLE_UP: &str = "\u{E937}"; pub const ARROW_CLOCKWISE: &str = "\u{E938}"; pub const ARROW_COUNTER_CLOCKWISE: &str = "\u{E939}"; pub const ARROW_DOWN_LEFT: &str = "\u{E93A}"; pub const ARROW_DOWN_RIGHT: &str = "\u{E93B}"; pub const ARROW_DOWN: &str = "\u{E93C}"; pub const ARROW_ELBOW_DOWN_LEFT: &str = "\u{E93D}"; pub const ARROW_ELBOW_DOWN_RIGHT: &str = "\u{E93E}"; pub const ARROW_ELBOW_LEFT_DOWN: &str = "\u{E93F}"; pub const ARROW_ELBOW_LEFT: &str = "\u{E940}"; pub const ARROW_ELBOW_LEFT_UP: &str = "\u{E941}"; pub const ARROW_ELBOW_RIGHT_DOWN: &str = "\u{E942}"; pub const ARROW_ELBOW_RIGHT: &str = "\u{E943}"; pub const ARROW_ELBOW_RIGHT_UP: &str = "\u{E944}"; pub const ARROW_ELBOW_UP_LEFT: &str = "\u{E945}"; pub const ARROW_ELBOW_UP_RIGHT: &str = "\u{E946}"; pub const ARROW_FAT_DOWN: &str = "\u{E947}"; pub const ARROW_FAT_LEFT: &str = "\u{E948}"; pub const ARROW_FAT_LINE_DOWN: &str = "\u{E949}"; pub const ARROW_FAT_LINE_LEFT: &str = "\u{E94A}"; pub const ARROW_FAT_LINE_RIGHT: &str = "\u{E94B}"; pub const ARROW_FAT_LINES_DOWN: &str = "\u{E94C}"; pub const ARROW_FAT_LINES_LEFT: &str = "\u{E94D}"; pub const ARROW_FAT_LINES_RIGHT: &str = "\u{E94E}"; pub const ARROW_FAT_LINES_UP: &str = "\u{E94F}"; pub const ARROW_FAT_LINE_UP: &str = "\u{E950}"; pub const ARROW_FAT_RIGHT: &str = "\u{E951}"; pub const ARROW_FAT_UP: &str = "\u{E952}"; pub const ARROW_LEFT: &str = "\u{E953}"; pub const ARROW_LINE_DOWN_LEFT: &str = "\u{E954}"; pub const ARROW_LINE_DOWN_RIGHT: &str = "\u{E955}"; pub const ARROW_LINE_DOWN: &str = "\u{E956}"; pub const ARROW_LINE_LEFT: &str = "\u{E957}"; pub const ARROW_LINE_RIGHT: &str = "\u{E958}"; pub const ARROW_LINE_UP_LEFT: &str = "\u{E959}"; pub const ARROW_LINE_UP_RIGHT: &str = "\u{E95A}"; pub const ARROW_LINE_UP: &str = "\u{E95B}"; pub const ARROW_RIGHT: &str = "\u{E95C}"; pub const ARROWS_CLOCKWISE: &str = "\u{E95D}"; pub const ARROWS_COUNTER_CLOCKWISE: &str = "\u{E95E}"; pub const ARROWS_DOWN_UP: &str = "\u{E95F}"; pub const ARROWS_HORIZONTAL: &str = "\u{E960}"; pub const ARROWS_IN_CARDINAL: &str = "\u{E961}"; pub const ARROWS_IN_LINE_HORIZONTAL: &str = "\u{E962}"; pub const ARROWS_IN_LINE_VERTICAL: &str = "\u{E963}"; pub const ARROWS_IN_SIMPLE: &str = "\u{E964}"; pub const ARROWS_IN: &str = "\u{E965}"; pub const ARROWS_LEFT_RIGHT: &str = "\u{E966}"; pub const ARROWS_MERGE: &str = "\u{E967}"; pub const ARROWS_OUT_CARDINAL: &str = "\u{E968}"; pub const ARROWS_OUT_LINE_HORIZONTAL: &str = "\u{E969}"; pub const ARROWS_OUT_LINE_VERTICAL: &str = "\u{E96A}"; pub const ARROWS_OUT_SIMPLE: &str = "\u{E96B}"; pub const ARROWS_OUT: &str = "\u{E96C}"; pub const ARROW_SQUARE_DOWN_LEFT: &str = "\u{E96D}"; pub const ARROW_SQUARE_DOWN_RIGHT: &str = "\u{E96E}"; pub const ARROW_SQUARE_DOWN: &str = "\u{E96F}"; pub const ARROW_SQUARE_IN: &str = "\u{E970}"; pub const ARROW_SQUARE_LEFT: &str = "\u{E971}"; pub const ARROW_SQUARE_OUT: &str = "\u{E972}"; pub const ARROW_SQUARE_RIGHT: &str = "\u{E973}"; pub const ARROW_SQUARE_UP_LEFT: &str = "\u{E974}"; pub const ARROW_SQUARE_UP_RIGHT: &str = "\u{E975}"; pub const ARROW_SQUARE_UP: &str = "\u{E976}"; pub const ARROWS_SPLIT: &str = "\u{E977}"; pub const ARROWS_VERTICAL: &str = "\u{E978}"; pub const ARROW_U_DOWN_LEFT: &str = "\u{E979}"; pub const ARROW_U_DOWN_RIGHT: &str = "\u{E97A}"; pub const ARROW_U_LEFT_DOWN: &str = "\u{E97B}"; pub const ARROW_U_LEFT_UP: &str = "\u{E97C}"; pub const ARROW_UP_LEFT: &str = "\u{E97D}"; pub const ARROW_UP_RIGHT: &str = "\u{E97E}"; pub const ARROW_UP: &str = "\u{E97F}"; pub const ARROW_U_RIGHT_DOWN: &str = "\u{E980}"; pub const ARROW_U_RIGHT_UP: &str = "\u{E981}"; pub const ARROW_U_UP_LEFT: &str = "\u{E982}"; pub const ARROW_U_UP_RIGHT: &str = "\u{E983}"; pub const ARTICLE_MEDIUM: &str = "\u{E984}"; pub const ARTICLE_NY_TIMES: &str = "\u{E985}"; pub const ARTICLE: &str = "\u{E986}"; pub const ASTERISK_SIMPLE: &str = "\u{E987}"; pub const ASTERISK: &str = "\u{E988}"; pub const ATOM: &str = "\u{E989}"; pub const AT: &str = "\u{E98A}"; pub const BABY: &str = "\u{E98B}"; pub const BACKPACK: &str = "\u{E98C}"; pub const BACKSPACE: &str = "\u{E98D}"; pub const BAG_SIMPLE: &str = "\u{E98E}"; pub const BAG: &str = "\u{E98F}"; pub const BALLOON: &str = "\u{E990}"; pub const BANDAIDS: &str = "\u{E991}"; pub const BANK: &str = "\u{E992}"; pub const BARBELL: &str = "\u{E993}"; pub const BARCODE: &str = "\u{E994}"; pub const BARRICADE: &str = "\u{E995}"; pub const BASEBALL_CAP: &str = "\u{E996}"; pub const BASEBALL: &str = "\u{E997}"; pub const BASKETBALL: &str = "\u{E998}"; pub const BASKET: &str = "\u{E999}"; pub const BATHTUB: &str = "\u{E99A}"; pub const BATTERY_CHARGING: &str = "\u{E99B}"; pub const BATTERY_CHARGING_VERTICAL: &str = "\u{E99C}"; pub const BATTERY_EMPTY: &str = "\u{E99D}"; pub const BATTERY_FULL: &str = "\u{E99E}"; pub const BATTERY_HIGH: &str = "\u{E99F}"; pub const BATTERY_LOW: &str = "\u{E9A0}"; pub const BATTERY_MEDIUM: &str = "\u{E9A1}"; pub const BATTERY_PLUS: &str = "\u{E9A2}"; pub const BATTERY_PLUS_VERTICAL: &str = "\u{E9A3}"; pub const BATTERY_VERTICAL_EMPTY: &str = "\u{E9A4}"; pub const BATTERY_VERTICAL_FULL: &str = "\u{E9A5}"; pub const BATTERY_VERTICAL_HIGH: &str = "\u{E9A6}"; pub const BATTERY_VERTICAL_LOW: &str = "\u{E9A7}"; pub const BATTERY_VERTICAL_MEDIUM: &str = "\u{E9A8}"; pub const BATTERY_WARNING: &str = "\u{E9A9}"; pub const BATTERY_WARNING_VERTICAL: &str = "\u{E9AA}"; pub const BED: &str = "\u{E9AB}"; pub const BEER_BOTTLE: &str = "\u{E9AC}"; pub const BEER_STEIN: &str = "\u{E9AD}"; pub const BEHANCE_LOGO: &str = "\u{E9AE}"; pub const BELL_RINGING: &str = "\u{E9AF}"; pub const BELL_SIMPLE_RINGING: &str = "\u{E9B0}"; pub const BELL_SIMPLE_SLASH: &str = "\u{E9B1}"; pub const BELL_SIMPLE: &str = "\u{E9B2}"; pub const BELL_SIMPLE_Z: &str = "\u{E9B3}"; pub const BELL_SLASH: &str = "\u{E9B4}"; pub const BELL: &str = "\u{E9B5}"; pub const BELL_Z: &str = "\u{E9B6}"; pub const BEZIER_CURVE: &str = "\u{E9B7}"; pub const BICYCLE: &str = "\u{E9B8}"; pub const BINOCULARS: &str = "\u{E9B9}"; pub const BIRD: &str = "\u{E9BA}"; pub const BLUETOOTH_CONNECTED: &str = "\u{E9BB}"; pub const BLUETOOTH_SLASH: &str = "\u{E9BC}"; pub const BLUETOOTH: &str = "\u{E9BD}"; pub const BLUETOOTH_X: &str = "\u{E9BE}"; pub const BOAT: &str = "\u{E9BF}"; pub const BONE: &str = "\u{E9C0}"; pub const BOOK_BOOKMARK: &str = "\u{E9C1}"; pub const BOOKMARK_SIMPLE: &str = "\u{E9C2}"; pub const BOOKMARKS_SIMPLE: &str = "\u{E9C3}"; pub const BOOKMARKS: &str = "\u{E9C4}"; pub const BOOKMARK: &str = "\u{E9C5}"; pub const BOOK_OPEN_TEXT: &str = "\u{E9C6}"; pub const BOOK_OPEN: &str = "\u{E9C7}"; pub const BOOKS: &str = "\u{E9C8}"; pub const BOOK: &str = "\u{E9C9}"; pub const BOOT: &str = "\u{E9CA}"; pub const BOUNDING_BOX: &str = "\u{E9CB}"; pub const BOWL_FOOD: &str = "\u{E9CC}"; pub const BRACKETS_ANGLE: &str = "\u{E9CD}"; pub const BRACKETS_CURLY: &str = "\u{E9CE}"; pub const BRACKETS_ROUND: &str = "\u{E9CF}"; pub const BRACKETS_SQUARE: &str = "\u{E9D0}"; pub const BRAIN: &str = "\u{E9D1}"; pub const BRANDY: &str = "\u{E9D2}"; pub const BRIDGE: &str = "\u{E9D3}"; pub const BRIEFCASE_METAL: &str = "\u{E9D4}"; pub const BRIEFCASE: &str = "\u{E9D5}"; pub const BROADCAST: &str = "\u{E9D6}"; pub const BROOM: &str = "\u{E9D7}"; pub const BROWSERS: &str = "\u{E9D8}"; pub const BROWSER: &str = "\u{E9D9}"; pub const BUG_BEETLE: &str = "\u{E9DA}"; pub const BUG_DROID: &str = "\u{E9DB}"; pub const BUG: &str = "\u{E9DC}"; pub const BUILDINGS: &str = "\u{E9DD}"; pub const BUS: &str = "\u{E9DE}"; pub const BUTTERFLY: &str = "\u{E9DF}"; pub const CACTUS: &str = "\u{E9E0}"; pub const CAKE: &str = "\u{E9E1}"; pub const CALCULATOR: &str = "\u{E9E2}"; pub const CALENDAR_BLANK: &str = "\u{E9E3}"; pub const CALENDAR_CHECK: &str = "\u{E9E4}"; pub const CALENDAR_PLUS: &str = "\u{E9E5}"; pub const CALENDAR: &str = "\u{E9E6}"; pub const CALENDAR_X: &str = "\u{E9E7}"; pub const CALL_BELL: &str = "\u{E9E8}"; pub const CAMERA_PLUS: &str = "\u{E9E9}"; pub const CAMERA_ROTATE: &str = "\u{E9EA}"; pub const CAMERA_SLASH: &str = "\u{E9EB}"; pub const CAMERA: &str = "\u{E9EC}"; pub const CAMPFIRE: &str = "\u{E9ED}"; pub const CARDHOLDER: &str = "\u{E9EE}"; pub const CARDS: &str = "\u{E9EF}"; pub const CARET_CIRCLE_DOUBLE_DOWN: &str = "\u{E9F0}"; pub const CARET_CIRCLE_DOUBLE_LEFT: &str = "\u{E9F1}"; pub const CARET_CIRCLE_DOUBLE_RIGHT: &str = "\u{E9F2}"; pub const CARET_CIRCLE_DOUBLE_UP: &str = "\u{E9F3}"; pub const CARET_CIRCLE_DOWN: &str = "\u{E9F4}"; pub const CARET_CIRCLE_LEFT: &str = "\u{E9F5}"; pub const CARET_CIRCLE_RIGHT: &str = "\u{E9F6}"; pub const CARET_CIRCLE_UP_DOWN: &str = "\u{E9F7}"; pub const CARET_CIRCLE_UP: &str = "\u{E9F8}"; pub const CARET_DOUBLE_DOWN: &str = "\u{E9F9}"; pub const CARET_DOUBLE_LEFT: &str = "\u{E9FA}"; pub const CARET_DOUBLE_RIGHT: &str = "\u{E9FB}"; pub const CARET_DOUBLE_UP: &str = "\u{E9FC}"; pub const CARET_DOWN: &str = "\u{E9FD}"; pub const CARET_LEFT: &str = "\u{E9FE}"; pub const CARET_RIGHT: &str = "\u{E9FF}"; pub const CARET_UP_DOWN: &str = "\u{EA00}"; pub const CARET_UP: &str = "\u{EA01}"; pub const CAR_PROFILE: &str = "\u{EA02}"; pub const CARROT: &str = "\u{EA03}"; pub const CAR_SIMPLE: &str = "\u{EA04}"; pub const CAR: &str = "\u{EA05}"; pub const CASSETTE_TAPE: &str = "\u{EA06}"; pub const CASTLE_TURRET: &str = "\u{EA07}"; pub const CAT: &str = "\u{EA08}"; pub const CELL_SIGNAL_FULL: &str = "\u{EA09}"; pub const CELL_SIGNAL_HIGH: &str = "\u{EA0A}"; pub const CELL_SIGNAL_LOW: &str = "\u{EA0B}"; pub const CELL_SIGNAL_MEDIUM: &str = "\u{EA0C}"; pub const CELL_SIGNAL_NONE: &str = "\u{EA0D}"; pub const CELL_SIGNAL_SLASH: &str = "\u{EA0E}"; pub const CELL_SIGNAL_X: &str = "\u{EA0F}"; pub const CERTIFICATE: &str = "\u{EA10}"; pub const CHAIR: &str = "\u{EA11}"; pub const CHALKBOARD_SIMPLE: &str = "\u{EA12}"; pub const CHALKBOARD_TEACHER: &str = "\u{EA13}"; pub const CHALKBOARD: &str = "\u{EA14}"; pub const CHAMPAGNE: &str = "\u{EA15}"; pub const CHARGING_STATION: &str = "\u{EA16}"; pub const CHART_BAR_HORIZONTAL: &str = "\u{EA17}"; pub const CHART_BAR: &str = "\u{EA18}"; pub const CHART_DONUT: &str = "\u{EA19}"; pub const CHART_LINE_DOWN: &str = "\u{EA1A}"; pub const CHART_LINE: &str = "\u{EA1B}"; pub const CHART_LINE_UP: &str = "\u{EA1C}"; pub const CHART_PIE_SLICE: &str = "\u{EA1D}"; pub const CHART_PIE: &str = "\u{EA1E}"; pub const CHART_POLAR: &str = "\u{EA1F}"; pub const CHART_SCATTER: &str = "\u{EA20}"; pub const CHAT_CENTERED_DOTS: &str = "\u{EA21}"; pub const CHAT_CENTERED_TEXT: &str = "\u{EA22}"; pub const CHAT_CENTERED: &str = "\u{EA23}"; pub const CHAT_CIRCLE_DOTS: &str = "\u{EA24}"; pub const CHAT_CIRCLE_TEXT: &str = "\u{EA25}"; pub const CHAT_CIRCLE: &str = "\u{EA26}"; pub const CHAT_DOTS: &str = "\u{EA27}"; pub const CHATS_CIRCLE: &str = "\u{EA28}"; pub const CHATS_TEARDROP: &str = "\u{EA29}"; pub const CHATS: &str = "\u{EA2A}"; pub const CHAT_TEARDROP_DOTS: &str = "\u{EA2B}"; pub const CHAT_TEARDROP_TEXT: &str = "\u{EA2C}"; pub const CHAT_TEARDROP: &str = "\u{EA2D}"; pub const CHAT_TEXT: &str = "\u{EA2E}"; pub const CHAT: &str = "\u{EA2F}"; pub const CHECK_CIRCLE: &str = "\u{EA30}"; pub const CHECK_FAT: &str = "\u{EA31}"; pub const CHECK_SQUARE_OFFSET: &str = "\u{EA32}"; pub const CHECK_SQUARE: &str = "\u{EA33}"; pub const CHECKS: &str = "\u{EA34}"; pub const CHECK: &str = "\u{EA35}"; pub const CHURCH: &str = "\u{EA36}"; pub const CIRCLE_DASHED: &str = "\u{EA37}"; pub const CIRCLE_HALF: &str = "\u{EA38}"; pub const CIRCLE_HALF_TILT: &str = "\u{EA39}"; pub const CIRCLE_NOTCH: &str = "\u{EA3A}"; pub const CIRCLES_FOUR: &str = "\u{EA3B}"; pub const CIRCLES_THREE_PLUS: &str = "\u{EA3C}"; pub const CIRCLES_THREE: &str = "\u{EA3D}"; pub const CIRCLE: &str = "\u{EA3E}"; pub const CIRCUITRY: &str = "\u{EA3F}"; pub const CLIPBOARD_TEXT: &str = "\u{EA40}"; pub const CLIPBOARD: &str = "\u{EA41}"; pub const CLOCK_AFTERNOON: &str = "\u{EA42}"; pub const CLOCK_CLOCKWISE: &str = "\u{EA43}"; pub const CLOCK_COUNTDOWN: &str = "\u{EA44}"; pub const CLOCK_COUNTER_CLOCKWISE: &str = "\u{EA45}"; pub const CLOCK: &str = "\u{EA46}"; pub const CLOSED_CAPTIONING: &str = "\u{EA47}"; pub const CLOUD_ARROW_DOWN: &str = "\u{EA48}"; pub const CLOUD_ARROW_UP: &str = "\u{EA49}"; pub const CLOUD_CHECK: &str = "\u{EA4A}"; pub const CLOUD_FOG: &str = "\u{EA4B}"; pub const CLOUD_LIGHTNING: &str = "\u{EA4C}"; pub const CLOUD_MOON: &str = "\u{EA4D}"; pub const CLOUD_RAIN: &str = "\u{EA4E}"; pub const CLOUD_SLASH: &str = "\u{EA4F}"; pub const CLOUD_SNOW: &str = "\u{EA50}"; pub const CLOUD_SUN: &str = "\u{EA51}"; pub const CLOUD: &str = "\u{EA52}"; pub const CLOUD_WARNING: &str = "\u{EA53}"; pub const CLOUD_X: &str = "\u{EA54}"; pub const CLUB: &str = "\u{EA55}"; pub const COAT_HANGER: &str = "\u{EA56}"; pub const CODA_LOGO: &str = "\u{EA57}"; pub const CODE_BLOCK: &str = "\u{EA58}"; pub const CODEPEN_LOGO: &str = "\u{EA59}"; pub const CODESANDBOX_LOGO: &str = "\u{EA5A}"; pub const CODE_SIMPLE: &str = "\u{EA5B}"; pub const CODE: &str = "\u{EA5C}"; pub const COFFEE: &str = "\u{EA5D}"; pub const COINS: &str = "\u{EA5E}"; pub const COIN: &str = "\u{EA5F}"; pub const COIN_VERTICAL: &str = "\u{EA60}"; pub const COLUMNS: &str = "\u{EA61}"; pub const COMMAND: &str = "\u{EA62}"; pub const COMPASS: &str = "\u{EA63}"; pub const COMPASS_TOOL: &str = "\u{EA64}"; pub const COMPUTER_TOWER: &str = "\u{EA65}"; pub const CONFETTI: &str = "\u{EA66}"; pub const CONTACTLESS_PAYMENT: &str = "\u{EA67}"; pub const CONTROL: &str = "\u{EA68}"; pub const COOKIE: &str = "\u{EA69}"; pub const COOKING_POT: &str = "\u{EA6A}"; pub const COPYLEFT: &str = "\u{EA6B}"; pub const COPYRIGHT: &str = "\u{EA6C}"; pub const COPY_SIMPLE: &str = "\u{EA6D}"; pub const COPY: &str = "\u{EA6E}"; pub const CORNERS_IN: &str = "\u{EA6F}"; pub const CORNERS_OUT: &str = "\u{EA70}"; pub const COUCH: &str = "\u{EA71}"; pub const CPU: &str = "\u{EA72}"; pub const CREDIT_CARD: &str = "\u{EA73}"; pub const CROP: &str = "\u{EA74}"; pub const CROSSHAIR_SIMPLE: &str = "\u{EA75}"; pub const CROSSHAIR: &str = "\u{EA76}"; pub const CROSS: &str = "\u{EA77}"; pub const CROWN_SIMPLE: &str = "\u{EA78}"; pub const CROWN: &str = "\u{EA79}"; pub const CUBE_FOCUS: &str = "\u{EA7A}"; pub const CUBE: &str = "\u{EA7B}"; pub const CUBE_TRANSPARENT: &str = "\u{EA7C}"; pub const CURRENCY_BTC: &str = "\u{EA7D}"; pub const CURRENCY_CIRCLE_DOLLAR: &str = "\u{EA7E}"; pub const CURRENCY_CNY: &str = "\u{EA7F}"; pub const CURRENCY_DOLLAR_SIMPLE: &str = "\u{EA80}"; pub const CURRENCY_DOLLAR: &str = "\u{EA81}"; pub const CURRENCY_ETH: &str = "\u{EA82}"; pub const CURRENCY_EUR: &str = "\u{EA83}"; pub const CURRENCY_GBP: &str = "\u{EA84}"; pub const CURRENCY_INR: &str = "\u{EA85}"; pub const CURRENCY_JPY: &str = "\u{EA86}"; pub const CURRENCY_KRW: &str = "\u{EA87}"; pub const CURRENCY_KZT: &str = "\u{EA88}"; pub const CURRENCY_NGN: &str = "\u{EA89}"; pub const CURRENCY_RUB: &str = "\u{EA8A}"; pub const CURSOR_CLICK: &str = "\u{EA8B}"; pub const CURSOR_TEXT: &str = "\u{EA8C}"; pub const CURSOR: &str = "\u{EA8D}"; pub const CYLINDER: &str = "\u{EA8E}"; pub const DATABASE: &str = "\u{EA8F}"; pub const DESKTOP: &str = "\u{EA90}"; pub const DESKTOP_TOWER: &str = "\u{EA91}"; pub const DETECTIVE: &str = "\u{EA92}"; pub const DEVICE_MOBILE_CAMERA: &str = "\u{EA93}"; pub const DEVICE_MOBILE_SPEAKER: &str = "\u{EA94}"; pub const DEVICE_MOBILE: &str = "\u{EA95}"; pub const DEVICES: &str = "\u{EA96}"; pub const DEVICE_TABLET_CAMERA: &str = "\u{EA97}"; pub const DEVICE_TABLET_SPEAKER: &str = "\u{EA98}"; pub const DEVICE_TABLET: &str = "\u{EA99}"; pub const DEV_TO_LOGO: &str = "\u{EA9A}"; pub const DIAMONDS_FOUR: &str = "\u{EA9B}"; pub const DIAMOND: &str = "\u{EA9C}"; pub const DICE_FIVE: &str = "\u{EA9D}"; pub const DICE_FOUR: &str = "\u{EA9E}"; pub const DICE_ONE: &str = "\u{EA9F}"; pub const DICE_SIX: &str = "\u{EAA0}"; pub const DICE_THREE: &str = "\u{EAA1}"; pub const DICE_TWO: &str = "\u{EAA2}"; pub const DISCORD_LOGO: &str = "\u{EAA3}"; pub const DISC: &str = "\u{EAA4}"; pub const DIVIDE: &str = "\u{EAA5}"; pub const DNA: &str = "\u{EAA6}"; pub const DOG: &str = "\u{EAA7}"; pub const DOOR_OPEN: &str = "\u{EAA8}"; pub const DOOR: &str = "\u{EAA9}"; pub const DOT_OUTLINE: &str = "\u{EAAA}"; pub const DOTS_NINE: &str = "\u{EAAB}"; pub const DOTS_SIX: &str = "\u{EAAC}"; pub const DOTS_SIX_VERTICAL: &str = "\u{EAAD}"; pub const DOTS_THREE_CIRCLE: &str = "\u{EAAE}"; pub const DOTS_THREE_CIRCLE_VERTICAL: &str = "\u{EAAF}"; pub const DOTS_THREE_OUTLINE: &str = "\u{EAB0}"; pub const DOTS_THREE_OUTLINE_VERTICAL: &str = "\u{EAB1}"; pub const DOTS_THREE: &str = "\u{EAB2}"; pub const DOTS_THREE_VERTICAL: &str = "\u{EAB3}"; pub const DOT: &str = "\u{EAB4}"; pub const DOWNLOAD_SIMPLE: &str = "\u{EAB5}"; pub const DOWNLOAD: &str = "\u{EAB6}"; pub const DRESS: &str = "\u{EAB7}"; pub const DRIBBBLE_LOGO: &str = "\u{EAB8}"; pub const DROPBOX_LOGO: &str = "\u{EAB9}"; pub const DROP_HALF_BOTTOM: &str = "\u{EABA}"; pub const DROP_HALF: &str = "\u{EABB}"; pub const DROP: &str = "\u{EABC}"; pub const EAR_SLASH: &str = "\u{EABD}"; pub const EAR: &str = "\u{EABE}"; pub const EGG_CRACK: &str = "\u{EABF}"; pub const EGG: &str = "\u{EAC0}"; pub const EJECT_SIMPLE: &str = "\u{EAC1}"; pub const EJECT: &str = "\u{EAC2}"; pub const ELEVATOR: &str = "\u{EAC3}"; pub const ENGINE: &str = "\u{EAC4}"; pub const ENVELOPE_OPEN: &str = "\u{EAC5}"; pub const ENVELOPE_SIMPLE_OPEN: &str = "\u{EAC6}"; pub const ENVELOPE_SIMPLE: &str = "\u{EAC7}"; pub const ENVELOPE: &str = "\u{EAC8}"; pub const EQUALIZER: &str = "\u{EAC9}"; pub const EQUALS: &str = "\u{EACA}"; pub const ERASER: &str = "\u{EACB}"; pub const ESCALATOR_DOWN: &str = "\u{EACC}"; pub const ESCALATOR_UP: &str = "\u{EACD}"; pub const EXAM: &str = "\u{EACE}"; pub const EXCLUDE_SQUARE: &str = "\u{EACF}"; pub const EXCLUDE: &str = "\u{EAD0}"; pub const EXPORT: &str = "\u{EAD1}"; pub const EYE_CLOSED: &str = "\u{EAD2}"; pub const EYEDROPPER_SAMPLE: &str = "\u{EAD3}"; pub const EYEDROPPER: &str = "\u{EAD4}"; pub const EYEGLASSES: &str = "\u{EAD5}"; pub const EYE_SLASH: &str = "\u{EAD6}"; pub const EYE: &str = "\u{EAD7}"; pub const FACEBOOK_LOGO: &str = "\u{EAD8}"; pub const FACE_MASK: &str = "\u{EAD9}"; pub const FACTORY: &str = "\u{EADA}"; pub const FADERS_HORIZONTAL: &str = "\u{EADB}"; pub const FADERS: &str = "\u{EADC}"; pub const FAN: &str = "\u{EADD}"; pub const FAST_FORWARD_CIRCLE: &str = "\u{EADE}"; pub const FAST_FORWARD: &str = "\u{EADF}"; pub const FEATHER: &str = "\u{EAE0}"; pub const FIGMA_LOGO: &str = "\u{EAE1}"; pub const FILE_ARCHIVE: &str = "\u{EAE2}"; pub const FILE_ARROW_DOWN: &str = "\u{EAE3}"; pub const FILE_ARROW_UP: &str = "\u{EAE4}"; pub const FILE_AUDIO: &str = "\u{EAE5}"; pub const FILE_CLOUD: &str = "\u{EAE6}"; pub const FILE_CODE: &str = "\u{EAE7}"; pub const FILE_CSS: &str = "\u{EAE8}"; pub const FILE_CSV: &str = "\u{EAE9}"; pub const FILE_DASHED: &str = "\u{EAEA}"; pub const FILE_DOTTED: &str = "\u{EAEA}"; pub const FILE_DOC: &str = "\u{EAEB}"; pub const FILE_HTML: &str = "\u{EAEC}"; pub const FILE_IMAGE: &str = "\u{EAED}"; pub const FILE_JPG: &str = "\u{EAEE}"; pub const FILE_JS: &str = "\u{EAEF}"; pub const FILE_JSX: &str = "\u{EAF0}"; pub const FILE_LOCK: &str = "\u{EAF1}"; pub const FILE_MAGNIFYING_GLASS: &str = "\u{EAF2}"; pub const FILE_SEARCH: &str = "\u{EAF2}"; pub const FILE_MINUS: &str = "\u{EAF3}"; pub const FILE_PDF: &str = "\u{EAF4}"; pub const FILE_PLUS: &str = "\u{EAF5}"; pub const FILE_PNG: &str = "\u{EAF6}"; pub const FILE_PPT: &str = "\u{EAF7}"; pub const FILE_RS: &str = "\u{EAF8}"; pub const FILE_SQL: &str = "\u{EAF9}"; pub const FILES: &str = "\u{EAFA}"; pub const FILE_SVG: &str = "\u{EAFB}"; pub const FILE_TEXT: &str = "\u{EAFC}"; pub const FILE: &str = "\u{EAFD}"; pub const FILE_TS: &str = "\u{EAFE}"; pub const FILE_TSX: &str = "\u{EAFF}"; pub const FILE_VIDEO: &str = "\u{EB00}"; pub const FILE_VUE: &str = "\u{EB01}"; pub const FILE_XLS: &str = "\u{EB02}"; pub const FILE_X: &str = "\u{EB03}"; pub const FILE_ZIP: &str = "\u{EB04}"; pub const FILM_REEL: &str = "\u{EB05}"; pub const FILM_SCRIPT: &str = "\u{EB06}"; pub const FILM_SLATE: &str = "\u{EB07}"; pub const FILM_STRIP: &str = "\u{EB08}"; pub const FINGERPRINT_SIMPLE: &str = "\u{EB09}"; pub const FINGERPRINT: &str = "\u{EB0A}"; pub const FINN_THE_HUMAN: &str = "\u{EB0B}"; pub const FIRE_EXTINGUISHER: &str = "\u{EB0C}"; pub const FIRE_SIMPLE: &str = "\u{EB0D}"; pub const FIRE: &str = "\u{EB0E}"; pub const FIRST_AID_KIT: &str = "\u{EB0F}"; pub const FIRST_AID: &str = "\u{EB10}"; pub const FISH_SIMPLE: &str = "\u{EB11}"; pub const FISH: &str = "\u{EB12}"; pub const FLAG_BANNER: &str = "\u{EB13}"; pub const FLAG_CHECKERED: &str = "\u{EB14}"; pub const FLAG_PENNANT: &str = "\u{EB15}"; pub const FLAG: &str = "\u{EB16}"; pub const FLAME: &str = "\u{EB17}"; pub const FLASHLIGHT: &str = "\u{EB18}"; pub const FLASK: &str = "\u{EB19}"; pub const FLOPPY_DISK_BACK: &str = "\u{EB1A}"; pub const FLOPPY_DISK: &str = "\u{EB1B}"; pub const FLOW_ARROW: &str = "\u{EB1C}"; pub const FLOWER_LOTUS: &str = "\u{EB1D}"; pub const FLOWER: &str = "\u{EB1E}"; pub const FLOWER_TULIP: &str = "\u{EB1F}"; pub const FLYING_SAUCER: &str = "\u{EB20}"; pub const FOLDER_DASHED: &str = "\u{EB21}"; pub const FOLDER_DOTTED: &str = "\u{EB21}"; pub const FOLDER_LOCK: &str = "\u{EB22}"; pub const FOLDER_MINUS: &str = "\u{EB23}"; pub const FOLDER_NOTCH_MINUS: &str = "\u{EB24}"; pub const FOLDER_NOTCH_OPEN: &str = "\u{EB25}"; pub const FOLDER_NOTCH_PLUS: &str = "\u{EB26}"; pub const FOLDER_NOTCH: &str = "\u{EB27}"; pub const FOLDER_OPEN: &str = "\u{EB28}"; pub const FOLDER_PLUS: &str = "\u{EB29}"; pub const FOLDER_SIMPLE_DASHED: &str = "\u{EB2A}"; pub const FOLDER_SIMPLE_DOTTED: &str = "\u{EB2A}"; pub const FOLDER_SIMPLE_LOCK: &str = "\u{EB2B}"; pub const FOLDER_SIMPLE_MINUS: &str = "\u{EB2C}"; pub const FOLDER_SIMPLE_PLUS: &str = "\u{EB2D}"; pub const FOLDER_SIMPLE_STAR: &str = "\u{EB2E}"; pub const FOLDER_SIMPLE: &str = "\u{EB2F}"; pub const FOLDER_SIMPLE_USER: &str = "\u{EB30}"; pub const FOLDER_STAR: &str = "\u{EB31}"; pub const FOLDERS: &str = "\u{EB32}"; pub const FOLDER: &str = "\u{EB33}"; pub const FOLDER_USER: &str = "\u{EB34}"; pub const FOOTBALL: &str = "\u{EB35}"; pub const FOOTPRINTS: &str = "\u{EB36}"; pub const FORK_KNIFE: &str = "\u{EB37}"; pub const FRAME_CORNERS: &str = "\u{EB38}"; pub const FRAMER_LOGO: &str = "\u{EB39}"; pub const FUNCTION: &str = "\u{EB3A}"; pub const FUNNEL_SIMPLE: &str = "\u{EB3B}"; pub const FUNNEL: &str = "\u{EB3C}"; pub const GAME_CONTROLLER: &str = "\u{EB3D}"; pub const GARAGE: &str = "\u{EB3E}"; pub const GAS_CAN: &str = "\u{EB3F}"; pub const GAS_PUMP: &str = "\u{EB40}"; pub const GAUGE: &str = "\u{EB41}"; pub const GAVEL: &str = "\u{EB42}"; pub const GEAR_FINE: &str = "\u{EB43}"; pub const GEAR_SIX: &str = "\u{EB44}"; pub const GEAR: &str = "\u{EB45}"; pub const GENDER_FEMALE: &str = "\u{EB46}"; pub const GENDER_INTERSEX: &str = "\u{EB47}"; pub const GENDER_MALE: &str = "\u{EB48}"; pub const GENDER_NEUTER: &str = "\u{EB49}"; pub const GENDER_NONBINARY: &str = "\u{EB4A}"; pub const GENDER_TRANSGENDER: &str = "\u{EB4B}"; pub const GHOST: &str = "\u{EB4C}"; pub const GIF: &str = "\u{EB4D}"; pub const GIFT: &str = "\u{EB4E}"; pub const GIT_BRANCH: &str = "\u{EB4F}"; pub const GIT_COMMIT: &str = "\u{EB50}"; pub const GIT_DIFF: &str = "\u{EB51}"; pub const GIT_FORK: &str = "\u{EB52}"; pub const GITHUB_LOGO: &str = "\u{EB53}"; pub const GITLAB_LOGO_SIMPLE: &str = "\u{EB54}"; pub const GITLAB_LOGO: &str = "\u{EB55}"; pub const GIT_MERGE: &str = "\u{EB56}"; pub const GIT_PULL_REQUEST: &str = "\u{EB57}"; pub const GLOBE_HEMISPHERE_EAST: &str = "\u{EB58}"; pub const GLOBE_HEMISPHERE_WEST: &str = "\u{EB59}"; pub const GLOBE_SIMPLE: &str = "\u{EB5A}"; pub const GLOBE_STAND: &str = "\u{EB5B}"; pub const GLOBE: &str = "\u{EB5C}"; pub const GOGGLES: &str = "\u{EB5D}"; pub const GOODREADS_LOGO: &str = "\u{EB5E}"; pub const GOOGLE_CARDBOARD_LOGO: &str = "\u{EB5F}"; pub const GOOGLE_CHROME_LOGO: &str = "\u{EB60}"; pub const GOOGLE_DRIVE_LOGO: &str = "\u{EB61}"; pub const GOOGLE_LOGO: &str = "\u{EB62}"; pub const GOOGLE_PHOTOS_LOGO: &str = "\u{EB63}"; pub const GOOGLE_PLAY_LOGO: &str = "\u{EB64}"; pub const GOOGLE_PODCASTS_LOGO: &str = "\u{EB65}"; pub const GRADIENT: &str = "\u{EB66}"; pub const GRADUATION_CAP: &str = "\u{EB67}"; pub const GRAINS_SLASH: &str = "\u{EB68}"; pub const GRAINS: &str = "\u{EB69}"; pub const GRAPH: &str = "\u{EB6A}"; pub const GRID_FOUR: &str = "\u{EB6B}"; pub const GRID_NINE: &str = "\u{EB6C}"; pub const GUITAR: &str = "\u{EB6D}"; pub const HAMBURGER: &str = "\u{EB6E}"; pub const HAMMER: &str = "\u{EB6F}"; pub const HANDBAG_SIMPLE: &str = "\u{EB70}"; pub const HANDBAG: &str = "\u{EB71}"; pub const HAND_COINS: &str = "\u{EB72}"; pub const HAND_EYE: &str = "\u{EB73}"; pub const HAND_FIST: &str = "\u{EB74}"; pub const HAND_GRABBING: &str = "\u{EB75}"; pub const HAND_HEART: &str = "\u{EB76}"; pub const HAND_PALM: &str = "\u{EB77}"; pub const HAND_POINTING: &str = "\u{EB78}"; pub const HANDS_CLAPPING: &str = "\u{EB79}"; pub const HANDSHAKE: &str = "\u{EB7A}"; pub const HAND_SOAP: &str = "\u{EB7B}"; pub const HANDS_PRAYING: &str = "\u{EB7C}"; pub const HAND_SWIPE_LEFT: &str = "\u{EB7D}"; pub const HAND_SWIPE_RIGHT: &str = "\u{EB7E}"; pub const HAND_TAP: &str = "\u{EB7F}"; pub const HAND: &str = "\u{EB80}"; pub const HAND_WAVING: &str = "\u{EB81}"; pub const HARD_DRIVES: &str = "\u{EB82}"; pub const HARD_DRIVE: &str = "\u{EB83}"; pub const HASH_STRAIGHT: &str = "\u{EB84}"; pub const HASH: &str = "\u{EB85}"; pub const HEADLIGHTS: &str = "\u{EB86}"; pub const HEADPHONES: &str = "\u{EB87}"; pub const HEADSET: &str = "\u{EB88}"; pub const HEARTBEAT: &str = "\u{EB89}"; pub const HEART_BREAK: &str = "\u{EB8A}"; pub const HEART_HALF: &str = "\u{EB8B}"; pub const HEART_STRAIGHT_BREAK: &str = "\u{EB8C}"; pub const HEART_STRAIGHT: &str = "\u{EB8D}"; pub const HEART: &str = "\u{EB8E}"; pub const HEXAGON: &str = "\u{EB8F}"; pub const HIGH_HEEL: &str = "\u{EB90}"; pub const HIGHLIGHTER_CIRCLE: &str = "\u{EB91}"; pub const HOODIE: &str = "\u{EB92}"; pub const HORSE: &str = "\u{EB93}"; pub const HOURGLASS_HIGH: &str = "\u{EB94}"; pub const HOURGLASS_LOW: &str = "\u{EB95}"; pub const HOURGLASS_MEDIUM: &str = "\u{EB96}"; pub const HOURGLASS_SIMPLE_HIGH: &str = "\u{EB97}"; pub const HOURGLASS_SIMPLE_LOW: &str = "\u{EB98}"; pub const HOURGLASS_SIMPLE_MEDIUM: &str = "\u{EB99}"; pub const HOURGLASS_SIMPLE: &str = "\u{EB9A}"; pub const HOURGLASS: &str = "\u{EB9B}"; pub const HOUSE_LINE: &str = "\u{EB9C}"; pub const HOUSE_SIMPLE: &str = "\u{EB9D}"; pub const HOUSE: &str = "\u{EB9E}"; pub const ICE_CREAM: &str = "\u{EB9F}"; pub const IDENTIFICATION_BADGE: &str = "\u{EBA0}"; pub const IDENTIFICATION_CARD: &str = "\u{EBA1}"; pub const IMAGE_SQUARE: &str = "\u{EBA2}"; pub const IMAGES_SQUARE: &str = "\u{EBA3}"; pub const IMAGES: &str = "\u{EBA4}"; pub const IMAGE: &str = "\u{EBA5}"; pub const INFINITY: &str = "\u{EBA6}"; pub const INFO: &str = "\u{EBA7}"; pub const INSTAGRAM_LOGO: &str = "\u{EBA8}"; pub const INTERSECT_SQUARE: &str = "\u{EBA9}"; pub const INTERSECT: &str = "\u{EBAA}"; pub const INTERSECT_THREE: &str = "\u{EBAB}"; pub const JEEP: &str = "\u{EBAC}"; pub const KANBAN: &str = "\u{EBAD}"; pub const KEYBOARD: &str = "\u{EBAE}"; pub const KEYHOLE: &str = "\u{EBAF}"; pub const KEY_RETURN: &str = "\u{EBB0}"; pub const KEY: &str = "\u{EBB1}"; pub const KNIFE: &str = "\u{EBB2}"; pub const LADDER_SIMPLE: &str = "\u{EBB3}"; pub const LADDER: &str = "\u{EBB4}"; pub const LAMP: &str = "\u{EBB5}"; pub const LAPTOP: &str = "\u{EBB6}"; pub const LAYOUT: &str = "\u{EBB7}"; pub const LEAF: &str = "\u{EBB8}"; pub const LIFEBUOY: &str = "\u{EBB9}"; pub const LIGHTBULB_FILAMENT: &str = "\u{EBBA}"; pub const LIGHTBULB: &str = "\u{EBBB}"; pub const LIGHTHOUSE: &str = "\u{EBBC}"; pub const LIGHTNING_A: &str = "\u{EBBD}"; pub const LIGHTNING_SLASH: &str = "\u{EBBE}"; pub const LIGHTNING: &str = "\u{EBBF}"; pub const LINE_SEGMENTS: &str = "\u{EBC0}"; pub const LINE_SEGMENT: &str = "\u{EBC1}"; pub const LINK_BREAK: &str = "\u{EBC2}"; pub const LINKEDIN_LOGO: &str = "\u{EBC3}"; pub const LINK_SIMPLE_BREAK: &str = "\u{EBC4}"; pub const LINK_SIMPLE_HORIZONTAL_BREAK: &str = "\u{EBC5}"; pub const LINK_SIMPLE_HORIZONTAL: &str = "\u{EBC6}"; pub const LINK_SIMPLE: &str = "\u{EBC7}"; pub const LINK: &str = "\u{EBC8}"; pub const LINUX_LOGO: &str = "\u{EBC9}"; pub const LIST_BULLETS: &str = "\u{EBCA}"; pub const LIST_CHECKS: &str = "\u{EBCB}"; pub const LIST_DASHES: &str = "\u{EBCC}"; pub const LIST_MAGNIFYING_GLASS: &str = "\u{EBCD}"; pub const LIST_NUMBERS: &str = "\u{EBCE}"; pub const LIST_PLUS: &str = "\u{EBCF}"; pub const LIST: &str = "\u{EBD0}"; pub const LOCKERS: &str = "\u{EBD1}"; pub const LOCK_KEY_OPEN: &str = "\u{EBD2}"; pub const LOCK_KEY: &str = "\u{EBD3}"; pub const LOCK_LAMINATED_OPEN: &str = "\u{EBD4}"; pub const LOCK_LAMINATED: &str = "\u{EBD5}"; pub const LOCK_OPEN: &str = "\u{EBD6}"; pub const LOCK_SIMPLE_OPEN: &str = "\u{EBD7}"; pub const LOCK_SIMPLE: &str = "\u{EBD8}"; pub const LOCK: &str = "\u{EBD9}"; pub const MAGIC_WAND: &str = "\u{EBDA}"; pub const MAGNET_STRAIGHT: &str = "\u{EBDB}"; pub const MAGNET: &str = "\u{EBDC}"; pub const MAGNIFYING_GLASS_MINUS: &str = "\u{EBDD}"; pub const MAGNIFYING_GLASS_PLUS: &str = "\u{EBDE}"; pub const MAGNIFYING_GLASS: &str = "\u{EBDF}"; pub const MAP_PIN_LINE: &str = "\u{EBE0}"; pub const MAP_PIN: &str = "\u{EBE1}"; pub const MAP_TRIFOLD: &str = "\u{EBE2}"; pub const MARKER_CIRCLE: &str = "\u{EBE3}"; pub const MARTINI: &str = "\u{EBE4}"; pub const MASK_HAPPY: &str = "\u{EBE5}"; pub const MASK_SAD: &str = "\u{EBE6}"; pub const MATH_OPERATIONS: &str = "\u{EBE7}"; pub const MEDAL_MILITARY: &str = "\u{EBE8}"; pub const MEDAL: &str = "\u{EBE9}"; pub const MEDIUM_LOGO: &str = "\u{EBEA}"; pub const MEGAPHONE_SIMPLE: &str = "\u{EBEB}"; pub const MEGAPHONE: &str = "\u{EBEC}"; pub const MESSENGER_LOGO: &str = "\u{EBED}"; pub const META_LOGO: &str = "\u{EBEE}"; pub const METRONOME: &str = "\u{EBEF}"; pub const MICROPHONE_SLASH: &str = "\u{EBF0}"; pub const MICROPHONE_STAGE: &str = "\u{EBF1}"; pub const MICROPHONE: &str = "\u{EBF2}"; pub const MICROSOFT_EXCEL_LOGO: &str = "\u{EBF3}";
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
true
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/rust_wasi_example/src/lib.rs
packages/rust_wasi_example/src/lib.rs
use std::{ffi::c_char, fs::Metadata, time::SystemTime}; #[no_mangle] pub extern "C" fn print_hello() { println!("Hello, world! 2"); } #[no_mangle] pub extern "C" fn stderr_log(msg_utf16: *const u16, msg_utf16_length: u32) { let msg = String::from_utf16(unsafe { std::slice::from_raw_parts(msg_utf16, msg_utf16_length.try_into().unwrap()) }) .unwrap(); let flt = unsafe { translate(msg_utf16_length.try_into().unwrap()) }; let err = format!("{} {}\n", flt, msg); // TODO: eprintln!("{} {}", flt, err); splits into multiple (5) lines eprint!("{}", err); } #[no_mangle] pub extern "C" fn read_file_size(path: *const c_char) -> u64 { let path = unsafe { std::ffi::CStr::from_ptr(path) }; let metadata = std::fs::metadata(path.to_str().unwrap()); if let Err(err) = &metadata { let err = format!("{path:?} {err:?}"); eprintln!("{err}"); } metadata.unwrap().len() } // TODO: test default -> Rust FileData -> memory bytes pointer -> Dart FileData // #[no_mangle] // pub extern "C" fn file_data(path_utf8: *const u8, path_utf8_length: u32) -> FileData { // let path = std::str::from_utf8(unsafe { // std::slice::from_raw_parts(path_utf8, path_utf8_length.try_into().unwrap()) // }) // .unwrap(); // let metadata = std::fs::metadata(path).unwrap(); // metadata.into() // } #[no_mangle] pub extern "C" fn file_data_raw(path_utf8: *const u8, path_utf8_length: u32) -> *const u8 { let path = std::str::from_utf8(unsafe { std::slice::from_raw_parts(path_utf8, path_utf8_length.try_into().unwrap()) }) .unwrap(); let metadata = std::fs::metadata(path).unwrap(); let data: FileData = metadata.into(); let mut bytes = Vec::new(); data.append_bytes(&mut bytes); forget_and_return_pointer(bytes) } pub struct FileData { pub size: u64, pub read_only: bool, pub modified: Option<u64>, pub accessed: Option<u64>, pub created: Option<u64>, } impl From<Metadata> for FileData { fn from(metadata: Metadata) -> Self { Self { size: metadata.len(), read_only: metadata.permissions().readonly(), modified: metadata.modified().ok().as_ref().map(timestamp), accessed: metadata.accessed().ok().as_ref().map(timestamp), created: metadata.created().ok().as_ref().map(timestamp), } } } impl FileData { fn append_bytes(&self, bytes: &mut Vec<u8>) { bytes.extend(self.size.to_ne_bytes()); bytes.push(if self.read_only { 1 } else { 0 }); append_option(bytes, &self.modified, |bytes, a| { bytes.extend(a.to_ne_bytes()) }); append_option(bytes, &self.accessed, |bytes, a| { bytes.extend(a.to_ne_bytes()) }); append_option(bytes, &self.created, |bytes, a| { bytes.extend(a.to_ne_bytes()) }); } } // final bool captureStdout; // final bool captureStderr; // final bool inheritStdin; #[no_mangle] pub extern "C" fn current_time() -> u64 { timestamp(&std::time::SystemTime::now()) } #[no_mangle] pub extern "C" fn get_args() -> *const u8 { // Vec::from_raw_parts(ptr, length, capacity); let mut bytes = Vec::new(); bytes.extend(vec_size(std::env::args())); std::env::args().for_each(|arg| { append_str(&mut bytes, &arg); }); forget_and_return_pointer(bytes) } #[no_mangle] pub unsafe extern "C" fn dealloc(pointer: *mut u8, bytes: usize) { let data = Vec::from_raw_parts(pointer, bytes, bytes); std::mem::drop(data); } #[no_mangle] pub unsafe extern "C" fn alloc(bytes: usize) -> *mut u8 { let mut data = Vec::with_capacity(bytes); let pointer = data.as_mut_ptr(); std::mem::forget(data); pointer } #[no_mangle] pub extern "C" fn get_env_vars() -> *const u8 { let mut bytes = Vec::new(); bytes.extend(vec_size(std::env::vars())); let iter = std::env::vars().flat_map(|(name, value)| -> Vec<u8> { EnvVar { name, value }.into() }); bytes.extend(iter); forget_and_return_pointer(bytes) } pub struct EnvVar { name: String, value: String, } impl From<EnvVar> for Vec<u8> { fn from(env_var: EnvVar) -> Self { let mut bytes = Vec::new(); append_str(&mut bytes, &env_var.name); append_str(&mut bytes, &env_var.value); bytes } } fn forget_and_return_pointer(bytes: Vec<u8>) -> *const u8 { let bytes = bytes.into_boxed_slice(); let pointer = bytes.as_ptr(); std::mem::forget(bytes); pointer } fn timestamp(time: &SystemTime) -> u64 { u64::try_from( time.duration_since(std::time::UNIX_EPOCH) .unwrap() .as_millis(), ) .unwrap() } fn vec_size(v: impl Iterator) -> [u8; 4] { let size = v.count(); println!("size {}", size); u32::try_from(size).unwrap().to_ne_bytes() } fn append_str(bytes: &mut Vec<u8>, value: &str) { println!("value {}", value); bytes.extend(u32::try_from(value.len()).unwrap().to_ne_bytes()); bytes.extend(value.as_bytes()); } fn append_option<T: Copy>( bytes: &mut Vec<u8>, option: &Option<T>, append: impl Fn(&mut Vec<u8>, &T), ) { bytes.push(if option.is_some() { 1 } else { 0 }); if let Some(value) = option { append(bytes, value); } } pub struct MyStruct { pub name: String, pub list: Vec<u8>, pub list_double: Option<f32>, pub opt: Option<bool>, pub int_v: i32, } // impl MyStruct { // #[wasm_bindgen(getter)] // pub fn name(&self) -> String { // self.name.clone() // } // #[wasm_bindgen(getter)] // pub fn list(&self) -> Uint8Array { // Uint8Array::from(self.list.as_slice()) // } // } #[link(wasm_import_module = "example_imports")] extern "C" { // functions can have integer/float arguments/return values fn translate(a: i32) -> f64; // Note that the ABI of Rust and wasm is somewhat in flux, so while this // works, it's recommended to rely on raw integer/float values where // possible. // pub fn translate_fancy(my_struct: MyStruct) -> u32; // you can also explicitly specify the name to import, this imports `bar` // instead of `baz` from `example_imports`. // #[link_name = "bar"] // fn baz(); }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/rust_wasi_example/src/main.rs
packages/rust_wasi_example/src/main.rs
fn main() { std::fs::metadata("foo.txt").unwrap(); println!("Hello, world!"); }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/rust_wasi_example/src/lib_wasm_bindgen.rs
packages/rust_wasi_example/src/lib_wasm_bindgen.rs
// use js_sys::{Array, Uint8Array}; // use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue}; // #[no_mangle] // pub extern "C" fn print_hello() { // println!("Hello, world!"); // } // #[wasm_bindgen] // pub fn read_file_size(path: String) -> u64 { // let metadata = std::fs::metadata(path).unwrap(); // metadata.len() // } // // permissions // // modified // // accessed // // created // // final bool captureStdout; // // final bool captureStderr; // // final bool inheritStdin; // #[wasm_bindgen] // pub fn current_time() -> u64 { // u64::try_from( // std::time::SystemTime::now() // .duration_since(std::time::UNIX_EPOCH) // .unwrap() // .as_millis(), // ) // .unwrap() // } // #[wasm_bindgen] // pub fn get_args() -> ArrayString { // std::env::args() // .map(JsValue::from) // .collect::<Array>() // .unchecked_into::<ArrayString>() // } // #[wasm_bindgen] // pub fn get_env_vars() -> ArrayEnvVar { // std::env::vars() // .map(|(name, value)| EnvVar { name, value }) // .map(JsValue::from) // .collect::<Array>() // .unchecked_into::<ArrayEnvVar>() // } // #[wasm_bindgen] // pub struct EnvVar { // name: String, // value: String, // } // #[wasm_bindgen] // impl EnvVar { // #[wasm_bindgen(getter)] // pub fn name(&self) -> String { // self.name.clone() // } // #[wasm_bindgen(getter)] // pub fn value(&self) -> String { // self.value.clone() // } // } // #[wasm_bindgen] // pub struct MyStruct { // name: String, // list: Vec<u8>, // pub list_double: Option<f32>, // pub opt: Option<bool>, // pub int_v: i32, // } // #[wasm_bindgen] // impl MyStruct { // #[wasm_bindgen(getter)] // pub fn name(&self) -> String { // self.name.clone() // } // #[wasm_bindgen(getter)] // pub fn list(&self) -> Uint8Array { // Uint8Array::from(self.list.as_slice()) // } // } // #[wasm_bindgen] // #[link(wasm_import_module = "the-wasm-import-module")] // extern "C" { // #[wasm_bindgen(typescript_type = "Array<string>")] // pub type ArrayString; // #[wasm_bindgen(typescript_type = "Array<EnvVar>")] // pub type ArrayEnvVar; // // imports the name `foo` from `the-wasm-import-module` // fn foo(); // // functions can have integer/float arguments/return values // fn translate(a: i32) -> f32; // // Note that the ABI of Rust and wasm is somewhat in flux, so while this // // works, it's recommended to rely on raw integer/float values where // // possible. // fn translate_fancy(my_struct: MyStruct) -> u32; // // you can also explicitly specify the name to import, this imports `bar` // // instead of `baz` from `the-wasm-import-module`. // #[link_name = "bar"] // fn baz(); // }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/rust_threads_example/src/lib.rs
packages/rust_threads_example/src/lib.rs
// This requires nightly rust and wasm32-unknown-unknown target, // you may comment out simd code and compile it in stable rust #![feature(portable_simd)] use std::cell::RefCell; use std::simd::{i64x2, u32x4, SimdInt, SimdUint}; use std::sync::atomic::{AtomicI64, Ordering}; static STATE: AtomicI64 = AtomicI64::new(0); thread_local!(static STATE_LOCAL: RefCell<u32> = RefCell::new(0)); #[no_mangle] pub extern "C" fn sum_u32(pointer: *mut u32, length: usize) -> u32 { let slice = unsafe { std::slice::from_raw_parts(pointer, length) }; slice.iter().sum() } #[no_mangle] pub extern "C" fn max_u32(pointer: *mut u32, length: usize) -> u32 { let slice = unsafe { std::slice::from_raw_parts(pointer, length) }; *slice.iter().max().unwrap() } #[no_mangle] pub extern "C" fn simd_sum_u32(pointer: *mut u32, length: usize) -> u32 { let slice = unsafe { std::slice::from_raw_parts(pointer, length) }; let mut sum = u32x4::splat(0); // [0, 0, 0, 0] for i in (0..slice.len()).step_by(4) { sum += u32x4::from_slice(&slice[i..]); } sum.reduce_sum() } #[no_mangle] pub extern "C" fn simd_max_u32(pointer: *mut u32, length: usize) -> u32 { let slice = unsafe { std::slice::from_raw_parts(pointer, length) }; let mut sum = u32x4::splat(0); // [0, 0, 0, 0] for i in (0..slice.len()).step_by(4) { sum = sum.max(u32x4::from_slice(&slice[i..])); } sum.reduce_max() } #[no_mangle] pub extern "C" fn sum_i64(pointer: *mut i64, length: usize) -> i64 { let slice = unsafe { std::slice::from_raw_parts(pointer, length) }; slice.iter().sum() } #[no_mangle] pub extern "C" fn max_i64(pointer: *mut i64, length: usize) -> i64 { let slice = unsafe { std::slice::from_raw_parts(pointer, length) }; *slice.iter().max().unwrap() } #[no_mangle] pub extern "C" fn simd_sum_i64(pointer: *mut i64, length: usize) -> i64 { let slice = unsafe { std::slice::from_raw_parts(pointer, length) }; let mut sum = i64x2::splat(0); // [0, 0, 0, 0] for i in (0..slice.len()).step_by(4) { sum += i64x2::from_slice(&slice[i..]); } sum.reduce_sum() } #[no_mangle] pub extern "C" fn simd_max_i64(pointer: *mut i64, length: usize) -> i64 { let slice = unsafe { std::slice::from_raw_parts(pointer, length) }; let mut sum = i64x2::splat(0); // [0, 0, 0, 0] for i in (0..slice.len()).step_by(4) { sum = sum.max(i64x2::from_slice(&slice[i..])); } sum.reduce_max() } #[no_mangle] pub extern "C" fn sum_f32(pointer: *mut f32, length: usize) -> f32 { let slice = unsafe { std::slice::from_raw_parts(pointer, length) }; slice.iter().sum() } #[no_mangle] pub extern "C" fn max_f32(pointer: *mut f32, length: usize) -> f32 { let slice = unsafe { std::slice::from_raw_parts(pointer, length) }; slice.iter().cloned().reduce(f32::max).unwrap() } #[no_mangle] pub extern "C" fn get_state_local() -> u32 { STATE_LOCAL.with(|cell| *cell.borrow()) } #[no_mangle] pub extern "C" fn set_state_local(value: u32) -> u32 { STATE_LOCAL.with(|cell| { let mut m = cell.borrow_mut(); let previous = *m; *m = value; previous }) } #[no_mangle] pub extern "C" fn get_state() -> i64 { STATE.load(Ordering::SeqCst) } #[no_mangle] pub extern "C" fn increase_state(value: i64) -> i64 { STATE.fetch_add(value, Ordering::SeqCst) } #[no_mangle] pub extern "C" fn map_state() { let mut result = Err(STATE.load(Ordering::SeqCst)); while let Err(value) = result { let mapped = unsafe { host_map_state(value) }; result = STATE.compare_exchange(value, mapped, Ordering::SeqCst, Ordering::SeqCst); } } #[no_mangle] pub unsafe extern "C" fn dealloc(pointer: *mut u8, bytes: usize) { let data = Vec::from_raw_parts(pointer, bytes, bytes); std::mem::drop(data); } #[no_mangle] pub unsafe extern "C" fn alloc(bytes: usize) -> *mut u8 { let mut data = Vec::with_capacity(bytes); let pointer = data.as_mut_ptr(); std::mem::forget(data); pointer } #[link(wasm_import_module = "threaded_imports")] extern "C" { fn host_map_state(state: i64) -> i64; }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/dart_wit_component/src/lib.rs
packages/dart_wit_component/src/lib.rs
use std::path::Path; mod function; pub mod generate; mod methods; mod strings; mod types; // Use a procedural macro to generate bindings for the world we specified in // `with/dart-wit-generator.wit` wit_bindgen::generate!("dart-wit-generator"); // Define a custom type and implement the generated `Host` trait for it which // represents implementing all the necessary exported interfaces for this // component. struct GeneratorImpl; impl DartWitGenerator for GeneratorImpl { fn generate_to_file(config: WitGeneratorConfig, file_path: String) -> Result<(), String> { let file = Self::generate(config)?; std::fs::write(file_path, file.contents).map_err(|e| e.to_string())?; Ok(()) } fn generate(config: WitGeneratorConfig) -> Result<WitFile, String> { let base_config = WitGeneratorConfig { inputs: WitGeneratorInput::FileSystemPaths(FileSystemPaths { input_path: "".to_string(), }), ..config }; let (path, pkg) = match config.inputs { WitGeneratorInput::InMemoryFiles(inputs) => { let mut source_map = wit_parser::SourceMap::new(); let world_path = inputs.world_file.path.clone(); for input in inputs.pkg_files.into_iter().chain([inputs.world_file]) { let path = Path::new(&input.path); source_map.push(&path, input.contents); } let parsed = source_map.parse().map_err(|e| e.to_string())?; (world_path, parsed) } WitGeneratorInput::FileSystemPaths(p) => { let parsed = wit_parser::UnresolvedPackage::parse_path(Path::new(&p.input_path)) .map_err(|e| e.to_string())?; (p.input_path, parsed) } }; let contents = generate::document_to_dart(&pkg, base_config)?; Ok(WitFile { path, contents }) } } export_dart_wit_generator!(GeneratorImpl);
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/dart_wit_component/src/methods.rs
packages/dart_wit_component/src/methods.rs
use crate::{strings::Normalize, types::Parsed}; use wit_parser::*; pub trait GeneratedMethodsTrait { fn to_wasm(&self, name: &str, p: &Parsed) -> String; fn to_json(&self, name: &str, p: &Parsed) -> String; fn from_json(&self, name: &str, p: &Parsed) -> Option<String>; fn to_string(&self, name: &str, p: &Parsed) -> Option<String>; fn copy_with(&self, name: &str, p: &Parsed) -> Option<String>; fn equality_hash_code(&self, name: &str, p: &Parsed) -> Option<String>; } impl GeneratedMethodsTrait for Record { fn to_wasm(&self, _name: &str, p: &Parsed) -> String { let props = self .fields .iter() .map(|f| p.type_to_wasm(&f.name.as_var(), &f.ty)) .collect::<Vec<_>>() .join(","); format!("List<Object?> toWasm() => [{props}];") } fn to_json(&self, name: &str, p: &Parsed) -> String { let content = self .fields .iter() .map(|f| format!("'{}': {},", f.name, p.type_to_json(&f.name.as_var(), &f.ty))) .collect::<String>(); format!("Map<String, Object?> toJson() => {{'runtimeType': '{name}', {content}}};") } fn from_json(&self, name: &str, p: &Parsed) -> Option<String> { if self.fields.is_empty() { Some(format!( "factory {name}.fromJson(Object? _) => const {name}();\n" )) } else { let spread = self .fields .iter() .map(|f| format!("final {}", f.name.as_var())) .collect::<Vec<_>>() .join(","); let s_comma = if self.fields.len() == 1 { "," } else { "" }; let from_json_items = self .fields .iter() .map(|f| { format!( "{}: {},", f.name.as_var(), p.type_from_json(&f.name.as_var(), &f.ty) ) }) .collect::<String>(); Some(format!( "factory {name}.fromJson(Object? json_) {{ final json = json_ is Map ? _spec.fields.map((f) => json_[f.label]).toList(growable: false) : json_; return switch (json) {{ [{spread}] || ({spread}{s_comma}) => {name}({from_json_items}), _ => throw Exception('Invalid JSON $json_')}}; }}", )) } } fn to_string(&self, name: &str, _p: &Parsed) -> Option<String> { Some(format!(" @override\nString toString() => '{name}${{Map.fromIterables(_spec.fields.map((f) => f.label), _props)}}';\n" )) } fn copy_with(&self, name: &str, p: &Parsed) -> Option<String> { let copy_with_params = if self.fields.is_empty() { "".to_string() } else { let params = self .fields .iter() .map(|f| { let mut tt = p.type_to_str(&f.ty); if tt.ends_with("?") { tt.pop(); format!("Option<{tt}>? {},", f.name.as_var(),) } else { format!( "{tt}{} {},", if tt.ends_with("?") { "" } else { "?" }, f.name.as_var(), ) } }) .collect::<String>(); format!("{{{params}}}",) }; let copy_with_content = if self.fields.is_empty() { "".to_string() } else { self.fields .iter() .map(|f| { let field = f.name.as_var(); if let (true, true) = (p.2.use_null_for_option, p.is_option(&f.ty)) { format!("{field}: {field} != null ? {field}.value : this.{field}") } else { format!("{field}: {field} ?? this.{field}") } }) .collect::<Vec<_>>() .join(",") }; Some(format!( "{name} copyWith({copy_with_params}) => {name}({copy_with_content});" )) } fn equality_hash_code(&self, name: &str, p: &Parsed) -> Option<String> { let comparator = p.comparator(); Some(format!(" @override\nbool operator ==(Object other) => identical(this, other) || other is {name} && {comparator}.arePropsEqual(_props, other._props); @override\nint get hashCode => {comparator}.hashProps(_props);\n ")) } } impl GeneratedMethodsTrait for Enum { fn to_wasm(&self, _name: &str, _p: &Parsed) -> String { "int toWasm() => index;".to_string() } fn to_json(&self, name: &str, _p: &Parsed) -> String { format!("Map<String, Object?> toJson() => {{'runtimeType':'{name}', _spec.labels[index]: null}};\n") } fn from_json(&self, name: &str, _p: &Parsed) -> Option<String> { Some(format!( "factory {name}.fromJson(Object? json) {{ return ToJsonSerializable.enumFromJson(json, values, _spec); }}", )) } fn to_string(&self, _name: &str, _p: &Parsed) -> Option<String> { None } fn copy_with(&self, _name: &str, _p: &Parsed) -> Option<String> { None } fn equality_hash_code(&self, _name: &str, _p: &Parsed) -> Option<String> { None } } fn base_string_case(data: &(usize, &Case), name: &str, p: &Parsed) -> String { let self_ = data.1; let comparator = p.comparator(); if let Some(ty) = self_.ty { format!( "Map<String, Object?> toJson() => {{'runtimeType':'{name}','{}': {}}}; @override String toString() => '{name}($value)'; @override bool operator ==(Object other) => other is {name} && {comparator}.areEqual(other.value, value); @override int get hashCode => {comparator}.hashValue(value);", self_.name, p.type_to_json("value", &ty) ) } else { format!( "Map<String, Object?> toJson() => {{'runtimeType':'{name}','{}': null}}; @override String toString() => '{name}()'; @override bool operator ==(Object other) => other is {name}; @override int get hashCode => ({name}).hashCode;", self_.name, ) } } impl GeneratedMethodsTrait for (usize, &Case) { fn to_wasm(&self, _name: &str, p: &Parsed) -> String { let index = self.0; if let Some(ty) = self.1.ty { format!( "@override (int, Object?) toWasm() => ({index}, {});", p.type_to_wasm("value", &ty) ) } else { format!("@override (int, Object?) toWasm() => ({index}, null);") } } fn to_json(&self, name: &str, p: &Parsed) -> String { base_string_case(self, name, p) .split("\n") .nth(0) .unwrap() .to_string() } fn from_json(&self, _name: &str, _p: &Parsed) -> Option<String> { None } fn to_string(&self, name: &str, p: &Parsed) -> Option<String> { Some( base_string_case(self, name, p) .split("\n") .nth(1) .unwrap() .to_string(), ) } fn copy_with(&self, _name: &str, _p: &Parsed) -> Option<String> { None } fn equality_hash_code(&self, name: &str, p: &Parsed) -> Option<String> { Some( base_string_case(self, name, p) .split("\n") .skip(2) .collect(), ) } } impl GeneratedMethodsTrait for (usize, &UnionCase) { fn to_wasm(&self, _name: &str, p: &Parsed) -> String { let override_ = if p.2.same_class_union { "" } else { "@override " }; format!( "{override_}(int, Object?) toWasm() => ({}, {});", self.0, p.type_to_wasm("value", &self.1.ty) ) } fn to_json(&self, name: &str, p: &Parsed) -> String { format!( "\nMap<String, Object?> toJson() => {{'runtimeType':'{name}','{}': {}}};", self.0, p.type_to_json("value", &self.1.ty) ) } fn from_json(&self, _name: &str, _p: &Parsed) -> Option<String> { None } fn to_string(&self, name: &str, _p: &Parsed) -> Option<String> { Some(format!("@override\nString toString() => '{name}($value)';")) } fn copy_with(&self, _name: &str, _p: &Parsed) -> Option<String> { None } fn equality_hash_code(&self, name: &str, p: &Parsed) -> Option<String> { let comparator = p.comparator(); Some( format!(" @override\nbool operator ==(Object other) => other is {name} && {comparator}.areEqual(other.value, value); @override\nint get hashCode => {comparator}.hashValue(value);",) ) } } impl GeneratedMethodsTrait for Flags { fn to_wasm(&self, _name: &str, _p: &Parsed) -> String { "Uint32List toWasm() => Uint32List.sublistView(flagsBits.data);".to_string() } fn to_json(&self, name: &str, _p: &Parsed) -> String { format!("Map<String, Object?> toJson() => flagsBits.toJson()..['runtimeType'] = '{name}';") } fn from_json(&self, name: &str, _p: &Parsed) -> Option<String> { Some(format!( "factory {name}.fromJson(Object? json) {{ final flagsBits = FlagsBits.fromJson(json, flagsKeys: _spec.labels); return {name}(flagsBits); }}" )) } fn to_string(&self, name: &str, _p: &Parsed) -> Option<String> { let to_string_content = self .flags .iter() .map(|v| format!("if ({}) '{}',", v.name.as_var(), v.name.as_var())) .collect::<String>(); Some(format!( "@override\nString toString() => '{name}(${{[{to_string_content}].join(', ')}})';", )) } fn copy_with(&self, _name: &str, _p: &Parsed) -> Option<String> { None } fn equality_hash_code(&self, name: &str, p: &Parsed) -> Option<String> { let comparator = p.comparator(); Some( format!(" @override\nbool operator ==(Object other) => other is {name} && {comparator}.areEqual(flagsBits, other.flagsBits); @override\nint get hashCode => {comparator}.hashValue(flagsBits);",) ) } }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/dart_wit_component/src/function.rs
packages/dart_wit_component/src/function.rs
use wit_parser::*; use crate::{ generate::add_docs, strings::Normalize, types::{function_resource, Parsed}, }; pub enum FuncKind { Resource(TypeOwner), MethodCall, Method, Field, } impl Parsed<'_> { pub fn function_import(&self, key: Option<&WorldKey>, id: &str, f: &Function) -> String { let interface_name_m = match key { Some(k) => self.0.name_world_key(k), None => "$root".to_string(), }; let interface_name = key.map(|key| self.world_key_type_name(key)); let getter = format!( "imports.{}{}", interface_name .map(|v| format!("{}.", v.as_var())) .unwrap_or("".to_string()), id.as_var(), ); let ft = self.function_spec(f); let exec = self.function_exec(&getter, f); let exec_name = getter.as_fn_suffix(); format!( "{{ const ft = {ft}; {exec} final lowered = loweredImportFunction(r'{interface_name_m}#{id}', ft, exec{exec_name}, getLib); builder.addImport(r'{interface_name_m}', '{id}', lowered); }}", ) } pub fn function_spec(&self, function: &Function) -> String { let params = function .params .iter() .map(|(name, ty)| format!("('{name}', {})", self.type_to_spec(ty))) .collect::<Vec<_>>() .join(", "); let results = match &function.results { Results::Anon(a) => format!("('', {})", self.type_to_spec(a)), Results::Named(results) => results .iter() .map(|(name, ty)| format!("('{name}', {})", self.type_to_spec(ty))) .collect::<Vec<_>>() .join(", "), }; format!("FuncType([{params}], [{results}])") } pub fn function_exec(&self, getter: &str, function: &Function) -> String { // TODO: post function let results_def = if function.results.len() == 0 { "" } else { "final results = " }; let n = getter.as_fn_suffix(); let args = function .params .iter() .enumerate() .map(|(i, (_name, _ty))| format!("final args{i} = args[{i}];")) .collect::<String>(); let args_from_json = function .params .iter() .enumerate() .map(|(i, (name, ty))| { let value = self.type_from_json(&format!("args{i}"), ty); format!("{}: {value}", name.as_var()) }) .collect::<Vec<_>>() .join(", "); let ret = match &function.results { Results::Anon(a) => format!("[{}]", self.type_to_wasm("results", a)), Results::Named(results) => { if results.is_empty() { "const []".to_string() } else { let values = results .iter() .map(|(name, ty)| { self.type_to_wasm(&format!("results.{}", name.as_var()), ty) }) .collect::<Vec<_>>() .join(", "); format!("[{values}]") } } }; format!( " (ListValue, void Function()) exec{n}(ListValue args) {{ {args} {results_def}{getter}({args_from_json}); return ({ret}, () {{}}); }} " ) } pub fn world_key_type_name<'a>(&'a self, key: &'a WorldKey) -> &'a str { match key { WorldKey::Name(name) => name, WorldKey::Interface(id) => { let interface = self.0.interfaces.get(*id).unwrap(); interface.name.as_ref().unwrap() } } } pub fn add_interfaces( &self, mut s: &mut String, map: &mut dyn Iterator<Item = (&WorldKey, &WorldItem)>, is_export: bool, mut func_imports: Option<&mut String>, ) { map.for_each(|(key, item)| match item { WorldItem::Interface(interface_id) => { let interface = self.0.interfaces.get(*interface_id).unwrap(); self.add_interface(&mut s, key, interface, is_export, &mut func_imports) } _ => {} }); } pub fn add_interface( &self, mut s: &mut String, key: &WorldKey, interface: &Interface, is_export: bool, func_imports: &mut Option<&mut String>, ) { let world_prefix = self.0.name_world_key(key); let interface_id = self.world_key_type_name(key); let world_name = heck::AsPascalCase(&self.0.worlds.iter().next().unwrap().1.name); let name = heck::AsPascalCase(interface_id); add_docs(&mut s, &interface.docs); if is_export { s.push_str(&format!( "class {name} {{ final {world_name}World _world; {name}(this._world)" )); if interface.functions.is_empty() { s.push_str(";"); } else { s.push_str(":"); interface .functions .iter() .enumerate() .for_each(|(index, (id, f))| { let fn_name = if self.2.async_worker { "getComponentFunctionWorker" } else { "getComponentFunction" }; s.push_str(&format!( "_{} = _world.library.{fn_name}('{world_prefix}#{id}', const {},)!", id.as_var(), self.function_spec(f) )); if index != interface.functions.len() - 1 { s.push_str(","); } }); s.push_str(";"); } interface.functions.iter().for_each(|(_id, f)| { self.add_function(&mut s, f, FuncKind::MethodCall, false); }); s.push_str("}"); } else { if interface.functions.is_empty() { return; } s.push_str(&format!("abstract class {name}Import {{",)); interface.functions.iter().for_each(|(id, f)| { self.add_function(&mut s, f, FuncKind::Method, false); if let Some(func_imports) = func_imports { func_imports.push_str(&self.function_import(Some(key), id, f)); } }); s.push_str("}"); } } pub fn is_option(&self, ty: &Type) -> bool { match ty { Type::Id(ty_id) => { let ty_def = self.0.types.get(*ty_id).unwrap(); matches!(ty_def.kind, TypeDefKind::Option(_)) } _ => false, } } pub fn type_param(&self, name: &str, ty: &Type, is_constructor: bool) -> String { let type_or_this = if is_constructor { "this.".to_string() } else { self.type_to_str(ty) }; if !self.2.required_option && self.is_option(ty) { if self.2.use_null_for_option { format!("{type_or_this} {},", name.as_var()) } else { format!("{type_or_this} {} = const None(),", name.as_var()) } } else { format!("required {type_or_this} {},", name.as_var()) } } pub fn is_unit(&self, ty: &Type) -> bool { match ty { Type::Id(ty_id) => { let ty_def = self.0.types.get(*ty_id).unwrap(); if let TypeDefKind::Tuple(Tuple { types }) = &ty_def.kind { types.is_empty() } else { false } } _ => false, } } pub fn add_function(&self, mut s: &mut String, f: &Function, kind: FuncKind, from_world: bool) { let is_static = match f.kind { FunctionKind::Static(_) | FunctionKind::Constructor(_) => true, _ => false, }; let is_resource = match kind { FuncKind::Resource(_) => true, _ => false, }; let mut params = f .params .iter() .filter(|(name, _)| !is_resource || name != "self") .map(|(name, ty)| self.type_param(name, ty, false)) .collect::<String>(); if params.len() > 0 { params = format!("{{{params}}}"); } let mut results = match &f.results { Results::Anon(ty) => self.type_to_str(ty), Results::Named(list) => { if list.is_empty() { "void".to_string() } else { let types = list .iter() .map(|(name, ty)| format!("{} {}", self.type_to_str(ty), name.as_var())) .collect::<Vec<_>>() .join(","); format!("({{{types}}})") } } }; let name = &f.name.as_fn(); match kind { FuncKind::Field => { add_docs(&mut s, &f.docs); s.push_str(&format!("final {results} Function({params}) {name};",)) } FuncKind::Method => { add_docs(&mut s, &f.docs); s.push_str(&format!("{results} {name}({params});",)) } FuncKind::Resource(owner) => { add_docs(&mut s, &f.docs); let async_ = if self.2.async_worker { "async " } else { "" }; let static_ = if let (FunctionKind::Static(_), _) | (FunctionKind::Constructor(_), true) = (&f.kind, self.2.async_worker) { "static " } else { "" }; let owner_getter = match owner { TypeOwner::World(_) => { if is_static { "world.".to_string() } else { "_world.".to_string() } } TypeOwner::Interface(i) => { if is_static { format!("{}.", self.0.interfaces[i].name.as_ref().unwrap().as_var()) } else { format!( "_world.{}.", self.0.interfaces[i].name.as_ref().unwrap().as_var() ) } } TypeOwner::None => "".to_string(), }; if is_static { let w_name = heck::AsPascalCase(&self.0.worlds.iter().next().unwrap().1.name); match owner { TypeOwner::Interface(i) => { let n = self.0.interfaces[i].name.as_ref().unwrap(); params = format!("{} {}, {params}", n.as_type(), n.as_var()); } _ => { params = format!("{w_name}World world, {params}"); } } } if let (FunctionKind::Constructor(_), false) = (&f.kind, self.2.async_worker) { s.push_str(&format!("factory {results}.{name}({params}) {{")); } else { let n = if let Some(r) = function_resource(&f.kind) { let ty_name = heck::AsPascalCase(self.0.types[*r].name.as_ref().unwrap()).to_string(); let mut m = name.match_indices(&ty_name); (&name.as_str()[m.next().unwrap().0 + ty_name.len()..]).as_fn() } else { name.clone() }; s.push_str(&format!("{static_}{results} {n}({params}) {async_}{{")); } { let args = f .params .iter() .map(|(name, _)| { let g = if !is_static && name == "self" { "this".to_string() } else { name.as_var() }; format!("{}: {}", name.as_var(), g,) }) .collect::<Vec<_>>() .join(", "); s.push_str(&format!("return {owner_getter}{name}({args});")); } s.push_str("}"); } FuncKind::MethodCall => { // s.push_str(&format!("late final _{} = lookup('{}');", f.name, f.name)); if self.2.async_worker { results = format!("Future<{results}>"); s.push_str(&format!( "final Future<ListValue> Function(ListValue) _{name};" )); } else { s.push_str(&format!("final ListValue Function(ListValue) _{name};")); } add_docs(&mut s, &f.docs); let async_ = if self.2.async_worker { "async " } else { "" }; s.push_str(&format!("{results} {name}({params}) {async_}{{")); { let await_ = if self.2.async_worker { "await " } else { "" }; let results_assignments = if f.results.len() == 0 || (f.results.len() == 1 && self.is_unit(f.results.iter_types().next().unwrap())) { "" } else { "final results = " }; let params = f .params .iter() .map(|(name, ty)| self.type_to_wasm(&name.as_var(), ty)) .collect::<Vec<_>>() .join(", "); let results_with_ctx = match &f.results { Results::Anon(Type::Id(_)) => true, Results::Named(p) => !p.is_empty(), _ => false, }; let ret = match &f.results { Results::Anon(a) => { if self.is_unit(&a) { "return ();".to_string() } else { if results_with_ctx { let parse_prefix = if from_world { "" } else { "_world." }; format!( "final result = results[0];return {parse_prefix}withContext(() => {});", self.type_from_json("result", a) ) } else { format!( "final result = results[0];return {};", self.type_from_json("result", a) ) } } } Results::Named(results) => { if results.is_empty() { "".to_string() } else { let assign = (0..results.len()) .map(|i| format!("final r{i} = results[{i}];")) .collect::<String>(); let values = results .iter() .enumerate() .map(|(i, (name, ty))| { format!( "{}: {}", name.as_var(), self.type_from_json(&format!("r{i}"), ty), ) }) .collect::<Vec<_>>() .join(", "); if results_with_ctx { let parse_prefix = if from_world { "" } else { "_world." }; format!("{assign}return {parse_prefix}withContext(() => ({values},));") } else { format!("{assign}return ({values},);") } } } }; s.push_str(&format!( "{results_assignments}{await_}_{name}([{params}]);{ret}" )); } s.push_str("}"); } } } }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/dart_wit_component/src/types.rs
packages/dart_wit_component/src/types.rs
use std::collections::HashMap; use crate::{ function::FuncKind, generate::*, strings::Normalize, Int64TypeConfig, WitGeneratorConfig, }; use wit_parser::*; pub struct Parsed<'a>( pub &'a Resolve, pub HashMap<&'a str, Vec<&'a TypeDef>>, pub WitGeneratorConfig, pub HashMap<String, Vec<String>>, ); const FROM_JSON_COMMENT: &str = "/// Returns a new instance from a JSON value. /// May throw if the value does not have the expected structure.\n"; const TO_JSON_COMMENT: &str = "/// Returns this as a serializable JSON value.\n"; const TO_WASM_COMMENT: &str = "/// Returns this as a WASM canonical abi value.\n"; const COPY_WITH_COMMENT: &str = "/// Returns a new instance by overriding the values passed as arguments\n"; enum MethodComment { FromJson, ToJson, ToWasm, CopyWith, } fn mapper_func(getter: &str, current: &str, is_required: bool) -> String { let func_params = format!("({getter})"); if current == getter { if is_required { "null".to_string() } else { "".to_string() } } else if current.ends_with(&func_params) { let current_func = current.trim_end_matches(&func_params); current_func.to_string() } else { format!("{func_params} => {current}") } } impl Parsed<'_> { pub fn type_to_str(&self, ty: &Type) -> String { match ty { Type::Id(ty_id) => { let ty_def = self.0.types.get(*ty_id).unwrap(); if let (TypeDefKind::Option(ty), true) = (&ty_def.kind, self.2.use_null_for_option) { let value = format!("{}?", self.type_to_str_inner(ty)); // TODO: remove when this ships https://github.com/dart-lang/sdk/issues/52591 if value == "()?" { "Object?".to_string() } else { value } } else { self.type_def_to_name(ty_def, true) } } _ => self.type_to_str_inner(ty), } } fn type_to_str_inner(&self, ty: &Type) -> String { match ty { Type::Id(ty_id) => { let ty_def = self.0.types.get(*ty_id).unwrap(); self.type_def_to_name(ty_def, true) } Type::Bool => "bool".to_string(), Type::String => "String".to_string(), Type::Char => "String /*Char*/".to_string(), Type::Float32 => "double /*F32*/".to_string(), Type::Float64 => "double /*F64*/".to_string(), Type::S8 => "int /*S8*/".to_string(), Type::S16 => "int /*S16*/".to_string(), Type::S32 => "int /*S32*/".to_string(), Type::S64 => match self.2.int64_type { Int64TypeConfig::BigInt => "BigInt /*S64*/".to_string(), Int64TypeConfig::NativeObject => "Object /*S64*/".to_string(), Int64TypeConfig::BigIntUnsignedOnly => "int /*S64*/".to_string(), Int64TypeConfig::CoreInt => "int /*S64*/".to_string(), }, Type::U8 => "int /*U8*/".to_string(), Type::U16 => "int /*U16*/".to_string(), Type::U32 => "int /*U32*/".to_string(), Type::U64 => match self.2.int64_type { Int64TypeConfig::BigInt => "BigInt /*U64*/".to_string(), Int64TypeConfig::NativeObject => "Object /*U64*/".to_string(), Int64TypeConfig::BigIntUnsignedOnly => "BigInt /*U64*/".to_string(), Int64TypeConfig::CoreInt => "int /*U64*/".to_string(), }, } } fn list_typed_data(&self, ty: &Type) -> Option<String> { if !self.2.typed_number_lists { return None; } match ty { Type::Float32 => Some("Float32List".to_string()), Type::Float64 => Some("Float64List".to_string()), Type::S8 => Some("Int8List".to_string()), Type::S16 => Some("Int16List".to_string()), Type::S32 => Some("Int32List".to_string()), Type::U8 => Some("Uint8List".to_string()), Type::U16 => Some("Uint16List".to_string()), Type::U32 => Some("Uint32List".to_string()), _ => None, } } pub fn type_to_json(&self, getter: &str, ty: &Type) -> String { match ty { Type::Id(ty_id) => { let ty_def = self.0.types.get(*ty_id).unwrap(); self.type_def_to_json(getter, ty_def) } _ => self.type_to_json_inner(getter, ty), } } fn type_to_json_inner(&self, getter: &str, ty: &Type) -> String { match ty { Type::Id(ty_id) => { let ty_def = self.0.types.get(*ty_id).unwrap(); self.type_def_to_json_inner(getter, ty_def) } Type::Bool => getter.to_string(), Type::String => getter.to_string(), Type::Char => getter.to_string(), Type::Float32 => getter.to_string(), Type::Float64 => getter.to_string(), Type::S8 => getter.to_string(), Type::S16 => getter.to_string(), Type::S32 => getter.to_string(), Type::S64 => match self.2.int64_type { Int64TypeConfig::BigInt => format!("{getter}.toString()"), Int64TypeConfig::NativeObject => format!("i64.toBigInt({getter}).toString()"), Int64TypeConfig::BigIntUnsignedOnly => getter.to_string(), Int64TypeConfig::CoreInt => getter.to_string(), }, Type::U8 => getter.to_string(), Type::U16 => getter.to_string(), Type::U32 => getter.to_string(), Type::U64 => match self.2.int64_type { Int64TypeConfig::BigInt => format!("{getter}.toString()"), Int64TypeConfig::NativeObject => format!("i64.toBigInt({getter}).toString()"), Int64TypeConfig::BigIntUnsignedOnly => format!("{getter}.toString()"), Int64TypeConfig::CoreInt => getter.to_string(), }, } } fn type_def_to_json(&self, getter: &str, ty: &TypeDef) -> String { match &ty.kind { TypeDefKind::Option(ty) => { let mapped = self.type_to_json_inner("some", &ty); let mapped = mapper_func("some", &mapped, false); if self.2.use_null_for_option { format!("({getter} == null ? const None().toJson() : Option.fromValue({getter}).toJson({mapped}))") } else { format!("{getter}.toJson({mapped})") } } _ => self.type_def_to_json_inner(getter, ty), } } fn type_def_to_json_inner(&self, getter: &str, ty: &TypeDef) -> String { match &ty.kind { TypeDefKind::Record(_record) => format!("{getter}.toJson()"), TypeDefKind::Enum(_enum_) => format!("{getter}.toJson()"), TypeDefKind::Union(_union) => format!("{getter}.toJson()"), TypeDefKind::Flags(_flags) => format!("{getter}.toJson()"), TypeDefKind::Variant(_variant) => format!("{getter}.toJson()"), TypeDefKind::Resource | TypeDefKind::Handle(_) => format!("{getter}.toWasm()"), TypeDefKind::Option(ty) => { let inner = self.type_to_json_inner("some", &ty); let inner = mapper_func("some", &inner, false); format!("{getter}.toJson({inner})") } TypeDefKind::Result(r) => { let map_ok = r.ok.map_or_else( || "null".to_string(), |ok| { let to_json = self.type_to_json("ok", &ok); mapper_func("ok", &to_json, true) }, ); let map_err = r.err.map_or_else( || "null".to_string(), |error| { let to_json = self.type_to_json("error", &error); mapper_func("error", &to_json, true) }, ); format!("{getter}.toJson({map_ok}, {map_err})") } TypeDefKind::Tuple(t) => { let list = t .types .iter() .enumerate() .map(|(i, t)| self.type_to_json(&format!("{getter}.${ind}", ind = i + 1), t)) .collect::<Vec<_>>() .join(", "); format!("[{list}]") } TypeDefKind::List(ty) => { let inner = self.type_to_json("e", &ty); if inner == "e" { format!("{getter}.toList()") } else { let inner = mapper_func("e", &inner, true); format!("{getter}.map({inner}).toList()") } } TypeDefKind::Future(_ty) => unreachable!("Future"), TypeDefKind::Stream(_s) => unreachable!("Stream"), TypeDefKind::Type(ty) => self.type_to_json_inner(getter, &ty), TypeDefKind::Unknown => unimplemented!("Unknown type"), } } pub fn type_to_wasm(&self, getter: &str, ty: &Type) -> String { match ty { Type::Id(ty_id) => { let ty_def = self.0.types.get(*ty_id).unwrap(); self.type_def_to_wasm(getter, ty_def) } _ => self.type_to_wasm_inner(getter, ty), } } fn type_to_wasm_inner(&self, getter: &str, ty: &Type) -> String { match ty { Type::Id(ty_id) => { let ty_def = self.0.types.get(*ty_id).unwrap(); self.type_def_to_wasm_inner(getter, ty_def) } Type::Bool => getter.to_string(), Type::String => getter.to_string(), Type::Char => getter.to_string(), Type::Float32 => getter.to_string(), Type::Float64 => getter.to_string(), Type::S8 => getter.to_string(), Type::S16 => getter.to_string(), Type::S32 => getter.to_string(), Type::S64 => getter.to_string(), Type::U8 => getter.to_string(), Type::U16 => getter.to_string(), Type::U32 => getter.to_string(), Type::U64 => getter.to_string(), } } fn type_def_to_wasm(&self, getter: &str, ty: &TypeDef) -> String { match &ty.kind { TypeDefKind::Option(ty) => { let mapper = self.type_to_wasm_inner("some", &ty); let mapper = mapper_func("some", &mapper, false); if self.2.use_null_for_option { format!("({getter} == null ? const None().toWasm() : Option.fromValue({getter}).toWasm({mapper}))") } else { format!("{getter}.toWasm({mapper})") } } _ => self.type_def_to_wasm_inner(getter, ty), } } fn type_def_to_wasm_inner(&self, getter: &str, ty: &TypeDef) -> String { match &ty.kind { TypeDefKind::Record(_record) => format!("{getter}.toWasm()"), TypeDefKind::Enum(_enum_) => format!("{getter}.toWasm()"), TypeDefKind::Union(_union) => { if self.2.same_class_union { format!( "{}.toWasm({getter})", self.type_def_to_name_definition(ty).unwrap() ) } else { format!("{getter}.toWasm()") } } TypeDefKind::Flags(_flags) => format!("{getter}.toWasm()"), TypeDefKind::Variant(_variant) => format!("{getter}.toWasm()"), TypeDefKind::Resource | TypeDefKind::Handle(_) => format!("{getter}.toWasm()"), TypeDefKind::Option(ty) => { format!( "{getter}.toWasm({})", mapper_func("some", &self.type_to_wasm_inner("some", &ty), false) ) } TypeDefKind::Result(r) => { let map_ok = r.ok.map_or_else( || "null".to_string(), |ok| { let to_wasm = self.type_to_wasm("ok", &ok); mapper_func("ok", &to_wasm, true) }, ); let map_err = r.err.map_or_else( || "null".to_string(), |error| { let to_wasm = self.type_to_wasm("error", &error); mapper_func("error", &to_wasm, true) }, ); format!("{getter}.toWasm({map_ok}, {map_err})") } TypeDefKind::Tuple(t) => { let list = t .types .iter() .enumerate() .map(|(i, t)| self.type_to_wasm(&format!("{getter}.${ind}", ind = i + 1), t)) .collect::<Vec<_>>() .join(", "); format!("[{list}]") } TypeDefKind::List(ty) => { let inner = self.type_to_wasm("e", &ty); // In toJson() we use toList(), but in toWasm() we just use the list directly // If we need to map, we use toList(growable: false). if inner == "e" { format!("{getter}") } else { let inner = mapper_func("e", &inner, true); format!("{getter}.map({inner}).toList(growable: false)") } } TypeDefKind::Future(_ty) => unreachable!("Future"), TypeDefKind::Stream(_s) => unreachable!("Stream"), TypeDefKind::Type(ty) => self.type_to_wasm_inner(getter, &ty), TypeDefKind::Unknown => unimplemented!("Unknown type"), } } pub fn type_class_name(&self, ty: &Type) -> Option<String> { if let Type::Id(ty_id) = ty { let ty_def = self.0.types.get(*ty_id).unwrap(); if let ( Some(name), TypeDefKind::Record(_) | TypeDefKind::Enum(_) | TypeDefKind::Union(_) | TypeDefKind::Variant(_) | TypeDefKind::Flags(_), ) = (self.type_def_to_name_definition(ty_def), &ty_def.kind) { return Some(name); } } None } pub fn type_to_spec(&self, ty: &Type) -> String { if let Some(name) = self.type_class_name(ty) { format!("{name}._spec") } else { self.type_to_spec_inner(ty) } } fn type_to_spec_inner(&self, ty: &Type) -> String { match ty { Type::Id(ty_id) => { let ty_def = self.0.types.get(*ty_id).unwrap(); self.type_def_to_spec(ty_def) } Type::Bool => "Bool()".to_string(), Type::String => "StringType()".to_string(), Type::Char => "Char()".to_string(), Type::Float32 => "Float32()".to_string(), Type::Float64 => "Float64()".to_string(), Type::S8 => "S8()".to_string(), Type::S16 => "S16()".to_string(), Type::S32 => "S32()".to_string(), Type::S64 => "S64()".to_string(), Type::U8 => "U8()".to_string(), Type::U16 => "U16()".to_string(), Type::U32 => "U32()".to_string(), Type::U64 => "U64()".to_string(), } } pub fn type_def_to_spec_option(&self, r: Option<Type>) -> String { r.map(|ty| self.type_to_spec(&ty)) .unwrap_or("null".to_string()) } pub fn type_def_to_spec(&self, ty: &TypeDef) -> String { match &ty.kind { TypeDefKind::Record(record) => { let fields = record .fields .iter() .map(|t| format!("(label: '{}', t: {})", t.name, self.type_to_spec(&t.ty))) .collect::<Vec<_>>() .join(", "); format!("RecordType([{fields}])") } TypeDefKind::Enum(enum_) => format!( "EnumType(['{}'])", enum_ .cases .iter() .map(|t| t.name.clone()) .collect::<Vec<_>>() .join("', '") ), TypeDefKind::Union(union) => format!( "Union([{}])", union .cases .iter() .map(|t| self.type_to_spec(&t.ty)) .collect::<Vec<_>>() .join(", ") ), TypeDefKind::Flags(flags) => format!( "Flags(['{}'])", flags .flags .iter() .map(|t| t.name.clone()) .collect::<Vec<_>>() .join("', '") ), TypeDefKind::Variant(variant) => { let options = variant .cases .iter() .map(|t| format!("Case('{}', {})", t.name, self.type_def_to_spec_option(t.ty))) .collect::<Vec<_>>() .join(", "); format!("Variant([{options}])") } TypeDefKind::Tuple(t) => { format!( "Tuple([{}])", t.types .iter() .map(|t| self.type_to_spec(t)) .collect::<Vec<_>>() .join(", ") ) } TypeDefKind::Option(ty) => format!("OptionType({})", self.type_to_spec(&ty)), TypeDefKind::Result(r) => format!( "ResultType({}, {})", self.type_def_to_spec_option(r.ok), self.type_def_to_spec_option(r.err), ), TypeDefKind::List(ty) => format!("ListType({})", self.type_to_spec(&ty)), TypeDefKind::Future(ty) => format!("FutureType({})", self.type_def_to_spec_option(*ty)), TypeDefKind::Stream(s) => format!( "StreamType({})", // TODO: stream.end self.type_def_to_spec_option(s.element), ), TypeDefKind::Type(ty) => self.type_to_spec(&ty), TypeDefKind::Resource => format!("ResourceType('{}')", self.type_handle_id(ty)), TypeDefKind::Handle(h) => match h { Handle::Own(resource_id) => format!( "Own({}._spec)", self.0 .types .get(*resource_id) .unwrap() .name .as_ref() .unwrap() .as_type() ), Handle::Borrow(resource_id) => { format!( "Borrow({}._spec)", self.0 .types .get(*resource_id) .unwrap() .name .as_ref() .unwrap() .as_type() ) } }, TypeDefKind::Unknown => unimplemented!("Unknown type"), } } pub fn type_handle_id(&self, ty: &TypeDef) -> String { let (_, package) = self.0.packages.iter().last().unwrap(); let owner = self.type_owner_name(ty.owner); format!( "{}/{}#{}", package.name, owner.unwrap_or("".to_string()), ty.name.as_ref().unwrap_or(&"".to_string()) ) } pub fn type_from_json(&self, getter: &str, ty: &Type) -> String { match ty { Type::Id(ty_id) => { let ty_def = self.0.types.get(*ty_id).unwrap(); match &ty_def.kind { TypeDefKind::Option(_ty) => { let val = self.type_def_from_json(getter, ty_def); if self.2.use_null_for_option { format!("{val}.value") } else { val } } _ => self.type_def_from_json(getter, ty_def), } } _ => self.type_from_json_inner(getter, ty), } } fn type_from_json_inner(&self, getter: &str, ty: &Type) -> String { match ty { Type::Id(ty_id) => { let ty_def = self.0.types.get(*ty_id).unwrap(); self.type_def_from_json(getter, ty_def) } Type::Bool => format!("{getter}! as bool"), Type::String => { format!("{getter} is String ? {getter} : ({getter}! as ParsedString).value") } Type::Char => format!("{getter}! as String"), Type::Float32 => format!("{getter}! as double"), Type::Float64 => format!("{getter}! as double"), Type::S8 => format!("{getter}! as int"), Type::S16 => format!("{getter}! as int"), Type::S32 => format!("{getter}! as int"), Type::S64 => match self.2.int64_type { Int64TypeConfig::BigInt => format!("bigIntFromJson({getter})"), Int64TypeConfig::NativeObject => format!("{getter}!"), Int64TypeConfig::BigIntUnsignedOnly => format!("{getter}! as int"), Int64TypeConfig::CoreInt => format!("{getter}! as int"), }, Type::U8 => format!("{getter}! as int"), Type::U16 => format!("{getter}! as int"), Type::U32 => format!("{getter}! as int"), Type::U64 => match self.2.int64_type { Int64TypeConfig::BigInt => format!("bigIntFromJson({getter})"), Int64TypeConfig::NativeObject => format!("{getter}!"), Int64TypeConfig::BigIntUnsignedOnly => format!("bigIntFromJson({getter})"), Int64TypeConfig::CoreInt => format!("{getter}! as int"), }, } } fn type_def_from_json_option(&self, getter: &str, r: Option<Type>) -> String { r.map(|ty| self.type_from_json(getter, &ty)) .unwrap_or("null".to_string()) } fn type_def_from_json(&self, getter: &str, ty: &TypeDef) -> String { let name = self.type_def_to_name_definition(ty); match &ty.kind { TypeDefKind::Record(_record) => format!("{}.fromJson({getter})", name.unwrap()), TypeDefKind::Enum(_enum_) => format!("{}.fromJson({getter})", name.unwrap()), TypeDefKind::Union(_union) => format!("{}.fromJson({getter})", name.unwrap()), TypeDefKind::Flags(_flags) => format!("{}.fromJson({getter})", name.unwrap()), TypeDefKind::Variant(_variant) => format!("{}.fromJson({getter})", name.unwrap()), TypeDefKind::Tuple(t) => { if t.types.len() == 0 { format!("()") } else { let spread = (0..t.types.len()) .map(|i| format!("final v{i}")) .collect::<Vec<_>>() .join(","); let s_comma = if t.types.len() == 1 { "," } else { "" }; let length = t.types.len(); let values = t.types .iter() .enumerate() .map(|(i, t)| self.type_from_json(&format!("v{i}"), t)) .collect::<Vec<_>>() .join(", "); format!( "(() {{final l = {getter} is Map ? List.generate({length}, (i) => {getter}[i.toString()], growable: false) : {getter}; return switch (l) {{ [{spread}] || ({spread}{s_comma}) => ({values},), _ => throw Exception('Invalid JSON ${getter}')}}; }})()" ) } } TypeDefKind::Option(ty) => format!( "Option.fromJson({getter}, (some) => {})", self.type_from_json_inner("some", &ty) ), TypeDefKind::Result(r) => format!( "Result.fromJson({getter}, (ok) => {}, (error) => {})", self.type_def_from_json_option("ok", r.ok), self.type_def_from_json_option("error", r.err), ), // TypeDefKind::Option(ty) => format!( // "{getter} == null ? none : {}", // self.type_from_json_inner(getter, &ty) // ), // TypeDefKind::Result(r) => format!( // "({getter} as Map).containsKey('ok') ? Ok({}) : Err({})", // self.type_def_from_json_option(&format!("({getter} as Map)['ok']"), r.ok), // self.type_def_from_json_option(&format!("({getter} as Map)['error']"), r.err), // ), TypeDefKind::List(ty) => self .list_typed_data(ty) .map(|type_data| format!("({getter} is {type_data} ? {getter} : {type_data}.fromList(({getter}! as List).cast()))") ) .unwrap_or_else(|| { let inner = self.type_from_json("e", &ty); if inner == "e" { format!("({getter}! as Iterable).toList()") } else { let inner = mapper_func("e", &inner, true); format!("({getter}! as Iterable).map({inner}).toList()") } }), TypeDefKind::Future(ty) => { format!( "FutureType({})", self.type_def_from_json_option(getter, *ty) ) } TypeDefKind::Stream(s) => format!( "StreamType({})", // TODO: stream.end self.type_def_from_json_option(getter, s.element), ), TypeDefKind::Type(ty) => self.type_from_json_inner(getter, &ty), TypeDefKind::Resource => format!("{}.fromJson({getter})", name.unwrap()), TypeDefKind::Handle(h) => format!("{}.fromJson({getter})", self.type_def_to_name_definition(self.handle_ty(h)).unwrap()), TypeDefKind::Unknown => unimplemented!("Unknown type"), } } pub fn type_to_dart_definition(&self, ty: &Type) -> String { match ty { Type::Id(ty_id) => { let ty_def = self.0.types.get(*ty_id).unwrap(); self.type_def_to_definition(ty_id, ty_def) } Type::Bool => "".to_string(), Type::String => "".to_string(), Type::Char => "".to_string(), Type::Float32 => "".to_string(), Type::Float64 => "".to_string(), Type::S8 => "".to_string(), Type::S16 => "".to_string(), Type::S32 => "".to_string(), Type::S64 => "".to_string(), Type::U8 => "".to_string(), Type::U16 => "".to_string(), Type::U32 => "".to_string(), Type::U64 => "".to_string(), } } fn handle_ty(&self, t: &Handle) -> &TypeDef { self.0 .types .get(*match t { Handle::Borrow(ty_id) => ty_id, Handle::Own(ty_id) => ty_id, }) .unwrap() } fn type_def_to_name(&self, ty: &TypeDef, allow_alias: bool) -> String { let name = self.type_def_to_name_definition(ty); if allow_alias && name.is_some() { return name.unwrap(); } match &ty.kind { TypeDefKind::Record(_record) => name.unwrap(), TypeDefKind::Enum(_enum) => name.unwrap(), TypeDefKind::Union(_union) => name.unwrap(), TypeDefKind::Flags(_flags) => name.unwrap(), TypeDefKind::Variant(_variant) => name.unwrap(), TypeDefKind::Resource => name.unwrap(), TypeDefKind::Handle(t) => self.type_def_to_name_definition(self.handle_ty(t)).unwrap(), TypeDefKind::Tuple(t) => { let values = t .types .iter() .map(|t| { let mut s = self.type_to_str(t); s.push_str(", "); s }) .collect::<String>(); format!("({values})") } TypeDefKind::Option(ty) => format!("Option<{}>", self.type_to_str_inner(&ty)), TypeDefKind::Result(r) => format!( "Result<{}, {}>", r.ok.map(|ty| self.type_to_str(&ty)) .unwrap_or("void".to_string()), r.err .map(|ty| self.type_to_str(&ty)) .unwrap_or("void".to_string()) ), TypeDefKind::List(ty) => self .list_typed_data(ty) .unwrap_or_else(|| format!("List<{}>", self.type_to_str(&ty))), TypeDefKind::Future(ty) => format!( "Future<{}>", ty.map(|ty| self.type_to_str(&ty)) .unwrap_or("void".to_string()) ), TypeDefKind::Stream(s) => format!( "Stream<{}>", // TODO: stream.end s.element .map(|ty| self.type_to_str(&ty)) .unwrap_or("void".to_string()), ), TypeDefKind::Type(ty) => self.type_to_str_inner(&ty), TypeDefKind::Unknown => unimplemented!("Unknown type"), } } fn type_owner_name(&self, owner: TypeOwner) -> Option<String> { match owner { TypeOwner::World(id) => Some(self.0.worlds.get(id).unwrap().name.clone()), TypeOwner::Interface(id) => self.0.interfaces.get(id).unwrap().name.clone(), TypeOwner::None => None, } } pub fn type_def_to_name_definition(&self, ty: &TypeDef) -> Option<String> { if let Some(v) = &ty.name { let defined = self.1.get(v as &str); if let Some(def) = defined { let owner = self.type_owner_name(ty.owner); let name = format!( "{v}-{}", owner.unwrap_or_else(|| def .iter() .position(|e| (*e).eq(ty)) .unwrap() .to_string()) ); Some(heck::AsPascalCase(name).to_string()) } else { Some(heck::AsPascalCase(v).to_string()) } } else { None } } fn method_comment(&self, comment: MethodComment) -> &str { if self.2.generate_docs { match comment { MethodComment::CopyWith => COPY_WITH_COMMENT, MethodComment::ToJson => TO_JSON_COMMENT, MethodComment::ToWasm => TO_WASM_COMMENT, MethodComment::FromJson => FROM_JSON_COMMENT, } } else { "" } } fn add_methods_trait<T: crate::methods::GeneratedMethodsTrait>( &self, s: &mut String, name: &str, methods: &T, ) { if self.2.json_serialization { if let Some(m) = methods.from_json(name, self) { s.push_str(self.method_comment(MethodComment::FromJson)); s.push_str(&m); } s.push_str("@override "); s.push_str(&methods.to_json(name, self)); } s.push_str(self.method_comment(MethodComment::ToWasm)); s.push_str(&methods.to_wasm(name, self)); if self.2.to_string { if let Some(m) = methods.to_string(name, self) { s.push_str(&m); } } if self.2.copy_with {
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
true
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/dart_wit_component/src/strings.rs
packages/dart_wit_component/src/strings.rs
pub trait Normalize { fn as_str(&self) -> &str; fn as_type(&self) -> String { heck::AsPascalCase(self.as_str()).to_string() } fn as_fn(&self) -> String { escape_reserved_word(&heck::AsLowerCamelCase(self.as_str()).to_string()) } fn as_fn_suffix(&self) -> String { heck::AsPascalCase(&self.as_str()).to_string() } fn as_var(&self) -> String { escape_reserved_word(&heck::AsLowerCamelCase(self.as_str()).to_string()) } fn as_const(&self) -> String { heck::AsShoutySnakeCase(self.as_str()).to_string() } fn as_namespace(&self) -> String { heck::AsShoutySnakeCase(self.as_str()).to_string() } } impl<T: AsRef<str>> Normalize for T { fn as_str(&self) -> &str { self.as_ref() } } /// Checks the given word against a list of reserved keywords. /// If the given word conflicts with a keyword, a trailing underscore will be /// appended. /// /// Adapted from [wiggle](https://docs.rs/wiggle/latest/wiggle/index.html) pub fn escape_reserved_word(word: &str) -> String { if RESERVED.contains(&word) { // If the camel-cased string matched any strict or reserved keywords, then // append a trailing underscore to the identifier we generate. format!("{word}_") } else { word.to_string() // Otherwise, use the string as is. } } // pub fn write_padding<W: Write>( // w: &mut PrettyWriter<W>, // pad_len: usize, // ) -> std::result::Result<(), Error> { // for i in 0..(pad_len & 1) { // w.write_line(format!("@u8() external int __pad8_{};", i))?; // } // for i in 0..(pad_len & 3) / 2 { // w.write_line(format!("@u16() external int __pad16_{};", i))?; // } // for i in 0..(pad_len & 7) / 4 { // w.write_line(format!("@u32() external int __pad32_{};", i))?; // } // for i in 0..pad_len / 8 { // w.write_line(format!("@u64() external int __pad64_{};", i))?; // } // Ok(()) // } const RESERVED: &[&str] = &[ // Reserved words. "assert", "break", "case", "catch", "class", "const", "continue", "default", "do", "else", "enum", "extends", "false", "final", "finally", "for", "if", "in", "is", "new", "null", "rethrow", "return", "super", "switch", "this", "throw", "true", "try", "var", "void", "while", "with", // Built-in identifiers. "abstract", "as", "covariant", "deferred", "dynamic", "export", "extension", "external", "factory", "Function", "get", "implements", "import", "interface", "late", "library", "operator", "mixin", "part", "required", "set", "static", "typedef", // "Contextual keywords". "await", "yield", // Other words used in the grammar. "async", "base", "hide", "of", "on", "sealed", "show", "sync", "when", // Other words used by the generator "toJson", "toMap", "fromJson", "fromMap", "toWasm", "fromWasm", "wasmSpec", "wasmType", "toString", "hashCode", "runtimeType", "props", "copyWith", "builder", "compareTo", "flagBits", "none", "all", "bool", "int", "double", "num", "i64", "index", // TODO: "init" ];
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/dart_wit_component/src/generate.rs
packages/dart_wit_component/src/generate.rs
use crate::{ function::FuncKind, strings::Normalize, types::*, Int64TypeConfig, WitGeneratorConfig, }; use std::collections::{HashMap, HashSet}; use wit_parser::*; pub fn document_to_dart( parsed: &UnresolvedPackage, config: WitGeneratorConfig, ) -> Result<String, String> { let mut s = String::new(); s.push_str(&format!( "{HEADER}{}", config.file_header.as_deref().unwrap_or("") )); let mut resolve = Resolve::new(); resolve .push(parsed.clone()) .map_err(|err| err.to_string())?; let names = HashMap::<&str, Vec<&TypeDef>>::new(); let unions = HashMap::<String, Vec<String>>::new(); let mut p = Parsed(&resolve, names, config, unions); // parsed.documents // parsed.foreign_deps // parsed.interfaces // parsed.types resolve.types.iter().for_each(|(_id, ty)| { if matches!(ty.kind, TypeDefKind::Type(_)) { return; } if let Some(name) = &ty.name { let entry = p.1.entry(name); entry.or_insert(vec![]).push(ty); } }); p.1.retain(|_k, v| v.len() > 1); if p.2.same_class_union { // Find all unions resolve.types.iter().for_each(|(_id, ty)| { if let TypeDefKind::Union(union) = &ty.kind { let union_name = p.type_def_to_name_definition(ty).unwrap(); union.cases.iter().for_each(|case| { if let (Some(_), Type::Id(id)) = (p.type_class_name(&case.ty), case.ty) { let case_ty = resolve.types.get(id).unwrap(); if let Some(name) = p.type_def_to_name_definition(case_ty) { let implements = p.3.entry(name).or_default(); implements.push(union_name.clone()); } } }); } }); } resolve.types.iter().for_each(|(id, ty)| { let docs = &ty.docs; if let (TypeDefKind::Type(ty), Some(name)) = (&ty.kind, p.type_def_to_name_definition(ty).as_ref()) { // Renamed imports and typedefs if let Type::Id(ref_id) = ty { let ty = resolve.types.get(*ref_id).unwrap(); if let Some(ref_name) = p.type_def_to_name_definition(ty).as_ref() { if ref_name != name { add_docs(&mut s, docs); s.push_str(&format!("typedef {name} = {ref_name};")); } } } else { let ref_name = p.type_to_str(ty); add_docs(&mut s, docs); s.push_str(&format!("typedef {name} = {ref_name};")); } return; } let definition = p.type_def_to_definition(&id, ty); if !definition.is_empty() { s.push_str(&definition); s.push_str("\n"); } }); resolve.worlds.iter().for_each(|(_id, w)| { let w_name = heck::AsPascalCase(&w.name); let mut func_imports = String::new(); let mut world_resource_finalizer = String::new(); // Imports Interfaces as Dart classes p.add_interfaces( &mut s, &mut w.imports.iter(), false, Some(&mut func_imports), ); let mut interfaces = HashSet::<InterfaceId>::new(); w.exports.iter().for_each(|(k, _v)| { if let WorldKey::Interface(i) = k { interfaces.insert(*i); } }); resolve .types .iter() .for_each(|(__id, ty)| match (&ty.owner, &ty.kind) { (TypeOwner::World(w_id), TypeDefKind::Resource) if _id == *w_id => { let resource_name = p.type_def_to_name_definition(ty).unwrap(); let resource_name_var = resource_name.as_var(); world_resource_finalizer.push_str(&format!( "late final _{resource_name_var}Finalizer = Finalizer<int>( (i) => canon_resource_drop(library.componentInstance, {resource_name}._spec, i), );" )); func_imports.push_str(&format!( "builder.addImports(resourceImports(getLib, {resource_name}._spec));" )); } (TypeOwner::Interface(i_id), TypeDefKind::Resource) if interfaces.contains(i_id) => { let resource_name = p.type_def_to_name_definition(ty).unwrap(); let resource_name_var = resource_name.as_var(); world_resource_finalizer.push_str(&format!( "late final _{resource_name_var}Finalizer = Finalizer<int>( (i) => canon_resource_drop(library.componentInstance, {resource_name}._spec, i), );" )); func_imports.push_str(&format!( "builder.addImports(resourceImports(getLib, {resource_name}._spec));" )); } _ => (), }); // World Imports s.push_str(&format!("class {w_name}WorldImports {{")); if w.imports.is_empty() { s.push_str(&format!("const {w_name}WorldImports();")); } else { let mut constructor = format!("const {w_name}WorldImports({{",); w.imports.iter().for_each(|(key, i)| { let id = p.world_key_type_name(key); let id_name = id.as_var(); match i { WorldItem::Interface(interface_id) => { let interface = p.0.interfaces.get(*interface_id).unwrap(); if interface.functions.is_empty() { return; } constructor.push_str(&format!("required this.{id_name},")); s.push_str(&format!( "final {}Import {id_name};", heck::AsPascalCase(id) )); } WorldItem::Type(_type_id) => {} WorldItem::Function(f) => { constructor.push_str(&format!("required this.{id_name},")); p.add_function(&mut s, f, FuncKind::Field, false); func_imports.push_str(&p.function_import(None, id, f)); } }; }); if constructor.ends_with("{") { constructor.pop(); constructor.push_str(");"); } else { constructor.push_str("});"); } s.push_str(&constructor); } s.push_str("}"); // World Exports //TODO: separate per document? p.add_interfaces(&mut s, &mut w.exports.iter(), true, None); add_docs(&mut s, &w.docs); s.push_str(&format!( "class {w_name}World {{ final {w_name}WorldImports imports; final WasmLibrary library; {world_resource_finalizer}", )); let mut constructor: Vec<String> = vec![]; let mut constructor_body: Vec<String> = vec![]; let mut methods = String::new(); w.exports.iter().for_each(|(key, i)| { let id = p.world_key_type_name(key); let id_name = id.as_var(); match i { WorldItem::Interface(_interface_id) => { constructor_body.push(format!("{id_name} = {}(this);", heck::AsPascalCase(id))); s.push_str(&format!("late final {} {id_name};", heck::AsPascalCase(id),)); } WorldItem::Type(_type_id) => {} WorldItem::Function(f) => { let fn_name = if p.2.async_worker { "getComponentFunctionWorker" } else { "getComponentFunction" }; constructor.push(format!( "_{id_name} = library.{fn_name}('{id}', const {},)!", p.function_spec(f) )); p.add_function(&mut methods, f, FuncKind::MethodCall, true); } }; }); s.push_str(&format!( "\n\n{w_name}World({{ required this.imports, required this.library, }})" )); if constructor.is_empty() && constructor_body.is_empty() { s.push_str(";"); } else if constructor_body.is_empty() { s.push_str(&format!(": {};", constructor.join(", "))); } else if constructor.is_empty() { s.push_str(&format!("{{{}}}", constructor_body.join("\n"))); } else { s.push_str(&format!( ": {} {{{}}}", constructor.join(", "), constructor_body.join("\n") )); } let int64_type = match p.2.int64_type { Int64TypeConfig::BigInt => "Int64TypeConfig.bigInt", Int64TypeConfig::BigIntUnsignedOnly => "Int64TypeConfig.bigIntUnsignedOnly", Int64TypeConfig::CoreInt => "Int64TypeConfig.coreInt", Int64TypeConfig::NativeObject => "Int64TypeConfig.nativeObject", }; let instantiate = if p.2.async_worker { worker_instantiation(int64_type) } else { let package = resolve.packages.get(w.package.unwrap()).unwrap(); let component_id = format!("{}/{}", package.name, w.name); format!( "final instance = await builder.build(); library = WasmLibrary(instance, componentId: '{component_id}', int64Type: {int64_type});" ) }; s.push_str(&format!( "\n\nstatic Future<{w_name}World> init( WasmInstanceBuilder builder, {{ required {w_name}WorldImports imports, }}) async {{ late final WasmLibrary library; WasmLibrary getLib() => library; {func_imports} {instantiate} return {w_name}World(imports: imports, library: library); }} static final _zoneKey = Object(); late final _zoneValues = {{_zoneKey: this}}; static {w_name}World? currentZoneWorld() => Zone.current[_zoneKey] as {w_name}World?; T withContext<T>(T Function() fn) => runZoned(fn, zoneValues: _zoneValues); {methods} ", )); s.push_str("}"); }); Ok(s) } fn worker_instantiation(int64_type: &str) -> String { format!( " var memType = MemoryTy(minimum: 1, maximum: 2, shared: true); try {{ // Find the shared memory import. May not work in web. final mem = builder.module.getImports().firstWhere( (e) => e.kind == WasmExternalKind.memory && (e.type!.field0 as MemoryTy).shared, ); memType = mem.type!.field0 as MemoryTy; }} catch (_) {{}} var attempts = 0; late WasmSharedMemory wasmMemory; WasmInstance? instance; while (instance == null) {{ try {{ wasmMemory = builder.module.createSharedMemory( minPages: memType.minimum, maxPages: memType.maximum! > memType.minimum ? memType.maximum! : memType.minimum + 1, ); builder.addImport('env', 'memory', wasmMemory); instance = await builder.build(); }} catch (e) {{ // TODO: This is not great, remove it. if (identical(0, 0.0) && attempts < 2) {{ final str = e.toString(); final init = RegExp('initial ([0-9]+)').firstMatch(str); final maxi = RegExp('maximum ([0-9]+)').firstMatch(str); if (init != null || maxi != null) {{ final initVal = init == null ? memType.minimum : int.parse(init.group(1)!); final maxVal = maxi == null ? memType.maximum : int.parse(maxi.group(1)!); memType = MemoryTy(minimum: initVal, maximum: maxVal, shared: true); attempts++; continue; }} }} rethrow; }} }} library = WasmLibrary( instance, int64Type: {int64_type}, wasmMemory: wasmMemory, );" ) } pub fn add_docs(s: &mut String, docs: &Docs) { if let Some(docs) = extract_dart_docs(docs) { s.push_str(&docs); } } pub fn extract_dart_docs(docs: &Docs) -> Option<String> { if let Some(docs) = &docs.contents { let mut m = docs.clone(); if m.ends_with('\n') { m.replace_range(m.len() - 1.., ""); } Some( m.split("\n") .map(|l| format!("/// {}\n", l)) .collect::<Vec<_>>() .join(""), ) } else { None } } const HEADER: &str = " // FILE GENERATED FROM WIT // ignore: lines_longer_than_80_chars // ignore_for_file: require_trailing_commas, unnecessary_raw_strings, unnecessary_non_null_assertion, unused_element, avoid_returning_null_for_void import 'dart:async'; // ignore: unused_import import 'dart:typed_data'; import 'package:wasm_wit_component/wasm_wit_component.dart'; "; #[cfg(test)] mod tests { use std::{fs::File, io::Write, path::Path}; use crate::{Int64TypeConfig, WitGeneratorConfig}; const PACKAGE_DIR: &str = env!("CARGO_MANIFEST_DIR"); fn default_wit_config(int64_type: Int64TypeConfig) -> WitGeneratorConfig { WitGeneratorConfig { inputs: crate::WitGeneratorInput::FileSystemPaths(crate::FileSystemPaths { input_path: "".to_string(), }), copy_with: true, equality_and_hash_code: true, generate_docs: true, json_serialization: true, to_string: true, file_header: None, use_null_for_option: true, object_comparator: None, required_option: false, typed_number_lists: true, async_worker: false, same_class_union: true, int64_type, } } #[test] pub fn parse_wit() { let parsed = wit_parser::UnresolvedPackage::parse( Path::new("../wasm_wit_component/example/lib/host.wit"), " default world host { import print: func(msg: string) export run: func() } ", ) .unwrap(); let s = super::document_to_dart(&parsed, default_wit_config(Int64TypeConfig::BigInt)).unwrap(); println!("{}", s); } fn parse_and_write_generation(path: &str, output_path: &str, config: WitGeneratorConfig) { let parsed = wit_parser::UnresolvedPackage::parse_file(Path::new(path)).unwrap(); let s = super::document_to_dart(&parsed, config).unwrap(); // println!("{}", s); File::create(output_path) .unwrap() .write(s.as_bytes()) .unwrap(); std::process::Command::new("dart") .arg("format") .arg(output_path) .output() .unwrap(); } #[test] pub fn parse_wit_types() { let path = format!( "{}/wasm_wit_component/example/rust_wit_component_example/wit/types-example.wit", PACKAGE_DIR ); let output_path = format!( "{}/wasm_wit_component/example/lib/types_gen.dart", PACKAGE_DIR ); let mut config = default_wit_config(Int64TypeConfig::CoreInt); config.file_header = Some( "// CUSTOM FILE HEADER const objectComparator = ObjectComparator();\n\n" .to_string(), ); config.object_comparator = Some("objectComparator".to_string()); config.use_null_for_option = false; config.typed_number_lists = false; // TODO: test config.required_option = false; parse_and_write_generation(&path, &output_path, config); } #[test] pub fn parse_wit_types_big_int() { let path = format!( "{}/wasm_wit_component/example/rust_wit_component_example/wit/types-example.wit", PACKAGE_DIR ); let output_path = format!( "{}/wasm_wit_component/example/lib/types_gen_big_int.dart", PACKAGE_DIR ); parse_and_write_generation( &path, &output_path, default_wit_config(Int64TypeConfig::BigInt), ); } #[test] pub fn generate_image_ops() { let path = format!( "{}/../wasm_packages/image_ops/image_ops_wasm/wit/image-ops.wit", PACKAGE_DIR ); let output_path = format!( "{}/../wasm_packages/image_ops/lib/src/image_ops_wit.gen.dart", PACKAGE_DIR ); parse_and_write_generation( &path, &output_path, default_wit_config(Int64TypeConfig::BigInt), ); } #[test] pub fn generate_compression_rs() { let path = format!( "{}/../wasm_packages/compression_rs/compression_rs_wasm/wit/compression-rs.wit", PACKAGE_DIR ); let output_path = format!( "{}/../wasm_packages/compression_rs/lib/src/compression_rs_wit.gen.dart", PACKAGE_DIR ); parse_and_write_generation( &path, &output_path, default_wit_config(Int64TypeConfig::BigInt), ); } #[test] pub fn generate_compression_rs_worker() { let path = format!( "{}/../wasm_packages/compression_rs/compression_rs_wasm/wit/compression-rs.wit", PACKAGE_DIR ); let output_path = format!( "{}/../wasm_packages/compression_rs/lib/src/compression_rs_wit.worker.gen.dart", PACKAGE_DIR ); let mut config = default_wit_config(Int64TypeConfig::BigInt); config.async_worker = true; parse_and_write_generation(&path, &output_path, config); } #[test] pub fn generate_wasm_parser() { let path = format!( "{}/../wasm_packages/wasm_parser/wasm_parser_wasm/wit/wasm-parser.wit", PACKAGE_DIR ); let output_path = format!( "{}/../wasm_packages/wasm_parser/lib/src/wasm_parser_wit.gen.dart", PACKAGE_DIR ); parse_and_write_generation( &path, &output_path, default_wit_config(Int64TypeConfig::BigInt), ); } #[test] pub fn generate_wasm_parser_worker() { let path = format!( "{}/../wasm_packages/wasm_parser/wasm_parser_wasm/wit/wasm-parser.wit", PACKAGE_DIR ); let output_path = format!( "{}/../wasm_packages/wasm_parser/lib/src/wasm_parser_wit.worker.gen.dart", PACKAGE_DIR ); let mut config = default_wit_config(Int64TypeConfig::BigInt); config.async_worker = true; parse_and_write_generation(&path, &output_path, config); } #[test] pub fn generate_rust_crypto() { let path = format!( "{}/../wasm_packages/rust_crypto/rust_crypto_wasm/wit/rust-crypto.wit", PACKAGE_DIR ); let output_path = format!( "{}/../wasm_packages/rust_crypto/lib/src/rust_crypto_wit.gen.dart", PACKAGE_DIR ); parse_and_write_generation( &path, &output_path, default_wit_config(Int64TypeConfig::BigInt), ); } #[test] pub fn generate_host() { let path = format!("{}/wasm_wit_component/example/lib/host.wit", PACKAGE_DIR); let output_path = format!( "{}/wasm_wit_component/example/lib/host_wit_generation.dart", PACKAGE_DIR ); parse_and_write_generation( &path, &output_path, default_wit_config(Int64TypeConfig::BigInt), ); let contents = std::fs::read_to_string(&output_path).unwrap(); std::fs::write( &output_path, format!("const hostWitDartOutput = r'''\n{contents}''';\n"), ) .unwrap(); } #[test] pub fn parse_generator() { let path = format!("{}/wit/dart-wit-generator.wit", PACKAGE_DIR); let output_path = format!("{}/wasm_wit_component/lib/src/generator.dart", PACKAGE_DIR); parse_and_write_generation( &path, &output_path, default_wit_config(Int64TypeConfig::BigInt), ); } #[test] pub fn generate_all() { parse_generator(); parse_wit_types(); parse_wit_types_big_int(); generate_image_ops(); generate_compression_rs(); generate_compression_rs_worker(); generate_rust_crypto(); generate_host(); generate_wasm_parser(); generate_wasm_parser_worker(); } }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/dart_wit_component/wasm_wit_component/example/rust_wit_component_example/src/lib.rs
packages/dart_wit_component/wasm_wit_component/example/rust_wit_component_example/src/lib.rs
// Use a procedural macro to generate bindings for the world we specified in // `host.wit` wit_bindgen::generate!({ path: "wit/types-example.wit", exports: { world: MyHost, "types-example-namespace:types-example-pkg/round-trip-numbers": MyHost, "types-example-namespace:types-example-pkg/api": MyHost, "types-example-namespace:types-example-pkg/api/r1": ResourceR1, }, }); use exports::types_example_namespace::types_example_pkg::{api, *}; use types_example_namespace::types_example_pkg::{ api_imports as imports, round_trip_numbers as round_trip_numbers_host, types_interface, }; // Define a custom type and implement the generated `Host` trait for it which // represents implementing all the necessary exported interfaces for this // component. struct MyHost; impl TypesExample for MyHost { fn f_f1(mut typedef: T10) -> T10 { if let Some(s) = typedef.last() { print(s, LogLevel::Info); } typedef.push("last_value".to_string()); typedef } fn f1(f: f32, f_list: Vec<(char, f64)>) -> (i64, String) { ( f.to_bits().into(), f_list.iter().map(|(c, f)| format!("{c}:{f}")).collect(), ) } fn re_named(perm: Option<Permissions>, e: Option<Empty>) -> T2Renamed { ( if let Some(perm) = perm { perm.bits().into() } else { 0 }, if e.is_some() { 0 } else { 1 }, ) } fn re_named2(tup: (Vec<u16>,), _e: Empty) -> (Option<u8>, i8) { ( if tup.0.len() < 256 { Some(tup.0.len().try_into().unwrap()) } else { None }, if tup.0.is_empty() { -1 } else { 1 }, ) } } impl api::Api for MyHost { fn f12() -> ((i32,), String) { ((1,), "hello".to_string()) } fn class(break_: Option<Option<api::T5>>) -> () { if let Some(v) = break_ { if let Some(v) = v { let charr = v.err().flatten().map(|e| e.c).flatten(); let r = inline::inline_imp(&[charr]); if let Err(e) = r { print(&e.to_string(), LogLevel::Warn); inline::inline_imp(&[Some(e)]).unwrap(); } else { inline::inline_imp(&[None, None]).unwrap(); } } else { inline::inline_imp(&[]).unwrap(); } } () } fn continue_(abstract_: Option<Result<(), api::Errno>>, _extends_: ()) -> Option<()> { if let Some(r) = abstract_ { if let Err(r) = r { _ = match (r.str, r.a_u1, r.c, r.list_s1.first()) { (Some(s), _, None, Some(i)) => { imports::api_a1_b2(&[imports::Human::Adult((s, None, (*i,)))]) } (None, _, Some(ch), Some(i)) => imports::api_a1_b2(&[imports::Human::Adult(( ch.to_lowercase().to_string(), Some(None), (*i,), ))]), (Some(s), _, Some(ch), Some(i)) => { imports::api_a1_b2(&[imports::Human::Adult(( s.clone(), Some(Some(format!("{s}{ch}"))), (*i,), ))]) } (None, v, _, _) => imports::api_a1_b2(&[imports::Human::Child(v)]), _ => imports::api_a1_b2(&[imports::Human::Baby]), }; } else { _ = imports::api_a1_b2(&[]); } Some(()) } else { None } } fn record_func( r: types_interface::R, e: types_interface::Errno, p: types_interface::Permissions, i: types_interface::Input, ) -> ( types_interface::R, types_interface::Errno, types_interface::Permissions, types_interface::Input, ) { imports::record_func(&r, e, p, &i) } fn static_f1(a: api::OwnR1) -> wit_bindgen::rt::string::String { <ResourceR1 as api::R1>::static_f1(a) } fn merge(lhs: &api::RepR1, rhs: &api::RepR1) -> api::OwnR1 { <ResourceR1 as api::R1>::merge(lhs, rhs) } } impl round_trip_numbers::RoundTripNumbers for MyHost { fn round_trip_numbers( data: round_trip_numbers::RoundTripNumbersData, ) -> round_trip_numbers::RoundTripNumbersData { let result = round_trip_numbers_host::round_trip_numbers( round_trip_numbers_host::RoundTripNumbersData { f32: data.f32, f64: data.f64, si8: data.si8, un8: data.un8, si16: data.si16, un16: data.un16, si32: data.si32, un32: data.un32, si64: data.si64, un64: data.un64, }, ); assert_eq!(result.si8, data.si8); assert_eq!(result.un8, data.un8); assert_eq!(result.si16, data.si16); assert_eq!(result.un16, data.un16); assert_eq!(result.si32, data.si32); assert_eq!(result.un32, data.un32); assert_eq!(result.si64, data.si64); assert_eq!(result.un64, data.un64); data } fn round_trip_numbers_list( data: round_trip_numbers::RoundTripNumbersListData, ) -> round_trip_numbers::RoundTripNumbersListData { let arg = round_trip_numbers_host::RoundTripNumbersListData { f32: data.f32.clone(), f64: data.f64.clone(), si8: data.si8.clone(), un8: data.un8.clone(), si16: data.si16.clone(), un16: data.un16.clone(), si32: data.si32.clone(), un32: data.un32.clone(), si64: data.si64.clone(), un64: data.un64.clone(), si64_list: data.si64_list.clone(), un64_list: data.un64_list.clone(), un8_list: data.un8_list.clone(), }; let result = round_trip_numbers_host::round_trip_numbers_list(&arg); assert_eq!(result.si8, data.si8); assert_eq!(result.un8, data.un8); assert_eq!(result.si16, data.si16); assert_eq!(result.un16, data.un16); assert_eq!(result.si32, data.si32); assert_eq!(result.un32, data.un32); assert_eq!(result.si64, data.si64); assert_eq!(result.un64, data.un64); assert_eq!(result.si64_list, data.si64_list); assert_eq!(result.un64_list, data.un64_list); assert_eq!(result.un8_list, data.un8_list); data } } pub struct ResourceR1(String); impl api::R1 for ResourceR1 { #[doc = " constructor for r1"] fn new(name: wit_bindgen::rt::string::String) -> Self { ResourceR1(name) } #[doc = " Comment for f2"] fn length(&self) -> u32 { self.0.len().try_into().unwrap() } fn name(&self) -> wit_bindgen::rt::string::String { self.0.clone() } fn static_default() -> wit_bindgen::rt::string::String { "DEFAULT".to_string() } #[doc = " Comment for static f1"] fn static_f1(a: api::OwnR1) -> wit_bindgen::rt::string::String { a.0.clone() } fn merge(lhs: &api::RepR1, rhs: &api::RepR1) -> api::OwnR1 { api::OwnR1::new(ResourceR1(format!("{}{}", lhs.0, rhs.0))) } }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_run/native/build.rs
packages/wasm_run/native/build.rs
use std::io::Write; use lib_flutter_rust_bridge_codegen::{ config_parse, frb_codegen, get_symbols_if_no_duplicates, RawOpts, }; const RUST_INPUT: &str = "src/api.rs"; const DART_OUTPUT: &str = "../lib/src/bridge_generated.dart"; const IOS_C_OUTPUT: &str = "../../wasm_run_flutter/ios/Classes/frb.h"; const MACOS_C_OUTPUT_DIR: &str = "../../wasm_run_flutter/macos/Classes/"; fn main() { // Tell Cargo that if the input Rust code changes, rerun this build script println!("cargo:rerun-if-changed={}", RUST_INPUT); let _ = std::fs::remove_file("../example/test/main_test.bootstrap.isolate.dart"); // Options for frb_codegen let raw_opts = RawOpts { rust_input: vec![RUST_INPUT.to_string()], dart_output: vec![DART_OUTPUT.to_string()], c_output: Some(vec![IOS_C_OUTPUT.to_string()]), extra_c_output_path: Some(vec![MACOS_C_OUTPUT_DIR.to_string()]), inline_rust: true, wasm: true, ..Default::default() }; // Generate Rust & Dart ffi bridges let configs = config_parse(raw_opts); let all_symbols = get_symbols_if_no_duplicates(&configs).unwrap(); for config in configs.iter() { frb_codegen(config, &all_symbols).unwrap(); } let mut generated = std::fs::File::options() .append(true) .open("../lib/src/bridge_generated.dart") .unwrap(); generated .write_all( " extension WasmRunDartImplPlatform on WasmRunDartImpl { WasmRunDartPlatform get platform => _platform; } " .as_bytes(), ) .unwrap(); for file in [ "../lib/src/bridge_generated.dart", "../lib/src/bridge_generated.io.dart", "../lib/src/bridge_generated.web.dart", ] { let mut buf = std::fs::read_to_string(file).unwrap(); buf = buf.replace("\nimport 'package:uuid/uuid.dart';", ""); std::fs::write(file, buf).unwrap(); } // Format the generated Dart code _ = std::process::Command::new("dart") .arg("format") .arg("..") .spawn(); }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_run/native/src/external.rs
packages/wasm_run/native/src/external.rs
use std::{ any::Any, fmt::Debug, panic::{RefUnwindSafe, UnwindSafe}, }; #[derive(Debug)] pub struct WFunc { #[cfg(not(feature = "wasmtime"))] pub func_wasmi: wasmi::Func, #[cfg(feature = "wasmtime")] pub func_wasmtime: wasmtime::Func, } #[cfg(feature = "wasmtime")] impl From<wasmtime::Func> for WFunc { fn from(func: wasmtime::Func) -> Self { Self { func_wasmtime: func, } } } #[cfg(feature = "wasmtime")] impl From<WFunc> for wasmtime::Func { fn from(func: WFunc) -> Self { func.func_wasmtime } } #[cfg(not(feature = "wasmtime"))] impl From<wasmi::Func> for WFunc { fn from(func: wasmi::Func) -> Self { Self { func_wasmi: func } } } #[cfg(not(feature = "wasmtime"))] impl From<WFunc> for wasmi::Func { fn from(func: WFunc) -> Self { func.func_wasmi } } #[derive(Debug)] pub struct WMemory { #[cfg(not(feature = "wasmtime"))] pub func_wasmi: wasmi::Memory, #[cfg(feature = "wasmtime")] pub func_wasmtime: wasmtime::Memory, } #[cfg(feature = "wasmtime")] impl From<wasmtime::Memory> for WMemory { fn from(func: wasmtime::Memory) -> Self { Self { func_wasmtime: func, } } } #[cfg(feature = "wasmtime")] impl From<WMemory> for wasmtime::Memory { fn from(func: WMemory) -> Self { func.func_wasmtime } } #[cfg(not(feature = "wasmtime"))] impl From<wasmi::Memory> for WMemory { fn from(func: wasmi::Memory) -> Self { Self { func_wasmi: func } } } #[cfg(not(feature = "wasmtime"))] impl From<WMemory> for wasmi::Memory { fn from(func: WMemory) -> Self { func.func_wasmi } } #[derive(Debug)] pub struct WGlobal(Box<dyn Any>); impl UnwindSafe for WGlobal {} impl RefUnwindSafe for WGlobal {} #[cfg(feature = "wasmtime")] impl From<wasmtime::Global> for WGlobal { fn from(func: wasmtime::Global) -> Self { Self(Box::new(func)) } } #[cfg(feature = "wasmtime")] impl From<WGlobal> for wasmtime::Global { fn from(func: WGlobal) -> Self { *func.0.downcast::<wasmtime::Global>().unwrap() } } #[cfg(not(feature = "wasmtime"))] impl From<wasmi::Global> for WGlobal { fn from(func: wasmi::Global) -> Self { Self(Box::new(func)) } } #[cfg(not(feature = "wasmtime"))] impl From<WGlobal> for wasmi::Global { fn from(func: WGlobal) -> Self { *func.0.downcast::<wasmi::Global>().unwrap() } } #[derive(Debug)] pub struct WTable(Box<dyn Any>); impl UnwindSafe for WTable {} impl RefUnwindSafe for WTable {} #[cfg(feature = "wasmtime")] impl From<wasmtime::Table> for WTable { fn from(func: wasmtime::Table) -> Self { Self(Box::new(func)) } } #[cfg(feature = "wasmtime")] impl From<WTable> for wasmtime::Table { fn from(func: WTable) -> Self { *func.0.downcast::<wasmtime::Table>().unwrap() } } #[cfg(not(feature = "wasmtime"))] impl From<wasmi::Table> for WTable { fn from(func: wasmi::Table) -> Self { Self(Box::new(func)) } } #[cfg(not(feature = "wasmtime"))] impl From<WTable> for wasmi::Table { fn from(func: WTable) -> Self { *func.0.downcast::<wasmi::Table>().unwrap() } }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_run/native/src/config.rs
packages/wasm_run/native/src/config.rs
#[derive(Debug)] pub struct WasiConfigNative { /// Whether to capture stdout. /// If this is true, you can use the [WasmInstance.stdout] /// getter to retrieve a stream of the module's stdout. pub capture_stdout: bool, /// Whether to capture stderr /// If this is true, you can use the [WasmInstance.stderr] /// getter to retrieve a stream of the module's stderr. pub capture_stderr: bool, // TODO: custom stdin /// Whether to inherit stdin from the host process. pub inherit_stdin: bool, /// Whether to inherit environment variables from the host process. pub inherit_env: bool, /// Whether to inherit the process arguments from the host process. pub inherit_args: bool, /// Custom process arguments to pass to the WASM module pub args: Vec<String>, /// Custom Environment variables to pass to the WASM module pub env: Vec<EnvVariable>, /// Custom preopened files to pass to the WASM module pub preopened_files: Vec<String>, /// Custom preopened directories to pass to the WASM module /// The module will be able to access and edit these directories pub preopened_dirs: Vec<PreopenedDir>, } #[derive(Debug)] #[allow(non_camel_case_types)] pub enum StdIOKind { stdout, stderr, } #[cfg(feature = "wasi")] impl WasiConfigNative { pub fn to_wasi_ctx(&self) -> anyhow::Result<wasi_common::WasiCtx> { #[cfg(not(feature = "wasmtime"))] use wasmi_wasi::{ambient_authority, WasiCtxBuilder}; #[cfg(feature = "wasmtime")] use wasmtime_wasi::{ambient_authority, WasiCtxBuilder}; // add wasi to linker #[cfg(not(feature = "wasmtime"))] let mut wasi_builder = WasiCtxBuilder::new(); #[cfg(feature = "wasmtime")] let mut wasi_builder = &mut WasiCtxBuilder::new(); if self.inherit_args { wasi_builder = wasi_builder.inherit_args()?; } if self.inherit_env { wasi_builder = wasi_builder.inherit_env()?; } if self.inherit_stdin { wasi_builder = wasi_builder.inherit_stdin(); } if !self.capture_stdout { wasi_builder = wasi_builder.inherit_stdout(); } if !self.capture_stderr { wasi_builder = wasi_builder.inherit_stderr(); } if !self.args.is_empty() { for value in &self.args { wasi_builder = wasi_builder.arg(value)?; } } if !self.env.is_empty() { for EnvVariable { name, value } in &self.env { wasi_builder = wasi_builder.env(name, value)?; } } if !self.preopened_dirs.is_empty() { for PreopenedDir { wasm_guest_path, host_path, } in &self.preopened_dirs { let dir = cap_std::fs::Dir::open_ambient_dir(host_path, ambient_authority())?; wasi_builder = wasi_builder.preopened_dir(dir, wasm_guest_path)?; } } Ok(wasi_builder.build()) } } #[derive(Debug)] pub struct EnvVariable { /// The name of the environment variable pub name: String, /// The value of the environment variable pub value: String, } /// A preopened directory that the WASM module will be able to access #[derive(Debug)] pub struct PreopenedDir { /// The path inside the WASM module. /// Should be "/" separated, if you are on windows, you will need to convert the path pub wasm_guest_path: String, /// The path on the host that the WASM module will be able to access /// and corresponds to the [wasm_guest_path] pub host_path: String, } pub struct WasmRuntimeFeatures { /// The name of the runtime. /// For example, "wasmi" or "wasmtime". pub name: String, /// The version of the runtime. /// For example, "0.31.0" or "14.0.4". pub version: String, /// Is `true` if the runtime is the one provided by the browser. pub is_browser: bool, /// The features supported by the runtime. pub supported_features: WasmFeatures, /// The default features of the runtime. /// If a feature is supported, but it is not enable by default, /// then it must be enabled manually, perhaps with [ModuleConfig], /// and it may be experimental. pub default_features: WasmFeatures, } impl Default for WasmRuntimeFeatures { #[cfg(not(feature = "wasmtime"))] fn default() -> Self { WasmRuntimeFeatures { name: "wasmi".to_string(), version: "0.31.0".to_string(), is_browser: false, supported_features: WasmFeatures::supported(), default_features: WasmFeatures::default(), } } #[cfg(feature = "wasmtime")] fn default() -> Self { WasmRuntimeFeatures { name: "wasmtime".to_string(), version: "14.0.4".to_string(), is_browser: false, supported_features: WasmFeatures::supported(), default_features: WasmFeatures::default(), } } } #[derive(Debug)] pub struct ModuleConfig { /// Is `true` if the [`multi-value`] Wasm proposal is enabled. pub multi_value: Option<bool>, /// Is `true` if the [`bulk-memory`] Wasm proposal is enabled. pub bulk_memory: Option<bool>, /// Is `true` if the [`reference-types`] Wasm proposal is enabled. pub reference_types: Option<bool>, /// Is `true` if executions shall consume fuel. pub consume_fuel: Option<bool>, /// Configuration specific to the wasmi runtime pub wasmi: Option<ModuleConfigWasmi>, /// Configuration specific to the wasmtime runtime pub wasmtime: Option<ModuleConfigWasmtime>, } #[cfg(feature = "wasmtime")] impl From<ModuleConfig> for wasmtime::Config { fn from(c: ModuleConfig) -> Self { let mut config = Self::new(); c.multi_value.map(|v| config.wasm_multi_value(v)); c.bulk_memory.map(|v| config.wasm_bulk_memory(v)); c.reference_types.map(|v| config.wasm_reference_types(v)); c.consume_fuel.map(|v| config.consume_fuel(v)); if let Some(wtc) = c.wasmtime { // TODO: feature incremental-cache // wtc.enable_incremental_compilation.map(|v| config.enable_incremental_compilation(v)); // wtc.async_support.map(|v| config.async_support(v)); wtc.debug_info.map(|v| config.debug_info(v)); wtc.wasm_backtrace.map(|v| config.wasm_backtrace(v)); wtc.native_unwind_info.map(|v| config.native_unwind_info(v)); // wtc.epoch_interruption.map(|v| config.epoch_interruption(v)); wtc.max_wasm_stack.map(|v| config.max_wasm_stack(v)); wtc.wasm_simd.map(|v| config.wasm_simd(v)); wtc.wasm_relaxed_simd.map(|v| config.wasm_relaxed_simd(v)); wtc.relaxed_simd_deterministic .map(|v| config.relaxed_simd_deterministic(v)); wtc.wasm_threads.map(|v| config.wasm_threads(v)); wtc.wasm_multi_memory.map(|v| config.wasm_multi_memory(v)); // TODO: wtc.tail_call.map(|v| config.wasm_tail_call(v)); wtc.wasm_memory64.map(|v| config.wasm_memory64(v)); // TODO: feature component-model // wtc.wasm_component_model.map(|v| config.wasm_component_model(v)); wtc.static_memory_maximum_size .map(|v| config.static_memory_maximum_size(v)); wtc.static_memory_forced .map(|v| config.static_memory_forced(v)); wtc.static_memory_guard_size .map(|v| config.static_memory_guard_size(v)); wtc.parallel_compilation .map(|v| config.parallel_compilation(v)); wtc.generate_address_map .map(|v| config.generate_address_map(v)); } config } } #[cfg(not(feature = "wasmtime"))] impl From<ModuleConfig> for wasmi::Config { fn from(c: ModuleConfig) -> Self { let mut config = Self::default(); c.multi_value.map(|v| config.wasm_multi_value(v)); c.bulk_memory.map(|v| config.wasm_bulk_memory(v)); c.reference_types.map(|v| config.wasm_reference_types(v)); c.consume_fuel.map(|v| config.consume_fuel(v)); if let Some(wic) = c.wasmi { wic.stack_limits .map(|v| config.set_stack_limits(v.try_into().unwrap())); wic.cached_stacks.map(|v| config.set_cached_stacks(v)); wic.mutable_global.map(|v| config.wasm_mutable_global(v)); wic.sign_extension.map(|v| config.wasm_sign_extension(v)); wic.saturating_float_to_int .map(|v| config.wasm_saturating_float_to_int(v)); wic.tail_call.map(|v| config.wasm_tail_call(v)); wic.extended_const.map(|v| config.wasm_extended_const(v)); wic.floats.map(|v| config.floats(v)); // config.set_fuel_costs(wic.flue_costs); } config } } #[derive(Debug)] pub struct ModuleConfigWasmi { /// The limits set on the value stack and call stack. pub stack_limits: Option<WasiStackLimits>, /// The amount of Wasm stacks to keep in cache at most. pub cached_stacks: Option<usize>, /// Is `true` if the `mutable-global` Wasm proposal is enabled. pub mutable_global: Option<bool>, /// Is `true` if the `sign-extension` Wasm proposal is enabled. pub sign_extension: Option<bool>, /// Is `true` if the `saturating-float-to-int` Wasm proposal is enabled. pub saturating_float_to_int: Option<bool>, /// Is `true` if the [`tail-call`] Wasm proposal is enabled. pub tail_call: Option<bool>, // wasmtime disabled /// Is `true` if the [`extended-const`] Wasm proposal is enabled. pub extended_const: Option<bool>, /// Is `true` if Wasm instructions on `f32` and `f64` types are allowed. pub floats: Option<bool>, // /// The fuel consumption mode of the `wasmi` [`Engine`](crate::Engine). // // TODO: pub fuel_consumption_mode: FuelConsumptionMode, // /// The configured fuel costs of all `wasmi` bytecode instructions. // // pub fuel_costs: FuelCosts, } /// The configured limits of the Wasm stack. #[derive(Debug, Copy, Clone)] pub struct WasiStackLimits { /// The initial value stack height that the Wasm stack prepares. pub initial_value_stack_height: usize, /// The maximum value stack height in use that the Wasm stack allows. pub maximum_value_stack_height: usize, /// The maximum number of nested calls that the Wasm stack allows. pub maximum_recursion_depth: usize, } #[cfg(not(feature = "wasmtime"))] impl TryFrom<WasiStackLimits> for wasmi::StackLimits { type Error = anyhow::Error; fn try_from(value: WasiStackLimits) -> std::result::Result<Self, Self::Error> { use crate::types::to_anyhow; Self::new( value.initial_value_stack_height, value.maximum_value_stack_height, value.maximum_recursion_depth, ) .map_err(to_anyhow) } } #[derive(Debug)] pub struct ModuleConfigWasmtime { // TODO: pub enable_incremental_compilation: Option<bool>, incremental-cache feature // TODO: pub async_support: Option<bool>, async feature /// Configures whether DWARF debug information will be emitted during /// compilation. pub debug_info: Option<bool>, pub wasm_backtrace: Option<bool>, pub native_unwind_info: Option<bool>, // TODO: pub wasm_backtrace_details: WasmBacktraceDetails, // Or WASMTIME_BACKTRACE_DETAILS env var // // TODO: pub epoch_interruption: Option<bool>, // vs consume_fuel pub max_wasm_stack: Option<usize>, /// Whether or not to enable the `threads` WebAssembly feature. /// This includes atomics and shared memory as well. /// This is not enabled by default. pub wasm_threads: Option<bool>, /// Whether or not to enable the `simd` WebAssembly feature. pub wasm_simd: Option<bool>, /// Whether or not to enable the `relaxed-simd` WebAssembly feature. /// This is not enabled by default. pub wasm_relaxed_simd: Option<bool>, /// Whether [wasm_relaxed_simd] should be deterministic. /// This is false by default. pub relaxed_simd_deterministic: Option<bool>, /// Whether or not to enable the `multi-memory` WebAssembly feature. /// This is not enabled by default. pub wasm_multi_memory: Option<bool>, /// Whether or not to enable the `memory64` WebAssembly feature. /// This is not enabled by default. pub wasm_memory64: Option<bool>, // TODO: pub wasm_component_model: Option<bool>, // false component-model feature // // pub strategy: Strategy, // TODO: pub profiler: ProfilingStrategy, // TODO: pub allocation_strategy: OnDemand, // vs Polling feature flag pub static_memory_maximum_size: Option<u64>, pub static_memory_forced: Option<bool>, pub static_memory_guard_size: Option<u64>, pub parallel_compilation: Option<bool>, pub generate_address_map: Option<bool>, } /// https://docs.wasmtime.dev/stability-wasm-proposals-support.html pub struct WasmFeatures { /// The WebAssembly `mutable-global` proposal (enabled by default) pub mutable_global: bool, /// The WebAssembly `nontrapping-float-to-int-conversions` proposal (enabled by default) pub saturating_float_to_int: bool, /// The WebAssembly `sign-extension-ops` proposal (enabled by default) pub sign_extension: bool, /// The WebAssembly reference types proposal (enabled by default) pub reference_types: bool, /// The WebAssembly multi-value proposal (enabled by default) pub multi_value: bool, /// The WebAssembly bulk memory operations proposal (enabled by default) pub bulk_memory: bool, /// The WebAssembly SIMD proposal pub simd: bool, /// The WebAssembly Relaxed SIMD proposal pub relaxed_simd: bool, /// The WebAssembly threads proposal, shared memory and atomics /// https://docs.rs/wasmtime/14.0.4/wasmtime/struct.Config.html#method.wasm_threads pub threads: bool, /// The WebAssembly tail-call proposal pub tail_call: bool, /// Whether or not floating-point instructions are enabled. /// /// This is enabled by default can be used to disallow floating-point /// operators and types. /// /// This does not correspond to a WebAssembly proposal but is instead /// intended for embeddings which have stricter-than-usual requirements /// about execution. Floats in WebAssembly can have different NaN patterns /// across hosts which can lead to host-dependent execution which some /// runtimes may not desire. pub floats: bool, /// The WebAssembly multi memory proposal pub multi_memory: bool, /// The WebAssembly exception handling proposal pub exceptions: bool, /// The WebAssembly memory64 proposal pub memory64: bool, /// The WebAssembly extended_const proposal pub extended_const: bool, /// The WebAssembly component model proposal pub component_model: bool, /// The WebAssembly memory control proposal pub memory_control: bool, /// The WebAssembly garbage collection (GC) proposal pub garbage_collection: bool, /// WebAssembly external types reflection or, for browsers, /// the js-types proposal (https://github.com/WebAssembly/js-types/blob/main/proposals/js-types/Overview.md) pub type_reflection: bool, /// The WebAssembly System Interface proposal pub wasi_features: Option<WasmWasiFeatures>, // TODO: // final bool moduleLinking; } /// https://docs.wasmtime.dev/stability-wasi-proposals-support.html pub struct WasmWasiFeatures { // TODO: pub snapshot_preview1: bool, /// Access to standard input, output, and error streams pub io: bool, /// Access to the filesystem pub filesystem: bool, /// Access to clocks and the system time pub clocks: bool, /// Access to random number generators pub random: bool, pub poll: bool, /// wasi-nn pub machine_learning: bool, /// wasi-crypto pub crypto: bool, /// WASM threads with ability to spawn /// https://github.com/WebAssembly/wasi-threads pub threads: bool, } impl WasmWasiFeatures { /// Returns the default set of Wasi features. pub fn default() -> WasmWasiFeatures { WasmWasiFeatures { io: true, filesystem: true, clocks: true, random: true, poll: true, // TODO: implement through separate libraries machine_learning: false, crypto: false, // Unsupported threads: false, } } pub fn supported() -> WasmWasiFeatures { WasmWasiFeatures::default() } } impl WasmFeatures { /// Returns the default set of Wasm features. pub fn default() -> WasmFeatures { #[cfg(feature = "wasmtime")] { return WasmFeatures { multi_value: true, bulk_memory: true, reference_types: true, mutable_global: true, saturating_float_to_int: true, sign_extension: true, extended_const: true, floats: true, simd: true, relaxed_simd: false, threads: false, // Default false multi_memory: false, // Default false memory64: false, // Default false // Unsupported component_model: false, // Feature garbage_collection: false, tail_call: false, exceptions: false, memory_control: false, type_reflection: true, wasi_features: if cfg!(feature = "wasi") { Some(WasmWasiFeatures::default()) } else { None }, }; } // TODO: use features crate #[allow(unreachable_code)] WasmFeatures { multi_value: true, bulk_memory: true, reference_types: true, mutable_global: true, saturating_float_to_int: true, sign_extension: true, tail_call: false, // Default false extended_const: false, // Default false floats: true, // Unsupported component_model: false, garbage_collection: false, simd: false, relaxed_simd: false, threads: false, multi_memory: false, exceptions: false, memory64: false, memory_control: false, type_reflection: true, wasi_features: if cfg!(feature = "wasi") { Some(WasmWasiFeatures::default()) } else { None }, } } pub fn supported() -> WasmFeatures { #[cfg(feature = "wasmtime")] { return WasmFeatures { multi_value: true, bulk_memory: true, reference_types: true, mutable_global: true, saturating_float_to_int: true, sign_extension: true, extended_const: true, floats: true, simd: true, relaxed_simd: true, threads: true, multi_memory: true, memory64: true, // Unsupported component_model: false, // Feature garbage_collection: false, exceptions: false, tail_call: false, memory_control: false, type_reflection: true, wasi_features: if cfg!(feature = "wasi") { Some(WasmWasiFeatures::supported()) } else { None }, }; } // TODO: use features crate #[allow(unreachable_code)] WasmFeatures { multi_value: true, bulk_memory: true, reference_types: true, mutable_global: true, saturating_float_to_int: true, sign_extension: true, tail_call: true, extended_const: true, floats: true, // Unsupported component_model: false, garbage_collection: false, simd: false, relaxed_simd: false, threads: false, multi_memory: false, exceptions: false, memory64: false, memory_control: false, type_reflection: true, wasi_features: if cfg!(feature = "wasi") { Some(WasmWasiFeatures::supported()) } else { None }, } } } impl ModuleConfig { /// Returns the [`WasmFeatures`] represented by the [`ModuleConfig`]. // TODO: use features crate #[allow(unreachable_code)] pub fn wasm_features(&self) -> WasmFeatures { #[cfg(feature = "wasmtime")] { let w = self.wasmtime.as_ref(); let def = WasmFeatures::default(); return WasmFeatures { multi_value: self.multi_value.unwrap_or(def.multi_value), bulk_memory: self.bulk_memory.unwrap_or(def.bulk_memory), reference_types: self.reference_types.unwrap_or(def.reference_types), // True by default, can't be configured mutable_global: true, saturating_float_to_int: true, sign_extension: true, extended_const: true, floats: true, simd: w.and_then(|w| w.wasm_simd).unwrap_or(def.simd), threads: w.and_then(|w| w.wasm_threads).unwrap_or(def.threads), multi_memory: w .and_then(|w| w.wasm_multi_memory) .unwrap_or(def.multi_memory), memory64: w.and_then(|w| w.wasm_memory64).unwrap_or(def.memory64), relaxed_simd: w .and_then(|w| w.wasm_relaxed_simd) .unwrap_or(def.relaxed_simd), // Unsupported component_model: false, // Feature garbage_collection: false, tail_call: false, exceptions: false, memory_control: false, type_reflection: true, wasi_features: if cfg!(feature = "wasi") { Some(WasmWasiFeatures::default()) } else { None }, }; } let w = self.wasmi.as_ref(); let def = WasmFeatures::default(); WasmFeatures { multi_value: self.multi_value.unwrap_or(def.multi_value), bulk_memory: self.bulk_memory.unwrap_or(def.bulk_memory), reference_types: self.reference_types.unwrap_or(def.reference_types), mutable_global: w .and_then(|w| w.mutable_global) .unwrap_or(def.mutable_global), saturating_float_to_int: w .and_then(|w| w.saturating_float_to_int) .unwrap_or(def.saturating_float_to_int), sign_extension: w .and_then(|w| w.sign_extension) .unwrap_or(def.sign_extension), tail_call: w.and_then(|w| w.tail_call).unwrap_or(def.tail_call), extended_const: w .and_then(|w| w.extended_const) .unwrap_or(def.extended_const), floats: w.and_then(|w| w.floats).unwrap_or(def.floats), // Unsupported garbage_collection: false, component_model: false, simd: false, relaxed_simd: false, threads: false, multi_memory: false, exceptions: false, memory64: false, memory_control: false, type_reflection: true, wasi_features: if cfg!(feature = "wasi") { Some(WasmWasiFeatures::default()) } else { None }, } } }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_run/native/src/lib.rs
packages/wasm_run/native/src/lib.rs
mod api; // #[cfg(feature = "wasmtime")] // mod api_wt; // #[cfg(not(feature = "wasmtime"))] // mod api_wasmi; mod bridge_generated; mod config; mod external; // mod interface; #[allow(dead_code)] mod atomics; mod types;
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_run/native/src/atomics.rs
packages/wasm_run/native/src/atomics.rs
use std::{cell::UnsafeCell, sync::atomic}; pub enum AtomicKind { I8, I16, I32, I64, U8, U16, U32, U64, } pub enum AtomicOrdering { Relaxed, Release, Acquire, AcqRel, SeqCst, } impl From<AtomicOrdering> for atomic::Ordering { fn from(order: AtomicOrdering) -> Self { match order { AtomicOrdering::Relaxed => atomic::Ordering::Relaxed, AtomicOrdering::Release => atomic::Ordering::Release, AtomicOrdering::Acquire => atomic::Ordering::Acquire, AtomicOrdering::AcqRel => atomic::Ordering::AcqRel, AtomicOrdering::SeqCst => atomic::Ordering::SeqCst, } } } /// Result of [SharedMemory.atomicWait32] and [SharedMemory.atomicWait64] #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[allow(non_camel_case_types)] pub enum SharedMemoryWaitResult { /// Indicates that a `wait` completed by being awoken by a different thread. /// This means the thread went to sleep and didn't time out. ok = 0, /// Indicates that `wait` did not complete and instead returned due to the /// value in memory not matching the expected value. mismatch = 1, /// Indicates that `wait` completed with a timeout, meaning that the /// original value matched as expected but nothing ever called `notify`. timedOut = 2, } #[cfg(feature = "wasmtime")] impl From<wasmtime::WaitResult> for SharedMemoryWaitResult { fn from(result: wasmtime::WaitResult) -> Self { match result { wasmtime::WaitResult::Ok => SharedMemoryWaitResult::ok, wasmtime::WaitResult::Mismatch => SharedMemoryWaitResult::mismatch, wasmtime::WaitResult::TimedOut => SharedMemoryWaitResult::timedOut, } } } pub struct CompareExchangeResult { pub success: bool, pub value: i64, } macro_rules! create_atomic { ($integer_struct:ty, $integer:ty, $integer_atomic:ty) => { impl $integer_struct { pub unsafe fn load(&self, offset: usize, order: AtomicOrdering) -> $integer { let r = &(self.0 as *const UnsafeCell<u8>).add(offset); { &*(r as *const _ as *const $integer_atomic) }.load(order.into()) } pub unsafe fn store(&self, offset: usize, val: $integer, order: AtomicOrdering) { let r = &(self.0 as *const UnsafeCell<u8>).add(offset); { &*(r as *const _ as *const $integer_atomic) }.store(val, order.into()) } pub unsafe fn swap( &self, offset: usize, val: $integer, order: AtomicOrdering, ) -> $integer { let r = &(self.0 as *const UnsafeCell<u8>).add(offset); { &*(r as *const _ as *const $integer_atomic) }.swap(val, order.into()) } pub unsafe fn compare_exchange( &self, offset: usize, current: $integer, new: $integer, success: AtomicOrdering, failure: AtomicOrdering, ) -> Result<$integer, $integer> { let r = &(self.0 as *const UnsafeCell<u8>).add(offset); { &*(r as *const _ as *const $integer_atomic) }.compare_exchange( current, new, success.into(), failure.into(), ) } pub unsafe fn add( &self, offset: usize, val: $integer, order: AtomicOrdering, ) -> $integer { let r = &(self.0 as *const UnsafeCell<u8>).add(offset); { &*(r as *const _ as *const $integer_atomic) }.fetch_add(val, order.into()) } pub unsafe fn sub( &self, offset: usize, val: $integer, order: AtomicOrdering, ) -> $integer { let r = &(self.0 as *const UnsafeCell<u8>).add(offset); { &*(r as *const _ as *const $integer_atomic) }.fetch_sub(val, order.into()) } pub unsafe fn and( &self, offset: usize, val: $integer, order: AtomicOrdering, ) -> $integer { let r = &(self.0 as *const UnsafeCell<u8>).add(offset); { &*(r as *const _ as *const $integer_atomic) }.fetch_and(val, order.into()) } pub unsafe fn or( &self, offset: usize, val: $integer, order: AtomicOrdering, ) -> $integer { let r = &(self.0 as *const UnsafeCell<u8>).add(offset); { &*(r as *const _ as *const $integer_atomic) }.fetch_or(val, order.into()) } pub unsafe fn xor( &self, offset: usize, val: $integer, order: AtomicOrdering, ) -> $integer { let r = &(self.0 as *const UnsafeCell<u8>).add(offset); { &*(r as *const _ as *const $integer_atomic) }.fetch_xor(val, order.into()) } } }; } pub struct Ati8(pub usize); create_atomic!(Ati8, i8, atomic::AtomicI8); pub struct Ati16(pub usize); create_atomic!(Ati16, i16, atomic::AtomicI16); pub struct Ati32(pub usize); create_atomic!(Ati32, i32, atomic::AtomicI32); pub struct Ati64(pub usize); create_atomic!(Ati64, i64, atomic::AtomicI64); pub struct Atu8(pub usize); create_atomic!(Atu8, u8, atomic::AtomicU8); pub struct Atu16(pub usize); create_atomic!(Atu16, u16, atomic::AtomicU16); pub struct Atu32(pub usize); create_atomic!(Atu32, u32, atomic::AtomicU32); pub struct Atu64(pub usize); create_atomic!(Atu64, u64, atomic::AtomicU64); pub struct Atomics(pub usize);
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_run/native/src/api.rs
packages/wasm_run/native/src/api.rs
pub use crate::atomics::*; use crate::bridge_generated::{wire_list_wasm_val, Wire2Api}; use crate::config::*; pub use crate::external::*; use crate::types::*; use anyhow::{Ok, Result}; use flutter_rust_bridge::{ support::new_leak_box_ptr, DartAbi, IntoDart, RustOpaque, StreamSink, SyncReturn, }; use once_cell::sync::Lazy; use std::io::Write; use std::sync::mpsc::{self, Receiver, Sender}; pub use std::sync::{Mutex, RwLock}; use std::{cell::RefCell, collections::HashMap, fs, sync::Arc}; use wasi_common::pipe::WritePipe; use wasmtime::*; pub use wasmtime::{Func, Global, GlobalType, Memory, Module, SharedMemory, Table}; type Value = wasmtime::Val; type ValueType = wasmtime::ValType; static ARRAY: Lazy<RwLock<GlobalState>> = Lazy::new(|| RwLock::new(Default::default())); thread_local!(static STORE: RefCell<Option<WasmiModuleImpl>> = RefCell::new(None)); #[derive(Default)] struct GlobalState { map: HashMap<u32, WasmiModuleImpl>, last_id: u32, } fn default_val(ty: &ValueType) -> Value { match ty { ValueType::I32 => Value::I32(0), ValueType::I64 => Value::I64(0), ValueType::F32 => Value::F32(0), ValueType::F64 => Value::F64(0), ValueType::V128 => Value::V128(0.into()), ValueType::ExternRef => Value::ExternRef(None), ValueType::FuncRef => Value::FuncRef(None), } } struct WasmiModuleImpl { module: Arc<Mutex<Module>>, linker: Linker<StoreState>, store: Store<StoreState>, instance: Option<Instance>, threads: Option<Arc<Mutex<Vec<Option<WasmiModuleImpl>>>>>, pool: Option<Arc<rayon::ThreadPool>>, channels: Option<Arc<Mutex<FunctionChannels>>>, } struct StoreState { wasi_ctx: Option<wasi_common::WasiCtx>, stdout: Option<StreamSink<Vec<u8>>>, stderr: Option<StreamSink<Vec<u8>>>, functions: HashMap<usize, HostFunction>, stack: CallStack, // TODO: add to stdin? } #[derive(Clone)] struct HostFunction { function_pointer: usize, function_id: u32, param_types: Vec<ValueTy>, result_types: Vec<ValueTy>, } #[derive(Clone)] pub struct WasmRunModuleId(pub u32, pub RustOpaque<CallStack>); #[derive(Clone, Default)] pub struct CallStack(Arc<RwLock<Vec<RwLock<StoreContextMut<'static, StoreState>>>>>); #[derive(Debug, Clone, Copy)] pub struct WasmRunInstanceId(pub u32); fn make_wasi_ctx( id: &WasmRunModuleId, wasi_config: &Option<WasiConfigNative>, ) -> Result<Option<wasi_common::WasiCtx>> { let mut wasi_ctx = None; if let Some(wasi_config) = wasi_config { let wasi = wasi_config.to_wasi_ctx()?; if !wasi_config.preopened_files.is_empty() { for value in &wasi_config.preopened_files { let file = fs::File::open(value)?; let wasm_file = wasmtime_wasi::file::File::from_cap_std(cap_std::fs::File::from_std(file)); wasi.push_file( Box::new(wasm_file), wasi_common::file::FileAccessMode::all(), )?; } } if wasi_config.capture_stdout { let stdout_handler = ModuleIOWriter { id: id.clone(), is_stdout: true, }; wasi.set_stdout(Box::new(WritePipe::new(stdout_handler))); } if wasi_config.capture_stderr { let stderr_handler = ModuleIOWriter { id: id.clone(), is_stdout: false, }; wasi.set_stderr(Box::new(WritePipe::new(stderr_handler))); } wasi_ctx = Some(wasi); } Ok(wasi_ctx) } pub fn module_builder( module: CompiledModule, num_threads: Option<usize>, wasi_config: Option<WasiConfigNative>, ) -> Result<SyncReturn<WasmRunModuleId>> { let guard = module.0.lock().unwrap(); let engine = guard.engine(); let mut arr = ARRAY.write().unwrap(); arr.last_id += 1; let id = arr.last_id; let stack: CallStack = Default::default(); let module_id = WasmRunModuleId(id, RustOpaque::new(stack.clone())); let mut linker = <Linker<StoreState>>::new(engine); let wasi_ctx = make_wasi_ctx(&module_id, &wasi_config)?; if wasi_ctx.is_some() { wasmtime_wasi::add_to_linker(&mut linker, |ctx| ctx.wasi_ctx.as_mut().unwrap())?; } let store = Store::new( engine, StoreState { wasi_ctx: wasi_ctx.clone(), stdout: None, stderr: None, functions: Default::default(), stack, }, ); let wasm_module = Arc::clone(&module.0); let threads = if let Some(num_threads) = num_threads { if num_threads <= 1 { return Err(anyhow::anyhow!(format!( "num_threads must be greater than 1. received: {num_threads}" ))); } let threads_vec = (0..num_threads) .map(|_index| { let mut linker = <Linker<StoreState>>::new(engine); if wasi_ctx.is_some() { wasmtime_wasi::add_to_linker(&mut linker, |ctx| { ctx.wasi_ctx.as_mut().unwrap() })?; } Ok(Some(WasmiModuleImpl { module: wasm_module.clone(), linker, store: Store::new( engine, StoreState { wasi_ctx: wasi_ctx.clone(), stdout: None, stderr: None, functions: Default::default(), stack: Default::default(), }, ), instance: None, threads: None, pool: None, channels: None, })) }) .collect::<Result<Vec<Option<WasmiModuleImpl>>>>()?; Some(Arc::new(Mutex::new(threads_vec))) } else { None }; let module_builder = WasmiModuleImpl { module: wasm_module, linker: linker.clone(), store, instance: None, pool: None, threads, channels: num_threads .map(|num_threads| Arc::new(Mutex::new(FunctionChannels::new(num_threads)))), }; arr.map.insert(id, module_builder); Ok(SyncReturn(module_id)) } struct ModuleIOWriter { id: WasmRunModuleId, is_stdout: bool, } impl Write for ModuleIOWriter { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { self.id.with_module(|store| { let data = store.data(); let sink = if self.is_stdout { data.stdout.as_ref() } else { data.stderr.as_ref() }; let mut bytes_written = buf.len(); if let Some(stream) = sink { if !stream.add(buf.to_owned()) { bytes_written = 0; } } std::io::Result::Ok(bytes_written) }) } fn flush(&mut self) -> std::io::Result<()> { std::io::Result::Ok(()) } } type WorkerSendRecv = Arc<Mutex<(usize, Sender<FunctionCall>, Receiver<Vec<Val>>)>>; struct FunctionChannels { main_send: Sender<FunctionCall>, main_recv: Arc<Mutex<Receiver<FunctionCall>>>, workers_out: Vec<Sender<Vec<Val>>>, workers: Vec<WorkerSendRecv>, } impl FunctionChannels { fn new(num_workers: usize) -> Self { let (main_send, main_recv) = mpsc::channel::<FunctionCall>(); let mut workers_out = vec![]; let mut workers = vec![]; (0..num_workers).for_each(|index| { let (send_out, recv_out) = mpsc::channel::<Vec<Val>>(); workers_out.push(send_out); workers.push(Arc::new(Mutex::new((index, main_send.clone(), recv_out)))); }); Self { main_send, main_recv: Arc::new(Mutex::new(main_recv)), workers_out, workers, } } } impl WasmRunInstanceId { pub fn exports(&self) -> SyncReturn<Vec<ModuleExportValue>> { let mut v = ARRAY.write().unwrap(); let value = v.map.get_mut(&self.0).unwrap(); let instance = value.instance.unwrap(); let l = instance .exports(&mut value.store) .map(|e| (e.name().to_owned(), e.into_extern())) .collect::<Vec<(String, wasmtime::Extern)>>(); SyncReturn( l.into_iter() .map(|e| ModuleExportValue::from_export(e, &value.store)) .collect(), ) } } impl WasmRunModuleId { pub fn instantiate_sync(&self) -> Result<SyncReturn<WasmRunInstanceId>> { Ok(SyncReturn(self.instantiate()?)) } pub fn instantiate(&self) -> Result<WasmRunInstanceId> { let mut state = ARRAY.write().unwrap(); let module = state.map.get_mut(&self.0).unwrap(); if module.instance.is_some() { return Err(anyhow::anyhow!("Instance already exists")); } let instance = module .linker .instantiate(&mut module.store, &module.module.lock().unwrap())?; module.instance = Some(instance); let threads = module.threads.take(); if let Some(threads) = threads { let len = { let mut threads_i = threads.lock().unwrap(); for thread in threads_i.iter_mut() { let thread = thread.as_mut().unwrap(); let thread_instance = thread .linker .instantiate(&mut thread.store, &thread.module.lock().unwrap())?; thread.instance = Some(thread_instance); } threads_i.len() }; let pool = rayon::ThreadPoolBuilder::new() .num_threads(len) .start_handler(move |index| { STORE.with(|cell| { let t = threads.clone(); let mut threads = t.lock().unwrap(); let mut local_store = cell.borrow_mut(); *local_store = Some(threads[index].take().unwrap()); }) }) .build() .unwrap(); module.pool = Some(Arc::new(pool)); // let channels = module.channels.take().unwrap(); // let module_id = self.0; // let runtime = tokio::runtime::Builder::new_current_thread() // .max_blocking_threads(1) // .worker_threads(1) // .enable_all() // .build() // .unwrap(); // runtime.block_on(async move { // // module.runtime = Some(runtime); // // TODO: only do this when using runParallel, use select for waiting a finish signal // // runtime.block_on(async move { // let c = channels.lock().unwrap(); // c.main_recv.iter().for_each(|req| { // let worker = &c.workers_out[req.worker_index]; // let mut results = (0..req.num_results) // .map(|_| default_val(&ValType::I32)) // .collect::<Vec<_>>(); // // TODO: use same module instance // WasmRunModuleId(module_id) // .with_module_mut(|ctx| { // let f: WasmFunction = // unsafe { std::mem::transmute(req.function_pointer) }; // Self::execute_function(ctx, req.args, f, req.function_id, &mut results) // }) // .unwrap(); // worker.send(results).unwrap(); // }) // // }); // }); } Ok(WasmRunInstanceId(self.0)) } fn map_function( m: &mut WasmiModuleImpl, func: &Func, thread_index: usize, new_context: StoreContextMut<'_, StoreState>, ) -> RustOpaque<WFunc> { let raw_id = unsafe { func.to_raw(&mut m.store) as usize }; let hf = m.store.data().functions.get(&raw_id).unwrap(); let ff = Self::_create_function( new_context, hf.clone(), Some(m.channels.as_ref().unwrap().lock().unwrap().workers[thread_index].clone()), ) .unwrap() .0; ff } pub fn link_imports(&self, imports: Vec<ModuleImport>) -> Result<SyncReturn<()>> { let mut arr = ARRAY.write().unwrap(); let m = arr.map.get_mut(&self.0).unwrap(); if m.instance.is_some() { return Err(anyhow::anyhow!("Instance already exists")); } for import in imports.iter() { m.linker .define(&mut m.store, &import.module, &import.name, &import.value)?; } if let Some(threads) = m.threads.clone().as_ref() { for (thread_index, thread) in &mut threads.lock().unwrap().iter_mut().enumerate() { let thread = thread.as_mut().unwrap(); for import in imports.iter() { let mapped_value = match &import.value { ExternalValue::Func(f) => { let ff = Self::map_function( m, &f.func_wasmtime, thread_index, thread.store.as_context_mut(), ); ExternalValue::Func(ff) } ExternalValue::SharedMemory(m) => ExternalValue::SharedMemory(m.clone()), ExternalValue::Global(g) => { let ty = g.ty(&m.store); let v = match g.get(&mut m.store) { Val::FuncRef(Some(v)) => { let ff = Self::map_function( m, &v, thread_index, thread.store.as_context_mut(), ); Val::FuncRef(Some(ff.func_wasmtime)) } v => v, }; let global = Global::new(&mut thread.store, ty, v)?; ExternalValue::Global(RustOpaque::new(global)) } ExternalValue::Memory(mem) => { let ty = mem.ty(&m.store); // TODO: should we copy the memory contents? let memory = Memory::new(&mut thread.store, ty)?; ExternalValue::Memory(RustOpaque::new(memory)) } ExternalValue::Table(t) => { let ty = t.ty(&m.store); let fill_value = if t.size(&m.store) > 0 { let v = t.get(&mut m.store, 0); if let Some(Val::FuncRef(Some(v))) = v { let ff = Self::map_function( m, &v, thread_index, thread.store.as_context_mut(), ); Some(Val::FuncRef(Some(ff.func_wasmtime))) } else { v } } else { None }; let v = fill_value.unwrap_or_else(|| default_val(&ty.element())); let table = Table::new(&mut thread.store, ty, v)?; ExternalValue::Table(RustOpaque::new(table)) } }; thread.linker.define( &mut thread.store, &import.module, &import.name, &mapped_value, )?; } } } Ok(SyncReturn(())) } pub fn stdio_stream(&self, sink: StreamSink<Vec<u8>>, kind: StdIOKind) -> Result<()> { self.with_module_mut(|mut store| { let store_state = store.data_mut(); { let value = match kind { StdIOKind::stdout => &store_state.stdout, StdIOKind::stderr => &store_state.stderr, }; if value.is_some() { return Err(anyhow::anyhow!("Stream sink already set")); } } match kind { StdIOKind::stdout => store_state.stdout = Some(sink), StdIOKind::stderr => store_state.stderr = Some(sink), }; Ok(()) }) } pub fn dispose(&self) -> Result<()> { let mut arr = ARRAY.write().unwrap(); arr.map.remove(&self.0); Ok(()) } pub fn call_function_handle_sync( &self, func: RustOpaque<WFunc>, args: Vec<WasmVal>, ) -> Result<SyncReturn<Vec<WasmVal>>> { self.call_function_handle(func, args).map(SyncReturn) } pub fn call_function_handle( &self, func: RustOpaque<WFunc>, args: Vec<WasmVal>, ) -> Result<Vec<WasmVal>> { let func: Func = func.func_wasmtime; self.with_module_mut(|mut store| { let mut outputs: Vec<Value> = func.ty(&store).results().map(|t| default_val(&t)).collect(); let inputs: Vec<Value> = args.into_iter().map(|v| v.to_val()).collect(); func.call(&mut store, inputs.as_slice(), &mut outputs)?; Ok(outputs.into_iter().map(WasmVal::from_val).collect()) }) } pub fn call_function_handle_parallel( &self, func_name: String, args: Vec<WasmVal>, num_tasks: usize, function_stream: StreamSink<ParallelExec>, ) { use rayon::prelude::*; let (num_params, result_types, pool, channels) = { let mut m = ARRAY.write().unwrap(); let module = m.map.get_mut(&self.0).unwrap(); let func: Func = module .instance .unwrap() .get_func(&mut module.store, &func_name) .unwrap(); let num_params = func.ty(&module.store).params().count(); if (num_params == 0 && !args.is_empty()) || (num_params != 0 && args.len() % num_params != 0) || num_params * num_tasks != args.len() { function_stream.add(ParallelExec::Err(format!( "Number of arguments must be a multiple of {num_params}" ))); return; } let result_types: Vec<ValType> = func.ty(&module.store).results().collect(); ( num_params, result_types, module.pool.clone(), module.channels.clone(), ) }; if let (Some(pool), Some(channels)) = (pool, channels) { let args: Vec<Value> = args.into_iter().map(|v| v.to_val()).collect(); let main_send = channels.lock().unwrap().main_send.clone(); // TODO: try with tokio std::thread::spawn(move || { let value: std::result::Result<Vec<WasmVal>, Error> = pool.install(|| { let iter: Vec<&[Val]> = if args.is_empty() { (0..num_tasks).map(|_| [].as_slice()).collect() } else { args.chunks_exact(num_params).collect() }; let v = iter .par_iter() .map(|inputs| { STORE.with(|cell| { let mut c = cell.borrow_mut(); let m = c.as_mut().unwrap(); let mut outputs: Vec<Value> = result_types.iter().map(default_val).collect(); let func = m .instance .unwrap() .get_func(&mut m.store, &func_name) .unwrap(); func.call(&mut m.store, inputs, &mut outputs)?; Ok(outputs .into_iter() .map(WasmVal::from_val) .collect::<Vec<WasmVal>>()) }) }) .collect::<Result<Vec<Vec<WasmVal>>>>()? .into_iter() .flatten() .collect::<Vec<WasmVal>>(); Ok(v) }); // TODO: don't unwrap main_send .send(FunctionCall { // TODO: don't unwrap args: value.unwrap(), function_id: 0, function_pointer: 0, num_results: 0, worker_index: 0, }) .unwrap(); }); let main_recv = channels.lock().unwrap().main_recv.clone(); let main_recv_c = main_recv.lock().unwrap(); loop { let req = main_recv_c.recv().unwrap(); if req.function_pointer == 0 { function_stream.add(ParallelExec::Ok(req.args)); return; } function_stream.add(ParallelExec::Call(req)); // TODO: try this code with sync function // let worker = &c.workers_out[req.worker_index]; // let mut results = (0..req.num_results) // .map(|_| default_val(&ValType::I32)) // .collect::<Vec<_>>(); // // TODO: use same module instance // self.with_module_mut(|ctx| { // let f: WasmFunction = unsafe { std::mem::transmute(req.function_pointer) }; // Self::execute_function(ctx, req.args, f, req.function_id, &mut results) // }) // .unwrap(); // worker.send(results).unwrap(); } } else { function_stream.add(ParallelExec::Err( "Instance has no thread pool configured".to_string(), )); } } pub fn worker_execution( &self, worker_index: usize, results: Vec<WasmVal>, ) -> Result<SyncReturn<()>> { let m = ARRAY.read().unwrap(); let module = m.map.get(&self.0).unwrap(); let worker = &module .channels .as_ref() .unwrap() .lock() .unwrap() .workers_out[worker_index]; worker.send(results.into_iter().map(|v| v.to_val()).collect())?; Ok(SyncReturn(())) } fn with_module_mut<T>(&self, f: impl FnOnce(StoreContextMut<'_, StoreState>) -> T) -> T { { let stack = self.1 .0.read().unwrap(); if let Some(caller) = stack.last() { return f(caller.write().unwrap().as_context_mut()); } } let mut arr = ARRAY.write().unwrap(); let value = arr.map.get_mut(&self.0).unwrap(); let mut ctx = value.store.as_context_mut(); { let v = RwLock::new(unsafe { std::mem::transmute(ctx.as_context_mut()) }); self.1 .0.write().unwrap().push(v); } let result = f(ctx); self.1 .0.write().unwrap().pop(); result } fn with_module<T>(&self, f: impl FnOnce(&StoreContext<'_, StoreState>) -> T) -> T { { let stack = self.1 .0.read().unwrap(); if let Some(caller) = stack.last() { return f(&caller.read().unwrap().as_context()); } } let arr = ARRAY.read().unwrap(); let value = arr.map.get(&self.0).unwrap(); f(&value.store.as_context()) } pub fn get_function_type(&self, func: RustOpaque<WFunc>) -> SyncReturn<FuncTy> { SyncReturn(self.with_module(|store| (&func.func_wasmtime.ty(store)).into())) } pub fn create_function( &self, function_pointer: usize, function_id: u32, param_types: Vec<ValueTy>, result_types: Vec<ValueTy>, ) -> Result<SyncReturn<RustOpaque<WFunc>>> { self.with_module_mut(|store| { Self::_create_function( store, HostFunction { function_pointer, function_id, param_types, result_types, }, None, ) }) } fn _create_function( mut store: StoreContextMut<'_, StoreState>, hf: HostFunction, worker_channel: Option<WorkerSendRecv>, ) -> Result<SyncReturn<RustOpaque<WFunc>>> { let f: WasmFunction = unsafe { std::mem::transmute(hf.function_pointer) }; let func = Func::new( store.as_context_mut(), FuncType::new( hf.param_types.iter().cloned().map(ValueType::from), hf.result_types.iter().cloned().map(ValueType::from), ), move |mut caller, params, results| { let mapped: Vec<WasmVal> = params .iter() .map(|a| WasmVal::from_val(a.clone())) .collect(); if let Some(worker_channel) = worker_channel.clone() { let guard = worker_channel.lock().unwrap(); // TODO: use StreamSink directly guard.1.send(FunctionCall { args: mapped, function_id: hf.function_id, function_pointer: hf.function_pointer, num_results: results.len(), worker_index: guard.0, })?; let output = guard.2.recv()?; let mut outputs = output.into_iter(); for value in results { *value = outputs.next().unwrap(); } return Ok(()); } Self::execute_function( caller.as_context_mut(), mapped, f, hf.function_id, results, )?; Ok(()) }, ); let raw_id = unsafe { func.to_raw(&mut store) as usize }; store.data_mut().functions.insert(raw_id, hf); Ok(SyncReturn(RustOpaque::new(func.into()))) } fn execute_function( caller: StoreContextMut<'_, StoreState>, mapped: Vec<WasmVal>, f: WasmFunction, function_id: u32, results: &mut [Val], ) -> Result<()> { let inputs = vec![mapped].into_dart(); let stack = { let stack = caller.data().stack.clone(); let v = RwLock::new(unsafe { std::mem::transmute(caller) }); stack.0.write().unwrap().push(v); stack }; let output: Vec<WasmVal> = unsafe { let pointer = new_leak_box_ptr(inputs); let result = f(function_id, pointer); pointer.drop_in_place(); result.wire2api() }; // TODO: use Drop for this let last_caller = stack.0.write().unwrap().pop(); if output.len() != results.len() { return Err(anyhow::anyhow!("Invalid output length")); } else if last_caller.is_none() { return Err(anyhow::anyhow!("CALLER_STACK is empty")); } else if output.is_empty() { return Ok(()); } // let last_caller = last_caller.unwrap(); // let mut caller = last_caller.write().unwrap(); let mut outputs = output.into_iter(); for value in results { *value = outputs.next().unwrap().to_val(); } Ok(()) } pub fn create_memory(&self, memory_type: MemoryTy) -> Result<SyncReturn<RustOpaque<Memory>>> { self.with_module_mut(|store| { let mem_type = memory_type.to_memory_type()?; let memory = Memory::new(store, mem_type).map_err(to_anyhow)?; Ok(SyncReturn(RustOpaque::new(memory))) }) } pub fn create_global( &self, value: WasmVal, mutable: bool, ) -> Result<SyncReturn<RustOpaque<Global>>> { self.with_module_mut(|mut store| { let mapped = value.to_val(); let global = Global::new( &mut store, GlobalType::new( mapped.ty(), if mutable { Mutability::Var } else { Mutability::Const }, ), mapped, )?; Ok(SyncReturn(RustOpaque::new(global))) }) } pub fn create_table( &self, value: WasmVal, table_type: TableArgs, ) -> Result<SyncReturn<RustOpaque<Table>>> { self.with_module_mut(|mut store| { let mapped_value = value.to_val(); let table = Table::new( &mut store, TableType::new(mapped_value.ty(), table_type.minimum, table_type.maximum), mapped_value, ) .map_err(to_anyhow)?; Ok(SyncReturn(RustOpaque::new(table))) }) } // GLOBAL pub fn get_global_type(&self, global: RustOpaque<Global>) -> SyncReturn<GlobalTy> { SyncReturn(self.with_module(|store| (&global.ty(store)).into())) } pub fn get_global_value(&self, global: RustOpaque<Global>) -> SyncReturn<WasmVal> { SyncReturn(self.with_module_mut(|store| WasmVal::from_val(global.get(store)))) } pub fn set_global_value( &self, global: RustOpaque<Global>, value: WasmVal, ) -> Result<SyncReturn<()>> { self.with_module_mut(|mut store| { let mapped = value.to_val(); global .set(&mut store, mapped) .map(|_| SyncReturn(())) .map_err(to_anyhow) }) } // MEMORY pub fn get_memory_type(&self, memory: RustOpaque<Memory>) -> SyncReturn<MemoryTy> { SyncReturn(self.with_module(|store| (&memory.ty(store)).into())) } pub fn get_memory_data(&self, memory: RustOpaque<Memory>) -> SyncReturn<Vec<u8>> { SyncReturn(self.with_module(|store| memory.data(store).to_owned())) } pub fn get_memory_data_pointer(&self, memory: RustOpaque<Memory>) -> SyncReturn<usize> { SyncReturn(self.with_module(|store| memory.data_ptr(store) as usize)) } pub fn get_memory_data_pointer_and_length( &self, memory: RustOpaque<Memory>, ) -> SyncReturn<PointerAndLength> { SyncReturn(self.with_module(|store| PointerAndLength { pointer: memory.data_ptr(store) as usize, length: memory.data_size(store), })) } pub fn read_memory( &self, memory: RustOpaque<Memory>, offset: usize, bytes: usize, ) -> Result<SyncReturn<Vec<u8>>> { self.with_module(|store| { let mut buffer = Vec::with_capacity(bytes); #[allow(clippy::uninit_vec)] unsafe { buffer.set_len(bytes) }; memory .read(store, offset, &mut buffer) .map(|_| SyncReturn(buffer)) .map_err(to_anyhow) }) } pub fn get_memory_pages(&self, memory: RustOpaque<Memory>) -> SyncReturn<u32> {
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
true
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_run/native/src/types.rs
packages/wasm_run/native/src/types.rs
use std::fmt::Display; use anyhow::Result; use flutter_rust_bridge::RustOpaque; use crate::external::*; #[cfg(not(feature = "wasmtime"))] use wasmi::{core::ValueType, *}; #[cfg(not(feature = "wasmtime"))] pub use wasmi::{Func, Global, GlobalType, Memory, Mutability, Table}; #[allow(non_camel_case_types)] #[derive(Debug)] pub enum WasmVal { /// Value of 32-bit signed or unsigned integer. i32(i32), /// Value of 64-bit signed or unsigned integer. i64(i64), /// Value of 32-bit IEEE 754-2008 floating point number. f32(f32), /// Value of 64-bit IEEE 754-2008 floating point number. f64(f64), /// A 128 bit number. v128([u8; 16]), /// A nullable function. funcRef(Option<RustOpaque<WFunc>>), /// A nullable external object reference. externRef(Option<u32>), // NonZeroU32 } impl WasmVal { #[cfg(not(feature = "wasmtime"))] #[allow(clippy::wrong_self_convention)] pub fn to_value(self, ctx: impl AsContextMut) -> Value { match self { WasmVal::i32(i) => Value::I32(i), WasmVal::i64(i) => Value::I64(i), WasmVal::f32(i) => Value::F32(i.to_bits().into()), WasmVal::f64(i) => Value::F64(i.to_bits().into()), WasmVal::v128(_i) => panic!("v128 is not supported in wasmi"), WasmVal::funcRef(i) => { let inner = i.map(|f| Func::clone(&f.func_wasmi)); Value::FuncRef(FuncRef::new(inner)) } WasmVal::externRef(i) => Value::ExternRef(ExternRef::new::<u32>(ctx, i)), } } #[cfg(not(feature = "wasmtime"))] pub fn from_value<'a, T: 'a>(value: &Value, ctx: impl Into<StoreContext<'a, T>>) -> Self { match value { Value::I32(i) => WasmVal::i32(*i), Value::I64(i) => WasmVal::i64(*i), Value::F32(i) => WasmVal::f32(i.to_float()), Value::F64(i) => WasmVal::f64(i.to_float()), Value::FuncRef(i) => WasmVal::funcRef(i.func().map(|f| RustOpaque::new((*f).into()))), // NonZeroU32::new(1).unwrap()), Value::ExternRef(i) => { WasmVal::externRef(i.data(ctx).map(|i| *i.downcast_ref::<u32>().unwrap())) } // NonZeroU32::new(1).unwrap()), } } #[cfg(feature = "wasmtime")] #[allow(clippy::wrong_self_convention)] pub fn to_val(self) -> wasmtime::Val { match self { WasmVal::i32(i) => wasmtime::Val::I32(i), WasmVal::i64(i) => wasmtime::Val::I64(i), WasmVal::f32(i) => wasmtime::Val::F32(i.to_bits()), WasmVal::f64(i) => wasmtime::Val::F64(i.to_bits()), WasmVal::v128(i) => wasmtime::Val::V128(wasmtime::V128::from(u128::from_ne_bytes(i))), WasmVal::funcRef(i) => wasmtime::Val::FuncRef(i.map(|f| f.func_wasmtime)), WasmVal::externRef(i) => wasmtime::Val::ExternRef(i.map(wasmtime::ExternRef::new)), } } #[cfg(feature = "wasmtime")] pub fn from_val(val: wasmtime::Val) -> Self { match val { wasmtime::Val::I32(i) => WasmVal::i32(i), wasmtime::Val::I64(i) => WasmVal::i64(i), wasmtime::Val::V128(i) => WasmVal::v128(i.as_u128().to_ne_bytes()), wasmtime::Val::F32(i) => WasmVal::f32(f32::from_bits(i)), wasmtime::Val::F64(i) => WasmVal::f64(f64::from_bits(i)), wasmtime::Val::FuncRef(i) => WasmVal::funcRef(i.map(|f| RustOpaque::new(f.into()))), wasmtime::Val::ExternRef(i) => { WasmVal::externRef(i.map(|i| *i.data().downcast_ref::<u32>().unwrap())) } } } } #[derive(Debug)] pub struct GlobalTy { /// The value type of the global variable. pub value: ValueTy, /// The mutability of the global variable. pub mutable: bool, } #[cfg(not(feature = "wasmtime"))] impl From<&GlobalType> for GlobalTy { fn from(value: &GlobalType) -> Self { GlobalTy { value: (&value.content()).into(), mutable: value.mutability() == Mutability::Var, } } } #[cfg(feature = "wasmtime")] impl From<&wasmtime::GlobalType> for GlobalTy { fn from(value: &wasmtime::GlobalType) -> Self { GlobalTy { value: value.content().into(), mutable: value.mutability() == wasmtime::Mutability::Var, } } } #[derive(Debug)] pub struct TableTy { /// The type of values stored in the [WasmTable]. pub element: ValueTy, /// The minimum number of elements the [WasmTable] must have. pub minimum: u32, /// The optional maximum number of elements the [WasmTable] can have. /// /// If this is `None` then the [WasmTable] is not limited in size. pub maximum: Option<u32>, } #[cfg(not(feature = "wasmtime"))] impl From<&TableType> for TableTy { fn from(value: &TableType) -> Self { TableTy { element: (&value.element()).into(), minimum: value.minimum(), maximum: value.maximum(), } } } #[cfg(feature = "wasmtime")] impl From<&wasmtime::TableType> for TableTy { fn from(value: &wasmtime::TableType) -> Self { TableTy { element: (&value.element()).into(), minimum: value.minimum(), maximum: value.maximum(), } } } #[allow(non_camel_case_types)] #[derive(Debug, Clone)] pub enum ValueTy { /// 32-bit signed or unsigned integer. i32, /// 64-bit signed or unsigned integer. i64, /// 32-bit IEEE 754-2008 floating point number. f32, /// 64-bit IEEE 754-2008 floating point number. f64, /// A 128 bit number. v128, /// A nullable function reference. funcRef, /// A nullable external reference. externRef, } #[cfg(not(feature = "wasmtime"))] impl From<&ValueType> for ValueTy { fn from(value: &ValueType) -> Self { match value { ValueType::I32 => ValueTy::i32, ValueType::I64 => ValueTy::i64, ValueType::F32 => ValueTy::f32, ValueType::F64 => ValueTy::f64, ValueType::FuncRef => ValueTy::funcRef, ValueType::ExternRef => ValueTy::externRef, } } } #[cfg(feature = "wasmtime")] impl From<&wasmtime::ValType> for ValueTy { fn from(value: &wasmtime::ValType) -> Self { match value { wasmtime::ValType::I32 => ValueTy::i32, wasmtime::ValType::I64 => ValueTy::i64, wasmtime::ValType::F32 => ValueTy::f32, wasmtime::ValType::F64 => ValueTy::f64, wasmtime::ValType::V128 => ValueTy::v128, wasmtime::ValType::FuncRef => ValueTy::funcRef, wasmtime::ValType::ExternRef => ValueTy::externRef, } } } #[cfg(not(feature = "wasmtime"))] impl From<ValueTy> for ValueType { fn from(value: ValueTy) -> Self { match value { ValueTy::i32 => ValueType::I32, ValueTy::i64 => ValueType::I64, ValueTy::f32 => ValueType::F32, ValueTy::f64 => ValueType::F64, ValueTy::v128 => panic!("V128 not supported for wasmi"), ValueTy::funcRef => ValueType::FuncRef, ValueTy::externRef => ValueType::ExternRef, } } } #[cfg(feature = "wasmtime")] impl From<ValueTy> for wasmtime::ValType { fn from(value: ValueTy) -> Self { match value { ValueTy::i32 => wasmtime::ValType::I32, ValueTy::i64 => wasmtime::ValType::I64, ValueTy::f32 => wasmtime::ValType::F32, ValueTy::f64 => wasmtime::ValType::F64, ValueTy::v128 => wasmtime::ValType::V128, ValueTy::funcRef => wasmtime::ValType::FuncRef, ValueTy::externRef => wasmtime::ValType::ExternRef, } } } #[derive(Debug)] pub struct ModuleImport { pub module: String, pub name: String, pub value: ExternalValue, } /// The type of an external (imported or exported) WASM value. #[derive(Debug)] pub enum ExternalType { /// A [FuncTy]. Func(FuncTy), /// A [GlobalTy]. Global(GlobalTy), /// A [TableTy]. Table(TableTy), /// A [MemoryTy]. Memory(MemoryTy), } #[cfg(not(feature = "wasmtime"))] impl From<&ExternType> for ExternalType { fn from(import: &ExternType) -> Self { match import { ExternType::Func(f) => ExternalType::Func(f.into()), ExternType::Global(f) => ExternalType::Global(f.into()), ExternType::Table(f) => ExternalType::Table(f.into()), ExternType::Memory(f) => ExternalType::Memory(f.into()), } } } #[cfg(feature = "wasmtime")] impl From<&wasmtime::ExternType> for ExternalType { fn from(import: &wasmtime::ExternType) -> Self { match import { wasmtime::ExternType::Func(f) => ExternalType::Func(f.into()), wasmtime::ExternType::Global(f) => ExternalType::Global(f.into()), wasmtime::ExternType::Table(f) => ExternalType::Table(f.into()), wasmtime::ExternType::Memory(f) => ExternalType::Memory(f.into()), } } } #[derive(Debug)] pub struct ModuleImportDesc { pub module: String, pub name: String, pub ty: ExternalType, } #[cfg(not(feature = "wasmtime"))] impl From<&ImportType<'_>> for ModuleImportDesc { fn from(import: &ImportType) -> Self { ModuleImportDesc { module: import.module().to_string(), name: import.name().to_string(), ty: import.ty().into(), } } } #[cfg(feature = "wasmtime")] impl From<&wasmtime::ImportType<'_>> for ModuleImportDesc { fn from(import: &wasmtime::ImportType) -> Self { ModuleImportDesc { module: import.module().to_string(), name: import.name().to_string(), ty: (&import.ty()).into(), } } } #[derive(Debug)] pub struct FuncTy { /// The number of function parameters. pub parameters: Vec<ValueTy>, /// The ordered and merged parameter and result types of the function type.] pub results: Vec<ValueTy>, } #[cfg(not(feature = "wasmtime"))] impl From<&FuncType> for FuncTy { fn from(func: &FuncType) -> Self { FuncTy { parameters: func.params().iter().map(ValueTy::from).collect(), results: func.results().iter().map(ValueTy::from).collect(), } } } #[cfg(feature = "wasmtime")] impl From<&wasmtime::FuncType> for FuncTy { fn from(func: &wasmtime::FuncType) -> Self { FuncTy { parameters: func.params().map(|a| ValueTy::from(&a)).collect(), results: func.results().map(|a| ValueTy::from(&a)).collect(), } } } #[allow(dead_code)] pub enum ParallelExec { Ok(Vec<WasmVal>), Err(String), Call(FunctionCall), } pub struct FunctionCall { pub args: Vec<WasmVal>, pub function_id: u32, pub function_pointer: usize, pub num_results: usize, pub worker_index: usize, } #[derive(Debug)] pub struct ModuleExportDesc { pub name: String, pub ty: ExternalType, } #[cfg(not(feature = "wasmtime"))] impl From<&ExportType<'_>> for ModuleExportDesc { fn from(export: &ExportType) -> Self { ModuleExportDesc { name: export.name().to_string(), ty: export.ty().into(), } } } #[cfg(feature = "wasmtime")] impl From<&wasmtime::ExportType<'_>> for ModuleExportDesc { fn from(export: &wasmtime::ExportType) -> Self { ModuleExportDesc { name: export.name().to_string(), ty: (&export.ty()).into(), } } } #[derive(Debug)] pub struct ModuleExportValue { pub desc: ModuleExportDesc, pub value: ExternalValue, } impl ModuleExportValue { #[cfg(not(feature = "wasmtime"))] pub fn from_export<T>(export: Export, store: &Store<T>) -> Self { ModuleExportValue { desc: ModuleExportDesc { name: export.name().to_string(), ty: (&export.ty(store)).into(), }, value: export.into_extern().into(), } } #[cfg(feature = "wasmtime")] pub fn from_export( export: (String, wasmtime::Extern), store: impl wasmtime::AsContext, ) -> Self { ModuleExportValue { desc: ModuleExportDesc { name: export.0, ty: (&export.1.ty(store)).into(), }, value: export.1.into(), } } } #[cfg(feature = "wasmtime")] #[derive(Debug)] pub enum ExternalValue { Func(RustOpaque<WFunc>), Global(RustOpaque<wasmtime::Global>), Table(RustOpaque<wasmtime::Table>), Memory(RustOpaque<wasmtime::Memory>), SharedMemory(crate::api::WasmRunSharedMemory), } #[cfg(not(feature = "wasmtime"))] #[derive(Debug)] pub enum ExternalValue { Func(RustOpaque<WFunc>), Global(RustOpaque<Global>), Table(RustOpaque<Table>), Memory(RustOpaque<Memory>), SharedMemory(crate::api::WasmRunSharedMemory), } #[cfg(not(feature = "wasmtime"))] impl From<Extern> for ExternalValue { fn from(extern_: Extern) -> Self { match extern_ { Extern::Func(f) => ExternalValue::Func(RustOpaque::new(f.into())), Extern::Global(g) => ExternalValue::Global(RustOpaque::new(g)), Extern::Table(t) => ExternalValue::Table(RustOpaque::new(t)), Extern::Memory(m) => ExternalValue::Memory(RustOpaque::new(m)), } } } #[cfg(feature = "wasmtime")] impl From<wasmtime::Extern> for ExternalValue { fn from(extern_: wasmtime::Extern) -> Self { match extern_ { wasmtime::Extern::Func(f) => ExternalValue::Func(RustOpaque::new(f.into())), wasmtime::Extern::Global(g) => ExternalValue::Global(RustOpaque::new(g)), wasmtime::Extern::Table(t) => ExternalValue::Table(RustOpaque::new(t)), wasmtime::Extern::Memory(m) => ExternalValue::Memory(RustOpaque::new(m)), wasmtime::Extern::SharedMemory(m) => ExternalValue::SharedMemory(m.into()), } } } #[cfg(not(feature = "wasmtime"))] impl From<&ExternalValue> for Extern { fn from(e: &ExternalValue) -> Extern { match e { ExternalValue::Func(f) => Extern::Func(f.func_wasmi), ExternalValue::Global(g) => Extern::Global(**g), ExternalValue::Table(t) => Extern::Table(**t), ExternalValue::Memory(m) => Extern::Memory(**m), ExternalValue::SharedMemory(_) => unreachable!(), } } // fn to_extern<T>(&self, store: &mut Store<T>) -> Result<Extern> { // match self { // ExternalValue::Global { value, mutability } => { // let mapped = value.to_value(store); // let global = Global::new(store, mapped, *mutability); // Ok(Extern::Global(global)) // } // ExternalValue::Table { value, ty } => { // let mapped_value = value.to_value(store); // let table = Table::new( // store, // TableType::new(mapped_value.ty(), ty.min, ty.max), // mapped_value, // ) // .map_err(to_anyhow)?; // Ok(Extern::Table(table)) // } // ExternalValue::Memory { ty } => { // let memory = Memory::new(store, ty.to_memory_type()?).map_err(to_anyhow)?; // Ok(Extern::Memory(memory)) // } // ExternalValue::Func { pointer } => { // let f: wasm_func = unsafe { std::mem::transmute(*pointer) }; // // TODO: let func = Func::wrap(store, f); // let func = Func::wrap(store, || {}); // Ok(Extern::Func(func)) // } // } // } } #[cfg(feature = "wasmtime")] impl From<&ExternalValue> for wasmtime::Extern { fn from(e: &ExternalValue) -> wasmtime::Extern { match e { ExternalValue::Func(f) => wasmtime::Extern::Func(f.func_wasmtime), ExternalValue::Global(g) => wasmtime::Extern::Global(**g), ExternalValue::Table(t) => wasmtime::Extern::Table(**t), ExternalValue::Memory(m) => wasmtime::Extern::Memory(**m), ExternalValue::SharedMemory(m) => { wasmtime::Extern::SharedMemory(m.0.read().unwrap().clone()) } } } } #[derive(Debug)] pub struct TableArgs { /// The minimum number of elements the [`Table`] must have. pub minimum: u32, /// The optional maximum number of elements the [`Table`] can have. /// /// If this is `None` then the [`Table`] is not limited in size. pub maximum: Option<u32>, } #[derive(Debug)] pub struct MemoryTy { /// Whether or not this memory could be shared between multiple processes. pub shared: bool, /// The number of initial pages associated with the memory. pub minimum: u32, /// The maximum number of pages this memory can have. pub maximum: Option<u32>, } impl MemoryTy { #[cfg(not(feature = "wasmtime"))] pub fn to_memory_type(&self) -> Result<MemoryType> { MemoryType::new(self.minimum, self.maximum).map_err(to_anyhow) } #[cfg(feature = "wasmtime")] pub fn to_memory_type(&self) -> Result<wasmtime::MemoryType> { if self.shared { return Ok(wasmtime::MemoryType::shared( self.minimum, self.maximum.ok_or(anyhow::anyhow!( "maximum_pages is required for shared memories" ))?, )); } Ok(wasmtime::MemoryType::new(self.minimum, self.maximum)) } } #[cfg(not(feature = "wasmtime"))] impl From<&MemoryType> for MemoryTy { fn from(memory_type: &MemoryType) -> Self { MemoryTy { minimum: memory_type.initial_pages().into(), maximum: memory_type.maximum_pages().map(|v| v.into()), shared: false, } } } #[cfg(feature = "wasmtime")] impl From<&wasmtime::MemoryType> for MemoryTy { fn from(memory_type: &wasmtime::MemoryType) -> Self { MemoryTy { minimum: memory_type.minimum().try_into().unwrap(), maximum: memory_type.maximum().map(|v| v.try_into().unwrap()), shared: memory_type.is_shared(), } } } pub struct PointerAndLength { pub pointer: usize, pub length: usize, } pub fn to_anyhow<T: Display>(value: T) -> anyhow::Error { anyhow::Error::msg(value.to_string()) }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_run/native/src/api_wasmtime.rs
packages/wasm_run/native/src/api_wasmtime.rs
pub use crate::atomics::*; use crate::bridge_generated::{wire_list_wasm_val, Wire2Api}; use crate::config::*; pub use crate::external::*; use crate::types::*; use anyhow::{Ok, Result}; use flutter_rust_bridge::{ support::new_leak_box_ptr, DartAbi, IntoDart, RustOpaque, StreamSink, SyncReturn, }; use once_cell::sync::Lazy; use std::io::Write; use std::sync::mpsc::{self, Receiver, Sender}; pub use std::sync::{Mutex, RwLock}; use std::{cell::RefCell, collections::HashMap, fs, sync::Arc}; use wasi_common::pipe::WritePipe; use wasmtime::*; pub use wasmtime::{Func, Global, GlobalType, Memory, Module, SharedMemory, Table}; type Value = wasmtime::Val; type ValueType = wasmtime::ValType; static ARRAY: Lazy<RwLock<GlobalState>> = Lazy::new(|| RwLock::new(Default::default())); thread_local!(static STORE: RefCell<Option<WasmiModuleImpl>> = RefCell::new(None)); #[derive(Default)] struct GlobalState { map: HashMap<u32, WasmiModuleImpl>, last_id: u32, } fn default_val(ty: &ValueType) -> Value { match ty { ValueType::I32 => Value::I32(0), ValueType::I64 => Value::I64(0), ValueType::F32 => Value::F32(0), ValueType::F64 => Value::F64(0), ValueType::V128 => Value::V128(0.into()), ValueType::ExternRef => Value::ExternRef(None), ValueType::FuncRef => Value::FuncRef(None), } } struct WasmiModuleImpl { module: Arc<Mutex<Module>>, linker: Linker<StoreState>, store: Store<StoreState>, instance: Option<Instance>, threads: Option<Arc<Mutex<Vec<Option<WasmiModuleImpl>>>>>, pool: Option<Arc<rayon::ThreadPool>>, channels: Option<Arc<Mutex<FunctionChannels>>>, } struct StoreState { wasi_ctx: Option<wasi_common::WasiCtx>, stdout: Option<StreamSink<Vec<u8>>>, stderr: Option<StreamSink<Vec<u8>>>, functions: HashMap<usize, HostFunction>, stack: CallStack, // TODO: add to stdin? } #[derive(Clone)] struct HostFunction { function_pointer: usize, function_id: u32, param_types: Vec<ValueTy>, result_types: Vec<ValueTy>, } #[derive(Clone)] pub struct WasmRunModuleId(pub u32, pub RustOpaque<CallStack>); #[derive(Clone, Default)] pub struct CallStack(Arc<RwLock<Vec<RwLock<StoreContextMut<'static, StoreState>>>>>); #[derive(Debug, Clone, Copy)] pub struct WasmRunInstanceId(pub u32); fn make_wasi_ctx( id: &WasmRunModuleId, wasi_config: &Option<WasiConfigNative>, ) -> Result<Option<wasi_common::WasiCtx>> { let mut wasi_ctx = None; if let Some(wasi_config) = wasi_config { let wasi = wasi_config.to_wasi_ctx()?; if !wasi_config.preopened_files.is_empty() { for value in &wasi_config.preopened_files { let file = fs::File::open(value)?; let wasm_file = wasmtime_wasi::file::File::from_cap_std(cap_std::fs::File::from_std(file)); wasi.push_file( Box::new(wasm_file), wasi_common::file::FileAccessMode::all(), )?; } } if wasi_config.capture_stdout { let stdout_handler = ModuleIOWriter { id: id.clone(), is_stdout: true, }; wasi.set_stdout(Box::new(WritePipe::new(stdout_handler))); } if wasi_config.capture_stderr { let stderr_handler = ModuleIOWriter { id: id.clone(), is_stdout: false, }; wasi.set_stderr(Box::new(WritePipe::new(stderr_handler))); } wasi_ctx = Some(wasi); } Ok(wasi_ctx) } pub fn module_builder( module: CompiledModule, num_threads: Option<usize>, wasi_config: Option<WasiConfigNative>, ) -> Result<SyncReturn<WasmRunModuleId>> { let guard = module.0.lock().unwrap(); let engine = guard.engine(); let mut arr = ARRAY.write().unwrap(); arr.last_id += 1; let id = arr.last_id; let stack: CallStack = Default::default(); let module_id = WasmRunModuleId(id, RustOpaque::new(stack.clone())); let mut linker = <Linker<StoreState>>::new(engine); let wasi_ctx = make_wasi_ctx(&module_id, &wasi_config)?; if wasi_ctx.is_some() { wasmtime_wasi::add_to_linker(&mut linker, |ctx| ctx.wasi_ctx.as_mut().unwrap())?; } let store = Store::new( engine, StoreState { wasi_ctx: wasi_ctx.clone(), stdout: None, stderr: None, functions: Default::default(), stack, }, ); let wasm_module = Arc::clone(&module.0); let threads = if let Some(num_threads) = num_threads { if num_threads <= 1 { return Err(anyhow::anyhow!(format!( "num_threads must be greater than 1. received: {num_threads}" ))); } let threads_vec = (0..num_threads) .map(|_index| { let mut linker = <Linker<StoreState>>::new(engine); if wasi_ctx.is_some() { wasmtime_wasi::add_to_linker(&mut linker, |ctx| { ctx.wasi_ctx.as_mut().unwrap() })?; } Ok(Some(WasmiModuleImpl { module: wasm_module.clone(), linker, store: Store::new( engine, StoreState { wasi_ctx: wasi_ctx.clone(), stdout: None, stderr: None, functions: Default::default(), stack: Default::default(), }, ), instance: None, threads: None, pool: None, channels: None, })) }) .collect::<Result<Vec<Option<WasmiModuleImpl>>>>()?; Some(Arc::new(Mutex::new(threads_vec))) } else { None }; let module_builder = WasmiModuleImpl { module: wasm_module, linker: linker.clone(), store, instance: None, pool: None, threads, channels: num_threads .map(|num_threads| Arc::new(Mutex::new(FunctionChannels::new(num_threads)))), }; arr.map.insert(id, module_builder); Ok(SyncReturn(module_id)) } struct ModuleIOWriter { id: WasmRunModuleId, is_stdout: bool, } impl Write for ModuleIOWriter { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { self.id.with_module(|store| { let data = store.data(); let sink = if self.is_stdout { data.stdout.as_ref() } else { data.stderr.as_ref() }; let mut bytes_written = buf.len(); if let Some(stream) = sink { if !stream.add(buf.to_owned()) { bytes_written = 0; } } std::io::Result::Ok(bytes_written) }) } fn flush(&mut self) -> std::io::Result<()> { std::io::Result::Ok(()) } } type WorkerSendRecv = Arc<Mutex<(usize, Sender<FunctionCall>, Receiver<Vec<Val>>)>>; struct FunctionChannels { main_send: Sender<FunctionCall>, main_recv: Arc<Mutex<Receiver<FunctionCall>>>, workers_out: Vec<Sender<Vec<Val>>>, workers: Vec<WorkerSendRecv>, } impl FunctionChannels { fn new(num_workers: usize) -> Self { let (main_send, main_recv) = mpsc::channel::<FunctionCall>(); let mut workers_out = vec![]; let mut workers = vec![]; (0..num_workers).for_each(|index| { let (send_out, recv_out) = mpsc::channel::<Vec<Val>>(); workers_out.push(send_out); workers.push(Arc::new(Mutex::new((index, main_send.clone(), recv_out)))); }); Self { main_send, main_recv: Arc::new(Mutex::new(main_recv)), workers_out, workers, } } } impl WasmRunInstanceId { pub fn exports(&self) -> SyncReturn<Vec<ModuleExportValue>> { let mut v = ARRAY.write().unwrap(); let value = v.map.get_mut(&self.0).unwrap(); let instance = value.instance.unwrap(); let l = instance .exports(&mut value.store) .map(|e| (e.name().to_owned(), e.into_extern())) .collect::<Vec<(String, wasmtime::Extern)>>(); SyncReturn( l.into_iter() .map(|e| ModuleExportValue::from_export(e, &value.store)) .collect(), ) } } impl WasmRunModuleId { pub fn instantiate_sync(&self) -> Result<SyncReturn<WasmRunInstanceId>> { Ok(SyncReturn(self.instantiate()?)) } pub fn instantiate(&self) -> Result<WasmRunInstanceId> { let mut state = ARRAY.write().unwrap(); let module = state.map.get_mut(&self.0).unwrap(); if module.instance.is_some() { return Err(anyhow::anyhow!("Instance already exists")); } let instance = module .linker .instantiate(&mut module.store, &module.module.lock().unwrap())?; module.instance = Some(instance); let threads = module.threads.take(); if let Some(threads) = threads { let len = { let mut threads_i = threads.lock().unwrap(); for thread in threads_i.iter_mut() { let thread = thread.as_mut().unwrap(); let thread_instance = thread .linker .instantiate(&mut thread.store, &thread.module.lock().unwrap())?; thread.instance = Some(thread_instance); } threads_i.len() }; let pool = rayon::ThreadPoolBuilder::new() .num_threads(len) .start_handler(move |index| { STORE.with(|cell| { let t = threads.clone(); let mut threads = t.lock().unwrap(); let mut local_store = cell.borrow_mut(); *local_store = Some(threads[index].take().unwrap()); }) }) .build() .unwrap(); module.pool = Some(Arc::new(pool)); // let channels = module.channels.take().unwrap(); // let module_id = self.0; // let runtime = tokio::runtime::Builder::new_current_thread() // .max_blocking_threads(1) // .worker_threads(1) // .enable_all() // .build() // .unwrap(); // runtime.block_on(async move { // // module.runtime = Some(runtime); // // TODO: only do this when using runParallel, use select for waiting a finish signal // // runtime.block_on(async move { // let c = channels.lock().unwrap(); // c.main_recv.iter().for_each(|req| { // let worker = &c.workers_out[req.worker_index]; // let mut results = (0..req.num_results) // .map(|_| default_val(&ValType::I32)) // .collect::<Vec<_>>(); // // TODO: use same module instance // WasmRunModuleId(module_id) // .with_module_mut(|ctx| { // let f: WasmFunction = // unsafe { std::mem::transmute(req.function_pointer) }; // Self::execute_function(ctx, req.args, f, req.function_id, &mut results) // }) // .unwrap(); // worker.send(results).unwrap(); // }) // // }); // }); } Ok(WasmRunInstanceId(self.0)) } fn map_function( m: &mut WasmiModuleImpl, func: &Func, thread_index: usize, new_context: StoreContextMut<'_, StoreState>, ) -> RustOpaque<WFunc> { let raw_id = unsafe { func.to_raw(&mut m.store) as usize }; let hf = m.store.data().functions.get(&raw_id).unwrap(); let ff = Self::_create_function( new_context, hf.clone(), Some(m.channels.as_ref().unwrap().lock().unwrap().workers[thread_index].clone()), ) .unwrap() .0; ff } pub fn link_imports(&self, imports: Vec<ModuleImport>) -> Result<SyncReturn<()>> { let mut arr = ARRAY.write().unwrap(); let m = arr.map.get_mut(&self.0).unwrap(); if m.instance.is_some() { return Err(anyhow::anyhow!("Instance already exists")); } for import in imports.iter() { m.linker .define(&mut m.store, &import.module, &import.name, &import.value)?; } if let Some(threads) = m.threads.clone().as_ref() { for (thread_index, thread) in &mut threads.lock().unwrap().iter_mut().enumerate() { let thread = thread.as_mut().unwrap(); for import in imports.iter() { let mapped_value = match &import.value { ExternalValue::Func(f) => { let ff = Self::map_function( m, &f.func_wasmtime, thread_index, thread.store.as_context_mut(), ); ExternalValue::Func(ff) } ExternalValue::SharedMemory(m) => ExternalValue::SharedMemory(m.clone()), ExternalValue::Global(g) => { let ty = g.ty(&m.store); let v = match g.get(&mut m.store) { Val::FuncRef(Some(v)) => { let ff = Self::map_function( m, &v, thread_index, thread.store.as_context_mut(), ); Val::FuncRef(Some(ff.func_wasmtime)) } v => v, }; let global = Global::new(&mut thread.store, ty, v)?; ExternalValue::Global(RustOpaque::new(global)) } ExternalValue::Memory(mem) => { let ty = mem.ty(&m.store); // TODO: should we copy the memory contents? let memory = Memory::new(&mut thread.store, ty)?; ExternalValue::Memory(RustOpaque::new(memory)) } ExternalValue::Table(t) => { let ty = t.ty(&m.store); let fill_value = if t.size(&m.store) > 0 { let v = t.get(&mut m.store, 0); if let Some(Val::FuncRef(Some(v))) = v { let ff = Self::map_function( m, &v, thread_index, thread.store.as_context_mut(), ); Some(Val::FuncRef(Some(ff.func_wasmtime))) } else { v } } else { None }; let v = fill_value.unwrap_or_else(|| default_val(&ty.element())); let table = Table::new(&mut thread.store, ty, v)?; ExternalValue::Table(RustOpaque::new(table)) } }; thread.linker.define( &mut thread.store, &import.module, &import.name, &mapped_value, )?; } } } Ok(SyncReturn(())) } pub fn stdio_stream(&self, sink: StreamSink<Vec<u8>>, kind: StdIOKind) -> Result<()> { self.with_module_mut(|mut store| { let store_state = store.data_mut(); { let value = match kind { StdIOKind::stdout => &store_state.stdout, StdIOKind::stderr => &store_state.stderr, }; if value.is_some() { return Err(anyhow::anyhow!("Stream sink already set")); } } match kind { StdIOKind::stdout => store_state.stdout = Some(sink), StdIOKind::stderr => store_state.stderr = Some(sink), }; Ok(()) }) } pub fn dispose(&self) -> Result<()> { let mut arr = ARRAY.write().unwrap(); arr.map.remove(&self.0); Ok(()) } pub fn call_function_handle_sync( &self, func: RustOpaque<WFunc>, args: Vec<WasmVal>, ) -> Result<SyncReturn<Vec<WasmVal>>> { self.call_function_handle(func, args).map(SyncReturn) } pub fn call_function_handle( &self, func: RustOpaque<WFunc>, args: Vec<WasmVal>, ) -> Result<Vec<WasmVal>> { let func: Func = func.func_wasmtime; self.with_module_mut(|mut store| { let mut outputs: Vec<Value> = func.ty(&store).results().map(|t| default_val(&t)).collect(); let inputs: Vec<Value> = args.into_iter().map(|v| v.to_val()).collect(); func.call(&mut store, inputs.as_slice(), &mut outputs)?; Ok(outputs.into_iter().map(WasmVal::from_val).collect()) }) } pub fn call_function_handle_parallel( &self, func_name: String, args: Vec<WasmVal>, num_tasks: usize, function_stream: StreamSink<ParallelExec>, ) { use rayon::prelude::*; let (num_params, result_types, pool, channels) = { let mut m = ARRAY.write().unwrap(); let module = m.map.get_mut(&self.0).unwrap(); let func: Func = module .instance .unwrap() .get_func(&mut module.store, &func_name) .unwrap(); let num_params = func.ty(&module.store).params().count(); if (num_params == 0 && !args.is_empty()) || (num_params != 0 && args.len() % num_params != 0) || num_params * num_tasks != args.len() { function_stream.add(ParallelExec::Err(format!( "Number of arguments must be a multiple of {num_params}" ))); return; } let result_types: Vec<ValType> = func.ty(&module.store).results().collect(); ( num_params, result_types, module.pool.clone(), module.channels.clone(), ) }; if let (Some(pool), Some(channels)) = (pool, channels) { let args: Vec<Value> = args.into_iter().map(|v| v.to_val()).collect(); let main_send = channels.lock().unwrap().main_send.clone(); // TODO: try with tokio std::thread::spawn(move || { let value: std::result::Result<Vec<WasmVal>, Error> = pool.install(|| { let iter: Vec<&[Val]> = if args.is_empty() { (0..num_tasks).map(|_| [].as_slice()).collect() } else { args.chunks_exact(num_params).collect() }; let v = iter .par_iter() .map(|inputs| { STORE.with(|cell| { let mut c = cell.borrow_mut(); let m = c.as_mut().unwrap(); let mut outputs: Vec<Value> = result_types.iter().map(default_val).collect(); let func = m .instance .unwrap() .get_func(&mut m.store, &func_name) .unwrap(); func.call(&mut m.store, inputs, &mut outputs)?; Ok(outputs .into_iter() .map(WasmVal::from_val) .collect::<Vec<WasmVal>>()) }) }) .collect::<Result<Vec<Vec<WasmVal>>>>()? .into_iter() .flatten() .collect::<Vec<WasmVal>>(); Ok(v) }); // TODO: don't unwrap main_send .send(FunctionCall { // TODO: don't unwrap args: value.unwrap(), function_id: 0, function_pointer: 0, num_results: 0, worker_index: 0, }) .unwrap(); }); let main_recv = channels.lock().unwrap().main_recv.clone(); let main_recv_c = main_recv.lock().unwrap(); loop { let req = main_recv_c.recv().unwrap(); if req.function_pointer == 0 { function_stream.add(ParallelExec::Ok(req.args)); return; } function_stream.add(ParallelExec::Call(req)); // TODO: try this code with sync function // let worker = &c.workers_out[req.worker_index]; // let mut results = (0..req.num_results) // .map(|_| default_val(&ValType::I32)) // .collect::<Vec<_>>(); // // TODO: use same module instance // self.with_module_mut(|ctx| { // let f: WasmFunction = unsafe { std::mem::transmute(req.function_pointer) }; // Self::execute_function(ctx, req.args, f, req.function_id, &mut results) // }) // .unwrap(); // worker.send(results).unwrap(); } } else { function_stream.add(ParallelExec::Err( "Instance has no thread pool configured".to_string(), )); } } pub fn worker_execution( &self, worker_index: usize, results: Vec<WasmVal>, ) -> Result<SyncReturn<()>> { let m = ARRAY.read().unwrap(); let module = m.map.get(&self.0).unwrap(); let worker = &module .channels .as_ref() .unwrap() .lock() .unwrap() .workers_out[worker_index]; worker.send(results.into_iter().map(|v| v.to_val()).collect())?; Ok(SyncReturn(())) } fn with_module_mut<T>(&self, f: impl FnOnce(StoreContextMut<'_, StoreState>) -> T) -> T { { let stack = self.1 .0.read().unwrap(); if let Some(caller) = stack.last() { return f(caller.write().unwrap().as_context_mut()); } } let mut arr = ARRAY.write().unwrap(); let value = arr.map.get_mut(&self.0).unwrap(); let mut ctx = value.store.as_context_mut(); { let v = RwLock::new(unsafe { std::mem::transmute(ctx.as_context_mut()) }); self.1 .0.write().unwrap().push(v); } let result = f(ctx); self.1 .0.write().unwrap().pop(); result } fn with_module<T>(&self, f: impl FnOnce(&StoreContext<'_, StoreState>) -> T) -> T { { let stack = self.1 .0.read().unwrap(); if let Some(caller) = stack.last() { return f(&caller.read().unwrap().as_context()); } } let arr = ARRAY.read().unwrap(); let value = arr.map.get(&self.0).unwrap(); f(&value.store.as_context()) } pub fn get_function_type(&self, func: RustOpaque<WFunc>) -> SyncReturn<FuncTy> { SyncReturn(self.with_module(|store| (&func.func_wasmtime.ty(store)).into())) } pub fn create_function( &self, function_pointer: usize, function_id: u32, param_types: Vec<ValueTy>, result_types: Vec<ValueTy>, ) -> Result<SyncReturn<RustOpaque<WFunc>>> { self.with_module_mut(|store| { Self::_create_function( store, HostFunction { function_pointer, function_id, param_types, result_types, }, None, ) }) } fn _create_function( mut store: StoreContextMut<'_, StoreState>, hf: HostFunction, worker_channel: Option<WorkerSendRecv>, ) -> Result<SyncReturn<RustOpaque<WFunc>>> { let f: WasmFunction = unsafe { std::mem::transmute(hf.function_pointer) }; let func = Func::new( store.as_context_mut(), FuncType::new( hf.param_types.iter().cloned().map(ValueType::from), hf.result_types.iter().cloned().map(ValueType::from), ), move |mut caller, params, results| { let mapped: Vec<WasmVal> = params .iter() .map(|a| WasmVal::from_val(a.clone())) .collect(); if let Some(worker_channel) = worker_channel.clone() { let guard = worker_channel.lock().unwrap(); // TODO: use StreamSink directly guard.1.send(FunctionCall { args: mapped, function_id: hf.function_id, function_pointer: hf.function_pointer, num_results: results.len(), worker_index: guard.0, })?; let output = guard.2.recv()?; let mut outputs = output.into_iter(); for value in results { *value = outputs.next().unwrap(); } return Ok(()); } Self::execute_function( caller.as_context_mut(), mapped, f, hf.function_id, results, )?; Ok(()) }, ); let raw_id = unsafe { func.to_raw(&mut store) as usize }; store.data_mut().functions.insert(raw_id, hf); Ok(SyncReturn(RustOpaque::new(func.into()))) } fn execute_function( caller: StoreContextMut<'_, StoreState>, mapped: Vec<WasmVal>, f: WasmFunction, function_id: u32, results: &mut [Val], ) -> Result<()> { let inputs = vec![mapped].into_dart(); let stack = { let stack = caller.data().stack.clone(); let v = RwLock::new(unsafe { std::mem::transmute(caller) }); stack.0.write().unwrap().push(v); stack }; let output: Vec<WasmVal> = unsafe { let pointer = new_leak_box_ptr(inputs); let result = f(function_id, pointer); pointer.drop_in_place(); result.wire2api() }; // TODO: use Drop for this let last_caller = stack.0.write().unwrap().pop(); if output.len() != results.len() { return Err(anyhow::anyhow!("Invalid output length")); } else if last_caller.is_none() { return Err(anyhow::anyhow!("CALLER_STACK is empty")); } else if output.is_empty() { return Ok(()); } // let last_caller = last_caller.unwrap(); // let mut caller = last_caller.write().unwrap(); let mut outputs = output.into_iter(); for value in results { *value = outputs.next().unwrap().to_val(); } Ok(()) } pub fn create_memory(&self, memory_type: MemoryTy) -> Result<SyncReturn<RustOpaque<Memory>>> { self.with_module_mut(|store| { let mem_type = memory_type.to_memory_type()?; let memory = Memory::new(store, mem_type).map_err(to_anyhow)?; Ok(SyncReturn(RustOpaque::new(memory))) }) } pub fn create_global( &self, value: WasmVal, mutable: bool, ) -> Result<SyncReturn<RustOpaque<Global>>> { self.with_module_mut(|mut store| { let mapped = value.to_val(); let global = Global::new( &mut store, GlobalType::new( mapped.ty(), if mutable { Mutability::Var } else { Mutability::Const }, ), mapped, )?; Ok(SyncReturn(RustOpaque::new(global))) }) } pub fn create_table( &self, value: WasmVal, table_type: TableArgs, ) -> Result<SyncReturn<RustOpaque<Table>>> { self.with_module_mut(|mut store| { let mapped_value = value.to_val(); let table = Table::new( &mut store, TableType::new(mapped_value.ty(), table_type.minimum, table_type.maximum), mapped_value, ) .map_err(to_anyhow)?; Ok(SyncReturn(RustOpaque::new(table))) }) } // GLOBAL pub fn get_global_type(&self, global: RustOpaque<Global>) -> SyncReturn<GlobalTy> { SyncReturn(self.with_module(|store| (&global.ty(store)).into())) } pub fn get_global_value(&self, global: RustOpaque<Global>) -> SyncReturn<WasmVal> { SyncReturn(self.with_module_mut(|store| WasmVal::from_val(global.get(store)))) } pub fn set_global_value( &self, global: RustOpaque<Global>, value: WasmVal, ) -> Result<SyncReturn<()>> { self.with_module_mut(|mut store| { let mapped = value.to_val(); global .set(&mut store, mapped) .map(|_| SyncReturn(())) .map_err(to_anyhow) }) } // MEMORY pub fn get_memory_type(&self, memory: RustOpaque<Memory>) -> SyncReturn<MemoryTy> { SyncReturn(self.with_module(|store| (&memory.ty(store)).into())) } pub fn get_memory_data(&self, memory: RustOpaque<Memory>) -> SyncReturn<Vec<u8>> { SyncReturn(self.with_module(|store| memory.data(store).to_owned())) } pub fn get_memory_data_pointer(&self, memory: RustOpaque<Memory>) -> SyncReturn<usize> { SyncReturn(self.with_module(|store| memory.data_ptr(store) as usize)) } pub fn get_memory_data_pointer_and_length( &self, memory: RustOpaque<Memory>, ) -> SyncReturn<PointerAndLength> { SyncReturn(self.with_module(|store| PointerAndLength { pointer: memory.data_ptr(store) as usize, length: memory.data_size(store), })) } pub fn read_memory( &self, memory: RustOpaque<Memory>, offset: usize, bytes: usize, ) -> Result<SyncReturn<Vec<u8>>> { self.with_module(|store| { let mut buffer = Vec::with_capacity(bytes); #[allow(clippy::uninit_vec)] unsafe { buffer.set_len(bytes) }; memory .read(store, offset, &mut buffer) .map(|_| SyncReturn(buffer)) .map_err(to_anyhow) }) } pub fn get_memory_pages(&self, memory: RustOpaque<Memory>) -> SyncReturn<u32> {
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
true
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_run/native/src/api_wasmi.rs
packages/wasm_run/native/src/api_wasmi.rs
pub use crate::atomics::*; use crate::bridge_generated::{wire_list_wasm_val, Wire2Api}; use crate::config::*; pub use crate::external::WFunc; use crate::types::*; use anyhow::{Ok, Result}; use flutter_rust_bridge::{ support::new_leak_box_ptr, DartAbi, IntoDart, RustOpaque, StreamSink, SyncReturn, }; use once_cell::sync::Lazy; use std::io::Write; pub use std::sync::RwLock; use std::{collections::HashMap, sync::Arc}; #[cfg(feature = "wasi")] use wasi_common::pipe::WritePipe; use wasmi::core::Trap; pub use wasmi::{core::Pages, Func, Global, Memory, Module, Table}; use wasmi::{core::ValueType, *}; static ARRAY: Lazy<RwLock<GlobalState>> = Lazy::new(|| RwLock::new(Default::default())); static CALLER_STACK2: Lazy<RwLock<Vec<RwLock<&mut Store<StoreState>>>>> = Lazy::new(|| RwLock::new(Default::default())); #[derive(Default)] struct GlobalState { map: HashMap<u32, WasmiModuleImpl>, last_id: u32, } struct WasmiModuleImpl { module: Arc<std::sync::Mutex<Module>>, linker: Linker<StoreState>, store: Store<StoreState>, instance: Option<Instance>, } struct StoreState { #[cfg(feature = "wasi")] wasi_ctx: Option<wasi_common::WasiCtx>, stdout: Option<StreamSink<Vec<u8>>>, stderr: Option<StreamSink<Vec<u8>>>, stack: CallStack, // TODO: add to stdin? } #[derive(Debug)] pub struct WasmRunSharedMemory(pub RustOpaque<Arc<RwLock<SharedMemory>>>); #[derive(Debug)] pub struct SharedMemory; #[derive(Clone)] pub struct WasmRunModuleId(pub u32, pub RustOpaque<CallStack>); #[derive(Clone, Default)] pub struct CallStack(Arc<RwLock<Vec<RwLock<StoreContextMut<'static, StoreState>>>>>); #[derive(Debug, Clone, Copy)] pub struct WasmRunInstanceId(pub u32); fn make_wasi_ctx( id: &WasmRunModuleId, wasi_config: &Option<WasiConfigNative>, ) -> Result<Option<wasi_common::WasiCtx>> { let mut wasi_ctx = None; if let Some(wasi_config) = wasi_config { let mut wasi = wasi_config.to_wasi_ctx()?; if wasi_config.capture_stdout { let stdout_handler = ModuleIOWriter { id: id.clone(), is_stdout: true, }; wasi.set_stdout(Box::new(WritePipe::new(stdout_handler))); } if wasi_config.capture_stderr { let stderr_handler = ModuleIOWriter { id: id.clone(), is_stdout: false, }; wasi.set_stderr(Box::new(WritePipe::new(stderr_handler))); } wasi_ctx = Some(wasi); } Ok(wasi_ctx) } pub fn module_builder( module: CompiledModule, num_threads: Option<usize>, wasi_config: Option<WasiConfigNative>, ) -> Result<SyncReturn<WasmRunModuleId>> { if wasi_config.is_some() && !cfg!(feature = "wasi") { return Err(anyhow::Error::msg( "WASI feature is not enabled. Please enable it by adding `--features wasi` when building.", )); } if num_threads.is_some() { return Err(anyhow::Error::msg( "Multi-threading is not supported for the wasmi runtime.", )); } let guard = module.0.lock().unwrap(); let engine = guard.engine(); let mut linker = <Linker<StoreState>>::new(engine); let mut arr = ARRAY.write().unwrap(); arr.last_id += 1; let id = arr.last_id; let stack: CallStack = Default::default(); let module_id = WasmRunModuleId(id, RustOpaque::new(stack.clone())); #[cfg(feature = "wasi")] let wasi_ctx = make_wasi_ctx(&module_id, &wasi_config)?; #[cfg(feature = "wasi")] if wasi_ctx.is_some() { wasmi_wasi::add_to_linker(&mut linker, |ctx| ctx.wasi_ctx.as_mut().unwrap())?; } let store = Store::new( engine, StoreState { #[cfg(feature = "wasi")] wasi_ctx, stdout: None, stderr: None, stack, }, ); let module_builder = WasmiModuleImpl { module: Arc::clone(&module.0), linker, store, instance: None, }; arr.map.insert(id, module_builder); Ok(SyncReturn(module_id)) } struct ModuleIOWriter { id: WasmRunModuleId, is_stdout: bool, } impl Write for ModuleIOWriter { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { self.id.with_module(|store| { let data = store.data(); let sink = if self.is_stdout { data.stdout.as_ref() } else { data.stderr.as_ref() }; let mut bytes_written = buf.len(); if let Some(stream) = sink { if !stream.add(buf.to_owned()) { bytes_written = 0; } } std::io::Result::Ok(bytes_written) }) } fn flush(&mut self) -> std::io::Result<()> { std::io::Result::Ok(()) } } impl WasmRunInstanceId { pub fn exports(&self) -> SyncReturn<Vec<ModuleExportValue>> { let value = &ARRAY.read().unwrap().map[&self.0]; SyncReturn( value .instance .unwrap() .exports(&value.store) .map(|e| ModuleExportValue::from_export(e, &value.store)) .collect(), ) } } impl WasmRunModuleId { pub fn instantiate_sync(&self) -> Result<SyncReturn<WasmRunInstanceId>> { Ok(SyncReturn(self.instantiate()?)) } pub fn instantiate(&self) -> Result<WasmRunInstanceId> { let mut state = ARRAY.write().unwrap(); let module = state.map.get_mut(&self.0).unwrap(); if module.instance.is_some() { return Err(anyhow::anyhow!("Instance already exists")); } let instance = module .linker .instantiate(&mut module.store, &module.module.lock().unwrap())? .start(&mut module.store)?; module.instance = Some(instance); Ok(WasmRunInstanceId(self.0)) } pub fn link_imports(&self, imports: Vec<ModuleImport>) -> Result<SyncReturn<()>> { let mut arr = ARRAY.write().unwrap(); let m = arr.map.get_mut(&self.0).unwrap(); for import in imports { m.linker .define(&import.module, &import.name, &import.value)?; } Ok(SyncReturn(())) } pub fn stdio_stream(&self, sink: StreamSink<Vec<u8>>, kind: StdIOKind) -> Result<()> { if !cfg!(feature = "wasi") { return Err(anyhow::anyhow!( "Stdio is not supported without the 'wasi' feature" )); } self.with_module_mut(|mut store| { let store_state = store.data_mut(); { let value = match kind { StdIOKind::stdout => &store_state.stdout, StdIOKind::stderr => &store_state.stderr, }; if value.is_some() { return Err(anyhow::anyhow!("Stream sink already set")); } } match kind { StdIOKind::stdout => store_state.stdout = Some(sink), StdIOKind::stderr => store_state.stderr = Some(sink), }; Ok(()) }) } pub fn dispose(&self) -> Result<()> { let mut arr = ARRAY.write().unwrap(); arr.map.remove(&self.0); Ok(()) } pub fn call_function_handle_sync( &self, func: RustOpaque<WFunc>, args: Vec<WasmVal>, ) -> Result<SyncReturn<Vec<WasmVal>>> { self.call_function_handle(func, args).map(SyncReturn) } pub fn call_function_handle( &self, func: RustOpaque<WFunc>, args: Vec<WasmVal>, ) -> Result<Vec<WasmVal>> { let func = func.func_wasmi; self.with_module_mut(|mut store| { let mut outputs: Vec<Value> = func .ty(&store) .results() .iter() .map(|t| Value::default(*t)) .collect(); let inputs: Vec<Value> = args.into_iter().map(|v| v.to_value(&mut store)).collect(); func.call(&mut store, inputs.as_slice(), &mut outputs)?; Ok(outputs .into_iter() .map(|a| WasmVal::from_value(&a, &store)) .collect()) }) } #[allow(unused_variables)] pub fn call_function_handle_parallel( &self, func_name: String, args: Vec<WasmVal>, num_tasks: usize, function_stream: StreamSink<ParallelExec>, ) { function_stream.add(ParallelExec::Err( "Parallel execution is not supported for wasmit.".to_string(), )); } #[allow(unused_variables)] pub fn worker_execution( &self, worker_index: usize, results: Vec<WasmVal>, ) -> Result<SyncReturn<()>> { Err(anyhow::anyhow!( "Parallel execution is not supported for wasmit." )) } fn with_module_mut<T>(&self, f: impl FnOnce(StoreContextMut<'_, StoreState>) -> T) -> T { { let stack = self.1 .0.read().unwrap(); if let Some(caller) = stack.last() { return f(caller.write().unwrap().as_context_mut()); } } let mut arr = ARRAY.write().unwrap(); let value = arr.map.get_mut(&self.0).unwrap(); let mut ctx = value.store.as_context_mut(); { let v = RwLock::new(unsafe { std::mem::transmute(ctx.as_context_mut()) }); self.1 .0.write().unwrap().push(v); } let result = f(ctx); self.1 .0.write().unwrap().pop(); result } fn with_module_mut2<T>(&self, f: impl FnOnce(&mut Store<StoreState>) -> T) -> T { { let stack = CALLER_STACK2.read().unwrap(); if let Some(caller) = stack.last() { return f(&mut caller.write().unwrap()); } } let mut arr = ARRAY.write().unwrap(); let value = arr.map.get_mut(&self.0).unwrap(); let ctx = &mut value.store; { let v = RwLock::new(unsafe { std::mem::transmute(&mut *ctx) }); CALLER_STACK2.write().unwrap().push(v); } let result = f(ctx); CALLER_STACK2.write().unwrap().pop(); result } fn with_module<T>(&self, f: impl FnOnce(&StoreContext<'_, StoreState>) -> T) -> T { { let stack = self.1 .0.read().unwrap(); if let Some(caller) = stack.last() { return f(&caller.read().unwrap().as_context()); } } let arr = ARRAY.read().unwrap(); let value = arr.map.get(&self.0).unwrap(); f(&value.store.as_context()) } pub fn get_function_type(&self, func: RustOpaque<WFunc>) -> SyncReturn<FuncTy> { SyncReturn(self.with_module(|store| (&func.func_wasmi.ty(store)).into())) } pub fn create_function( &self, function_pointer: usize, function_id: u32, param_types: Vec<ValueTy>, result_types: Vec<ValueTy>, ) -> Result<SyncReturn<RustOpaque<WFunc>>> { self.with_module_mut(|store| { let f: WasmFunction = unsafe { std::mem::transmute(function_pointer) }; let func = Func::new( store, FuncType::new( param_types.into_iter().map(ValueType::from), result_types.into_iter().map(ValueType::from), ), move |mut caller, params, results| { let mapped: Vec<WasmVal> = params .iter() .map(|a| WasmVal::from_value(a, &caller)) .collect(); let inputs = vec![mapped].into_dart(); let stack = { let stack = caller.data().stack.clone(); let v = RwLock::new(unsafe { std::mem::transmute(caller.as_context_mut()) }); stack.0.write().unwrap().push(v); stack }; let output: Vec<WasmVal> = unsafe { let pointer = new_leak_box_ptr(inputs); let result = f(function_id, pointer); pointer.drop_in_place(); result.wire2api() }; let last_caller = stack.0.write().unwrap().pop(); if output.len() != results.len() { return std::result::Result::Err(Trap::new("Invalid output length")); } else if last_caller.is_none() { return std::result::Result::Err(Trap::new("CALLER_STACK is empty")); } else if output.is_empty() { return std::result::Result::Ok(()); } let last_caller = last_caller.unwrap(); let mut caller = last_caller.write().unwrap(); let mut outputs = output.into_iter(); for value in results { *value = outputs.next().unwrap().to_value(caller.as_context_mut()); } std::result::Result::Ok(()) }, ); Ok(SyncReturn(RustOpaque::new(func.into()))) }) } pub fn create_memory(&self, memory_type: MemoryTy) -> Result<SyncReturn<RustOpaque<Memory>>> { self.with_module_mut(|store| { let mem_type = memory_type.to_memory_type()?; let memory = Memory::new(store, mem_type).map_err(to_anyhow)?; Ok(SyncReturn(RustOpaque::new(memory))) }) } pub fn create_global( &self, value: WasmVal, mutable: bool, ) -> Result<SyncReturn<RustOpaque<Global>>> { self.with_module_mut(|mut store| { let mapped = value.to_value(&mut store); let global = Global::new( &mut store, mapped, if mutable { Mutability::Var } else { Mutability::Const }, ); Ok(SyncReturn(RustOpaque::new(global))) }) } pub fn create_table( &self, value: WasmVal, table_type: TableArgs, ) -> Result<SyncReturn<RustOpaque<Table>>> { self.with_module_mut(|mut store| { let mapped_value = value.to_value(&mut store); let table = Table::new( &mut store, TableType::new(mapped_value.ty(), table_type.minimum, table_type.maximum), mapped_value, ) .map_err(to_anyhow)?; Ok(SyncReturn(RustOpaque::new(table))) }) } // GLOBAL pub fn get_global_type(&self, global: RustOpaque<Global>) -> SyncReturn<GlobalTy> { SyncReturn(self.with_module(|store| (&global.ty(store)).into())) } pub fn get_global_value(&self, global: RustOpaque<Global>) -> SyncReturn<WasmVal> { SyncReturn(self.with_module(|store| WasmVal::from_value(&global.get(store), store))) } pub fn set_global_value( &self, global: RustOpaque<Global>, value: WasmVal, ) -> Result<SyncReturn<()>> { self.with_module_mut(|mut store| { let mapped = value.to_value(&mut store); global .set(&mut store, mapped) .map(|_| SyncReturn(())) .map_err(to_anyhow) }) } // MEMORY pub fn get_memory_type(&self, memory: RustOpaque<Memory>) -> SyncReturn<MemoryTy> { SyncReturn(self.with_module(|store| (&memory.ty(store)).into())) } pub fn get_memory_data(&self, memory: RustOpaque<Memory>) -> SyncReturn<Vec<u8>> { SyncReturn(self.with_module(|store| memory.data(store).to_owned())) } pub fn get_memory_data_pointer(&self, memory: RustOpaque<Memory>) -> SyncReturn<usize> { SyncReturn(self.with_module_mut(|store| memory.data_mut(store).as_mut_ptr() as usize)) } pub fn get_memory_data_pointer_and_length( &self, memory: RustOpaque<Memory>, ) -> SyncReturn<PointerAndLength> { SyncReturn(self.with_module(|store| { let data = memory.data(store); PointerAndLength { pointer: data.as_ptr() as usize, length: data.len(), } })) } pub fn read_memory( &self, memory: RustOpaque<Memory>, offset: usize, bytes: usize, ) -> Result<SyncReturn<Vec<u8>>> { self.with_module(|store| { let mut buffer = Vec::with_capacity(bytes); #[allow(clippy::uninit_vec)] unsafe { buffer.set_len(bytes) }; memory .read(store, offset, &mut buffer) .map(|_| SyncReturn(buffer)) .map_err(to_anyhow) }) } pub fn get_memory_pages(&self, memory: RustOpaque<Memory>) -> SyncReturn<u32> { SyncReturn(self.with_module(|store| memory.current_pages(store).into())) } pub fn write_memory( &self, memory: RustOpaque<Memory>, offset: usize, buffer: Vec<u8>, ) -> Result<SyncReturn<()>> { self.with_module_mut(|store| { memory .write(store, offset, &buffer) .map(SyncReturn) .map_err(to_anyhow) }) } pub fn grow_memory(&self, memory: RustOpaque<Memory>, pages: u32) -> Result<SyncReturn<u32>> { self.with_module_mut(|store| { memory .grow( store, Pages::new(pages).ok_or(anyhow::anyhow!("Invalid pages"))?, ) .map(|p| SyncReturn(p.into())) .map_err(to_anyhow) }) } // TABLE pub fn get_table_size(&self, table: RustOpaque<Table>) -> SyncReturn<u32> { SyncReturn(self.with_module(|store| table.size(store))) } pub fn get_table_type(&self, table: RustOpaque<Table>) -> SyncReturn<TableTy> { SyncReturn(self.with_module(|store| (&table.ty(store)).into())) } pub fn grow_table( &self, table: RustOpaque<Table>, delta: u32, value: WasmVal, ) -> Result<SyncReturn<u32>> { self.with_module_mut(|mut store| { let mapped = value.to_value(&mut store); table .grow(&mut store, delta, mapped) .map(SyncReturn) .map_err(to_anyhow) }) } pub fn get_table(&self, table: RustOpaque<Table>, index: u32) -> SyncReturn<Option<WasmVal>> { SyncReturn(self.with_module(|store| { table .get(store, index) .map(|v| WasmVal::from_value(&v, store)) })) } pub fn set_table( &self, table: RustOpaque<Table>, index: u32, value: WasmVal, ) -> Result<SyncReturn<()>> { self.with_module_mut(|mut store| { let mapped = value.to_value(&mut store); table .set(&mut store, index, mapped) .map(SyncReturn) .map_err(to_anyhow) }) } pub fn fill_table( &self, table: RustOpaque<Table>, index: u32, value: WasmVal, len: u32, ) -> Result<SyncReturn<()>> { self.with_module_mut(|mut store| { let mapped = value.to_value(&mut store); table .fill(&mut store, index, mapped, len) .map(|_| SyncReturn(())) .map_err(to_anyhow) }) } // FUEL // pub fn add_fuel(&self, delta: u64) -> Result<SyncReturn<()>> { self.with_module_mut2(|store| store.add_fuel(delta).map(SyncReturn).map_err(to_anyhow)) } pub fn fuel_consumed(&self) -> SyncReturn<Option<u64>> { self.with_module_mut2(|store| SyncReturn(store.fuel_consumed())) } pub fn consume_fuel(&self, delta: u64) -> Result<SyncReturn<u64>> { self.with_module_mut2(|store| store.consume_fuel(delta).map(SyncReturn).map_err(to_anyhow)) } } pub fn parse_wat_format(wat: String) -> Result<Vec<u8>> { Ok(wat::parse_str(wat)?) } type WasmFunction = unsafe extern "C" fn(function_id: u32, args: *mut DartAbi) -> *mut wire_list_wasm_val; pub struct CompiledModule(pub RustOpaque<Arc<std::sync::Mutex<Module>>>); impl CompiledModule { #[allow(unused)] pub fn create_shared_memory( &self, memory_type: MemoryTy, ) -> Result<SyncReturn<WasmRunSharedMemory>> { Err(anyhow::Error::msg( "shared_memory is not supported for wasmi", )) } pub fn get_module_imports(&self) -> SyncReturn<Vec<ModuleImportDesc>> { SyncReturn( self.0 .lock() .unwrap() .imports() .map(|i| (&i).into()) .collect(), ) } pub fn get_module_exports(&self) -> SyncReturn<Vec<ModuleExportDesc>> { SyncReturn( self.0 .lock() .unwrap() .exports() .map(|i| (&i).into()) .collect(), ) } } impl From<Module> for CompiledModule { fn from(module: Module) -> Self { CompiledModule(RustOpaque::new(Arc::new(std::sync::Mutex::new(module)))) } } pub fn compile_wasm(module_wasm: Vec<u8>, config: ModuleConfig) -> Result<CompiledModule> { let config: Config = config.into(); let engine = Engine::new(&config); let module = Module::new(&engine, &mut &module_wasm[..])?; Ok(module.into()) } pub fn compile_wasm_sync( module_wasm: Vec<u8>, config: ModuleConfig, ) -> Result<SyncReturn<CompiledModule>> { compile_wasm(module_wasm, config).map(SyncReturn) } pub fn wasm_features_for_config(config: ModuleConfig) -> SyncReturn<WasmFeatures> { SyncReturn(config.wasm_features()) } pub fn wasm_runtime_features() -> SyncReturn<WasmRuntimeFeatures> { SyncReturn(WasmRuntimeFeatures::default()) } #[allow(unused)] impl WasmRunSharedMemory { pub fn ty(&self) -> SyncReturn<MemoryTy> { unreachable!() } pub fn size(&self) -> SyncReturn<u64> { unreachable!() } pub fn data_size(&self) -> SyncReturn<usize> { unreachable!() } pub fn data_pointer(&self) -> SyncReturn<usize> { unreachable!() } pub fn grow(&self, delta: u64) -> Result<SyncReturn<u64>> { unreachable!() } // pub fn atomic_i8(&self) -> crate::atomics::Ati8 { // crate::atomics::Ati8(self.0.read().unwrap().data().as_ptr() as usize) // } pub fn atomics(&self) -> Atomics { unreachable!() } pub fn atomic_notify(&self, addr: u64, count: u32) -> Result<SyncReturn<u32>> { unreachable!() } /// Equivalent of the WebAssembly `memory.atomic.wait32` instruction for /// this shared memory. /// /// This method allows embedders to block the current thread until notified /// via the `memory.atomic.notify` instruction or the /// [`SharedMemory::atomic_notify`] method, enabling synchronization with /// the wasm guest as desired. /// /// The `expected` argument is the expected 32-bit value to be stored at /// the byte address `addr` specified. The `addr` specified is an index /// into this linear memory. /// /// The optional `timeout` argument is the point in time after which the /// calling thread is guaranteed to be woken up. Blocking will not occur /// past this point. /// /// This function returns one of three possible values: /// /// * `WaitResult::Ok` - this function, loaded the value at `addr`, found /// it was equal to `expected`, and then blocked (all as one atomic /// operation). The thread was then awoken with a `memory.atomic.notify` /// instruction or the [`SharedMemory::atomic_notify`] method. /// * `WaitResult::Mismatch` - the value at `addr` was loaded but was not /// equal to `expected` so the thread did not block and immediately /// returned. /// * `WaitResult::TimedOut` - all the steps of `Ok` happened, except this /// thread was woken up due to a timeout. /// /// This function will not return due to spurious wakeups. /// /// # Errors /// /// This function will return an error if `addr` is not within bounds or /// not aligned to a 4-byte boundary. pub fn atomic_wait32( &self, addr: u64, expected: u32, // TODO: timeout: Option<Instant>, ) -> Result<SyncReturn<SharedMemoryWaitResult>> { unreachable!() } /// Equivalent of the WebAssembly `memory.atomic.wait64` instruction for /// this shared memory. /// /// For more information see [`SharedMemory::atomic_wait32`]. /// /// # Errors /// /// Returns the same error as [`SharedMemory::atomic_wait32`] except that /// the specified address must be 8-byte aligned instead of 4-byte aligned. pub fn atomic_wait64( &self, addr: u64, expected: u64, // TODO: timeout: Option<Instant>, ) -> Result<SyncReturn<SharedMemoryWaitResult>> { unreachable!() } } #[allow(unused)] impl Atomics { /// Adds the provided value to the existing value at the specified index of the array. Returns the old value at that index. pub fn add(&self, offset: usize, kind: AtomicKind, val: i64, order: AtomicOrdering) -> i64 { unreachable!() } /// Returns the value at the specified index of the array. pub fn load(&self, offset: usize, kind: AtomicKind, order: AtomicOrdering) -> i64 { unreachable!() } /// Stores a value at the specified index of the array. Returns the value. pub fn store(&self, offset: usize, kind: AtomicKind, val: i64, order: AtomicOrdering) { unreachable!() } /// Stores a value at the specified index of the array. Returns the old value. pub fn swap(&self, offset: usize, kind: AtomicKind, val: i64, order: AtomicOrdering) -> i64 { unreachable!() } /// Stores a value at the specified index of the array, if it equals a value. Returns the old value. pub fn compare_exchange( &self, offset: usize, kind: AtomicKind, current: i64, new_value: i64, success: AtomicOrdering, failure: AtomicOrdering, ) -> CompareExchangeResult { unreachable!() } /// Subtracts a value at the specified index of the array. Returns the old value at that index. pub fn sub(&self, offset: usize, kind: AtomicKind, val: i64, order: AtomicOrdering) -> i64 { unreachable!() } /// Computes a bitwise AND on the value at the specified index of the array with the provided value. Returns the old value at that index. pub fn and(&self, offset: usize, kind: AtomicKind, val: i64, order: AtomicOrdering) -> i64 { unreachable!() } /// Computes a bitwise OR on the value at the specified index of the array with the provided value. Returns the old value at that index. pub fn or(&self, offset: usize, kind: AtomicKind, val: i64, order: AtomicOrdering) -> i64 { unreachable!() } /// Computes a bitwise XOR on the value at the specified index of the array with the provided value. Returns the old value at that index. pub fn xor(&self, offset: usize, kind: AtomicKind, val: i64, order: AtomicOrdering) -> i64 { unreachable!() } }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_run/native/src/bridge_generated.rs
packages/wasm_run/native/src/bridge_generated.rs
#![allow( non_camel_case_types, unused, clippy::redundant_closure, clippy::useless_conversion, clippy::unit_arg, clippy::double_parens, non_snake_case, clippy::too_many_arguments )] // AUTO GENERATED FILE, DO NOT EDIT. // Generated by `flutter_rust_bridge`@ 1.82.4. use crate::api::*; use core::panic::UnwindSafe; use flutter_rust_bridge::rust2dart::IntoIntoDart; use flutter_rust_bridge::*; use std::ffi::c_void; use std::sync::Arc; // Section: imports use crate::atomics::AtomicKind; use crate::atomics::AtomicOrdering; use crate::atomics::Atomics; use crate::atomics::CompareExchangeResult; use crate::atomics::SharedMemoryWaitResult; use crate::config::EnvVariable; use crate::config::ModuleConfig; use crate::config::ModuleConfigWasmi; use crate::config::ModuleConfigWasmtime; use crate::config::PreopenedDir; use crate::config::StdIOKind; use crate::config::WasiConfigNative; use crate::config::WasiStackLimits; use crate::config::WasmFeatures; use crate::config::WasmRuntimeFeatures; use crate::config::WasmWasiFeatures; use crate::types::ExternalType; use crate::types::ExternalValue; use crate::types::FuncTy; use crate::types::FunctionCall; use crate::types::GlobalTy; use crate::types::MemoryTy; use crate::types::ModuleExportDesc; use crate::types::ModuleExportValue; use crate::types::ModuleImport; use crate::types::ModuleImportDesc; use crate::types::ParallelExec; use crate::types::PointerAndLength; use crate::types::TableArgs; use crate::types::TableTy; use crate::types::ValueTy; use crate::types::WasmVal; // Section: wire functions fn wire_module_builder_impl( module: impl Wire2Api<CompiledModule> + UnwindSafe, num_threads: impl Wire2Api<Option<usize>> + UnwindSafe, wasi_config: impl Wire2Api<Option<WasiConfigNative>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "module_builder", port: None, mode: FfiCallMode::Sync, }, move || { let api_module = module.wire2api(); let api_num_threads = num_threads.wire2api(); let api_wasi_config = wasi_config.wire2api(); module_builder(api_module, api_num_threads, api_wasi_config) }, ) } fn wire_parse_wat_format_impl(port_: MessagePort, wat: impl Wire2Api<String> + UnwindSafe) { FLUTTER_RUST_BRIDGE_HANDLER.wrap::<_, _, _, Vec<u8>, _>( WrapInfo { debug_name: "parse_wat_format", port: Some(port_), mode: FfiCallMode::Normal, }, move || { let api_wat = wat.wire2api(); move |task_callback| parse_wat_format(api_wat) }, ) } fn wire_compile_wasm_impl( port_: MessagePort, module_wasm: impl Wire2Api<Vec<u8>> + UnwindSafe, config: impl Wire2Api<ModuleConfig> + UnwindSafe, ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap::<_, _, _, CompiledModule, _>( WrapInfo { debug_name: "compile_wasm", port: Some(port_), mode: FfiCallMode::Normal, }, move || { let api_module_wasm = module_wasm.wire2api(); let api_config = config.wire2api(); move |task_callback| compile_wasm(api_module_wasm, api_config) }, ) } fn wire_compile_wasm_sync_impl( module_wasm: impl Wire2Api<Vec<u8>> + UnwindSafe, config: impl Wire2Api<ModuleConfig> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "compile_wasm_sync", port: None, mode: FfiCallMode::Sync, }, move || { let api_module_wasm = module_wasm.wire2api(); let api_config = config.wire2api(); compile_wasm_sync(api_module_wasm, api_config) }, ) } fn wire_wasm_features_for_config_impl( config: impl Wire2Api<ModuleConfig> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "wasm_features_for_config", port: None, mode: FfiCallMode::Sync, }, move || { let api_config = config.wire2api(); Result::<_, ()>::Ok(wasm_features_for_config(api_config)) }, ) } fn wire_wasm_runtime_features_impl() -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "wasm_runtime_features", port: None, mode: FfiCallMode::Sync, }, move || Result::<_, ()>::Ok(wasm_runtime_features()), ) } fn wire_exports__method__WasmRunInstanceId_impl( that: impl Wire2Api<WasmRunInstanceId> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "exports__method__WasmRunInstanceId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); Result::<_, ()>::Ok(WasmRunInstanceId::exports(&api_that)) }, ) } fn wire_instantiate_sync__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "instantiate_sync__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); WasmRunModuleId::instantiate_sync(&api_that) }, ) } fn wire_instantiate__method__WasmRunModuleId_impl( port_: MessagePort, that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap::<_, _, _, WasmRunInstanceId, _>( WrapInfo { debug_name: "instantiate__method__WasmRunModuleId", port: Some(port_), mode: FfiCallMode::Normal, }, move || { let api_that = that.wire2api(); move |task_callback| WasmRunModuleId::instantiate(&api_that) }, ) } fn wire_link_imports__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, imports: impl Wire2Api<Vec<ModuleImport>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "link_imports__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_imports = imports.wire2api(); WasmRunModuleId::link_imports(&api_that, api_imports) }, ) } fn wire_stdio_stream__method__WasmRunModuleId_impl( port_: MessagePort, that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, kind: impl Wire2Api<StdIOKind> + UnwindSafe, ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap::<_, _, _, (), _>( WrapInfo { debug_name: "stdio_stream__method__WasmRunModuleId", port: Some(port_), mode: FfiCallMode::Stream, }, move || { let api_that = that.wire2api(); let api_kind = kind.wire2api(); move |task_callback| { WasmRunModuleId::stdio_stream( &api_that, task_callback.stream_sink::<_, Vec<u8>>(), api_kind, ) } }, ) } fn wire_dispose__method__WasmRunModuleId_impl( port_: MessagePort, that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap::<_, _, _, (), _>( WrapInfo { debug_name: "dispose__method__WasmRunModuleId", port: Some(port_), mode: FfiCallMode::Normal, }, move || { let api_that = that.wire2api(); move |task_callback| WasmRunModuleId::dispose(&api_that) }, ) } fn wire_call_function_handle_sync__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, func: impl Wire2Api<RustOpaque<WFunc>> + UnwindSafe, args: impl Wire2Api<Vec<WasmVal>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "call_function_handle_sync__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_func = func.wire2api(); let api_args = args.wire2api(); WasmRunModuleId::call_function_handle_sync(&api_that, api_func, api_args) }, ) } fn wire_call_function_handle__method__WasmRunModuleId_impl( port_: MessagePort, that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, func: impl Wire2Api<RustOpaque<WFunc>> + UnwindSafe, args: impl Wire2Api<Vec<WasmVal>> + UnwindSafe, ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap::<_, _, _, Vec<WasmVal>, _>( WrapInfo { debug_name: "call_function_handle__method__WasmRunModuleId", port: Some(port_), mode: FfiCallMode::Normal, }, move || { let api_that = that.wire2api(); let api_func = func.wire2api(); let api_args = args.wire2api(); move |task_callback| { WasmRunModuleId::call_function_handle(&api_that, api_func, api_args) } }, ) } fn wire_call_function_handle_parallel__method__WasmRunModuleId_impl( port_: MessagePort, that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, func_name: impl Wire2Api<String> + UnwindSafe, args: impl Wire2Api<Vec<WasmVal>> + UnwindSafe, num_tasks: impl Wire2Api<usize> + UnwindSafe, ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap::<_, _, _, (), _>( WrapInfo { debug_name: "call_function_handle_parallel__method__WasmRunModuleId", port: Some(port_), mode: FfiCallMode::Stream, }, move || { let api_that = that.wire2api(); let api_func_name = func_name.wire2api(); let api_args = args.wire2api(); let api_num_tasks = num_tasks.wire2api(); move |task_callback| { Result::<_, ()>::Ok(WasmRunModuleId::call_function_handle_parallel( &api_that, api_func_name, api_args, api_num_tasks, task_callback.stream_sink::<_, ParallelExec>(), )) } }, ) } fn wire_worker_execution__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, worker_index: impl Wire2Api<usize> + UnwindSafe, results: impl Wire2Api<Vec<WasmVal>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "worker_execution__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_worker_index = worker_index.wire2api(); let api_results = results.wire2api(); WasmRunModuleId::worker_execution(&api_that, api_worker_index, api_results) }, ) } fn wire_get_function_type__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, func: impl Wire2Api<RustOpaque<WFunc>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "get_function_type__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_func = func.wire2api(); Result::<_, ()>::Ok(WasmRunModuleId::get_function_type(&api_that, api_func)) }, ) } fn wire_create_function__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, function_pointer: impl Wire2Api<usize> + UnwindSafe, function_id: impl Wire2Api<u32> + UnwindSafe, param_types: impl Wire2Api<Vec<ValueTy>> + UnwindSafe, result_types: impl Wire2Api<Vec<ValueTy>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "create_function__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_function_pointer = function_pointer.wire2api(); let api_function_id = function_id.wire2api(); let api_param_types = param_types.wire2api(); let api_result_types = result_types.wire2api(); WasmRunModuleId::create_function( &api_that, api_function_pointer, api_function_id, api_param_types, api_result_types, ) }, ) } fn wire_create_memory__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, memory_type: impl Wire2Api<MemoryTy> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "create_memory__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_memory_type = memory_type.wire2api(); WasmRunModuleId::create_memory(&api_that, api_memory_type) }, ) } fn wire_create_global__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, value: impl Wire2Api<WasmVal> + UnwindSafe, mutable: impl Wire2Api<bool> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "create_global__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_value = value.wire2api(); let api_mutable = mutable.wire2api(); WasmRunModuleId::create_global(&api_that, api_value, api_mutable) }, ) } fn wire_create_table__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, value: impl Wire2Api<WasmVal> + UnwindSafe, table_type: impl Wire2Api<TableArgs> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "create_table__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_value = value.wire2api(); let api_table_type = table_type.wire2api(); WasmRunModuleId::create_table(&api_that, api_value, api_table_type) }, ) } fn wire_get_global_type__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, global: impl Wire2Api<RustOpaque<Global>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "get_global_type__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_global = global.wire2api(); Result::<_, ()>::Ok(WasmRunModuleId::get_global_type(&api_that, api_global)) }, ) } fn wire_get_global_value__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, global: impl Wire2Api<RustOpaque<Global>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "get_global_value__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_global = global.wire2api(); Result::<_, ()>::Ok(WasmRunModuleId::get_global_value(&api_that, api_global)) }, ) } fn wire_set_global_value__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, global: impl Wire2Api<RustOpaque<Global>> + UnwindSafe, value: impl Wire2Api<WasmVal> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "set_global_value__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_global = global.wire2api(); let api_value = value.wire2api(); WasmRunModuleId::set_global_value(&api_that, api_global, api_value) }, ) } fn wire_get_memory_type__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, memory: impl Wire2Api<RustOpaque<Memory>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "get_memory_type__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_memory = memory.wire2api(); Result::<_, ()>::Ok(WasmRunModuleId::get_memory_type(&api_that, api_memory)) }, ) } fn wire_get_memory_data__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, memory: impl Wire2Api<RustOpaque<Memory>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "get_memory_data__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_memory = memory.wire2api(); Result::<_, ()>::Ok(WasmRunModuleId::get_memory_data(&api_that, api_memory)) }, ) } fn wire_get_memory_data_pointer__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, memory: impl Wire2Api<RustOpaque<Memory>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "get_memory_data_pointer__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_memory = memory.wire2api(); Result::<_, ()>::Ok(WasmRunModuleId::get_memory_data_pointer( &api_that, api_memory, )) }, ) } fn wire_get_memory_data_pointer_and_length__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, memory: impl Wire2Api<RustOpaque<Memory>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "get_memory_data_pointer_and_length__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_memory = memory.wire2api(); Result::<_, ()>::Ok(WasmRunModuleId::get_memory_data_pointer_and_length( &api_that, api_memory, )) }, ) } fn wire_read_memory__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, memory: impl Wire2Api<RustOpaque<Memory>> + UnwindSafe, offset: impl Wire2Api<usize> + UnwindSafe, bytes: impl Wire2Api<usize> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "read_memory__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_memory = memory.wire2api(); let api_offset = offset.wire2api(); let api_bytes = bytes.wire2api(); WasmRunModuleId::read_memory(&api_that, api_memory, api_offset, api_bytes) }, ) } fn wire_get_memory_pages__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, memory: impl Wire2Api<RustOpaque<Memory>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "get_memory_pages__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_memory = memory.wire2api(); Result::<_, ()>::Ok(WasmRunModuleId::get_memory_pages(&api_that, api_memory)) }, ) } fn wire_write_memory__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, memory: impl Wire2Api<RustOpaque<Memory>> + UnwindSafe, offset: impl Wire2Api<usize> + UnwindSafe, buffer: impl Wire2Api<Vec<u8>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "write_memory__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_memory = memory.wire2api(); let api_offset = offset.wire2api(); let api_buffer = buffer.wire2api(); WasmRunModuleId::write_memory(&api_that, api_memory, api_offset, api_buffer) }, ) } fn wire_grow_memory__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, memory: impl Wire2Api<RustOpaque<Memory>> + UnwindSafe, pages: impl Wire2Api<u32> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "grow_memory__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_memory = memory.wire2api(); let api_pages = pages.wire2api(); WasmRunModuleId::grow_memory(&api_that, api_memory, api_pages) }, ) } fn wire_get_table_size__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, table: impl Wire2Api<RustOpaque<Table>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "get_table_size__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_table = table.wire2api(); Result::<_, ()>::Ok(WasmRunModuleId::get_table_size(&api_that, api_table)) }, ) } fn wire_get_table_type__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, table: impl Wire2Api<RustOpaque<Table>> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "get_table_type__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_table = table.wire2api(); Result::<_, ()>::Ok(WasmRunModuleId::get_table_type(&api_that, api_table)) }, ) } fn wire_grow_table__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, table: impl Wire2Api<RustOpaque<Table>> + UnwindSafe, delta: impl Wire2Api<u32> + UnwindSafe, value: impl Wire2Api<WasmVal> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "grow_table__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_table = table.wire2api(); let api_delta = delta.wire2api(); let api_value = value.wire2api(); WasmRunModuleId::grow_table(&api_that, api_table, api_delta, api_value) }, ) } fn wire_get_table__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, table: impl Wire2Api<RustOpaque<Table>> + UnwindSafe, index: impl Wire2Api<u32> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "get_table__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_table = table.wire2api(); let api_index = index.wire2api(); Result::<_, ()>::Ok(WasmRunModuleId::get_table(&api_that, api_table, api_index)) }, ) } fn wire_set_table__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, table: impl Wire2Api<RustOpaque<Table>> + UnwindSafe, index: impl Wire2Api<u32> + UnwindSafe, value: impl Wire2Api<WasmVal> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "set_table__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_table = table.wire2api(); let api_index = index.wire2api(); let api_value = value.wire2api(); WasmRunModuleId::set_table(&api_that, api_table, api_index, api_value) }, ) } fn wire_fill_table__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, table: impl Wire2Api<RustOpaque<Table>> + UnwindSafe, index: impl Wire2Api<u32> + UnwindSafe, value: impl Wire2Api<WasmVal> + UnwindSafe, len: impl Wire2Api<u32> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "fill_table__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_table = table.wire2api(); let api_index = index.wire2api(); let api_value = value.wire2api(); let api_len = len.wire2api(); WasmRunModuleId::fill_table(&api_that, api_table, api_index, api_value, api_len) }, ) } fn wire_add_fuel__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, delta: impl Wire2Api<u64> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "add_fuel__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_delta = delta.wire2api(); WasmRunModuleId::add_fuel(&api_that, api_delta) }, ) } fn wire_fuel_consumed__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "fuel_consumed__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); Result::<_, ()>::Ok(WasmRunModuleId::fuel_consumed(&api_that)) }, ) } fn wire_consume_fuel__method__WasmRunModuleId_impl( that: impl Wire2Api<WasmRunModuleId> + UnwindSafe, delta: impl Wire2Api<u64> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "consume_fuel__method__WasmRunModuleId", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_delta = delta.wire2api(); WasmRunModuleId::consume_fuel(&api_that, api_delta) }, ) } fn wire_create_shared_memory__method__CompiledModule_impl( that: impl Wire2Api<CompiledModule> + UnwindSafe, memory_type: impl Wire2Api<MemoryTy> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "create_shared_memory__method__CompiledModule", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_memory_type = memory_type.wire2api(); CompiledModule::create_shared_memory(&api_that, api_memory_type) }, ) } fn wire_get_module_imports__method__CompiledModule_impl( that: impl Wire2Api<CompiledModule> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "get_module_imports__method__CompiledModule", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); Result::<_, ()>::Ok(CompiledModule::get_module_imports(&api_that)) }, ) } fn wire_get_module_exports__method__CompiledModule_impl( that: impl Wire2Api<CompiledModule> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "get_module_exports__method__CompiledModule", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); Result::<_, ()>::Ok(CompiledModule::get_module_exports(&api_that)) }, ) } fn wire_ty__method__WasmRunSharedMemory_impl( that: impl Wire2Api<WasmRunSharedMemory> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "ty__method__WasmRunSharedMemory", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); Result::<_, ()>::Ok(WasmRunSharedMemory::ty(&api_that)) }, ) } fn wire_size__method__WasmRunSharedMemory_impl( that: impl Wire2Api<WasmRunSharedMemory> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "size__method__WasmRunSharedMemory", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); Result::<_, ()>::Ok(WasmRunSharedMemory::size(&api_that)) }, ) } fn wire_data_size__method__WasmRunSharedMemory_impl( that: impl Wire2Api<WasmRunSharedMemory> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "data_size__method__WasmRunSharedMemory", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); Result::<_, ()>::Ok(WasmRunSharedMemory::data_size(&api_that)) }, ) } fn wire_data_pointer__method__WasmRunSharedMemory_impl( that: impl Wire2Api<WasmRunSharedMemory> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "data_pointer__method__WasmRunSharedMemory", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); Result::<_, ()>::Ok(WasmRunSharedMemory::data_pointer(&api_that)) }, ) } fn wire_grow__method__WasmRunSharedMemory_impl( that: impl Wire2Api<WasmRunSharedMemory> + UnwindSafe, delta: impl Wire2Api<u64> + UnwindSafe, ) -> support::WireSyncReturn { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync( WrapInfo { debug_name: "grow__method__WasmRunSharedMemory", port: None, mode: FfiCallMode::Sync, }, move || { let api_that = that.wire2api(); let api_delta = delta.wire2api(); WasmRunSharedMemory::grow(&api_that, api_delta) },
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
true
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_packages/image_ops/image_ops_wasm/src/lib.rs
packages/wasm_packages/image_ops/image_ops_wasm/src/lib.rs
use std::io::Cursor; use std::{collections::HashMap, sync::RwLock}; use once_cell::sync::Lazy; static IMAGES_MAP: Lazy<RwLock<GlobalState>> = Lazy::new(|| RwLock::new(Default::default())); #[derive(Debug, Default)] pub struct GlobalState { pub last_id: u32, pub images: HashMap<u32, image::DynamicImage>, } impl GlobalState { fn save_image(&mut self, image: image::DynamicImage) -> ImageRef { let id = self.last_id; self.last_id += 1; let image_ref = ImageRef { id, // TODO: pointer? // format: image::guess_format(&image.as_bytes()) // .map(map_image_format) // .unwrap_or(ImageFormat::Unknown), // pixel: None, width: image.width(), height: image.height(), color: map_color_type(image.color()), }; self.images.insert(id, image); image_ref } } fn with_mut<T>(f: impl FnOnce(&mut GlobalState) -> T) -> T { let mut state = IMAGES_MAP.write().unwrap(); f(&mut state) } fn with<T>(f: impl FnOnce(&GlobalState) -> T) -> T { let state = IMAGES_MAP.read().unwrap(); f(&state) } fn operation( image_ref: ImageRef, f: impl FnOnce(&image::DynamicImage) -> image::DynamicImage, ) -> ImageRef { with_mut(|state| { let img = &state.images[&image_ref.id]; let mapped = f(img); state.save_image(mapped) }) } // Use a procedural macro to generate bindings for the world we specified in // `with/dart-wit-generator.wit` wit_bindgen::generate!("image-ops"); use exports::wasm_run_dart::image_ops; use exports::wasm_run_dart::image_ops::operations::{FilterType, ImageCrop}; // Define a custom type and implement the generated `Host` trait for it which // represents implementing all the necessary exported interfaces for this // component. struct ImageOpsImpl; export_image_ops!(ImageOpsImpl); impl ImageOps for ImageOpsImpl { fn guess_buffer_format(buffer: Vec<u8>) -> Result<ImageFormat, String> { image::guess_format(&buffer) .map(map_image_format) .map_err(map_err) } fn format_extensions(f: ImageFormat) -> Vec<String> { map_image_format_to(f) .extensions_str() .iter() .map(|e| e.to_string()) .collect() } fn file_image_size(path: String) -> Result<ImageSize, String> { image::image_dimensions(&path) .map(|(width, height)| ImageSize { width, height }) .map_err(map_err) } fn image_buffer_pointer_and_size(image_ref: ImageRef) -> (u32, u32) { with(|state| { let buffer = state.images[&image_ref.id].as_bytes(); (buffer.as_ptr() as u32, buffer.len() as u32) }) } fn copy_image_buffer(image_ref: ImageRef) -> Image { with(|state| { let img = &state.images[&image_ref.id]; let len = Some(img.color().channel_count() as usize) .and_then(|size| size.checked_mul(img.width() as usize)) .and_then(|size| size.checked_mul(img.height() as usize)); let bytes = img.as_bytes()[..len.unwrap()].to_vec(); Image { bytes } }) } fn convert_color(image_ref: ImageRef, color: ColorType) -> ImageRef { operation(image_ref, |img| { let mapped = match color { ColorType::L8 => image::DynamicImage::ImageLuma8(img.to_luma8()), ColorType::La8 => image::DynamicImage::ImageLumaA8(img.to_luma_alpha8()), ColorType::Rgb8 => image::DynamicImage::ImageRgb8(img.to_rgb8()), ColorType::Rgba8 => image::DynamicImage::ImageRgba8(img.to_rgba8()), ColorType::L16 => image::DynamicImage::ImageLuma16(img.to_luma16()), ColorType::La16 => image::DynamicImage::ImageLumaA16(img.to_luma_alpha16()), ColorType::Rgb16 => image::DynamicImage::ImageRgb16(img.to_rgb16()), ColorType::Rgba16 => image::DynamicImage::ImageRgba16(img.to_rgba16()), ColorType::Rgb32f => image::DynamicImage::ImageRgb32F(img.to_rgb32f()), ColorType::Rgba32f => image::DynamicImage::ImageRgba32F(img.to_rgba32f()), ColorType::Unknown => img.clone(), }; mapped }) } fn convert_format(image_ref: ImageRef, image_format: ImageFormat) -> Result<Vec<u8>, String> { with(|state| { use image::error::*; use image::DynamicImage; let mut output = Cursor::new(Vec::new()); let image_format = map_image_format_to(image_format); let img = &state.images[&image_ref.id]; match img { DynamicImage::ImageLuma8(p) => p.write_to(&mut output, image_format), DynamicImage::ImageLumaA8(p) => p.write_to(&mut output, image_format), DynamicImage::ImageRgb8(p) => p.write_to(&mut output, image_format), DynamicImage::ImageRgba8(p) => p.write_to(&mut output, image_format), DynamicImage::ImageLuma16(p) => p.write_to(&mut output, image_format), DynamicImage::ImageLumaA16(p) => p.write_to(&mut output, image_format), DynamicImage::ImageRgb16(p) => p.write_to(&mut output, image_format), DynamicImage::ImageRgba16(p) => p.write_to(&mut output, image_format), DynamicImage::ImageRgb32F(p) => p.write_to(&mut output, image_format), DynamicImage::ImageRgba32F(p) => p.write_to(&mut output, image_format), _ => Err(image::ImageError::Unsupported( UnsupportedError::from_format_and_kind( ImageFormatHint::Unknown, UnsupportedErrorKind::GenericFeature( "Unsupported input format".to_string(), ), ), )), } .map_err(map_err)?; Ok(output.into_inner()) }) } fn dispose_image(image_ref: ImageRef) -> Result<u32, String> { with_mut(|state| { state .images .remove(&image_ref.id) .map(|_| image_ref.id) .ok_or_else(|| "Image not found".to_string()) }) } fn read_buffer(buffer: Vec<u8>) -> Result<ImageRef, String> { image::load_from_memory(&buffer) .map(|image| with_mut(|state| state.save_image(image))) .map_err(map_err) } fn read_file(path: String) -> Result<ImageRef, String> { image::open(path) .map(|image| with_mut(|state| state.save_image(image))) .map_err(map_err) } fn save_file(image_ref: ImageRef, path: String) -> Result<u32, String> { with(|state| { let img = &state.images[&image_ref.id]; let len = img.as_bytes().len() as u32; // TODO: save with format img.save(path).map(|_| len).map_err(map_err) }) } } impl image_ops::operations::Operations for ImageOpsImpl { fn blur(image_ref: ImageRef, sigma: f32) -> ImageRef { operation(image_ref, |img| img.blur(sigma)) } fn brighten(image_ref: ImageRef, value: i32) -> ImageRef { operation(image_ref, |img| img.brighten(value)) } fn huerotate(image_ref: ImageRef, value: i32) -> ImageRef { operation(image_ref, |img| img.huerotate(value)) } fn adjust_contrast(image_ref: ImageRef, c: f32) -> ImageRef { operation(image_ref, |img| img.adjust_contrast(c)) } fn flip_horizontal(image_ref: ImageRef) -> ImageRef { operation(image_ref, |img| img.fliph()) } fn flip_vertical(image_ref: ImageRef) -> ImageRef { operation(image_ref, |img| img.flipv()) } fn grayscale(image_ref: ImageRef) -> ImageRef { operation(image_ref, |img| img.grayscale()) } fn invert(image_ref: ImageRef) -> ImageRef { operation(image_ref, |img| { let mut nimg = img.clone(); nimg.invert(); nimg }) } fn rotate180(image_ref: ImageRef) -> ImageRef { operation(image_ref, |img| img.rotate180()) } fn rotate270(image_ref: ImageRef) -> ImageRef { operation(image_ref, |img| img.rotate270()) } fn rotate90(image_ref: ImageRef) -> ImageRef { operation(image_ref, |img| img.rotate90()) } fn unsharpen(image_ref: ImageRef, sigma: f32, threshold: i32) -> ImageRef { operation(image_ref, |img| img.unsharpen(sigma, threshold)) } fn resize(image_ref: ImageRef, size: ImageSize, filter: FilterType) -> ImageRef { operation(image_ref, |img| { img.resize(size.width, size.height, map_filter_type(filter)) }) } fn resize_exact(image_ref: ImageRef, size: ImageSize, filter: FilterType) -> ImageRef { operation(image_ref, |img| { img.resize_exact(size.width, size.height, map_filter_type(filter)) }) } fn resize_to_fill(image_ref: ImageRef, size: ImageSize, filter: FilterType) -> ImageRef { operation(image_ref, |img| { img.resize_to_fill(size.width, size.height, map_filter_type(filter)) }) } fn crop(image_ref: ImageRef, image_crop: ImageCrop) -> ImageRef { operation(image_ref, |img| { img.crop_imm( image_crop.x, image_crop.y, image_crop.width, image_crop.height, ) }) } fn filter3x3(image_ref: ImageRef, kernel: Vec<f32>) -> ImageRef { operation(image_ref, |img| img.filter3x3(&kernel)) } fn thumbnail(image_ref: ImageRef, size: ImageSize) -> ImageRef { operation(image_ref, |img| img.thumbnail(size.width, size.height)) } fn thumbnail_exact(image_ref: ImageRef, size: ImageSize) -> ImageRef { operation(image_ref, |img| { img.thumbnail_exact(size.width, size.height) }) } fn overlay(image_ref: ImageRef, other: ImageRef, x: u32, y: u32) -> ImageRef { with_mut(|state| { // image::imageops::dither(image, color_map) // image::imageops::tile(bottom, top) // image::imageops::vertical_gradient(img, start, stop) // image::imageops::horizontal_gradient(img, start, stop) let mut new_img = state.images[&image_ref.id].clone(); let other_img = &state.images[&other.id]; image::imageops::overlay(&mut new_img, other_img, x.into(), y.into()); state.save_image(new_img) }) } fn replace(image_ref: ImageRef, other: ImageRef, x: u32, y: u32) -> ImageRef { with_mut(|state| { let mut new_img = state.images[&image_ref.id].clone(); let other_img = &state.images[&other.id]; image::imageops::replace(&mut new_img, other_img, x.into(), y.into()); state.save_image(new_img) }) } } fn map_err(e: image::ImageError) -> String { e.to_string() } fn map_image_format(f: image::ImageFormat) -> ImageFormat { match f { image::ImageFormat::Png => ImageFormat::Png, image::ImageFormat::Jpeg => ImageFormat::Jpeg, image::ImageFormat::Gif => ImageFormat::Gif, image::ImageFormat::WebP => ImageFormat::WebP, image::ImageFormat::Pnm => ImageFormat::Pnm, image::ImageFormat::Tiff => ImageFormat::Tiff, image::ImageFormat::Tga => ImageFormat::Tga, image::ImageFormat::Dds => ImageFormat::Dds, image::ImageFormat::Bmp => ImageFormat::Bmp, image::ImageFormat::Ico => ImageFormat::Ico, image::ImageFormat::Hdr => ImageFormat::Hdr, image::ImageFormat::Farbfeld => ImageFormat::Farbfeld, _ => ImageFormat::Unknown, } } fn map_image_format_to(f: ImageFormat) -> image::ImageFormat { match f { ImageFormat::Png => image::ImageFormat::Png, ImageFormat::Jpeg => image::ImageFormat::Jpeg, ImageFormat::Gif => image::ImageFormat::Gif, ImageFormat::WebP => image::ImageFormat::WebP, ImageFormat::Pnm => image::ImageFormat::Pnm, ImageFormat::Tiff => image::ImageFormat::Tiff, ImageFormat::Tga => image::ImageFormat::Tga, ImageFormat::Dds => image::ImageFormat::Dds, ImageFormat::Bmp => image::ImageFormat::Bmp, ImageFormat::Ico => image::ImageFormat::Ico, ImageFormat::Hdr => image::ImageFormat::Hdr, ImageFormat::Farbfeld => image::ImageFormat::Farbfeld, ImageFormat::OpenExr => image::ImageFormat::OpenExr, ImageFormat::Qoi => image::ImageFormat::Qoi, ImageFormat::Avif => image::ImageFormat::Avif, ImageFormat::Unknown => image::ImageFormat::Png, } } fn map_color_type(f: image::ColorType) -> ColorType { match f { image::ColorType::L8 => ColorType::L8, image::ColorType::La8 => ColorType::La8, image::ColorType::Rgb8 => ColorType::Rgb8, image::ColorType::Rgba8 => ColorType::Rgba8, image::ColorType::L16 => ColorType::L16, image::ColorType::La16 => ColorType::La16, image::ColorType::Rgb16 => ColorType::Rgb16, image::ColorType::Rgba16 => ColorType::Rgba16, _ => ColorType::Unknown, } } fn map_filter_type(f: FilterType) -> image::imageops::FilterType { match f { FilterType::Nearest => image::imageops::FilterType::Nearest, FilterType::CatmullRom => image::imageops::FilterType::CatmullRom, FilterType::Gaussian => image::imageops::FilterType::Gaussian, FilterType::Lanczos3 => image::imageops::FilterType::Lanczos3, FilterType::Triangle => image::imageops::FilterType::Triangle, } }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_packages/wasm_parser/wasm_parser_wasm/src/lib.rs
packages/wasm_packages/wasm_parser/wasm_parser_wasm/src/lib.rs
use std::fmt::Display; // Use a procedural macro to generate bindings for the world we specified in `wasm-parser.wit` wit_bindgen::generate!("wasm-parser"); // Define a custom type and implement the generated trait for it which represents // implementing all the necessary exported interfaces for this component. struct WitImplementation; export_wasm_parser!(WitImplementation); fn map_error<E: Display>(e: E) -> String { e.to_string() } impl WasmInput { fn to_bytes(self) -> Result<Vec<u8>, String> { match self { WasmInput::Binary(bytes) => Ok(bytes), WasmInput::FilePath(path) => std::fs::read(path).map_err(map_error), } } } impl WasmParser for WitImplementation { fn wasm2wasm_component( input: WasmInput, // TODO: add support for wit embed _wit: Option<String>, adapters: Vec<ComponentAdapter>, ) -> Result<Vec<u8>, String> { let validate = false; let bytes = input.to_bytes()?; let mut encoder = wit_component::ComponentEncoder::default() .validate(validate) .module(&bytes) .map_err(map_error)?; for ComponentAdapter { name, wasm } in adapters.into_iter() { let bytes = wasm.to_bytes()?; encoder = encoder.adapter(&name, &bytes).map_err(map_error)?; } encoder.encode().map_err(map_error) } fn wasm_component2wit(input: WasmInput) -> Result<String, String> { let bytes = input.to_bytes()?; let decoded = decode_wasm(&bytes).map_err(map_error)?; wit_component::WitPrinter::default() .print(decoded.resolve(), decoded.package()) .map_err(map_error) } fn wat2wasm(input: WatInput) -> Result<Vec<u8>, String> { match input { WatInput::Text(wat) => wat::parse_str(&wat).map_err(map_error), WatInput::Binary(wat) => { let wasm = wat::parse_bytes(&wat).map_err(map_error)?; Ok(wasm.into_owned()) } WatInput::FilePath(path) => wat::parse_file(&path).map_err(map_error), } } fn wasm2wat(input: WasmInput) -> Result<String, String> { match input { WasmInput::Binary(wat) => wasmprinter::print_bytes(&wat).map_err(map_error), WasmInput::FilePath(path) => wasmprinter::print_file(&path).map_err(map_error), } } fn parse_wat(input: WatInput) -> Result<WasmType, String> { WitImplementation::wat2wasm(input) .and_then(|bytes| WitImplementation::parse_wasm(WasmInput::Binary(bytes))) } fn parse_wasm(input: WasmInput) -> Result<WasmType, String> { let bytes = input.to_bytes()?; let types = wasmparser::Validator::new_with_features(features_all_true()) .validate_all(&bytes) .map_err(map_error)?; to_wasm_type(&types, bytes) } fn default_wasm_features() -> WasmFeatures { map_parser_features(wasmparser::WasmFeatures::default()) } fn validate_wasm(input: WasmInput, features: Option<WasmFeatures>) -> Result<WasmType, String> { let bytes = input.to_bytes()?; let types = if let Some(features) = features { let mapped_features = map_features(features); wasmparser::Validator::new_with_features(mapped_features) .validate_all(&bytes) .map_err(map_error)? } else { wasmparser::validate(&bytes).map_err(map_error)? }; to_wasm_type(&types, bytes) } // wasm_compose::composer::ComponentComposer::new( // &"component", // &wasm_compose::config::Config::default(), // ); // let bytes = input.to_bytes()?; // let decoded = wit_component::decode(&bytes).map_err(map_error)?; // wit_component::encode(decoded.resolve(), decoded.package()).map_err(map_error) } fn to_wasm_type(types: &wasmparser::types::Types, bytes: Vec<u8>) -> Result<WasmType, String> { use wasmparser::Payload; let parser = TypeParser { types: &types }; if types.type_at(0, true).is_none() { // Component Model let mut modules = Vec::new(); for i in 0..types.module_count() { let mut module_type = ModuleType { imports: Vec::new(), exports: Vec::new(), }; let module = types.module_at(i as u32).unwrap(); module .imports .iter() .for_each(|((module_name, name), entity)| { let mapped = parser.map_type(entity); let import = ModuleImport { module: module_name.to_string(), name: name.to_string(), type_: mapped, }; module_type.imports.push(import); }); module.exports.iter().for_each(|(name, entity)| { let mapped = parser.map_type(entity); let export = ModuleExport { name: name.to_string(), type_: mapped, }; module_type.exports.push(export); }); modules.push(module_type); } return Ok(WasmType::ComponentType(ComponentType { modules })); } let mut module = ModuleType { imports: Vec::new(), exports: Vec::new(), }; for payload in wasmparser::Parser::new(0).parse_all(&bytes) { match payload.map_err(map_error)? { Payload::ExportSection(s) => { for export in s { let export = export.map_err(map_error)?; let mapped = parser.map_export(export); module.exports.push(mapped); } } Payload::ImportSection(s) => { for import in s { let import = import.map_err(map_error)?; let mapped = parser.map_import(import); module.imports.push(mapped); } } // Payload::TypeSection(s) => , // Payload::FunctionSection(s) => , // Payload::TableSection(s) => , // Payload::MemorySection(s) => , // Payload::TagSection(s) => , // Payload::GlobalSection(s) => , _other => {} } } Ok(WasmType::ModuleType(module)) } fn decode_wasm(bytes: &[u8]) -> Result<wit_component::DecodedWasm, String> { if wasmparser::Parser::is_component(bytes) { wit_component::decode(bytes).map_err(map_error) } else { let (_wasm, bindgen) = wit_component::metadata::decode(bytes).map_err(map_error)?; Ok(wit_component::DecodedWasm::Component( bindgen.resolve, bindgen.world, )) } } fn map_features(features: WasmFeatures) -> wasmparser::WasmFeatures { wasmparser::WasmFeatures { bulk_memory: features.bulk_memory, multi_value: features.multi_value, simd: features.simd, threads: features.threads, reference_types: features.reference_types, tail_call: features.tail_call, multi_memory: features.multi_memory, memory64: features.memory64, exceptions: features.exceptions, sign_extension: features.sign_extension, function_references: features.function_references, gc: features.gc, component_model: features.component_model, extended_const: features.extended_const, floats: features.floats, memory_control: features.memory_control, mutable_global: features.mutable_global, relaxed_simd: features.relaxed_simd, saturating_float_to_int: features.saturating_float_to_int, } } fn map_parser_features(features: wasmparser::WasmFeatures) -> WasmFeatures { WasmFeatures { bulk_memory: features.bulk_memory, multi_value: features.multi_value, simd: features.simd, threads: features.threads, reference_types: features.reference_types, tail_call: features.tail_call, multi_memory: features.multi_memory, memory64: features.memory64, exceptions: features.exceptions, sign_extension: features.sign_extension, function_references: features.function_references, gc: features.gc, component_model: features.component_model, extended_const: features.extended_const, floats: features.floats, memory_control: features.memory_control, mutable_global: features.mutable_global, relaxed_simd: features.relaxed_simd, saturating_float_to_int: features.saturating_float_to_int, } } fn features_all_true() -> wasmparser::WasmFeatures { wasmparser::WasmFeatures { mutable_global: true, saturating_float_to_int: true, sign_extension: true, reference_types: true, multi_value: true, bulk_memory: true, simd: true, relaxed_simd: true, threads: true, tail_call: true, floats: true, multi_memory: true, exceptions: true, memory64: true, extended_const: true, component_model: true, function_references: true, memory_control: true, gc: true, } } struct TypeParser<'a> { types: &'a wasmparser::types::Types, } impl<'a> TypeParser<'a> { fn map_export(&self, export: wasmparser::Export) -> ModuleExport { let entity = self.types.entity_type_from_export(&export).unwrap(); let mapped = self.map_type(&entity); ModuleExport { name: export.name.to_string(), type_: mapped, } } fn map_import(&self, import: wasmparser::Import) -> ModuleImport { let entity = self.types.entity_type_from_import(&import).unwrap(); let mapped = self.map_type(&entity); ModuleImport { module: import.module.to_string(), name: import.name.to_string(), type_: mapped, } } fn map_type(&self, ty: &wasmparser::types::EntityType) -> ExternType { use wasmparser::types::EntityType; match ty { EntityType::Func(id) => { let ty = self .types .type_from_id(*id) .unwrap() .as_func_type() .unwrap(); ExternType::FunctionType(FunctionType { parameters: ty .params() .iter() .cloned() .map(|p| self.map_val_type(p)) .collect(), results: ty .results() .iter() .cloned() .map(|p| self.map_val_type(p)) .collect(), }) } EntityType::Table(ty) => ExternType::TableType(TableType { element: self.map_ref_type(ty.element_type), maximum: ty.maximum, minimum: ty.initial, }), EntityType::Memory(ty) => ExternType::MemoryType(MemoryType { memory64: ty.memory64, maximum: ty.maximum, minimum: ty.initial, shared: ty.shared, }), EntityType::Global(ty) => ExternType::GlobalType(GlobalType { mutable: ty.mutable, value: self.map_val_type(ty.content_type), }), EntityType::Tag(id) => { let kind = wasmparser::TagKind::Exception; let kind = match kind { wasmparser::TagKind::Exception => TagKind::Exception, }; ExternType::TagType(TagType { kind, function_type: match self.map_type(&EntityType::Func(*id)) { ExternType::FunctionType(ty) => ty, _ => unreachable!(), }, }) } } } fn map_val_type(&self, ty: wasmparser::ValType) -> ValueType { match ty { wasmparser::ValType::I32 => ValueType::I32, wasmparser::ValType::I64 => ValueType::I64, wasmparser::ValType::F32 => ValueType::F32, wasmparser::ValType::F64 => ValueType::F64, wasmparser::ValType::V128 => ValueType::V128, wasmparser::ValType::Ref(ty) => ValueType::Ref(self.map_ref_type(ty)), } } fn map_ref_type(&self, ty: wasmparser::RefType) -> RefType { RefType { heap_type: self.map_heap_type(ty.heap_type()), nullable: ty.is_nullable(), } } fn map_heap_type(&self, heap_type: wasmparser::HeapType) -> HeapType { match heap_type { wasmparser::HeapType::Indexed(index) => HeapType::Indexed(index), wasmparser::HeapType::Func => HeapType::Func, wasmparser::HeapType::Extern => HeapType::Extern, wasmparser::HeapType::Any => HeapType::Any, wasmparser::HeapType::None => HeapType::None, wasmparser::HeapType::NoExtern => HeapType::NoExtern, wasmparser::HeapType::NoFunc => HeapType::NoFunc, wasmparser::HeapType::Eq => HeapType::Eq, wasmparser::HeapType::Struct => HeapType::Struct, wasmparser::HeapType::Array => HeapType::Array, wasmparser::HeapType::I31 => HeapType::I31, } } }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_packages/rust_crypto/rust_crypto_wasm/src/lib.rs
packages/wasm_packages/rust_crypto/rust_crypto_wasm/src/lib.rs
// Use a procedural macro to generate bindings for the world we specified in // `with/dart-wit-generator.wit` wit_bindgen::generate!("rust-crypto"); use std::{fmt::Display, fs, io::Read}; use aes_gcm_siv::aead::Aead; use argon2::password_hash::{rand_core::OsRng, PasswordHasher, PasswordVerifier}; use hmac::Mac; use sha2::Digest; use crate::rust_crypto::fs_hash::HashKind; use exports::wasm_run_dart::rust_crypto; // Define a custom type and implement the generated `Host` trait for it which // represents implementing all the necessary exported interfaces for this // component. struct RustCryptoImpl; fn map_err<T: Display>(err: T) -> String { err.to_string() } impl rust_crypto::hmac::Hmac for RustCryptoImpl { fn hmac_sha256(key: Vec<u8>, input: Vec<u8>) -> Result<Vec<u8>, String> { let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(&key).map_err(map_err)?; mac.update(&input); Ok(mac.finalize().into_bytes().to_vec()) } fn hmac_sha512(key: Vec<u8>, input: Vec<u8>) -> Result<Vec<u8>, String> { let mut mac = hmac::Hmac::<sha2::Sha512>::new_from_slice(&key).map_err(map_err)?; mac.update(&input); Ok(mac.finalize().into_bytes().to_vec()) } fn hmac_sha384(key: Vec<u8>, input: Vec<u8>) -> Result<Vec<u8>, String> { let mut mac = hmac::Hmac::<sha2::Sha384>::new_from_slice(&key).map_err(map_err)?; mac.update(&input); Ok(mac.finalize().into_bytes().to_vec()) } fn hmac_sha224(key: Vec<u8>, input: Vec<u8>) -> Result<Vec<u8>, String> { let mut mac = hmac::Hmac::<sha2::Sha224>::new_from_slice(&key).map_err(map_err)?; mac.update(&input); Ok(mac.finalize().into_bytes().to_vec()) } fn hmac_blake3(key: Vec<u8>, input: Vec<u8>) -> Result<Vec<u8>, String> { use crate::exports::wasm_run_dart::rust_crypto::blake3::Blake3; RustCryptoImpl::mac_keyed_hash(key, input) // let mut mac = hmac::SimpleHmac::<blake3::Hasher>::new_from_slice(&key).unwrap(); // mac.update(&input); // mac.finalize().into_bytes().to_vec() } } impl rust_crypto::fs_hash::FsHash for RustCryptoImpl { fn hash_file(kind: HashKind, path: String) -> Result<Vec<u8>, String> { let mut file = fs::File::open(path).map_err(|e| e.to_string())?; get_hasher(kind, |h| { std::io::copy(&mut file, h).map(|_| ()).map_err(map_err) }) } fn hmac_file(kind: HashKind, key: Vec<u8>, path: String) -> Result<Vec<u8>, String> { let mut file = fs::File::open(path).map_err(|e| e.to_string())?; get_hmac(kind, key, |h| { std::io::copy(&mut file, h).map(|_| ()).map_err(map_err) }) } fn crc32_file(path: String) -> Result<u32, String> { let mut file = fs::File::open(path).map_err(|e| e.to_string())?; let mut hasher = crc32fast::Hasher::new(); let buff = &mut [0; 1024 * 4 * 2]; loop { let read = file.read(buff).map_err(map_err)?; if read == 0 { break; } hasher.update(&buff[..read]); } Ok(hasher.finalize()) } } impl rust_crypto::hashes::Hashes for RustCryptoImpl { fn sha1(input: Vec<u8>) -> Vec<u8> { let mut hasher = sha1::Sha1::new(); hasher.update(input); hasher.finalize().to_vec() } fn md5(input: Vec<u8>) -> Vec<u8> { let mut hasher = md5::Md5::new(); hasher.update(input); hasher.finalize().to_vec() } fn crc32(input: Vec<u8>) -> u32 { let mut hasher = crc32fast::Hasher::new(); hasher.update(input.as_slice()); hasher.finalize() } } impl rust_crypto::sha2::Sha2 for RustCryptoImpl { fn sha256(input: Vec<u8>) -> Vec<u8> { let mut hasher = sha2::Sha256::new(); hasher.update(input); hasher.finalize().to_vec() } fn sha512(input: Vec<u8>) -> Vec<u8> { let mut hasher = sha2::Sha512::new(); hasher.update(input); hasher.finalize().to_vec() } fn sha384(input: Vec<u8>) -> Vec<u8> { let mut hasher = sha2::Sha384::new(); hasher.update(input); hasher.finalize().to_vec() } fn sha224(input: Vec<u8>) -> Vec<u8> { let mut hasher = sha2::Sha224::new(); hasher.update(input); hasher.finalize().to_vec() } } impl rust_crypto::blake3::Blake3 for RustCryptoImpl { fn hash(bytes: Vec<u8>) -> Vec<u8> { blake3::hash(&bytes).as_bytes().to_vec() } fn mac_keyed_hash(key: Vec<u8>, bytes: Vec<u8>) -> Result<Vec<u8>, String> { Ok(blake3::keyed_hash( &key.try_into().map_err(|e: Vec<u8>| { format!("key byte length should be 32, got {} bytes", e.len()) })?, &bytes, ) .as_bytes() .to_vec()) } fn derive_key(context: String, key_material: Vec<u8>) -> Vec<u8> { blake3::derive_key(&context, &key_material).to_vec() } } fn to_argon2<'a>( config: &'a rust_crypto::argon2::Argon2Config, ) -> Result<argon2::Argon2<'a>, String> { let algorithm = match config.algorithm { rust_crypto::argon2::Argon2Algorithm::Argon2d => argon2::Algorithm::Argon2d, rust_crypto::argon2::Argon2Algorithm::Argon2i => argon2::Algorithm::Argon2i, rust_crypto::argon2::Argon2Algorithm::Argon2id => argon2::Algorithm::Argon2id, }; let version = match config.version { rust_crypto::argon2::Argon2Version::V0x10 => argon2::Version::V0x10, rust_crypto::argon2::Argon2Version::V0x13 => argon2::Version::V0x13, }; let params = argon2::Params::new( config.memory_cost, config.time_cost, config.parallelism_cost, if let Some(i) = config.output_length { Some(i.try_into().map_err(map_err)?) } else { None }, ) .map_err(map_err)?; if let Some(secret) = &config.secret { argon2::Argon2::new_with_secret(secret, algorithm, version, params).map_err(map_err) } else { Ok(argon2::Argon2::new(algorithm, version, params)) } } impl rust_crypto::argon2::Argon2 for RustCryptoImpl { fn default_config() -> rust_crypto::argon2::Argon2Config { let algorithm = match argon2::Algorithm::default() { argon2::Algorithm::Argon2d => rust_crypto::argon2::Argon2Algorithm::Argon2d, argon2::Algorithm::Argon2i => rust_crypto::argon2::Argon2Algorithm::Argon2i, argon2::Algorithm::Argon2id => rust_crypto::argon2::Argon2Algorithm::Argon2id, }; let version = match argon2::Version::default() { argon2::Version::V0x10 => rust_crypto::argon2::Argon2Version::V0x10, argon2::Version::V0x13 => rust_crypto::argon2::Argon2Version::V0x13, }; let params = argon2::Params::default(); rust_crypto::argon2::Argon2Config { algorithm, memory_cost: params.m_cost(), time_cost: params.t_cost(), parallelism_cost: params.p_cost(), output_length: Some(argon2::Params::DEFAULT_OUTPUT_LEN as u32), version, secret: None, } } fn generate_salt() -> String { let salt = argon2::password_hash::SaltString::generate(&mut OsRng); salt.to_string() } fn hash_password( config: rust_crypto::argon2::Argon2Config, bytes: Vec<u8>, salt: String, ) -> Result<String, String> { let salt = argon2::password_hash::Salt::from_b64(&salt).map_err(map_err)?; let hash = to_argon2(&config)? .hash_password(&bytes, salt) .map_err(map_err)?; Ok(hash.to_string()) } fn verify_password( password: Vec<u8>, hash: String, secret: Option<Vec<u8>>, ) -> Result<bool, String> { let hash = argon2::password_hash::PasswordHash::new(&hash).map_err(map_err)?; if let Some(secret) = secret { Ok(argon2::Argon2::new_with_secret( secret.as_slice(), argon2::Algorithm::default(), argon2::Version::default(), argon2::Params::default(), ) .map_err(map_err)? .verify_password(&password, &hash) .is_ok()) } else { Ok(argon2::Argon2::default() .verify_password(&password, &hash) .is_ok()) } } fn raw_hash( config: rust_crypto::argon2::Argon2Config, bytes: Vec<u8>, salt: Vec<u8>, ) -> Result<Vec<u8>, String> { let byte_length = config .output_length .unwrap_or(argon2::Params::DEFAULT_OUTPUT_LEN as u32) as usize; let mut out = Vec::with_capacity(byte_length); unsafe { out.set_len(byte_length) } to_argon2(&config)? .hash_password_into(&bytes, &salt, &mut out) .map_err(map_err)?; Ok(out) } } impl rust_crypto::aes_gcm_siv::AesGcmSiv for RustCryptoImpl { fn generate_key(kind: rust_crypto::aes_gcm_siv::AesKind) -> Vec<u8> { use aes_gcm_siv::KeyInit; match kind { rust_crypto::aes_gcm_siv::AesKind::Bits128 => { aes_gcm_siv::Aes128GcmSiv::generate_key(&mut OsRng).to_vec() } rust_crypto::aes_gcm_siv::AesKind::Bits256 => { aes_gcm_siv::Aes256GcmSiv::generate_key(&mut OsRng).to_vec() } } } fn encrypt( kind: rust_crypto::aes_gcm_siv::AesKind, key: Vec<u8>, nonce: Vec<u8>, plain_text: Vec<u8>, associated_data: Option<Vec<u8>>, ) -> Result<Vec<u8>, String> { use aes_gcm_siv::KeyInit; if nonce.len() != 12 { return Err(format!("nonce must be 12 bytes, got {} bytes", nonce.len())); } let nonce = aes_gcm_siv::Nonce::from_slice(&nonce); // 96-bits; unique per message let payload = aes_gcm_siv::aead::Payload { msg: plain_text.as_ref(), aad: associated_data.as_deref().unwrap_or(b""), }; match kind { rust_crypto::aes_gcm_siv::AesKind::Bits128 => { let cipher = aes_gcm_siv::Aes128GcmSiv::new_from_slice(&key).map_err(map_err)?; cipher.encrypt(nonce, payload).map_err(map_err) } rust_crypto::aes_gcm_siv::AesKind::Bits256 => { let cipher = aes_gcm_siv::Aes256GcmSiv::new_from_slice(&key).map_err(map_err)?; cipher.encrypt(nonce, payload).map_err(map_err) } } } fn decrypt( kind: rust_crypto::aes_gcm_siv::AesKind, key: Vec<u8>, nonce: Vec<u8>, cipher_text: Vec<u8>, associated_data: Option<Vec<u8>>, ) -> Result<Vec<u8>, String> { use aes_gcm_siv::KeyInit; if nonce.len() != 12 { return Err(format!("nonce must be 12 bytes, got {} bytes", nonce.len())); } let nonce = aes_gcm_siv::Nonce::from_slice(&nonce); // 96-bits; unique per message let payload = aes_gcm_siv::aead::Payload { msg: cipher_text.as_ref(), aad: associated_data.as_deref().unwrap_or(b""), }; match kind { rust_crypto::aes_gcm_siv::AesKind::Bits128 => { let cipher = aes_gcm_siv::Aes128GcmSiv::new_from_slice(&key).map_err(map_err)?; cipher.decrypt(nonce, payload).map_err(map_err) } rust_crypto::aes_gcm_siv::AesKind::Bits256 => { let cipher = aes_gcm_siv::Aes256GcmSiv::new_from_slice(&key).map_err(map_err)?; cipher.decrypt(nonce, payload).map_err(map_err) } } } } export_rust_crypto!(RustCryptoImpl); fn get_hmac( kind: HashKind, key: Vec<u8>, f: impl FnOnce(&mut dyn std::io::Write) -> Result<(), String>, ) -> Result<Vec<u8>, String> { match kind { HashKind::Md5 => { let mut h = hmac::Hmac::<md5::Md5>::new_from_slice(&key).map_err(map_err)?; f(&mut h)?; Ok(h.finalize().into_bytes().to_vec()) } HashKind::Sha1 => { let mut h = hmac::Hmac::<sha1::Sha1>::new_from_slice(&key).map_err(map_err)?; f(&mut h)?; Ok(h.finalize().into_bytes().to_vec()) } HashKind::Sha256 => { let mut h = hmac::Hmac::<sha2::Sha256>::new_from_slice(&key).map_err(map_err)?; f(&mut h)?; Ok(h.finalize().into_bytes().to_vec()) } HashKind::Sha512 => { let mut h = hmac::Hmac::<sha2::Sha512>::new_from_slice(&key).map_err(map_err)?; f(&mut h)?; Ok(h.finalize().into_bytes().to_vec()) } HashKind::Sha384 => { let mut h = hmac::Hmac::<sha2::Sha384>::new_from_slice(&key).map_err(map_err)?; f(&mut h)?; Ok(h.finalize().into_bytes().to_vec()) } HashKind::Sha224 => { let mut h = hmac::Hmac::<sha2::Sha224>::new_from_slice(&key).map_err(map_err)?; f(&mut h)?; Ok(h.finalize().into_bytes().to_vec()) } HashKind::Blake3 => { let mut h = blake3::Hasher::new_keyed( &(key.try_into().map_err(|e: Vec<u8>| { format!("Key length should be 32 bytes, got {} bytes", e.len()) })?), ); f(&mut h)?; Ok(h.finalize().as_bytes().to_vec()) } } } fn get_hasher( kind: HashKind, f: impl FnOnce(&mut dyn std::io::Write) -> Result<(), String>, ) -> Result<Vec<u8>, String> { match kind { HashKind::Md5 => { let mut h = md5::Md5::new(); f(&mut h)?; Ok(h.finalize().to_vec()) } HashKind::Sha1 => { let mut h = sha1::Sha1::new(); f(&mut h)?; Ok(h.finalize().to_vec()) } HashKind::Sha256 => { let mut h = sha2::Sha256::new(); f(&mut h)?; Ok(h.finalize().to_vec()) } HashKind::Sha512 => { let mut h = sha2::Sha512::new(); f(&mut h)?; Ok(h.finalize().to_vec()) } HashKind::Sha384 => { let mut h = sha2::Sha384::new(); f(&mut h)?; Ok(h.finalize().to_vec()) } HashKind::Sha224 => { let mut h = sha2::Sha224::new(); f(&mut h)?; Ok(h.finalize().to_vec()) } HashKind::Blake3 => { let mut h = blake3::Hasher::new(); f(&mut h)?; Ok(h.finalize().as_bytes().to_vec()) } } }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_packages/compression_rs/compression_rs_wasm/src/lib.rs
packages/wasm_packages/compression_rs/compression_rs_wasm/src/lib.rs
mod archive; pub use crate::archive::*; use std::fmt::Display; use std::fs::File; use std::io::prelude::*; // Use a procedural macro to generate bindings for the world we specified in `compression-rs.wit` wit_bindgen::generate!("compression-rs"); use compression_rs_namespace::compression_rs::flate::Input; use exports::compression_rs_namespace::compression_rs; // Define a custom type and implement the generated trait for it which // represents implementing all the necessary exported interfaces for this // component. struct WitImplementation; export_compression_rs!(WitImplementation); impl Input { fn with_read<T>( &mut self, f: impl FnOnce(&mut dyn Read) -> Result<T, String>, ) -> Result<T, String> { match self { Input::Bytes(bytes) => f(&mut bytes.as_slice()), #[cfg(feature = "wasi")] Input::File(file) => f(&mut File::open(file).map_err(map_err)?), #[cfg(not(feature = "wasi"))] Input::File(file) => { Err(format!("The wasm module should be compiled with the wasi feature. Tried to open file {file}.")) } } } } pub fn map_err<E: Display>(e: E) -> String { e.to_string() } #[cfg(not(feature = "brotli"))] #[allow(unused_variables, unused_mut)] impl compression_rs::brotli::Brotli for WitImplementation { fn brotli_compress(mut i: Input) -> Result<Vec<u8>, String> { Err("The wasm module should be compiled with the brotli feature".to_string()); } fn brotli_decompress(mut i: Input) -> Result<Vec<u8>, String> { Err("The wasm module should be compiled with the brotli feature".to_string()); } fn brotli_compress_file(mut i: Input, path: String) -> Result<u64, String> { Err("The wasm module should be compiled with the brotli feature".to_string()); } fn brotli_decompress_file(mut i: Input, path: String) -> Result<u64, String> { Err("The wasm module should be compiled with the brotli feature".to_string()); } } #[cfg(feature = "brotli")] impl compression_rs::brotli::Brotli for WitImplementation { fn brotli_compress(mut i: Input) -> Result<Vec<u8>, String> { i.with_read(|i| { let mut w = brotli::CompressorWriter::with_params( Vec::new(), 4096, /* buffer size */ &brotli::enc::BrotliEncoderParams::default(), ); std::io::copy(i, &mut w).map_err(map_err)?; Ok(w.into_inner()) }) } fn brotli_decompress(mut i: Input) -> Result<Vec<u8>, String> { i.with_read(|i| { let mut d = brotli::Decompressor::new(i, 4096 /* buffer size */); let mut output = Vec::new(); d.read_to_end(&mut output).map_err(map_err)?; Ok(output) }) } fn brotli_compress_file(mut i: Input, path: String) -> Result<u64, String> { i.with_read(|i| { let file = File::options().write(true).open(path).map_err(map_err)?; let mut w = brotli::CompressorWriter::with_params( file, 4096, /* buffer size */ &brotli::enc::BrotliEncoderParams::default(), ); let size = std::io::copy(i, &mut w).map_err(map_err)?; Ok(size) }) } fn brotli_decompress_file(mut i: Input, path: String) -> Result<u64, String> { i.with_read(|i| { let mut d = brotli::Decompressor::new(i, 4096 /* buffer size */); let mut file = File::options().write(true).open(path).map_err(map_err)?; let size = std::io::copy(&mut d, &mut file).map_err(map_err)?; Ok(size) }) } } #[cfg(not(feature = "zstd"))] #[allow(unused_variables, unused_mut)] impl compression_rs::zstd::Zstd for WitImplementation { fn zstd_compress(mut i: Input) -> Result<Vec<u8>, String> { Err("The wasm module should be compiled with the zstd feature".to_string()); } fn zstd_decompress(mut i: Input) -> Result<Vec<u8>, String> { Err("The wasm module should be compiled with the zstd feature".to_string()); } fn zstd_compress_file(mut i: Input, path: String) -> Result<u64, String> { Err("The wasm module should be compiled with the zstd feature".to_string()); } fn zstd_decompress_file(mut i: Input, path: String) -> Result<u64, String> { Err("The wasm module should be compiled with the zstd feature".to_string()); } } #[cfg(feature = "zstd")] impl compression_rs::zstd::Zstd for WitImplementation { fn zstd_compress(mut _i: Input) -> Result<Vec<u8>, String> { Err("zstd compression is not implemented".to_string()) } fn zstd_decompress(mut i: Input) -> Result<Vec<u8>, String> { i.with_read(|i| { let mut d = ruzstd::FrameDecoder::new(); d.init(i).map_err(map_err)?; let mut output = Vec::new(); d.read_to_end(&mut output).map_err(map_err)?; Ok(output) }) } fn zstd_compress_file(mut _i: Input, _path: String) -> Result<u64, String> { Err("zstd compression is not implemented".to_string()) } fn zstd_decompress_file(mut i: Input, path: String) -> Result<u64, String> { i.with_read(|i| { let mut d = ruzstd::FrameDecoder::new(); d.init(i).map_err(map_err)?; let mut file = File::options().write(true).open(path).map_err(map_err)?; let size = std::io::copy(&mut d, &mut file).map_err(map_err)?; Ok(size) }) } } #[cfg(not(feature = "lz4"))] #[allow(unused_variables, unused_mut)] impl compression_rs::lz4::Lz4 for WitImplementation { fn lz4_compress(mut i: Input) -> Result<Vec<u8>, String> { Err("The wasm module should be compiled with the lz4 feature".to_string()); } fn lz4_decompress(mut i: Input) -> Result<Vec<u8>, String> { Err("The wasm module should be compiled with the lz4 feature".to_string()); } fn lz4_compress_file(mut i: Input, path: String) -> Result<u64, String> { Err("The wasm module should be compiled with the lz4 feature".to_string()); } fn lz4_decompress_file(mut i: Input, path: String) -> Result<u64, String> { Err("The wasm module should be compiled with the lz4 feature".to_string()); } } #[cfg(feature = "lz4")] impl compression_rs::lz4::Lz4 for WitImplementation { fn lz4_compress(mut i: Input) -> Result<Vec<u8>, String> { i.with_read(|i| { let mut w = lz4_flex::frame::FrameEncoder::new(Vec::new()); std::io::copy(i, &mut w).map_err(map_err)?; Ok(w.finish().map_err(map_err)?) }) } fn lz4_decompress(mut i: Input) -> Result<Vec<u8>, String> { i.with_read(|i| { let mut d = lz4_flex::frame::FrameDecoder::new(i); let mut output = Vec::new(); d.read_to_end(&mut output).map_err(map_err)?; Ok(output) }) } fn lz4_compress_file(mut i: Input, path: String) -> Result<u64, String> { i.with_read(|i| { let file = File::options().write(true).open(path).map_err(map_err)?; let mut w = lz4_flex::frame::FrameEncoder::new(file); let size = std::io::copy(i, &mut w).map_err(map_err)?; w.finish().map_err(map_err)?; Ok(size) }) } fn lz4_decompress_file(mut i: Input, path: String) -> Result<u64, String> { i.with_read(|i| { let mut d = lz4_flex::frame::FrameDecoder::new(i); let mut file = File::options().write(true).open(path).map_err(map_err)?; let size = std::io::copy(&mut d, &mut file).map_err(map_err)?; Ok(size) }) } } #[cfg(not(feature = "gzip"))] #[allow(unused_variables, unused_mut)] impl compression_rs::gzip::Gzip for WitImplementation { fn gzip_compress(mut i: Input) -> Result<Vec<u8>, String> { Err("The wasm module should be compiled with the gzip feature".to_string()); } fn gzip_decompress(mut i: Input) -> Result<Vec<u8>, String> { Err("The wasm module should be compiled with the gzip feature".to_string()); } fn gzip_compress_file(mut i: Input, path: String) -> Result<u64, String> { Err("The wasm module should be compiled with the gzip feature".to_string()); } fn gzip_decompress_file(mut i: Input, path: String) -> Result<u64, String> { Err("The wasm module should be compiled with the gzip feature".to_string()); } } #[cfg(feature = "gzip")] impl compression_rs::gzip::Gzip for WitImplementation { fn gzip_compress(mut i: Input) -> Result<Vec<u8>, String> { i.with_read(|i| { let mut w = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); std::io::copy(i, &mut w).map_err(map_err)?; Ok(w.finish().map_err(map_err)?) }) } fn gzip_decompress(mut i: Input) -> Result<Vec<u8>, String> { i.with_read(|i| { let mut d = flate2::read::GzDecoder::new(i); let mut output = Vec::new(); d.read_to_end(&mut output).map_err(map_err)?; Ok(output) }) } fn gzip_compress_file(mut i: Input, path: String) -> Result<u64, String> { i.with_read(|i| { let file = File::options().write(true).open(path).map_err(map_err)?; let mut w = flate2::write::GzEncoder::new(file, flate2::Compression::default()); let size = std::io::copy(i, &mut w).map_err(map_err)?; w.finish().map_err(map_err)?; Ok(size) }) } fn gzip_decompress_file(mut i: Input, path: String) -> Result<u64, String> { i.with_read(|i| { let mut d = flate2::read::GzDecoder::new(i); let mut file = File::options().write(true).open(path).map_err(map_err)?; let size = std::io::copy(&mut d, &mut file).map_err(map_err)?; Ok(size) }) } } #[cfg(not(feature = "zlib"))] #[allow(unused_variables, unused_mut)] impl compression_rs::zlib::Zlib for WitImplementation { fn zlib_compress(mut i: Input) -> Result<Vec<u8>, String> { Err("The wasm module should be compiled with the zlib feature".to_string()); } fn zlib_decompress(mut i: Input) -> Result<Vec<u8>, String> { Err("The wasm module should be compiled with the zlib feature".to_string()); } fn zlib_compress_file(mut i: Input, path: String) -> Result<u64, String> { Err("The wasm module should be compiled with the zlib feature".to_string()); } fn zlib_decompress_file(mut i: Input, path: String) -> Result<u64, String> { Err("The wasm module should be compiled with the zlib feature".to_string()); } } #[cfg(feature = "zlib")] impl compression_rs::zlib::Zlib for WitImplementation { fn zlib_compress(mut i: Input) -> Result<Vec<u8>, String> { i.with_read(|i| { let mut w = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); std::io::copy(i, &mut w).map_err(map_err)?; Ok(w.finish().map_err(map_err)?) }) } fn zlib_decompress(mut i: Input) -> Result<Vec<u8>, String> { i.with_read(|i| { let mut d = flate2::read::ZlibDecoder::new(i); let mut output = Vec::new(); d.read_to_end(&mut output).map_err(map_err)?; Ok(output) }) } fn zlib_compress_file(mut i: Input, path: String) -> Result<u64, String> { i.with_read(|i| { let file = File::options().write(true).open(path).map_err(map_err)?; let mut w = flate2::write::ZlibEncoder::new(file, flate2::Compression::default()); let size = std::io::copy(i, &mut w).map_err(map_err)?; w.finish().map_err(map_err)?; Ok(size) }) } fn zlib_decompress_file(mut i: Input, path: String) -> Result<u64, String> { i.with_read(|i| { let mut d = flate2::read::ZlibDecoder::new(i); let mut file = File::options().write(true).open(path).map_err(map_err)?; let size = std::io::copy(&mut d, &mut file).map_err(map_err)?; Ok(size) }) } } #[cfg(not(feature = "deflate"))] #[allow(unused_variables, unused_mut)] impl compression_rs::deflate::Deflate for WitImplementation { fn deflate_compress(mut i: Input) -> Result<Vec<u8>, String> { Err("The wasm module should be compiled with the deflate feature".to_string()); } fn deflate_decompress(mut i: Input) -> Result<Vec<u8>, String> { Err("The wasm module should be compiled with the deflate feature".to_string()); } fn deflate_compress_file(mut i: Input, path: String) -> Result<u64, String> { Err("The wasm module should be compiled with the deflate feature".to_string()); } fn deflate_decompress_file(mut i: Input, path: String) -> Result<u64, String> { Err("The wasm module should be compiled with the deflate feature".to_string()); } } #[cfg(feature = "deflate")] impl compression_rs::deflate::Deflate for WitImplementation { fn deflate_compress(mut i: Input) -> Result<Vec<u8>, String> { i.with_read(|i| { let mut w = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default()); std::io::copy(i, &mut w).map_err(map_err)?; Ok(w.finish().map_err(map_err)?) }) } fn deflate_decompress(mut i: Input) -> Result<Vec<u8>, String> { i.with_read(|i| { let mut d = flate2::read::DeflateDecoder::new(i); let mut output = Vec::new(); d.read_to_end(&mut output).map_err(map_err)?; Ok(output) }) } fn deflate_compress_file(mut i: Input, path: String) -> Result<u64, String> { i.with_read(|i| { let file = File::options().write(true).open(path).map_err(map_err)?; let mut w = flate2::write::DeflateEncoder::new(file, flate2::Compression::default()); let size = std::io::copy(i, &mut w).map_err(map_err)?; w.finish().map_err(map_err)?; Ok(size) }) } fn deflate_decompress_file(mut i: Input, path: String) -> Result<u64, String> { i.with_read(|i| { let mut d = flate2::read::DeflateDecoder::new(i); let mut file = File::options().write(true).open(path).map_err(map_err)?; let size = std::io::copy(&mut d, &mut file).map_err(map_err)?; Ok(size) }) } }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_packages/compression_rs/compression_rs_wasm/src/archive.rs
packages/wasm_packages/compression_rs/compression_rs_wasm/src/archive.rs
use crate::{map_err, WitImplementation}; use crate::compression_rs::archive::*; use crate::exports::compression_rs_namespace::compression_rs; use std::fs::File; use std::io::{prelude::*, Cursor}; impl compression_rs::archive::Archive for WitImplementation { fn write_archive(input: ArchiveInput, path: String) -> Result<(), String> { match input { ArchiveInput::Zip(values) => zip_write(values, path), ArchiveInput::Tar(values) => tar_write(values, path), } } fn create_archive(input: ArchiveInput) -> Result<Vec<u8>, String> { match input { ArchiveInput::Zip(values) => zip_create(values), ArchiveInput::Tar(values) => tar_create(values), } } fn read_tar(path: String) -> Result<Vec<TarFile>, String> { let tar = File::open(&path).map_err(map_err)?; let mut a = tar::Archive::new(tar); tar_open(&mut a) } fn view_tar(bytes: Vec<u8>) -> Result<Vec<TarFile>, String> { let mut a = tar::Archive::new(bytes.as_slice()); tar_open(&mut a) } fn read_zip(path: String) -> Result<Vec<ZipFile>, String> { let file = File::open(&path).map_err(map_err)?; let mut a = zip::ZipArchive::new(file).map_err(map_err)?; zip_open(&mut a) } fn view_zip(bytes: Vec<u8>) -> Result<Vec<ZipFile>, String> { // let zip = File::open("a.zip.gz").map_err(map_err)?; // let dec = flate2::read::GzDecoder::new(zip); let mut a = zip::ZipArchive::new(Cursor::new(bytes.as_slice())).map_err(map_err)?; zip_open(&mut a) } fn extract_zip(input: Input, path: String) -> Result<(), String> { match input { Input::Bytes(bytes) => { let mut a = zip::ZipArchive::new(Cursor::new(bytes.as_slice())).map_err(map_err)?; a.extract(path).map_err(map_err) } Input::File(file_path) => { let file = File::open(file_path).map_err(map_err)?; let mut a = zip::ZipArchive::new(file).map_err(map_err)?; a.extract(path).map_err(map_err) } } } fn extract_tar(input: Input, path: String) -> Result<(), String> { match input { Input::Bytes(bytes) => { let mut a = zip::ZipArchive::new(Cursor::new(bytes.as_slice())).map_err(map_err)?; a.extract(path).map_err(map_err) } Input::File(file_path) => { let file = File::open(file_path).map_err(map_err)?; let mut a = zip::ZipArchive::new(file).map_err(map_err)?; a.extract(path).map_err(map_err) } } } // TODO: extract } fn zip_write(data: Vec<ZipArchiveInput>, path: String) -> Result<(), String> { let file = File::create(path).map_err(map_err)?; let mut ar = zip::ZipWriter::new(file); update_zip(&mut ar, data).map_err(map_err)?; ar.finish().map_err(map_err)?; Ok(()) } fn zip_create(files: Vec<ZipArchiveInput>) -> Result<Vec<u8>, String> { let mut ar = zip::ZipWriter::new(Cursor::new(Vec::new())); update_zip(&mut ar, files).map_err(map_err)?; Ok(ar.finish().map_err(map_err)?.into_inner()) } // fn zip_open_bytes(data: Vec<u8>) -> Result<Vec<ZipFile>, String> { // // let zip = File::open("a.zip.gz").map_err(map_err)?; // // let dec = flate2::read::GzDecoder::new(zip); // // let tar = File::create("a.tar.gz").map_err(map_err)?; // // let enc = GzEncoder::new(tar, Compression::default()); // // let mut a = tar::Builder::new(enc); // // a.append_dir_all("", "in").map_err(map_err)?; // } fn map_zip_method(method: ZipCompressionMethod) -> zip::CompressionMethod { match method { ZipCompressionMethod::Stored => zip::CompressionMethod::Stored, ZipCompressionMethod::Deflated => zip::CompressionMethod::Deflated, } } fn map_zip_method_to(method: zip::CompressionMethod) -> ZipCompressionMethod { match method { zip::CompressionMethod::Stored => ZipCompressionMethod::Stored, zip::CompressionMethod::Deflated => ZipCompressionMethod::Deflated, // TODO: unkown _ => ZipCompressionMethod::Stored, } } fn zip_option(input: &ZipOptions) -> zip::write::FileOptions { let mut opts = zip::write::FileOptions::default(); opts = opts.compression_method(map_zip_method(input.compression_method)); if let Some(v) = input.permissions { opts = opts.unix_permissions(v); } opts = opts.compression_level(input.compression_level); if let Some(v) = input.last_modified_time { let v = time::OffsetDateTime::from_unix_timestamp(v); if let Ok(Ok(v)) = v.map(|v| zip::DateTime::try_from(v)) { opts = opts.last_modified_time(v); } } opts } fn set_zip_comment<W: Write + Seek>(ar: &mut zip::ZipWriter<W>, input: Option<BytesOrUnicode>) { if let Some(comment) = input { match comment { BytesOrUnicode::U8List(v) => ar.set_raw_comment(v), BytesOrUnicode::String(v) => ar.set_comment(v), } } } fn update_zip<W: Write + Seek>( ar: &mut zip::ZipWriter<W>, files: Vec<ZipArchiveInput>, ) -> Result<(), String> { for file in files { let (mut options, comment) = if let Some(mut options) = file.options { (zip_option(&options), options.comment.take()) } else { (zip::write::FileOptions::default(), None) }; match file.item { ItemInput::DirPath(DirPath { path, name, all_recursive, }) => { // TODO: symlink ar.add_directory(name.as_ref().unwrap_or(&path), options) .map_err(map_err)?; set_zip_comment(ar, comment); if all_recursive { let mut entries = std::fs::read_dir(path).map_err(map_err)?; let mut files = Vec::new(); while let Some(entry) = entries.next() { let entry = entry.map_err(map_err)?; let path = entry.path(); if path.is_dir() { files.push(ZipArchiveInput { options: None, item: ItemInput::DirPath(DirPath { // TODO: don't unwrap path: path.to_str().unwrap().to_string(), name: None, all_recursive: true, }), }); } else { files.push(ZipArchiveInput { options: None, item: ItemInput::FilePath(FilePath { // TODO: don't unwrap path: path.to_str().unwrap().to_string(), name: None, }), }); } } update_zip(ar, files).map_err(map_err)?; } } ItemInput::FilePath(FilePath { path, name }) => { ar.start_file(name.as_ref().unwrap_or(&path), options) .map_err(map_err)?; set_zip_comment(ar, comment); let buf = std::fs::read(path).map_err(map_err)?; ar.write_all(buf.as_ref()).map_err(map_err)?; } ItemInput::FileBytes(FileBytes { path, bytes }) => { options = options.large_file(bytes.len() > 4294967295); ar.start_file(&path, options).map_err(map_err)?; set_zip_comment(ar, comment); ar.write_all(bytes.as_ref()).map_err(map_err)?; } } } Ok(()) } fn zip_open<R: Read + Seek>(a: &mut zip::ZipArchive<R>) -> Result<Vec<ZipFile>, String> { // TODO: a.set_unpack_xattrs(unpack_xattrs) (0..a.len()) .map(|i| { let mut e = a.by_index(i).map_err(map_err)?; let mut bytes = Vec::new(); e.read_to_end(&mut bytes).map_err(map_err)?; Ok(ZipFile { compression_method: map_zip_method_to(e.compression()), comment: e.comment().to_string(), last_modified_time: e.last_modified().to_time().unwrap().unix_timestamp(), permissions: e.unix_mode(), crc32: e.crc32(), enclosed_name: e .enclosed_name() .map(|n| n.to_str()) .flatten() .map(|n| n.to_string()), compressed_size: e.compressed_size(), extra_data: e.extra_data().to_vec(), is_dir: e.is_dir(), file: FileBytes { path: e.name().to_string(), bytes, }, }) }) .collect::<Result<Vec<_>, String>>() } // TAR fn tar_write(data: Vec<TarArchiveInput>, path: String) -> Result<(), String> { let file = File::create(path).map_err(map_err)?; let mut ar = tar::Builder::new(file); update_tar(&mut ar, data).map_err(map_err)?; ar.into_inner().map_err(map_err)?; Ok(()) } fn tar_create(files: Vec<TarArchiveInput>) -> Result<Vec<u8>, String> { let mut ar = tar::Builder::new(Vec::new()); update_tar(&mut ar, files).map_err(map_err)?; ar.into_inner().map_err(map_err) } fn tar_map_header(input: TarHeaderInput) -> Result<tar::Header, String> { match input { TarHeaderInput::Bytes(bytes) => { if bytes.len() != 512 { Err("Header bytes should be a 512 bytes buffer".to_string()) } else { Ok(tar::Header::from_byte_slice(bytes.as_slice()).clone()) } } TarHeaderInput::Model(data) => { let mut header = tar::Header::new_gnu(); data.mode.map(|v| header.set_mode(v)); data.uid.map(|v| header.set_uid(v)); data.gid.map(|v| header.set_gid(v)); data.mtime.map(|v| header.set_mtime(v)); if let Some(v) = data.username { header.set_username(&v).map_err(map_err)?; } if let Some(v) = data.groupname { header.set_groupname(&v).map_err(map_err)?; } if let Some(v) = data.device_major { header.set_device_major(v).map_err(map_err)?; } if let Some(v) = data.device_minor { header.set_device_minor(v).map_err(map_err)?; } Ok(header) } } } fn tar_map_header_to(header: &tar::Header) -> TarHeader { let mut format_errors = Vec::new(); TarHeader { mode: header .mode() // TODO: always returns error when empty .map_err(|e| format_errors.push(map_err(e))) .ok(), uid: header .uid() // TODO: always returns error when empty .map_err(|e| format_errors.push(map_err(e))) .ok(), gid: header .gid() // TODO: always returns error when empty .map_err(|e| format_errors.push(map_err(e))) .ok(), mtime: header .mtime() .map_err(|e| format_errors.push(map_err(e))) .ok(), username: header .username() .map_err(|e| format_errors.push(map_err(e))) .ok() .flatten() .map(|v| v.to_string()), groupname: header .groupname() .map_err(|e| format_errors.push(map_err(e))) .ok() .flatten() .map(|v| v.to_string()), device_major: header .device_major() // TODO: always returns error when empty .map_err(|e| format_errors.push(map_err(e))) .ok() .flatten(), device_minor: header .device_minor() // TODO: always returns error when empty .map_err(|e| format_errors.push(map_err(e))) .ok() .flatten(), bytes: header.as_bytes().to_vec(), cksum: header .cksum() .map_err(|e| format_errors.push(map_err(e))) .ok(), entry_type: map_entry_type(header.entry_type()), groupname_bytes: header.groupname_bytes().map(|f| f.to_vec()), username_bytes: header.username_bytes().map(|f| f.to_vec()), link_name: header .link_name() .map_err(|e| format_errors.push(map_err(e))) .ok() .flatten() .map(|v| v.to_str().unwrap().to_string()), link_name_bytes: header.link_name_bytes().map(|f| f.to_vec()), path: header .path() .map_err(|e| format_errors.push(map_err(e))) .ok() .map(|v| v.to_str().unwrap().to_string()), path_bytes: header.path_bytes().to_vec(), format_errors, } } fn map_entry_type(entry_type: tar::EntryType) -> TarEntryType { match entry_type { tar::EntryType::Regular => TarEntryType::Regular, tar::EntryType::Link => TarEntryType::Link, tar::EntryType::Symlink => TarEntryType::Symlink, tar::EntryType::Char => TarEntryType::Char, tar::EntryType::Block => TarEntryType::Block, tar::EntryType::Directory => TarEntryType::Directory, tar::EntryType::Fifo => TarEntryType::Fifo, tar::EntryType::Continuous => TarEntryType::Continuous, tar::EntryType::GNULongName => TarEntryType::GnuLongName, tar::EntryType::GNULongLink => TarEntryType::GnuLongLink, tar::EntryType::GNUSparse => TarEntryType::GnuSparse, tar::EntryType::XGlobalHeader => TarEntryType::XGlobalHeader, tar::EntryType::XHeader => TarEntryType::XHeader, _ => TarEntryType::Unknown, } } fn update_tar<W: Write>( ar: &mut tar::Builder<W>, files: Vec<TarArchiveInput>, ) -> Result<(), String> { for file in files { let mut header = if let Some(header) = file.header { tar_map_header(header)? } else { tar::Header::new_gnu() }; match file.item { ItemInput::DirPath(DirPath { path, name, all_recursive, }) => { // TODO: symlink if all_recursive { ar.append_dir_all(name.as_ref().unwrap_or(&path), &path) .map_err(map_err)?; } else { ar.append_dir(name.as_ref().unwrap_or(&path), &path) .map_err(map_err)?; } } ItemInput::FilePath(FilePath { path, name }) => { // TODO: use header ar.append_path_with_name(&path, name.as_ref().unwrap_or(&path)) .map_err(map_err)?; } ItemInput::FileBytes(FileBytes { path, bytes }) => { header.set_size(bytes.len() as u64); ar.append_data(&mut header, path, bytes.as_slice()) .map_err(map_err)?; } } // if let Some(bytes) = file.bytes { // let mut header = tar::Header::new_gnu(); // header.set_size(bytes.len() as u64); // ar.append_data(&mut header, file.path, bytes.as_slice()) // .map_err(map_err)?; // } else { // // let mut file_open = File::open(file.path).map_err(map_err)?; // // TODO: with name // ar.append_path(file.path).map_err(map_err)?; // // ar.append_file("bar.txt", &mut File::open("bar.txt").map_err(map_err)?) // // .map_err(map_err)?; // } } Ok(()) } // fn tar_unpack(data: Vec<TarArchiveInput>, path: String) -> u32 { // update_(ar, files); // a.unpack("out").map_err(map_err)?; // } // fn tar_open_path(path: String) -> Result<Vec<TarFile>, String> {} // fn tar_open_bytes(data: Vec<u8>) -> Result<Vec<TarFile>, String> { // // let tar = File::open("a.tar.gz").map_err(map_err)?; // // let dec = flate2::read::GzDecoder::new(tar); // // let tar = File::create("a.tar.gz").map_err(map_err)?; // // let enc = GzEncoder::new(tar, Compression::default()); // // let mut a = tar::Builder::new(enc); // // a.append_dir_all("", "in").map_err(map_err)?; // } fn tar_open<R: Read>(a: &mut tar::Archive<R>) -> Result<Vec<TarFile>, String> { // TODO: a.set_unpack_xattrs(unpack_xattrs) a.entries() .map_err(map_err)? .map(|e| { let mut e = e.map_err(map_err)?; let mut bytes = Vec::new(); // TODO: e.header() // TODO: e.path_bytes() e.read_to_end(&mut bytes).map_err(map_err)?; Ok(TarFile { header: tar_map_header_to(e.header()), file: FileBytes { path: e.path().map_err(map_err)?.to_str().unwrap().to_string(), bytes, }, }) }) .collect::<Result<Vec<_>, String>>() } // int mode = 420; // octal 644 (-rw-r--r--) // int ownerId = 0; // int groupId = 0; // int lastModTime = DateTime.now().millisecondsSinceEpoch ~/ 1000; // String nameOfLinkedFile = ''; // String? comment; // bool compress = true; // enum TarInput { // FilePath(String), // Values(Vec<TarArchiveInput>), // } // enum TarFile { // File(String, Vec<u8>), // Directory(String, Vec<TarFile>), // } // struct TarFile { // path: String, // bytes: Vec<u8>, // } // struct TarFileInput { // path: String, // is_dir: bool, // name: Option<String>, // bytes: Option<Vec<u8>>, // } // enum TarFileInput { // FilePath { // path: String, // name: Option<String>, // }, // DirPath { // path: String, // name: Option<String>, // all: bool, // }, // FileBytes { // path: String, // bytes: Vec<u8>, // }, // }
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
false
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_packages/typesql_parser/typesql_parser_wasm/src/lib.rs
packages/wasm_packages/typesql_parser/typesql_parser_wasm/src/lib.rs
// Use a procedural macro to generate bindings for the world we specified in `typesql-parser.wit` wit_bindgen::generate!("typesql-parser"); use sqlparser::ast::{self}; // Comment out the following lines to include other generated wit interfaces // use exports::typesql_parser_namespace::typesql_parser::*; // use typesql_parser_namespace::typesql_parser::interface_name; // Define a custom type and implement the generated trait for it which represents // implementing all the necessary exported interfaces for this component. struct WitImplementation; export_typesql_parser!(WitImplementation); impl TypesqlParser for WitImplementation { fn parse_sql(sql_string: String) -> Result<ParsedSql, String> { let dialect = sqlparser::dialect::GenericDialect {}; let mut state = ParserState::new(); let statements = sqlparser::parser::Parser::parse_sql(&dialect, &sql_string) .map_err(|e| format!("Error parsing SQL: {}", e))?; state.process(statements); Ok(state.parsed) } } struct ParserState { pub parsed: ParsedSql, } impl ParserState { pub fn new() -> Self { Self { parsed: ParsedSql { statements: vec![], sql_ast_refs: vec![], sql_query_refs: vec![], sql_insert_refs: vec![], sql_update_refs: vec![], sql_select_refs: vec![], set_expr_refs: vec![], expr_refs: vec![], data_type_refs: vec![], array_agg_refs: vec![], list_agg_refs: vec![], sql_function_refs: vec![], table_with_joins_refs: vec![], warnings: vec![], }, } } pub fn process(&mut self, statements: Vec<ast::Statement>) { statements.into_iter().for_each(|s| { let a = self.statement(s); self.parsed.statements.push(a); }); } fn statement(&mut self, statement: ast::Statement) -> SqlAst { let v = match statement { ast::Statement::Query(query) => SqlAst::SqlQuery(self.query(*query)), ast::Statement::Insert { .. } => SqlAst::SqlInsert(self.insert(statement)), ast::Statement::Update { .. } => SqlAst::SqlUpdate(self.update(statement)), ast::Statement::CreateTable { .. } => { SqlAst::SqlCreateTable(self.create_table(statement)) } ast::Statement::CreateView { .. } => SqlAst::SqlCreateView(self.create_view(statement)), ast::Statement::Delete { .. } => SqlAst::SqlDelete(self.delete(statement)), ast::Statement::CreateIndex { .. } => { SqlAst::SqlCreateIndex(self.create_index(statement)) } ast::Statement::AlterTable { name, operation } => SqlAst::AlterTable(AlterTable { name: self.object_name(name), operation: self.alter_table_operation(operation), }), ast::Statement::AlterIndex { name, operation } => SqlAst::AlterIndex(AlterIndex { name: self.object_name(name), operation: self.alter_index_operation(operation), }), ast::Statement::Assert { condition, message } => SqlAst::SqlAssert(SqlAssert { condition: self.expr(condition), message: message.map(|message| self.expr(message)), }), ast::Statement::CreateVirtualTable { name, if_not_exists, module_name, module_args, } => SqlAst::CreateVirtualTable(CreateVirtualTable { name: self.object_name(name), if_not_exists, module_name: self.ident(module_name), module_args: module_args.into_iter().map(|a| self.ident(a)).collect(), }), ast::Statement::Declare { name, binary, sensitive, scroll, hold, query, } => SqlAst::SqlDeclare(SqlDeclare { name: self.ident(name), binary, sensitive, scroll, hold, query: self.query(*query), }), ast::Statement::SetVariable { local, hivevar, variable, value, } => SqlAst::SetVariable(SetVariable { local, hivevar, variable: self.object_name(variable), value: self.exprs(value), }), ast::Statement::StartTransaction { modes } => { SqlAst::StartTransaction(StartTransaction { modes: modes .into_iter() .map(|m| self.transaction_mode(m)) .collect(), }) } ast::Statement::SetTransaction { modes, snapshot, session, } => SqlAst::SetTransaction(SetTransaction { modes: modes .into_iter() .map(|m| self.transaction_mode(m)) .collect(), session, snapshot: snapshot.map(|s| self.sql_value(s)), }), ast::Statement::Commit { chain } => SqlAst::Commit(Commit { chain }), ast::Statement::Savepoint { name } => SqlAst::Savepoint(Savepoint { name: self.ident(name), }), ast::Statement::Rollback { chain } => SqlAst::Rollback(Rollback { chain }), ast::Statement::CreateFunction { or_replace, name, args, temporary, return_type, params, } => SqlAst::CreateFunction(CreateFunction { or_replace, name: self.object_name(name), args: args.map(|args| { args.into_iter() .map(|a| self.operate_function_arg(a)) .collect() }), temporary, return_type: return_type.map(|t| self.data_type(t)), params: self.create_function_body(params), }), ast::Statement::CreateProcedure { name, body, params, or_alter, } => SqlAst::CreateProcedure(CreateProcedure { name: self.object_name(name), body: body.into_iter().map(|s| self.statement_ref(s)).collect(), params: params.map(|params| { params .into_iter() .map(|p| self.procedure_param(p)) .collect() }), or_alter, }), ast::Statement::CreateMacro { definition, temporary, or_replace, name, args, } => SqlAst::CreateMacro(CreateMacro { definition: self.macro_definition(definition), temporary, or_replace, name: self.object_name(name), args: args.map(|args| args.into_iter().map(|a| self.macro_arg(a)).collect()), }), ast::Statement::Execute { name, parameters } => SqlAst::SqlExecute(SqlExecute { name: self.ident(name), parameters: parameters.into_iter().map(|p| self.expr(p)).collect(), }), ast::Statement::CreateType { name, representation, } => SqlAst::CreateType(CreateType { name: self.object_name(name), representation: match representation { ast::UserDefinedTypeRepresentation::Composite { attributes } => { UserDefinedTypeRepresentation::CompositeUserDefinedType( CompositeUserDefinedType { attributes: attributes .into_iter() .map(|v| UserDefinedTypeCompositeAttributeDef { name: self.ident(v.name), data_type: self.data_type(v.data_type), collation: v.collation.map(|c| self.object_name(c)), }) .collect(), }, ) } }, }), ast::Statement::Analyze { table_name, partitions, for_columns, columns, cache_metadata, noscan, compute_statistics, } => SqlAst::SqlAnalyze(SqlAnalyze { table_name: self.object_name(table_name), partitions: partitions.map(|p| self.exprs(p)), for_columns, columns: self.idents(columns), cache_metadata, noscan, compute_statistics, }), ast::Statement::Drop { object_type, if_exists, names, cascade, restrict, purge, } => SqlAst::SqlDrop(SqlDrop { object_type: self.object_type(object_type), if_exists, names: names.into_iter().map(|n| self.object_name(n)).collect(), cascade, restrict, purge, }), ast::Statement::DropFunction { if_exists, func_desc, option, } => SqlAst::SqlDropFunction(SqlDropFunction { if_exists, func_desc: func_desc .into_iter() .map(|v| self.drop_function_desc(v)) .collect(), option: option.map(|o| self.referential_action(o)), }), ast::Statement::ShowFunctions { filter } => SqlAst::ShowFunctions(ShowFunctions { filter: filter.map(|f| self.show_statement_filter(f)), }), ast::Statement::ShowVariable { variable } => SqlAst::ShowVariable(ShowVariable { variable: self.idents(variable), }), ast::Statement::ShowVariables { filter } => SqlAst::ShowVariables(ShowVariables { filter: filter.map(|f| self.show_statement_filter(f)), }), ast::Statement::ShowCreate { obj_type, obj_name } => SqlAst::ShowCreate(ShowCreate { obj_type: self.show_create_object(obj_type), obj_name: self.object_name(obj_name), }), ast::Statement::ShowColumns { extended, full, table_name, filter, } => SqlAst::ShowColumns(ShowColumns { extended, full, table_name: self.object_name(table_name), filter: filter.map(|f| self.show_statement_filter(f)), }), ast::Statement::ShowTables { extended, full, db_name, filter, } => SqlAst::ShowTables(ShowTables { extended, full, db_name: db_name.map(|n| self.ident(n)), filter: filter.map(|f| self.show_statement_filter(f)), }), ast::Statement::ShowCollation { filter } => SqlAst::ShowCollation(ShowCollation { filter: filter.map(|f| self.show_statement_filter(f)), }), ast::Statement::Comment { object_type, object_name, comment, if_exists, } => SqlAst::SqlComment(SqlComment { object_type: self.comment_object(object_type), object_name: self.object_name(object_name), comment, if_exists, }), ast::Statement::Use { db_name } => SqlAst::SqlUse(SqlUse { db_name: self.ident(db_name), }), ast::Statement::ExplainTable { describe_alias, table_name, } => SqlAst::SqlExplainTable(SqlExplainTable { describe_alias, table_name: self.object_name(table_name), }), ast::Statement::Explain { describe_alias, analyze, verbose, statement, format, } => SqlAst::SqlExplain(SqlExplain { describe_alias, analyze, verbose, statement: self.statement_ref(*statement), format: format.map(|f| self.analyze_format(f)), }), ast::Statement::Merge { into, table, source, on, clauses, } => SqlAst::SqlMerge(SqlMerge { into, table: self.table_factor(table), source: self.table_factor(source), on: self.expr(*on), clauses: clauses.into_iter().map(|c| self.merge_clause(c)).collect(), }), _ => todo!(), }; v } fn query(&mut self, query: ast::Query) -> SqlQuery { SqlQuery { with: if let Some(l) = query.with { Some(self.with(l)) } else { None }, body: self.set_expr(query.body), order_by: self.order_by(query.order_by), limit: if let Some(l) = query.limit { Some(self.expr(l)) } else { None }, offset: self.offset(query.offset), fetch: self.fetch(query.fetch), locks: query .locks .into_iter() .map(|a| self.lock_clause(a)) .collect(), } } fn expr(&mut self, expr: ast::Expr) -> Expr { match expr { ast::Expr::Identifier(ident) => Expr::Ident(self.ident(ident)), ast::Expr::CompoundIdentifier(idents) => Expr::CompoundIdentifier(self.idents(idents)), ast::Expr::UnaryOp { op, expr } => Expr::UnaryOp(UnaryOp { op: self.unary_op(op), expr: self.expr_ref(*expr), }), ast::Expr::IsFalse(expr) => Expr::BoolUnaryOp(BoolUnaryOp { op: BoolUnaryOperator::IsFalse, expr: self.expr_ref(*expr), }), ast::Expr::IsNotFalse(expr) => Expr::BoolUnaryOp(BoolUnaryOp { op: BoolUnaryOperator::IsNotFalse, expr: self.expr_ref(*expr), }), ast::Expr::IsTrue(expr) => Expr::BoolUnaryOp(BoolUnaryOp { op: BoolUnaryOperator::IsTrue, expr: self.expr_ref(*expr), }), ast::Expr::IsNotTrue(expr) => Expr::BoolUnaryOp(BoolUnaryOp { op: BoolUnaryOperator::IsNotTrue, expr: self.expr_ref(*expr), }), ast::Expr::IsNull(expr) => Expr::BoolUnaryOp(BoolUnaryOp { op: BoolUnaryOperator::IsNull, expr: self.expr_ref(*expr), }), ast::Expr::IsNotNull(expr) => Expr::BoolUnaryOp(BoolUnaryOp { op: BoolUnaryOperator::IsNotNull, expr: self.expr_ref(*expr), }), ast::Expr::IsUnknown(expr) => Expr::BoolUnaryOp(BoolUnaryOp { op: BoolUnaryOperator::IsUnknown, expr: self.expr_ref(*expr), }), ast::Expr::IsNotUnknown(expr) => Expr::BoolUnaryOp(BoolUnaryOp { op: BoolUnaryOperator::IsNotUnknown, expr: self.expr_ref(*expr), }), ast::Expr::BinaryOp { left, op, right } => Expr::BinaryOp(BinaryOp { op: self.binary_operator(op), left: self.expr_ref(*left), right: self.expr_ref(*right), }), ast::Expr::IsDistinctFrom(left, right) => Expr::IsDistinctFrom(IsDistinctFrom { left: self.expr_ref(*left), right: self.expr_ref(*right), }), ast::Expr::IsNotDistinctFrom(left, right) => { Expr::IsNotDistinctFrom(IsNotDistinctFrom { left: self.expr_ref(*left), right: self.expr_ref(*right), }) } ast::Expr::AnyOp(a) => Expr::AnyOp(AnyOp { expr: self.expr_ref(*a), }), ast::Expr::AllOp(a) => Expr::AllOp(AllOp { expr: self.expr_ref(*a), }), ast::Expr::Nested(expr) => Expr::NestedExpr(NestedExpr { expr: self.expr_ref(*expr), }), ast::Expr::Exists { subquery, negated } => Expr::Exists(Exists { subquery: self.query_ref(subquery), negated, }), ast::Expr::Value(value) => Expr::SqlValue(self.sql_value(value)), ast::Expr::Subquery(query) => Expr::Subquery(Subquery { query: self.query_ref(query), }), ast::Expr::Function(func) => Expr::SqlFunctionRef(self.function_ref(func)), ast::Expr::InList { expr, list, negated, } => Expr::InList(InList { expr: self.expr_ref(*expr), list: list.into_iter().map(|e| self.expr_ref(e)).collect(), negated, }), ast::Expr::InSubquery { expr, subquery, negated, } => Expr::InSubquery(InSubquery { expr: self.expr_ref(*expr), subquery: self.query_ref(subquery), negated, }), ast::Expr::Between { expr, negated, low, high, } => Expr::Between(Between { expr: self.expr_ref(*expr), negated, low: self.expr_ref(*low), high: self.expr_ref(*high), }), ast::Expr::JsonAccess { left, operator, right, } => Expr::JsonAccess(JsonAccess { left: self.expr_ref(*left), operator: self.json_operator(operator), right: self.expr_ref(*right), }), ast::Expr::CompositeAccess { expr, key } => Expr::CompositeAccess(CompositeAccess { expr: self.expr_ref(*expr), key: self.ident(key), }), ast::Expr::InUnnest { expr, array_expr, negated, } => Expr::InUnnest(InUnnest { expr: self.expr_ref(*expr), array_expr: self.expr_ref(*array_expr), negated, }), ast::Expr::Like { negated, expr, pattern, escape_char, } => Expr::Like(Like { negated, expr: self.expr_ref(*expr), pattern: self.expr_ref(*pattern), escape_char, }), ast::Expr::ILike { negated, expr, pattern, escape_char, } => Expr::ILike(ILike { negated, expr: self.expr_ref(*expr), pattern: self.expr_ref(*pattern), escape_char, }), ast::Expr::SimilarTo { negated, expr, pattern, escape_char, } => Expr::SimilarTo(SimilarTo { negated, expr: self.expr_ref(*expr), pattern: self.expr_ref(*pattern), escape_char, }), ast::Expr::Cast { expr, data_type } => Expr::Cast(Cast { expr: self.expr_ref(*expr), data_type: self.data_type(data_type), }), ast::Expr::TryCast { expr, data_type } => Expr::TryCast(TryCast { expr: self.expr_ref(*expr), data_type: self.data_type(data_type), }), ast::Expr::SafeCast { expr, data_type } => Expr::SafeCast(SafeCast { expr: self.expr_ref(*expr), data_type: self.data_type(data_type), }), ast::Expr::AtTimeZone { timestamp, time_zone, } => Expr::AtTimeZone(AtTimeZone { timestamp: self.expr_ref(*timestamp), time_zone, }), ast::Expr::Extract { field, expr } => Expr::Extract(Extract { field: self.date_time_field(field), expr: self.expr_ref(*expr), }), ast::Expr::Ceil { expr, field } => Expr::Ceil(Ceil { field: self.date_time_field(field), expr: self.expr_ref(*expr), }), ast::Expr::Floor { expr, field } => Expr::Floor(Floor { field: self.date_time_field(field), expr: self.expr_ref(*expr), }), ast::Expr::Position { expr, r#in } => Expr::Position(Position { expr: self.expr_ref(*expr), in_: self.expr_ref(*r#in), }), ast::Expr::Substring { expr, substring_from, substring_for, } => Expr::Substring(Substring { expr: self.expr_ref(*expr), substring_from: substring_from.map(|e| self.expr_ref(*e)), substring_for: substring_for.map(|e| self.expr_ref(*e)), }), ast::Expr::Trim { expr, trim_where, trim_what, } => Expr::Trim(Trim { expr: self.expr_ref(*expr), trim_where: trim_where.map(|trim_where| self.trim_where_field(trim_where)), trim_what: trim_what.map(|trim_what| self.expr_ref(*trim_what)), }), ast::Expr::Overlay { expr, overlay_what, overlay_from, overlay_for, } => Expr::Overlay(Overlay { expr: self.expr_ref(*expr), overlay_what: self.expr_ref(*overlay_what), overlay_from: self.expr_ref(*overlay_from), overlay_for: overlay_for.map(|e| self.expr_ref(*e)), }), ast::Expr::Collate { collation, expr } => Expr::Collate(Collate { collation: self.object_name(collation), expr: self.expr_ref(*expr), }), ast::Expr::IntroducedString { introducer, value } => { Expr::IntroducedString(IntroducedString { introducer, value: self.sql_value(value), }) } ast::Expr::TypedString { data_type, value } => Expr::TypedString(TypedString { data_type: self.data_type(data_type), value, }), ast::Expr::MapAccess { column, keys } => Expr::MapAccess(MapAccess { column: self.expr_ref(*column), keys: keys.into_iter().map(|e| self.expr_ref(e)).collect(), }), ast::Expr::Case { operand, conditions, results, else_result, } => Expr::CaseExpr(CaseExpr { operand: operand.map(|o| self.expr_ref(*o)), conditions: conditions.into_iter().map(|c| self.expr_ref(c)).collect(), results: results.into_iter().map(|r| self.expr_ref(r)).collect(), else_result: else_result.map(|e| self.expr_ref(*e)), }), ast::Expr::ListAgg(l) => Expr::ListAggRef(self.list_agg_ref(l)), ast::Expr::ArrayAgg(l) => Expr::ArrayAggRef(self.array_agg_ref(l)), ast::Expr::ArraySubquery(l) => Expr::ArraySubquery(ArraySubquery { query: self.query_ref(l), }), ast::Expr::GroupingSets(l) => Expr::GroupingSets(GroupingSets { values: l .into_iter() .map(|s| s.into_iter().map(|e| self.expr_ref(e)).collect()) .collect(), }), ast::Expr::Cube(l) => Expr::CubeExpr(CubeExpr { values: l .into_iter() .map(|s| s.into_iter().map(|e| self.expr_ref(e)).collect()) .collect(), }), ast::Expr::Rollup(l) => Expr::RollupExpr(RollupExpr { values: l .into_iter() .map(|s| s.into_iter().map(|e| self.expr_ref(e)).collect()) .collect(), }), ast::Expr::Tuple(l) => Expr::TupleExpr(TupleExpr { values: l.into_iter().map(|s| self.expr_ref(s)).collect(), }), ast::Expr::ArrayIndex { obj, indexes } => Expr::ArrayIndex(ArrayIndex { obj: self.expr_ref(*obj), indexes: indexes.into_iter().map(|i| self.expr_ref(i)).collect(), }), ast::Expr::MatchAgainst { columns, match_value, opt_search_modifier, } => Expr::MatchAgainst(MatchAgainst { columns: columns.into_iter().map(|c| self.ident(c)).collect(), match_value: self.sql_value(match_value), opt_search_modifier: opt_search_modifier.map(|s| self.search_modifier(s)), }), ast::Expr::Array(values) => Expr::ArrayExpr(ArrayExpr { elem: values.elem.into_iter().map(|e| self.expr_ref(e)).collect(), named: values.named, }), ast::Expr::Interval(l) => Expr::IntervalExpr(IntervalExpr { value: self.expr_ref(*l.value), leading_field: l.leading_field.map(|v| self.date_time_field(v)), leading_precision: l.leading_precision, last_field: l.last_field.map(|v| self.date_time_field(v)), fractional_seconds_precision: l.fractional_seconds_precision, }), ast::Expr::AggregateExpressionWithFilter { expr, filter } => { Expr::AggregateExpressionWithFilter(AggregateExpressionWithFilter { expr: self.expr_ref(*expr), filter: self.expr_ref(*filter), }) } } } fn ident(&mut self, ident: ast::Ident) -> Ident { Ident { value: ident.value, quote_style: ident.quote_style, } } fn idents(&mut self, idents: Vec<ast::Ident>) -> Vec<Ident> { idents.into_iter().map(|i| self.ident(i)).collect() } fn order_by(&mut self, order_by: Vec<ast::OrderByExpr>) -> Vec<OrderByExpr> { order_by .into_iter() .map(|i| OrderByExpr { expr: self.expr(i.expr), asc: i.asc, nulls_first: i.nulls_first, }) .collect() } fn set_expr(&mut self, body: Box<ast::SetExpr>) -> SetExpr { match *body { ast::SetExpr::Select(v) => SetExpr::SqlSelectRef(self.select_ref(v)), ast::SetExpr::Query(v) => SetExpr::SqlQueryRef(self.query_ref(v)), ast::SetExpr::SetOperation { op, left, right, set_quantifier, } => SetExpr::SetOperation(SetOperation { op: self.set_operator(op), left: self.set_expr_ref(left), right: self.set_expr_ref(right), set_quantifier: self.set_quantifier(set_quantifier), }), ast::SetExpr::Values(v) => SetExpr::Values(self.values(v)), ast::SetExpr::Insert(v) => SetExpr::SqlInsertRef(self.insert_ref(v)), ast::SetExpr::Update(v) => SetExpr::SqlUpdateRef(self.update_ref(v)), ast::SetExpr::Table(v) => SetExpr::Table(self.table(v)), } } fn query_ref(&mut self, v: Box<ast::Query>) -> SqlQueryRef { let q = self.query(*v); let index = self.parsed.sql_query_refs.len() as u32; self.parsed.sql_query_refs.push(q); SqlQueryRef { index } } fn with(&mut self, with: ast::With) -> With { With { recursive: with.recursive, cte_tables: with .cte_tables .into_iter() .map(|c| self.cte(c)) .collect::<Vec<_>>(), } } fn select_ref(&mut self, v: Box<ast::Select>) -> SqlSelectRef { let s = self.select(*v); let index = self.parsed.sql_select_refs.len() as u32; self.parsed.sql_select_refs.push(s); SqlSelectRef { index } } fn values(&mut self, v: ast::Values) -> Values { Values { explicit_row: v.explicit_row, rows: v .rows .into_iter() .map(|r| r.into_iter().map(|e| self.expr(e)).collect()) .collect(), } } fn insert(&mut self, v: ast::Statement) -> SqlInsert { match v { ast::Statement::Insert { or, into, table_name, columns, overwrite, source, partitioned, after_columns, table, on, returning, } => SqlInsert { or: or.map(|v| self.sqlite_on_conflict(v)), into, table_name: self.object_name(table_name), columns: self.idents(columns), overwrite, source: self.query(*source), partitioned: partitioned.map(|v| self.exprs(v)), after_columns: self.idents(after_columns), table, on: on.map(|v| self.on_insert(v)), returning: returning.map(|v| self.select_items(v)), }, _ => unreachable!("insert statement {}", v), } } fn sqlite_on_conflict(&mut self, e: ast::SqliteOnConflict) -> SqliteOnConflict { match e { ast::SqliteOnConflict::Rollback => SqliteOnConflict::Rollback, ast::SqliteOnConflict::Abort => SqliteOnConflict::Abort, ast::SqliteOnConflict::Fail => SqliteOnConflict::Fail, ast::SqliteOnConflict::Ignore => SqliteOnConflict::Ignore, ast::SqliteOnConflict::Replace => SqliteOnConflict::Replace, } } fn insert_ref(&mut self, v: ast::Statement) -> SqlInsertRef { let i = self.insert(v); let index = self.parsed.sql_insert_refs.len() as u32; self.parsed.sql_insert_refs.push(i); SqlInsertRef { index } } fn update(&mut self, v: ast::Statement) -> SqlUpdate { match v { ast::Statement::Update { table, assignments, from, selection, returning, } => SqlUpdate { table: self.table_with_joins(table), assignments: self.assignments(assignments), from: from.map(|v| self.table_with_joins(v)), selection: selection.map(|v| self.expr(v)), returning: returning.map(|v| self.select_items(v)), }, _ => unreachable!("update statement {}", v), } } fn update_ref(&mut self, v: ast::Statement) -> SqlUpdateRef { let u = self.update(v); let index = self.parsed.sql_update_refs.len() as u32;
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
true
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_packages/typesql_parser/typesql_parser_wasm/src/lib_expand.rs
packages/wasm_packages/typesql_parser/typesql_parser_wasm/src/lib_expand.rs
#![feature(prelude_import)] #[prelude_import] use std::prelude::rust_2021::*; #[macro_use] extern crate std; /// https://docs.rs/sqlparser/0.35.0/sqlparser/ast/enum.WindowFrameUnits.html #[repr(u8)] pub enum WindowFrameUnits { Rows, Range, Groups, } #[automatically_derived] impl ::core::clone::Clone for WindowFrameUnits { #[inline] fn clone(&self) -> WindowFrameUnits { *self } } #[automatically_derived] impl ::core::marker::Copy for WindowFrameUnits {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for WindowFrameUnits {} #[automatically_derived] impl ::core::cmp::PartialEq for WindowFrameUnits { #[inline] fn eq(&self, other: &WindowFrameUnits) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for WindowFrameUnits {} #[automatically_derived] impl ::core::cmp::Eq for WindowFrameUnits { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for WindowFrameUnits { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { WindowFrameUnits::Rows => f.debug_tuple("WindowFrameUnits::Rows").finish(), WindowFrameUnits::Range => f.debug_tuple("WindowFrameUnits::Range").finish(), WindowFrameUnits::Groups => { f.debug_tuple("WindowFrameUnits::Groups").finish() } } } } #[repr(C)] pub struct UniqueOption { pub is_primary: bool, } #[automatically_derived] impl ::core::marker::Copy for UniqueOption {} #[automatically_derived] impl ::core::clone::Clone for UniqueOption { #[inline] fn clone(&self) -> UniqueOption { let _: ::core::clone::AssertParamIsClone<bool>; *self } } impl ::core::fmt::Debug for UniqueOption { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("UniqueOption").field("is-primary", &self.is_primary).finish() } } #[repr(u8)] pub enum UnaryOperator { Plus, Minus, Not, PgBitwiseNot, PgSquareRoot, PgCubeRoot, PgPostfixFactorial, PgPrefixFactorial, PgAbs, } #[automatically_derived] impl ::core::clone::Clone for UnaryOperator { #[inline] fn clone(&self) -> UnaryOperator { *self } } #[automatically_derived] impl ::core::marker::Copy for UnaryOperator {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for UnaryOperator {} #[automatically_derived] impl ::core::cmp::PartialEq for UnaryOperator { #[inline] fn eq(&self, other: &UnaryOperator) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for UnaryOperator {} #[automatically_derived] impl ::core::cmp::Eq for UnaryOperator { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for UnaryOperator { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { UnaryOperator::Plus => f.debug_tuple("UnaryOperator::Plus").finish(), UnaryOperator::Minus => f.debug_tuple("UnaryOperator::Minus").finish(), UnaryOperator::Not => f.debug_tuple("UnaryOperator::Not").finish(), UnaryOperator::PgBitwiseNot => { f.debug_tuple("UnaryOperator::PgBitwiseNot").finish() } UnaryOperator::PgSquareRoot => { f.debug_tuple("UnaryOperator::PgSquareRoot").finish() } UnaryOperator::PgCubeRoot => { f.debug_tuple("UnaryOperator::PgCubeRoot").finish() } UnaryOperator::PgPostfixFactorial => { f.debug_tuple("UnaryOperator::PgPostfixFactorial").finish() } UnaryOperator::PgPrefixFactorial => { f.debug_tuple("UnaryOperator::PgPrefixFactorial").finish() } UnaryOperator::PgAbs => f.debug_tuple("UnaryOperator::PgAbs").finish(), } } } #[repr(u8)] pub enum TrimWhereField { Both, Leading, Trailing, } #[automatically_derived] impl ::core::clone::Clone for TrimWhereField { #[inline] fn clone(&self) -> TrimWhereField { *self } } #[automatically_derived] impl ::core::marker::Copy for TrimWhereField {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for TrimWhereField {} #[automatically_derived] impl ::core::cmp::PartialEq for TrimWhereField { #[inline] fn eq(&self, other: &TrimWhereField) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for TrimWhereField {} #[automatically_derived] impl ::core::cmp::Eq for TrimWhereField { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for TrimWhereField { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { TrimWhereField::Both => f.debug_tuple("TrimWhereField::Both").finish(), TrimWhereField::Leading => f.debug_tuple("TrimWhereField::Leading").finish(), TrimWhereField::Trailing => { f.debug_tuple("TrimWhereField::Trailing").finish() } } } } /// https://docs.rs/sqlparser/0.35.0/sqlparser/ast/enum.TransactionIsolationLevel.html #[repr(u8)] pub enum TransactionIsolationLevel { ReadUncommitted, ReadCommitted, RepeatableRead, Serializable, } #[automatically_derived] impl ::core::clone::Clone for TransactionIsolationLevel { #[inline] fn clone(&self) -> TransactionIsolationLevel { *self } } #[automatically_derived] impl ::core::marker::Copy for TransactionIsolationLevel {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for TransactionIsolationLevel {} #[automatically_derived] impl ::core::cmp::PartialEq for TransactionIsolationLevel { #[inline] fn eq(&self, other: &TransactionIsolationLevel) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for TransactionIsolationLevel {} #[automatically_derived] impl ::core::cmp::Eq for TransactionIsolationLevel { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for TransactionIsolationLevel { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { TransactionIsolationLevel::ReadUncommitted => { f.debug_tuple("TransactionIsolationLevel::ReadUncommitted").finish() } TransactionIsolationLevel::ReadCommitted => { f.debug_tuple("TransactionIsolationLevel::ReadCommitted").finish() } TransactionIsolationLevel::RepeatableRead => { f.debug_tuple("TransactionIsolationLevel::RepeatableRead").finish() } TransactionIsolationLevel::Serializable => { f.debug_tuple("TransactionIsolationLevel::Serializable").finish() } } } } /// https://docs.rs/sqlparser/0.35.0/sqlparser/ast/enum.TransactionAccessMode.html #[repr(u8)] pub enum TransactionAccessMode { ReadOnly, ReadWrite, } #[automatically_derived] impl ::core::clone::Clone for TransactionAccessMode { #[inline] fn clone(&self) -> TransactionAccessMode { *self } } #[automatically_derived] impl ::core::marker::Copy for TransactionAccessMode {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for TransactionAccessMode {} #[automatically_derived] impl ::core::cmp::PartialEq for TransactionAccessMode { #[inline] fn eq(&self, other: &TransactionAccessMode) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for TransactionAccessMode {} #[automatically_derived] impl ::core::cmp::Eq for TransactionAccessMode { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for TransactionAccessMode { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { TransactionAccessMode::ReadOnly => { f.debug_tuple("TransactionAccessMode::ReadOnly").finish() } TransactionAccessMode::ReadWrite => { f.debug_tuple("TransactionAccessMode::ReadWrite").finish() } } } } pub enum TransactionMode { AccessMode(TransactionAccessMode), IsolationLevel(TransactionIsolationLevel), } #[automatically_derived] impl ::core::clone::Clone for TransactionMode { #[inline] fn clone(&self) -> TransactionMode { let _: ::core::clone::AssertParamIsClone<TransactionAccessMode>; let _: ::core::clone::AssertParamIsClone<TransactionIsolationLevel>; *self } } #[automatically_derived] impl ::core::marker::Copy for TransactionMode {} impl ::core::fmt::Debug for TransactionMode { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { TransactionMode::AccessMode(e) => { f.debug_tuple("TransactionMode::AccessMode").field(e).finish() } TransactionMode::IsolationLevel(e) => { f.debug_tuple("TransactionMode::IsolationLevel").field(e).finish() } } } } /// https://docs.rs/sqlparser/0.35.0/sqlparser/ast/enum.TimezoneInfo.html #[repr(u8)] pub enum TimezoneInfo { None, WithTimezone, WithoutTimezone, Tz, } #[automatically_derived] impl ::core::clone::Clone for TimezoneInfo { #[inline] fn clone(&self) -> TimezoneInfo { *self } } #[automatically_derived] impl ::core::marker::Copy for TimezoneInfo {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for TimezoneInfo {} #[automatically_derived] impl ::core::cmp::PartialEq for TimezoneInfo { #[inline] fn eq(&self, other: &TimezoneInfo) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for TimezoneInfo {} #[automatically_derived] impl ::core::cmp::Eq for TimezoneInfo { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for TimezoneInfo { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { TimezoneInfo::None => f.debug_tuple("TimezoneInfo::None").finish(), TimezoneInfo::WithTimezone => { f.debug_tuple("TimezoneInfo::WithTimezone").finish() } TimezoneInfo::WithoutTimezone => { f.debug_tuple("TimezoneInfo::WithoutTimezone").finish() } TimezoneInfo::Tz => f.debug_tuple("TimezoneInfo::Tz").finish(), } } } #[repr(C)] pub struct TimestampType { pub value: Option<u64>, pub timezone_info: TimezoneInfo, } #[automatically_derived] impl ::core::marker::Copy for TimestampType {} #[automatically_derived] impl ::core::clone::Clone for TimestampType { #[inline] fn clone(&self) -> TimestampType { let _: ::core::clone::AssertParamIsClone<Option<u64>>; let _: ::core::clone::AssertParamIsClone<TimezoneInfo>; *self } } impl ::core::fmt::Debug for TimestampType { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("TimestampType") .field("value", &self.value) .field("timezone-info", &self.timezone_info) .finish() } } #[repr(C)] pub struct TableWithJoinsRef { pub index: u32, } #[automatically_derived] impl ::core::marker::Copy for TableWithJoinsRef {} #[automatically_derived] impl ::core::clone::Clone for TableWithJoinsRef { #[inline] fn clone(&self) -> TableWithJoinsRef { let _: ::core::clone::AssertParamIsClone<u32>; *self } } impl ::core::fmt::Debug for TableWithJoinsRef { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("TableWithJoinsRef").field("index", &self.index).finish() } } pub struct Table { pub table_name: Option<wit_bindgen::rt::string::String>, pub schema_name: Option<wit_bindgen::rt::string::String>, } #[automatically_derived] impl ::core::clone::Clone for Table { #[inline] fn clone(&self) -> Table { Table { table_name: ::core::clone::Clone::clone(&self.table_name), schema_name: ::core::clone::Clone::clone(&self.schema_name), } } } impl ::core::fmt::Debug for Table { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("Table") .field("table-name", &self.table_name) .field("schema-name", &self.schema_name) .finish() } } pub struct StartTransaction { pub modes: wit_bindgen::rt::vec::Vec<TransactionMode>, } #[automatically_derived] impl ::core::clone::Clone for StartTransaction { #[inline] fn clone(&self) -> StartTransaction { StartTransaction { modes: ::core::clone::Clone::clone(&self.modes), } } } impl ::core::fmt::Debug for StartTransaction { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("StartTransaction").field("modes", &self.modes).finish() } } #[repr(u8)] pub enum SqliteOnConflict { Rollback, Abort, Fail, Ignore, Replace, } #[automatically_derived] impl ::core::clone::Clone for SqliteOnConflict { #[inline] fn clone(&self) -> SqliteOnConflict { *self } } #[automatically_derived] impl ::core::marker::Copy for SqliteOnConflict {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for SqliteOnConflict {} #[automatically_derived] impl ::core::cmp::PartialEq for SqliteOnConflict { #[inline] fn eq(&self, other: &SqliteOnConflict) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for SqliteOnConflict {} #[automatically_derived] impl ::core::cmp::Eq for SqliteOnConflict { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for SqliteOnConflict { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { SqliteOnConflict::Rollback => { f.debug_tuple("SqliteOnConflict::Rollback").finish() } SqliteOnConflict::Abort => f.debug_tuple("SqliteOnConflict::Abort").finish(), SqliteOnConflict::Fail => f.debug_tuple("SqliteOnConflict::Fail").finish(), SqliteOnConflict::Ignore => { f.debug_tuple("SqliteOnConflict::Ignore").finish() } SqliteOnConflict::Replace => { f.debug_tuple("SqliteOnConflict::Replace").finish() } } } } #[repr(C)] pub struct SqlUpdateRef { pub index: u32, } #[automatically_derived] impl ::core::marker::Copy for SqlUpdateRef {} #[automatically_derived] impl ::core::clone::Clone for SqlUpdateRef { #[inline] fn clone(&self) -> SqlUpdateRef { let _: ::core::clone::AssertParamIsClone<u32>; *self } } impl ::core::fmt::Debug for SqlUpdateRef { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("SqlUpdateRef").field("index", &self.index).finish() } } #[repr(C)] pub struct SqlSelectRef { pub index: u32, } #[automatically_derived] impl ::core::marker::Copy for SqlSelectRef {} #[automatically_derived] impl ::core::clone::Clone for SqlSelectRef { #[inline] fn clone(&self) -> SqlSelectRef { let _: ::core::clone::AssertParamIsClone<u32>; *self } } impl ::core::fmt::Debug for SqlSelectRef { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("SqlSelectRef").field("index", &self.index).finish() } } #[repr(C)] pub struct SqlQueryRef { pub index: u32, } #[automatically_derived] impl ::core::marker::Copy for SqlQueryRef {} #[automatically_derived] impl ::core::clone::Clone for SqlQueryRef { #[inline] fn clone(&self) -> SqlQueryRef { let _: ::core::clone::AssertParamIsClone<u32>; *self } } impl ::core::fmt::Debug for SqlQueryRef { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("SqlQueryRef").field("index", &self.index).finish() } } #[repr(C)] pub struct Subquery { pub query: SqlQueryRef, } #[automatically_derived] impl ::core::marker::Copy for Subquery {} #[automatically_derived] impl ::core::clone::Clone for Subquery { #[inline] fn clone(&self) -> Subquery { let _: ::core::clone::AssertParamIsClone<SqlQueryRef>; *self } } impl ::core::fmt::Debug for Subquery { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("Subquery").field("query", &self.query).finish() } } #[repr(C)] pub struct SqlInsertRef { pub index: u32, } #[automatically_derived] impl ::core::marker::Copy for SqlInsertRef {} #[automatically_derived] impl ::core::clone::Clone for SqlInsertRef { #[inline] fn clone(&self) -> SqlInsertRef { let _: ::core::clone::AssertParamIsClone<u32>; *self } } impl ::core::fmt::Debug for SqlInsertRef { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("SqlInsertRef").field("index", &self.index).finish() } } #[repr(C)] pub struct SqlFunctionRef { pub index: u32, } #[automatically_derived] impl ::core::marker::Copy for SqlFunctionRef {} #[automatically_derived] impl ::core::clone::Clone for SqlFunctionRef { #[inline] fn clone(&self) -> SqlFunctionRef { let _: ::core::clone::AssertParamIsClone<u32>; *self } } impl ::core::fmt::Debug for SqlFunctionRef { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("SqlFunctionRef").field("index", &self.index).finish() } } #[repr(C)] pub struct SqlAstRef { pub index: u32, } #[automatically_derived] impl ::core::marker::Copy for SqlAstRef {} #[automatically_derived] impl ::core::clone::Clone for SqlAstRef { #[inline] fn clone(&self) -> SqlAstRef { let _: ::core::clone::AssertParamIsClone<u32>; *self } } impl ::core::fmt::Debug for SqlAstRef { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("SqlAstRef").field("index", &self.index).finish() } } #[repr(u8)] pub enum ShowCreateObject { Event, Function, Procedure, Table, Trigger, View, } #[automatically_derived] impl ::core::clone::Clone for ShowCreateObject { #[inline] fn clone(&self) -> ShowCreateObject { *self } } #[automatically_derived] impl ::core::marker::Copy for ShowCreateObject {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for ShowCreateObject {} #[automatically_derived] impl ::core::cmp::PartialEq for ShowCreateObject { #[inline] fn eq(&self, other: &ShowCreateObject) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for ShowCreateObject {} #[automatically_derived] impl ::core::cmp::Eq for ShowCreateObject { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for ShowCreateObject { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { ShowCreateObject::Event => f.debug_tuple("ShowCreateObject::Event").finish(), ShowCreateObject::Function => { f.debug_tuple("ShowCreateObject::Function").finish() } ShowCreateObject::Procedure => { f.debug_tuple("ShowCreateObject::Procedure").finish() } ShowCreateObject::Table => f.debug_tuple("ShowCreateObject::Table").finish(), ShowCreateObject::Trigger => { f.debug_tuple("ShowCreateObject::Trigger").finish() } ShowCreateObject::View => f.debug_tuple("ShowCreateObject::View").finish(), } } } #[repr(u8)] pub enum SetQuantifier { All, Distinct, None, } #[automatically_derived] impl ::core::clone::Clone for SetQuantifier { #[inline] fn clone(&self) -> SetQuantifier { *self } } #[automatically_derived] impl ::core::marker::Copy for SetQuantifier {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for SetQuantifier {} #[automatically_derived] impl ::core::cmp::PartialEq for SetQuantifier { #[inline] fn eq(&self, other: &SetQuantifier) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for SetQuantifier {} #[automatically_derived] impl ::core::cmp::Eq for SetQuantifier { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for SetQuantifier { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { SetQuantifier::All => f.debug_tuple("SetQuantifier::All").finish(), SetQuantifier::Distinct => f.debug_tuple("SetQuantifier::Distinct").finish(), SetQuantifier::None => f.debug_tuple("SetQuantifier::None").finish(), } } } /// https://docs.rs/sqlparser/0.35.0/sqlparser/ast/enum.SetOperator.html #[repr(u8)] pub enum SetOperator { Union, Except, Intersect, } #[automatically_derived] impl ::core::clone::Clone for SetOperator { #[inline] fn clone(&self) -> SetOperator { *self } } #[automatically_derived] impl ::core::marker::Copy for SetOperator {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for SetOperator {} #[automatically_derived] impl ::core::cmp::PartialEq for SetOperator { #[inline] fn eq(&self, other: &SetOperator) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for SetOperator {} #[automatically_derived] impl ::core::cmp::Eq for SetOperator { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for SetOperator { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { SetOperator::Union => f.debug_tuple("SetOperator::Union").finish(), SetOperator::Except => f.debug_tuple("SetOperator::Except").finish(), SetOperator::Intersect => f.debug_tuple("SetOperator::Intersect").finish(), } } } #[repr(C)] pub struct SetExprRef { pub index: u32, } #[automatically_derived] impl ::core::marker::Copy for SetExprRef {} #[automatically_derived] impl ::core::clone::Clone for SetExprRef { #[inline] fn clone(&self) -> SetExprRef { let _: ::core::clone::AssertParamIsClone<u32>; *self } } impl ::core::fmt::Debug for SetExprRef { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("SetExprRef").field("index", &self.index).finish() } } #[repr(C)] pub struct SetOperation { pub op: SetOperator, pub set_quantifier: SetQuantifier, pub left: SetExprRef, pub right: SetExprRef, } #[automatically_derived] impl ::core::marker::Copy for SetOperation {} #[automatically_derived] impl ::core::clone::Clone for SetOperation { #[inline] fn clone(&self) -> SetOperation { let _: ::core::clone::AssertParamIsClone<SetOperator>; let _: ::core::clone::AssertParamIsClone<SetQuantifier>; let _: ::core::clone::AssertParamIsClone<SetExprRef>; *self } } impl ::core::fmt::Debug for SetOperation { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("SetOperation") .field("op", &self.op) .field("set-quantifier", &self.set_quantifier) .field("left", &self.left) .field("right", &self.right) .finish() } } /// https://docs.rs/sqlparser/0.35.0/sqlparser/ast/enum.SearchModifier.html #[repr(u8)] pub enum SearchModifier { InNaturalLanguageMode, InNaturalLanguageModeWithQueryExpansion, InBooleanMode, WithQueryExpansion, } #[automatically_derived] impl ::core::clone::Clone for SearchModifier { #[inline] fn clone(&self) -> SearchModifier { *self } } #[automatically_derived] impl ::core::marker::Copy for SearchModifier {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for SearchModifier {} #[automatically_derived] impl ::core::cmp::PartialEq for SearchModifier { #[inline] fn eq(&self, other: &SearchModifier) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for SearchModifier {} #[automatically_derived] impl ::core::cmp::Eq for SearchModifier { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for SearchModifier { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { SearchModifier::InNaturalLanguageMode => { f.debug_tuple("SearchModifier::InNaturalLanguageMode").finish() } SearchModifier::InNaturalLanguageModeWithQueryExpansion => { f.debug_tuple("SearchModifier::InNaturalLanguageModeWithQueryExpansion") .finish() } SearchModifier::InBooleanMode => { f.debug_tuple("SearchModifier::InBooleanMode").finish() } SearchModifier::WithQueryExpansion => { f.debug_tuple("SearchModifier::WithQueryExpansion").finish() } } } } #[repr(C)] pub struct Rollback { pub chain: bool, } #[automatically_derived] impl ::core::marker::Copy for Rollback {} #[automatically_derived] impl ::core::clone::Clone for Rollback { #[inline] fn clone(&self) -> Rollback { let _: ::core::clone::AssertParamIsClone<bool>; *self } } impl ::core::fmt::Debug for Rollback { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { f.debug_struct("Rollback").field("chain", &self.chain).finish() } } /// https://docs.rs/sqlparser/0.35.0/sqlparser/ast/enum.ReferentialAction.html #[repr(u8)] pub enum ReferentialAction { Restrict, Cascade, SetNull, NoAction, SetDefault, } #[automatically_derived] impl ::core::clone::Clone for ReferentialAction { #[inline] fn clone(&self) -> ReferentialAction { *self } } #[automatically_derived] impl ::core::marker::Copy for ReferentialAction {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for ReferentialAction {} #[automatically_derived] impl ::core::cmp::PartialEq for ReferentialAction { #[inline] fn eq(&self, other: &ReferentialAction) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for ReferentialAction {} #[automatically_derived] impl ::core::cmp::Eq for ReferentialAction { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for ReferentialAction { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { ReferentialAction::Restrict => { f.debug_tuple("ReferentialAction::Restrict").finish() } ReferentialAction::Cascade => { f.debug_tuple("ReferentialAction::Cascade").finish() } ReferentialAction::SetNull => { f.debug_tuple("ReferentialAction::SetNull").finish() } ReferentialAction::NoAction => { f.debug_tuple("ReferentialAction::NoAction").finish() } ReferentialAction::SetDefault => { f.debug_tuple("ReferentialAction::SetDefault").finish() } } } } #[repr(u8)] pub enum OnCommit { PreserveRows, DeleteRows, Drop, } #[automatically_derived] impl ::core::clone::Clone for OnCommit { #[inline] fn clone(&self) -> OnCommit { *self } } #[automatically_derived] impl ::core::marker::Copy for OnCommit {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for OnCommit {} #[automatically_derived] impl ::core::cmp::PartialEq for OnCommit { #[inline] fn eq(&self, other: &OnCommit) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for OnCommit {} #[automatically_derived] impl ::core::cmp::Eq for OnCommit { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for OnCommit { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { OnCommit::PreserveRows => f.debug_tuple("OnCommit::PreserveRows").finish(), OnCommit::DeleteRows => f.debug_tuple("OnCommit::DeleteRows").finish(), OnCommit::Drop => f.debug_tuple("OnCommit::Drop").finish(), } } } #[repr(u8)] pub enum OffsetRows { None, Row, Rows, } #[automatically_derived] impl ::core::clone::Clone for OffsetRows { #[inline] fn clone(&self) -> OffsetRows { *self } } #[automatically_derived] impl ::core::marker::Copy for OffsetRows {} #[automatically_derived] impl ::core::marker::StructuralPartialEq for OffsetRows {} #[automatically_derived] impl ::core::cmp::PartialEq for OffsetRows { #[inline] fn eq(&self, other: &OffsetRows) -> bool { let __self_tag = ::core::intrinsics::discriminant_value(self); let __arg1_tag = ::core::intrinsics::discriminant_value(other); __self_tag == __arg1_tag } } #[automatically_derived] impl ::core::marker::StructuralEq for OffsetRows {} #[automatically_derived] impl ::core::cmp::Eq for OffsetRows { #[inline] #[doc(hidden)] #[no_coverage] fn assert_receiver_is_total_eq(&self) -> () {} } impl ::core::fmt::Debug for OffsetRows { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { OffsetRows::None => f.debug_tuple("OffsetRows::None").finish(),
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
true
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_packages/y_crdt/y_crdt_wasm/src/lib.rs
packages/wasm_packages/y_crdt/y_crdt_wasm/src/lib.rs
// Use a procedural macro to generate bindings for the world we specified in `y-crdt.wit` wit_bindgen::generate!({ path: "wit/y-crdt.wit", exports: { world: WitImplementation, "y-crdt-namespace:y-crdt/y-doc-methods": WitImplementation, }, }); use exports::y_crdt_namespace::y_crdt::y_doc_methods::*; use lib0::any::Any; use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; use std::convert::TryFrom; use std::mem::ManuallyDrop; use std::ops::Deref; use std::rc::Rc; use std::sync::Arc; use y_crdt_namespace::y_crdt::y_doc_methods_types::{ EventPathItem, JsonArrayRef, JsonMapRef, JsonValue, StackItemSets, StartLength, YArrayDelta, YArrayDeltaDelete, YArrayDeltaInsert, YArrayDeltaRetain, YArrayEvent, YMapDelta, YMapDeltaAction, YMapEvent, YTextDeltaDelete, YTextDeltaInsert, YTextDeltaRetain, YTextEvent, YUndoKind, }; use yrs::block::{ClientID, ItemContent, Prelim, Unused}; use yrs::types::array::ArrayEvent; use yrs::types::map::MapEvent; use yrs::types::text::{ChangeKind, Diff, TextEvent, YChange}; use yrs::types::xml::{XmlEvent, XmlTextEvent}; use yrs::types::{ Attrs, Branch, BranchPtr, Change, DeepEventsSubscription, DeepObservable, Delta, EntryChange, Event, Events, Path, PathSegment, ToJson, TypeRef, Value, }; use yrs::undo::{EventKind, StackItem, UndoEventSubscription}; use yrs::updates::decoder::{Decode, DecoderV1}; use yrs::updates::encoder::{Encode, Encoder, EncoderV1, EncoderV2}; use yrs::{ Array, ArrayRef, Assoc, DeleteSet, DestroySubscription, Doc, GetString, IndexScope, Map, MapRef, Observable, Offset, Options, Origin, ReadTxn, Snapshot, StateVector, StickyIndex, Store, SubdocsEvent, SubdocsEventIter, SubdocsSubscription, Subscription, Text, TextRef, Transact, Transaction, TransactionCleanupEvent, TransactionCleanupSubscription, TransactionMut, UndoManager, Update, UpdateSubscription, Xml, XmlElementPrelim, XmlElementRef, XmlFragment, XmlFragmentRef, XmlNode, XmlTextPrelim, XmlTextRef, ID, }; use once_cell::unsync::Lazy; thread_local! { static IMAGES_MAP: Lazy<RefCell<GlobalState>> = Lazy::new(|| Default::default()); static TXN_STATE: Lazy<RefCell<TxnState>> = Lazy::new(|| Default::default()); static UNDO_STATE: Lazy<RefCell<UndoState>> = Lazy::new(|| Default::default()); } #[derive(Default)] pub struct GlobalState { pub last_id: u32, pub docs: HashMap<u32, Doc>, pub texts: HashMap<u32, TextRef>, pub arrays: HashMap<u32, ArrayRef>, pub maps: HashMap<u32, MapRef>, pub xml_elements: HashMap<u32, XmlElementRef>, pub xml_fragments: HashMap<u32, XmlFragmentRef>, pub xml_texts: HashMap<u32, XmlTextRef>, pub snapshots: HashMap<u32, Snapshot>, pub callbacks: HashMap<u32, Subscription<Arc<dyn std::any::Any>>>, } impl GlobalState { fn save_doc(&mut self, image: Doc) -> YDoc { let id = self.last_id; self.last_id += 1; let image_ref = YDoc { ref_: id }; self.docs.insert(id, image); image_ref } fn save_text(&mut self, t: TextRef) -> YText { let id = self.last_id; self.last_id += 1; let v = YText { ref_: id }; self.texts.insert(id, t); v } fn save_array(&mut self, t: ArrayRef) -> YArray { let id = self.last_id; self.last_id += 1; let v = YArray { ref_: id }; self.arrays.insert(id, t); v } fn save_map(&mut self, t: MapRef) -> YMap { let id = self.last_id; self.last_id += 1; let v = YMap { ref_: id }; self.maps.insert(id, t); v } fn save_xml_element(&mut self, t: XmlElementRef) -> YXmlElement { let id = self.last_id; self.last_id += 1; let v = YXmlElement { ref_: id }; self.xml_elements.insert(id, t); v } fn save_xml_fragment(&mut self, t: XmlFragmentRef) -> YXmlFragment { let id = self.last_id; self.last_id += 1; let v = YXmlFragment { ref_: id }; self.xml_fragments.insert(id, t); v } fn save_xml_text(&mut self, t: XmlTextRef) -> YXmlText { let id = self.last_id; self.last_id += 1; let v = YXmlText { ref_: id }; self.xml_texts.insert(id, t); v } fn save_snapshot(&mut self, t: Snapshot) -> YSnapshot { let id = self.last_id; self.last_id += 1; let v = YSnapshot { ref_: id }; self.snapshots.insert(id, t); v } fn save_callback(&mut self, subs: Subscription<Arc<dyn std::any::Any>>) -> EventObserver { self.last_id += 1; let id = self.last_id; self.callbacks.insert(id, subs); EventObserver { ref_: id } } } #[derive(Default)] pub struct TxnState { pub last_id: u32, pub transactions: HashMap<u32, Rc<Transaction<'static>>>, pub transactions_mut: HashMap<u32, TransactionMut<'static>>, } impl TxnState { fn save_transaction(&mut self, t: Transaction<'static>) -> ReadTransaction { let id = self.last_id; self.last_id += 1; let v = ReadTransaction { ref_: id }; self.transactions.insert(id, Rc::new(t)); v } fn save_transaction_mut(&mut self, t: TransactionMut<'static>) -> WriteTransaction { let id = self.last_id; self.last_id += 1; let v = WriteTransaction { ref_: id }; self.transactions_mut.insert(id, t); // Rc::new(RefCell::new(t))); v } } #[derive(Default)] pub struct UndoState { pub last_id: u32, pub undo_managers: HashMap<u32, UndoManager>, } impl UndoState { fn save_undo_manager(&mut self, um: UndoManager) -> UndoManagerRef { self.last_id += 1; let id = self.last_id; self.undo_managers.insert(id, um); UndoManagerRef { ref_: id } } } fn with_mut<T>(f: impl FnOnce(&mut GlobalState) -> T) -> T { IMAGES_MAP.with(|v| f(&mut v.borrow_mut())) } fn with<T>(f: impl FnOnce(&GlobalState) -> T) -> T { IMAGES_MAP.with(|v| f(&v.borrow())) } fn with_txn_state<T>(f: impl FnOnce(&mut TxnState) -> T) -> T { TXN_STATE.with(|v| f(&mut v.borrow_mut())) } fn operation<T>(image_ref: YDoc, f: impl FnOnce(&Doc) -> T) -> T { with(|state| { let img = &state.docs[&image_ref.ref_]; f(img) }) } fn with_undo_state<T>(f: impl FnOnce(&mut GlobalState, &mut UndoState) -> T) -> T { IMAGES_MAP.with(|v| UNDO_STATE.with(|state| f(&mut v.borrow_mut(), &mut state.borrow_mut()))) } fn with_undo_manager<T>(um: UndoManagerRef, f: impl FnOnce(&mut UndoManager) -> T) -> T { UNDO_STATE.with(|v| { let v = &mut v.borrow_mut(); let um = v.undo_managers.get_mut(&um.ref_).unwrap(); f(um) }) } fn with_mut_all<T>(f: impl FnOnce(&mut GlobalState, &mut TxnState) -> T) -> T { IMAGES_MAP.with(|v| TXN_STATE.with(|state| f(&mut v.borrow_mut(), &mut state.borrow_mut()))) } fn with_txn<T>(t: YTransaction, f: impl FnOnce(&YTransactionInner) -> T) -> T { TXN_STATE.with(|state| { let mut m = state.borrow_mut(); let t = YTransactionInner::from_ref(t, &mut m); f(&t) }) } fn with_text<T>( text: YText, txn: ImplicitTransaction, f: impl FnOnce(&TextRef, &mut TransactionMut<'static>) -> T, ) -> T { IMAGES_MAP.with(|state| { TXN_STATE.with(|txs| { let v = &state.borrow_mut().texts[&text.ref_]; YTransactionInner::from_transact_mut_f(txn, v, &mut txs.borrow_mut(), |txn| f(v, txn)) }) }) } fn with_array<T>( array: YArray, txn: ImplicitTransaction, f: impl FnOnce(&ArrayRef, &mut TransactionMut<'static>) -> T, ) -> T { IMAGES_MAP.with(|state| { TXN_STATE.with(|txs| { let v = &state.borrow_mut().arrays[&array.ref_]; YTransactionInner::from_transact_mut_f(txn, v, &mut txs.borrow_mut(), |txn| f(v, txn)) }) }) } fn with_map<T>( map: YMap, txn: ImplicitTransaction, f: impl FnOnce(&MapRef, &mut TransactionMut<'static>) -> T, ) -> T { IMAGES_MAP.with(|state| { TXN_STATE.with(|txs| { let v = &state.borrow_mut().maps[&map.ref_]; YTransactionInner::from_transact_mut_f(txn, v, &mut txs.borrow_mut(), |txn| f(v, txn)) }) }) } struct YTransactionInner<'a>(InnerTxn<'a>); enum InnerTxn<'a> { ReadOnly(Rc<Transaction<'static>>), ReadWrite(&'a mut TransactionMut<'static>), } impl<'a> YTransactionInner<'a> { fn from_ref(txn: YTransaction, state: &'a mut TxnState) -> Self { match txn { YTransaction::ReadTransaction(t) => { let txn = &state.transactions[&t.ref_]; YTransactionInner(InnerTxn::ReadOnly(txn.clone())) } YTransaction::WriteTransaction(t) => { let txn = state.transactions_mut.get_mut(&t.ref_).unwrap(); YTransactionInner(InnerTxn::ReadWrite(txn)) } } } fn from_transact<T: Transact>( txn: ImplicitTransaction, transact: &'a T, state: &'a mut TxnState, ) -> Self { txn.map(|t| YTransactionInner::from_ref(t, state)) .unwrap_or_else(|| { YTransactionInner(InnerTxn::ReadOnly(Rc::new(unsafe { std::mem::transmute(transact.transact()) }))) }) } // fn from_transact_mut<T: Transact>( // txn: ImplicitTransaction, // transact: T, // state: &mut TxnState, // ) -> &mut TransactionMut<'static> { // match txn { // Some(YTransaction::WriteTransaction(txn)) => { // state.transactions_mut.get_mut(&txn.ref_).unwrap() // } // // TODO: remove // _ => unsafe { std::mem::transmute(&mut transact.transact_mut()) }, // } // } fn from_transact_mut_f<T: Transact, P>( txn: ImplicitTransaction, transact: T, state: &mut TxnState, f: impl FnOnce(&mut TransactionMut<'static>) -> P, ) -> P { match txn { Some(YTransaction::WriteTransaction(txn)) => { f(state.transactions_mut.get_mut(&txn.ref_).unwrap()) } // TODO: remove _ => { let mut a = transact.transact_mut(); f(unsafe { std::mem::transmute(&mut a) }) } } } fn from_transact_mut_none<T: Transact>( txn: ImplicitTransaction, transact: T, state: &mut TxnState, ) -> Option<&mut TransactionMut<'static>> { match txn { Some(YTransaction::WriteTransaction(txn)) => { Some(state.transactions_mut.get_mut(&txn.ref_).unwrap()) } // TODO: remove _ => None, } } fn try_mut(&mut self) -> Option<&mut TransactionMut<'static>> { match &mut self.0 { InnerTxn::ReadOnly(_) => None, InnerTxn::ReadWrite(txn) => Some(txn), } } fn try_apply(&mut self, update: Update) -> Result<(), String> { if let Some(txn) = self.try_mut() { txn.apply_update(update); Ok(()) } else { Err("cannot apply an update using a read-only transaction".to_string()) } } } impl<'a> ReadTxn for YTransactionInner<'a> { fn store(&self) -> &Store { match &self.0 { InnerTxn::ReadOnly(txn) => txn.store(), InnerTxn::ReadWrite(txn) => txn.store(), } } } enum SharedType<T, P> { Integrated(T), Prelim(P), } impl<T, P> SharedType<T, P> { #[inline(always)] fn new(value: T) -> RefCell<Self> { RefCell::new(SharedType::Integrated(value)) } #[inline(always)] fn prelim(prelim: P) -> RefCell<Self> { RefCell::new(SharedType::Prelim(prelim)) } fn as_integrated(&self) -> Option<&T> { if let SharedType::Integrated(value) = self { Some(value) } else { None } } } struct YTextInner(RefCell<SharedType<TextRef, String>>); // Comment out the following lines to include other generated wit interfaces // use exports::y_crdt_namespace::y_crdt::*; // use y_crdt_namespace::y_crdt::interface_name; // Define a custom type and implement the generated trait for it which represents // implementing all the necessary exported interfaces for this component. struct WitImplementation; fn parse_options(options: YDocOptions) -> Options { let mut opts = Options::default(); options.client_id.map(|v| opts.client_id = v); options.guid.map(|v| opts.guid = v.into()); opts.collection_id = options.collection_id; options.offset_kind.map(|v| { opts.offset_kind = match v { OffsetKind::Utf16 => yrs::OffsetKind::Utf16, OffsetKind::Utf32 => yrs::OffsetKind::Utf32, OffsetKind::Bytes => yrs::OffsetKind::Bytes, } }); options.skip_gc.map(|v| opts.skip_gc = v); options.auto_load.map(|v| opts.auto_load = v); options.should_load.map(|v| opts.should_load = v); opts } impl YDocMethods for WitImplementation { fn y_doc_dispose(doc: YDoc) -> bool { with_mut(|state| state.docs.remove(&doc.ref_).is_some()) } fn y_text_dispose(text: YText) -> bool { with_mut(|state| state.texts.remove(&text.ref_).is_some()) } fn y_array_dispose(array: YArray) -> bool { with_mut(|state| state.arrays.remove(&array.ref_).is_some()) } fn y_map_dispose(map: YMap) -> bool { with_mut(|state| state.maps.remove(&map.ref_).is_some()) } fn y_xml_element_dispose(xml_element: YXmlElement) -> bool { with_mut(|state| state.xml_elements.remove(&xml_element.ref_).is_some()) } fn y_xml_fragment_dispose(xml_fragment: YXmlFragment) -> bool { with_mut(|state| state.xml_fragments.remove(&xml_fragment.ref_).is_some()) } fn y_xml_text_dispose(xml_text: YXmlText) -> bool { with_mut(|state| state.xml_texts.remove(&xml_text.ref_).is_some()) } fn y_transaction_dispose(transaction: YTransaction) -> bool { with_txn_state(|state| match transaction { YTransaction::ReadTransaction(a) => state.transactions.remove(&a.ref_).is_some(), YTransaction::WriteTransaction(a) => state.transactions.remove(&a.ref_).is_some(), }) } fn y_value_dispose(value: YValue) -> bool { match value { YValue::JsonValueItem(_) => false, YValue::YType(YType::YText(a)) => Self::y_text_dispose(a), YValue::YType(YType::YArray(a)) => Self::y_array_dispose(a), YValue::YType(YType::YMap(a)) => Self::y_map_dispose(a), YValue::YType(YType::YXmlElement(a)) => Self::y_xml_element_dispose(a), YValue::YType(YType::YXmlFragment(a)) => Self::y_xml_fragment_dispose(a), YValue::YType(YType::YXmlText(a)) => Self::y_xml_text_dispose(a), YValue::YDoc(a) => Self::y_doc_dispose(a), } } fn y_snapshot_dispose(snapshot: YSnapshot) -> bool { with_mut(|state: &mut GlobalState| state.snapshots.remove(&snapshot.ref_).is_some()) } fn callback_dispose(obs: EventObserver) -> bool { with_mut(|state| state.callbacks.remove(&obs.ref_).is_some()) } fn undo_manager_dispose(obs: UndoManagerRef) -> bool { UNDO_STATE.with(|state| state.borrow_mut().undo_managers.remove(&obs.ref_).is_some()) } // TextRef // ArrayRef // MapRef // XmlElementRef // XmlFragmentRef // XmlTextRef // YTransactionMut fn y_doc_new(options: Option<YDocOptions>) -> YDoc { let options = options.map(parse_options).unwrap_or_default(); with_mut(|m| m.save_doc(Doc::with_options(options))) } fn y_doc_parent_doc(doc: YDoc) -> Option<YDoc> { with_mut(|state| { let img = &state.docs[&doc.ref_]; img.parent_doc().map(|d| state.save_doc(d)) }) } fn y_doc_id(doc: YDoc) -> u64 { operation(doc, |doc| doc.client_id()) } fn y_doc_guid(doc: YDoc) -> String { operation(doc, |doc| doc.guid().to_string()) } fn y_doc_read_transaction(doc: YDoc) -> ReadTransaction { with_mut_all(|state, txs| { let d = unsafe { std::mem::transmute(state.docs[&doc.ref_].transact()) }; txs.save_transaction(d) }) } // TODO: optional origin fn y_doc_write_transaction(doc: YDoc, origin: Vec<u8>) -> WriteTransaction { with_mut_all(|state, txs| { let d = unsafe { std::mem::transmute(state.docs[&doc.ref_].transact_mut()) }; txs.save_transaction_mut(d) }) } fn y_doc_text(doc: YDoc, name: String) -> YText { with_mut(|state| { let d = &state.docs[&doc.ref_]; state.save_text(d.get_or_insert_text(&name)) }) } fn y_doc_array(doc: YDoc, name: String) -> YArray { with_mut(|state| { let d = &state.docs[&doc.ref_]; state.save_array(d.get_or_insert_array(&name)) }) } fn y_doc_map(doc: YDoc, name: String) -> YMap { with_mut(|state| { let d = &state.docs[&doc.ref_]; state.save_map(d.get_or_insert_map(&name)) }) } fn y_doc_xml_fragment(doc: YDoc, _: String) -> YXmlFragment { todo!() } fn y_doc_xml_element(doc: YDoc, _: String) -> YXmlElement { todo!() } fn y_doc_xml_text(doc: YDoc, _: String) -> YXmlText { todo!() } fn y_doc_on_update_v1(doc: YDoc, _: u32) -> EventObserver { todo!() } fn y_doc_subdocs(doc: YDoc, txn: ImplicitTransaction) -> Vec<YDoc> { with_mut_all(|state, txs| { let doc = &state.docs[&doc.ref_]; let list: Vec<_> = YTransactionInner::from_transact(txn, doc, txs) .subdocs() .into_iter() .map(|d| d.clone()) .collect(); list.into_iter() .map(|d| state.save_doc(d.clone())) .collect() }) } fn y_doc_subdoc_guids(doc: YDoc, txn: ImplicitTransaction) -> Vec<String> { with_mut_all(|state, txs| { let doc = &state.docs[&doc.ref_]; YTransactionInner::from_transact(txn, doc, txs) .subdoc_guids() .into_iter() .map(|d| d.to_string()) .collect() }) } fn y_doc_load(doc: YDoc, txn: ImplicitTransaction) { with_mut_all(|state, txs| { let d = &state.docs[&doc.ref_]; if let Some(YTransaction::WriteTransaction(txn)) = txn { let txn = txs.transactions_mut.get_mut(&txn.ref_).unwrap(); d.load(txn) } else { if let Some(parent) = d.parent_doc() { let mut txn = parent.transact_mut(); d.load(&mut txn) } } }) } fn y_doc_destroy(doc: YDoc, txn: ImplicitTransaction) { with_mut_all(|state, txs| { let d = state.docs.get_mut(&doc.ref_).unwrap(); if let Some(YTransaction::WriteTransaction(txn)) = txn { let txn = txs.transactions_mut.get_mut(&txn.ref_).unwrap(); d.destroy(txn) } else { if let Some(parent) = d.parent_doc() { let mut txn = parent.transact_mut(); d.destroy(&mut txn) } } }) } fn y_text_to_delta( text: YText, snapshot: Option<YSnapshot>, prev_snapshot: Option<YSnapshot>, txn: ImplicitTransaction, ) -> Vec<YTextDelta> { with_mut_all(|state, txs| { let v = &state.texts[&text.ref_]; YTransactionInner::from_transact_mut_f(txn, v, txs, |txn| { let hi = snapshot.map(|s| state.snapshots.get(&s.ref_)).flatten(); let lo = prev_snapshot .map(|s| state.snapshots.get(&s.ref_)) .flatten(); // fn changes(change: YChange) -> YChange { // let kind = match change.kind { // ChangeKind::Added => ("added"), // ChangeKind::Removed => ("removed"), // }; // let js: JsValue = js_sys::Object::new().into(); // js_sys::Reflect::set(&js, &JsValue::from("type"), &kind).unwrap(); // js // let result = if let Some(func) = compute_ychange { // let id = change.id.into_js(); // func.call2(&JsValue::UNDEFINED, &kind, &id).unwrap() // } else { // let js: JsValue = js_sys::Object::new().into(); // js_sys::Reflect::set(&js, &JsValue::from("type"), &kind).unwrap(); // js // }; // result // } v.diff_range(txn, hi, lo, |change| change) .into_iter() .map(ytext_change_into_delta) .collect() }) }) } fn snapshot(doc: YDoc) -> YSnapshot { with_mut(|state| { let d = state.docs.get_mut(&doc.ref_).unwrap().transact().snapshot(); state.save_snapshot(d) }) } fn equal_snapshot(left: YSnapshot, right: YSnapshot) -> bool { with(|state| { let left = &state.snapshots[&left.ref_]; let right = &state.snapshots[&right.ref_]; left == right }) } fn encode_snapshot_v1(snapshot: YSnapshot) -> Vec<u8> { with(|state| { let snapshot = &state.snapshots[&snapshot.ref_]; snapshot.encode_v1() }) } fn encode_snapshot_v2(snapshot: YSnapshot) -> Vec<u8> { with(|state| { let snapshot = &state.snapshots[&snapshot.ref_]; snapshot.encode_v2() }) } fn decode_snapshot_v1(snapshot: Vec<u8>) -> Result<YSnapshot, Error> { with_mut(|state| { let s = Snapshot::decode_v1(&snapshot).map_err(|e| { format!("failed to deserialize snapshot using lib0 v1 decoding. {e}") })?; Ok(state.save_snapshot(s)) }) } fn decode_snapshot_v2(snapshot: Vec<u8>) -> Result<YSnapshot, Error> { with_mut(|state| { let s = Snapshot::decode_v2(&snapshot).map_err(|e| { format!("failed to deserialize snapshot using lib0 v2 decoding. {e}") })?; Ok(state.save_snapshot(s)) }) } fn encode_state_from_snapshot_v1(doc: YDoc, snapshot: YSnapshot) -> Result<Vec<u8>, Error> { with_mut(|state| { let mut encoder = EncoderV1::new(); let snapshot = &state.snapshots[&snapshot.ref_]; match state.docs[&doc.ref_] .transact() .encode_state_from_snapshot(snapshot, &mut encoder) { Ok(_) => Ok(encoder.to_vec()), Err(e) => Err(e.to_string()), } }) } fn encode_state_from_snapshot_v2(doc: YDoc, snapshot: YSnapshot) -> Result<Vec<u8>, Error> { with_mut(|state| { let mut encoder = EncoderV2::new(); let snapshot = &state.snapshots[&snapshot.ref_]; match state.docs[&doc.ref_] .transact() .encode_state_from_snapshot(snapshot, &mut encoder) { Ok(_) => Ok(encoder.to_vec()), Err(e) => Err(e.to_string()), } }) } // TODO: end new methods fn encode_state_vector(doc: YDoc) -> Vec<u8> { operation(doc, |doc| doc.transact().state_vector().encode_v1()) } fn encode_state_as_update(doc: YDoc, vector: Option<Vec<u8>>) -> Result<Vec<u8>, String> { operation(doc, |doc| { let s = doc.transact(); diff_v1(&s, vector) }) } fn encode_state_as_update_v2(doc: YDoc, vector: Option<Vec<u8>>) -> Result<Vec<u8>, String> { operation(doc, |doc| { let s = doc.transact(); diff_v2(&s, vector) }) } fn apply_update(doc: YDoc, diff: Vec<u8>, origin: Vec<u8>) -> Result<(), String> { operation(doc, |doc| { let mut txn = doc.transact_mut(); let mut decoder = DecoderV1::from(diff.as_slice()); match Update::decode(&mut decoder) { Ok(update) => Ok(txn.apply_update(update)), Err(e) => Err(e.to_string()), } }) } fn apply_update_v2(doc: YDoc, diff: Vec<u8>, origin: Vec<u8>) -> Result<(), String> { operation(doc, |doc| { let mut txn = doc.transact_mut(); match Update::decode_v2(&diff) { Ok(update) => Ok(txn.apply_update(update)), Err(e) => Err(e.to_string()), } }) } fn transaction_origin(t: YTransaction) -> Option<Vec<u8>> { // TODO: Not mut with_txn_state(|state| match t { YTransaction::ReadTransaction(t) => None, YTransaction::WriteTransaction(t) => state.transactions_mut[&t.ref_] .origin() .map(|r| r.as_ref().to_vec()), }) } fn transaction_commit(t: YTransaction) { with_txn_state(|state| match &t { YTransaction::ReadTransaction(t) => { state.transactions.remove(&t.ref_); } YTransaction::WriteTransaction(t) => { state.transactions_mut.remove(&t.ref_).unwrap().commit() } }) } fn transaction_state_vector_v1(t: YTransaction) -> Vec<u8> { with_txn(t, |t| t.state_vector().encode_v1().to_vec()) } fn transaction_diff_v1(t: YTransaction, vector: Option<Vec<u8>>) -> Result<Vec<u8>, String> { with_txn(t, |t| diff_v1(t, vector)) } fn transaction_diff_v2(txn: YTransaction, vector: Option<Vec<u8>>) -> Result<Vec<u8>, String> { with_txn(txn, |txn| diff_v2(txn, vector)) } fn transaction_apply_v1(txn: YTransaction, diff: Vec<u8>) -> Result<(), Error> { match txn { YTransaction::ReadTransaction(_) => { Err("Cannot apply update to read transaction".to_string()) } YTransaction::WriteTransaction(txn) => with_txn_state(|txs| { let txn = txs.transactions_mut.get_mut(&txn.ref_).unwrap(); let mut decoder = DecoderV1::from(diff.as_slice()); match Update::decode(&mut decoder) { Ok(update) => Ok(txn.apply_update(update)), Err(e) => Err(e.to_string()), } }), } } fn transaction_apply_v2(txn: YTransaction, diff: Vec<u8>) -> Result<(), String> { match txn { YTransaction::ReadTransaction(_) => { Err("Cannot apply update to read transaction".to_string()) } YTransaction::WriteTransaction(txn) => with_txn_state(|txs| { let txn = txs.transactions_mut.get_mut(&txn.ref_).unwrap(); match Update::decode_v2(diff.as_slice()) { Ok(update) => Ok(txn.apply_update(update)), Err(e) => Err(e.to_string()), } }), } } fn transaction_encode_update(t: YTransaction) -> Vec<u8> { match t { YTransaction::ReadTransaction(_) => vec![0u8, 0u8], YTransaction::WriteTransaction(txn) => { with_txn_state(|state| state.transactions_mut[&txn.ref_].encode_update_v1()) } } } fn transaction_encode_update_v2(t: YTransaction) -> Vec<u8> { match t { YTransaction::ReadTransaction(_) => vec![0u8, 0u8], YTransaction::WriteTransaction(txn) => { with_txn_state(|state| state.transactions_mut[&txn.ref_].encode_update_v2()) } } } fn y_text_new(init: Option<String>) -> YText { // TODO: implement prelim todo!() } fn y_text_prelim(text: YText) -> bool { // TODO: implement prelim false } fn y_text_length(text: YText, txn: ImplicitTransaction) -> u32 { with_mut_all(|state, txs| { let text = &state.texts[&text.ref_]; let txn = YTransactionInner::from_transact(txn, text, txs); text.len(&txn) as u32 }) } fn y_text_to_string(text: YText, txn: ImplicitTransaction) -> String { with_mut_all(|state, txs| { let text = &state.texts[&text.ref_]; let txn = YTransactionInner::from_transact(txn, text, txs); text.get_string(&txn) }) } fn y_text_to_json(text: YText, txn: ImplicitTransaction) -> String { // TODO: use to_json Self::y_text_to_string(text, txn) } fn y_text_insert( text: YText, index: u32, chunk: String, attributes: Option<JsonObject>, txn: ImplicitTransaction, ) { with_text(text, txn, |v, txn| { let chunk = &chunk; if let Some(attrs) = attributes.map(parse_attrs) { v.insert_with_attributes(txn, index, chunk, attrs) } else { v.insert(txn, index, chunk) } }) } fn y_text_insert_embed( text: YText, index: u32, // TODO: embed cloud be other y-value types embed: JsonValueItem, attributes: Option<JsonObject>, txn: ImplicitTransaction, ) { with_text(text, txn, |v, txn| { let embed = map_json_value_any(embed); if let Some(attrs) = attributes.map(parse_attrs) { v.insert_embed_with_attributes(txn, index, embed, attrs); } else { v.insert_embed(txn, index, embed); } }) } fn y_text_format( text: YText, index: u32, length: u32, attributes: JsonObject, txn: ImplicitTransaction, ) { with_text(text, txn, |v, txn| { let attrs = parse_attrs(attributes); v.format(txn, index, length, attrs); }) } fn y_text_push( text: YText, chunk: String, attributes: Option<JsonObject>, txn: ImplicitTransaction, ) { with_text(text, txn, |v, txn| { let chunk = &chunk; if let Some(attrs) = attributes.map(parse_attrs) { let index = v.len(txn); v.insert_with_attributes(txn, index, chunk, attrs) } else { v.push(txn, chunk) } }) } fn y_text_delete(text: YText, index: u32, length: u32, txn: ImplicitTransaction) { with_text(text, txn, |v, txn| { v.remove_range(txn, index, length); }) } fn y_text_observe(text: YText, function_id: u32) -> EventObserver { with_mut(|state| { let v = state.texts.get_mut(&text.ref_).unwrap(); let subs = unsafe { std::mem::transmute(v.observe(move |e_txn, e| { let event = map_text_event(text.clone(), e_txn, e); event_callback(function_id, &event) })) }; state.save_callback(subs) }) } fn y_text_observe_deep(text: YText, function_id: u32) -> EventObserver { with_mut(|state| { let v = state.texts.get_mut(&text.ref_).unwrap(); let subs = unsafe { std::mem::transmute(v.observe_deep(observer_deep(function_id))) }; state.save_callback(subs) }) } fn y_array_new(_: Option<JsonArray>) -> YArray { // TODO: implement prelim todo!() } fn y_array_prelim(array: YArray) -> bool { // TODO: implement prelim false } fn y_array_length(array: YArray, txn: ImplicitTransaction) -> u32 { with_mut_all(|state, txs| { let v = &state.arrays[&array.ref_]; let txn = YTransactionInner::from_transact(txn, v, txs); v.len(&txn) }) } fn y_array_to_json(array: YArray, txn: ImplicitTransaction) -> JsonValueItem { with_mut_all(|state, txs| { let v = &state.arrays[&array.ref_]; let txn = YTransactionInner::from_transact(txn, v, txs); map_any_json_value(v.to_json(&txn))
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
true
juancastillo0/wasm_run
https://github.com/juancastillo0/wasm_run/blob/14b14337c181ac0592c306e8c6a68802e86d1a5b/packages/wasm_packages/y_crdt/y_crdt_wasm/src/lib_expand.rs
packages/wasm_packages/y_crdt/y_crdt_wasm/src/lib_expand.rs
#![feature(prelude_import)] #[prelude_import] use std::prelude::rust_2021::*; #[macro_use] extern crate std; pub type YEvent = y_crdt_namespace::y_crdt::y_doc_methods_types::YEvent; pub type YUndoEvent = y_crdt_namespace::y_crdt::y_doc_methods_types::YUndoEvent; #[allow(clippy::all)] pub fn event_callback(function_id: u32, event: &YEvent) { #[allow(unused_imports)] use wit_bindgen::rt::{alloc, vec::Vec, string::String}; unsafe { let mut cleanup_list = Vec::new(); let ( result157_0, result157_1, result157_2, result157_3, result157_4, result157_5, ) = match event { y_crdt_namespace::y_crdt::y_doc_methods_types::YEvent::YArrayEvent(e) => { let y_crdt_namespace::y_crdt::y_doc_methods_types::YArrayEvent { target: target0, delta: delta0, path: path0, } = e; let y_crdt_namespace::y_crdt::y_doc_methods_types::YArray { ref_: ref_1, } = target0; let vec35 = delta0; let len35 = vec35.len() as i32; let layout35 = alloc::Layout::from_size_align_unchecked( vec35.len() * 12, 4, ); let result35 = if layout35.size() != 0 { let ptr = alloc::alloc(layout35); if ptr.is_null() { alloc::handle_alloc_error(layout35); } ptr } else { ::core::ptr::null_mut() }; for (i, e) in vec35.into_iter().enumerate() { let base = result35 as i32 + (i as i32) * 12; { match e { y_crdt_namespace::y_crdt::y_doc_methods_types::YArrayDelta::YArrayDeltaInsert( e, ) => { *((base + 0) as *mut u8) = (0i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::YArrayDeltaInsert { insert: insert2, } = e; let vec32 = insert2; let len32 = vec32.len() as i32; let layout32 = alloc::Layout::from_size_align_unchecked( vec32.len() * 40, 8, ); let result32 = if layout32.size() != 0 { let ptr = alloc::alloc(layout32); if ptr.is_null() { alloc::handle_alloc_error(layout32); } ptr } else { ::core::ptr::null_mut() }; for (i, e) in vec32.into_iter().enumerate() { let base = result32 as i32 + (i as i32) * 40; { match e { y_crdt_namespace::y_crdt::y_doc_methods_types::YValue::JsonValueItem( e, ) => { *((base + 0) as *mut u8) = (0i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::JsonValueItem { item: item3, array_references: array_references3, map_references: map_references3, } = e; use y_crdt_namespace::y_crdt::y_doc_methods_types::JsonValue as V8; match item3 { V8::Null => { *((base + 8) as *mut u8) = (0i32) as u8; } V8::Undefined => { *((base + 8) as *mut u8) = (1i32) as u8; } V8::Boolean(e) => { *((base + 8) as *mut u8) = (2i32) as u8; *((base + 16) as *mut u8) = (match e { true => 1, false => 0, }) as u8; } V8::Number(e) => { *((base + 8) as *mut u8) = (3i32) as u8; *((base + 16) as *mut f64) = wit_bindgen::rt::as_f64(e); } V8::BigInt(e) => { *((base + 8) as *mut u8) = (4i32) as u8; *((base + 16) as *mut i64) = wit_bindgen::rt::as_i64(e); } V8::Str(e) => { *((base + 8) as *mut u8) = (5i32) as u8; let vec4 = e; let ptr4 = vec4.as_ptr() as i32; let len4 = vec4.len() as i32; *((base + 20) as *mut i32) = len4; *((base + 16) as *mut i32) = ptr4; } V8::Buffer(e) => { *((base + 8) as *mut u8) = (6i32) as u8; let vec5 = e; let ptr5 = vec5.as_ptr() as i32; let len5 = vec5.len() as i32; *((base + 20) as *mut i32) = len5; *((base + 16) as *mut i32) = ptr5; } V8::Array(e) => { *((base + 8) as *mut u8) = (7i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::JsonArrayRef { index: index6, } = e; *((base + 16) as *mut i32) = wit_bindgen::rt::as_i32(index6); } V8::Map(e) => { *((base + 8) as *mut u8) = (8i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::JsonMapRef { index: index7, } = e; *((base + 16) as *mut i32) = wit_bindgen::rt::as_i32(index7); } } let vec15 = array_references3; let len15 = vec15.len() as i32; let layout15 = alloc::Layout::from_size_align_unchecked( vec15.len() * 8, 4, ); let result15 = if layout15.size() != 0 { let ptr = alloc::alloc(layout15); if ptr.is_null() { alloc::handle_alloc_error(layout15); } ptr } else { ::core::ptr::null_mut() }; for (i, e) in vec15.into_iter().enumerate() { let base = result15 as i32 + (i as i32) * 8; { let vec14 = e; let len14 = vec14.len() as i32; let layout14 = alloc::Layout::from_size_align_unchecked( vec14.len() * 16, 8, ); let result14 = if layout14.size() != 0 { let ptr = alloc::alloc(layout14); if ptr.is_null() { alloc::handle_alloc_error(layout14); } ptr } else { ::core::ptr::null_mut() }; for (i, e) in vec14.into_iter().enumerate() { let base = result14 as i32 + (i as i32) * 16; { use y_crdt_namespace::y_crdt::y_doc_methods_types::JsonValue as V13; match e { V13::Null => { *((base + 0) as *mut u8) = (0i32) as u8; } V13::Undefined => { *((base + 0) as *mut u8) = (1i32) as u8; } V13::Boolean(e) => { *((base + 0) as *mut u8) = (2i32) as u8; *((base + 8) as *mut u8) = (match e { true => 1, false => 0, }) as u8; } V13::Number(e) => { *((base + 0) as *mut u8) = (3i32) as u8; *((base + 8) as *mut f64) = wit_bindgen::rt::as_f64(e); } V13::BigInt(e) => { *((base + 0) as *mut u8) = (4i32) as u8; *((base + 8) as *mut i64) = wit_bindgen::rt::as_i64(e); } V13::Str(e) => { *((base + 0) as *mut u8) = (5i32) as u8; let vec9 = e; let ptr9 = vec9.as_ptr() as i32; let len9 = vec9.len() as i32; *((base + 12) as *mut i32) = len9; *((base + 8) as *mut i32) = ptr9; } V13::Buffer(e) => { *((base + 0) as *mut u8) = (6i32) as u8; let vec10 = e; let ptr10 = vec10.as_ptr() as i32; let len10 = vec10.len() as i32; *((base + 12) as *mut i32) = len10; *((base + 8) as *mut i32) = ptr10; } V13::Array(e) => { *((base + 0) as *mut u8) = (7i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::JsonArrayRef { index: index11, } = e; *((base + 8) as *mut i32) = wit_bindgen::rt::as_i32(index11); } V13::Map(e) => { *((base + 0) as *mut u8) = (8i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::JsonMapRef { index: index12, } = e; *((base + 8) as *mut i32) = wit_bindgen::rt::as_i32(index12); } } } } *((base + 4) as *mut i32) = len14; *((base + 0) as *mut i32) = result14 as i32; cleanup_list.extend_from_slice(&[(result14, layout14)]); } } *((base + 28) as *mut i32) = len15; *((base + 24) as *mut i32) = result15 as i32; let vec24 = map_references3; let len24 = vec24.len() as i32; let layout24 = alloc::Layout::from_size_align_unchecked( vec24.len() * 8, 4, ); let result24 = if layout24.size() != 0 { let ptr = alloc::alloc(layout24); if ptr.is_null() { alloc::handle_alloc_error(layout24); } ptr } else { ::core::ptr::null_mut() }; for (i, e) in vec24.into_iter().enumerate() { let base = result24 as i32 + (i as i32) * 8; { let vec23 = e; let len23 = vec23.len() as i32; let layout23 = alloc::Layout::from_size_align_unchecked( vec23.len() * 24, 8, ); let result23 = if layout23.size() != 0 { let ptr = alloc::alloc(layout23); if ptr.is_null() { alloc::handle_alloc_error(layout23); } ptr } else { ::core::ptr::null_mut() }; for (i, e) in vec23.into_iter().enumerate() { let base = result23 as i32 + (i as i32) * 24; { let (t16_0, t16_1) = e; let vec17 = t16_0; let ptr17 = vec17.as_ptr() as i32; let len17 = vec17.len() as i32; *((base + 4) as *mut i32) = len17; *((base + 0) as *mut i32) = ptr17; use y_crdt_namespace::y_crdt::y_doc_methods_types::JsonValue as V22; match t16_1 { V22::Null => { *((base + 8) as *mut u8) = (0i32) as u8; } V22::Undefined => { *((base + 8) as *mut u8) = (1i32) as u8; } V22::Boolean(e) => { *((base + 8) as *mut u8) = (2i32) as u8; *((base + 16) as *mut u8) = (match e { true => 1, false => 0, }) as u8; } V22::Number(e) => { *((base + 8) as *mut u8) = (3i32) as u8; *((base + 16) as *mut f64) = wit_bindgen::rt::as_f64(e); } V22::BigInt(e) => { *((base + 8) as *mut u8) = (4i32) as u8; *((base + 16) as *mut i64) = wit_bindgen::rt::as_i64(e); } V22::Str(e) => { *((base + 8) as *mut u8) = (5i32) as u8; let vec18 = e; let ptr18 = vec18.as_ptr() as i32; let len18 = vec18.len() as i32; *((base + 20) as *mut i32) = len18; *((base + 16) as *mut i32) = ptr18; } V22::Buffer(e) => { *((base + 8) as *mut u8) = (6i32) as u8; let vec19 = e; let ptr19 = vec19.as_ptr() as i32; let len19 = vec19.len() as i32; *((base + 20) as *mut i32) = len19; *((base + 16) as *mut i32) = ptr19; } V22::Array(e) => { *((base + 8) as *mut u8) = (7i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::JsonArrayRef { index: index20, } = e; *((base + 16) as *mut i32) = wit_bindgen::rt::as_i32(index20); } V22::Map(e) => { *((base + 8) as *mut u8) = (8i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::JsonMapRef { index: index21, } = e; *((base + 16) as *mut i32) = wit_bindgen::rt::as_i32(index21); } } } } *((base + 4) as *mut i32) = len23; *((base + 0) as *mut i32) = result23 as i32; cleanup_list.extend_from_slice(&[(result23, layout23)]); } } *((base + 36) as *mut i32) = len24; *((base + 32) as *mut i32) = result24 as i32; cleanup_list .extend_from_slice( &[(result15, layout15), (result24, layout24)], ); } y_crdt_namespace::y_crdt::y_doc_methods_types::YValue::YDoc( e, ) => { *((base + 0) as *mut u8) = (1i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::YDoc { ref_: ref_25, } = e; *((base + 8) as *mut i32) = wit_bindgen::rt::as_i32(ref_25); } y_crdt_namespace::y_crdt::y_doc_methods_types::YValue::YType( e, ) => { *((base + 0) as *mut u8) = (2i32) as u8; match e { y_crdt_namespace::y_crdt::y_doc_methods_types::YType::YText( e, ) => { *((base + 8) as *mut u8) = (0i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::YText { ref_: ref_26, } = e; *((base + 12) as *mut i32) = wit_bindgen::rt::as_i32(ref_26); } y_crdt_namespace::y_crdt::y_doc_methods_types::YType::YArray( e, ) => { *((base + 8) as *mut u8) = (1i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::YArray { ref_: ref_27, } = e; *((base + 12) as *mut i32) = wit_bindgen::rt::as_i32(ref_27); } y_crdt_namespace::y_crdt::y_doc_methods_types::YType::YMap( e, ) => { *((base + 8) as *mut u8) = (2i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::YMap { ref_: ref_28, } = e; *((base + 12) as *mut i32) = wit_bindgen::rt::as_i32(ref_28); } y_crdt_namespace::y_crdt::y_doc_methods_types::YType::YXmlFragment( e, ) => { *((base + 8) as *mut u8) = (3i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::YXmlFragment { ref_: ref_29, } = e; *((base + 12) as *mut i32) = wit_bindgen::rt::as_i32(ref_29); } y_crdt_namespace::y_crdt::y_doc_methods_types::YType::YXmlElement( e, ) => { *((base + 8) as *mut u8) = (4i32) as u8; let y_crdt_namespace::y_crdt::y_doc_methods_types::YXmlElement { ref_: ref_30, } = e; *((base + 12) as *mut i32) = wit_bindgen::rt::as_i32(ref_30); } y_crdt_namespace::y_crdt::y_doc_methods_types::YType::YXmlText( e, ) => {
rust
MIT
14b14337c181ac0592c306e8c6a68802e86d1a5b
2026-01-04T20:15:50.642058Z
true
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_test/src/lib.rs
crates/synd_test/src/lib.rs
use std::path::PathBuf; pub mod jwt; pub mod kvsd; pub mod mock; pub const TEST_EMAIL: &str = "ymgyt@ymgyt.io"; pub const TEST_USER_ID: &str = "899cf3fa5afc0aa1"; pub const GITHUB_INVALID_TOKEN: &str = "github_invalid_token"; pub fn certificate() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("..") .join("..") .join("etc") .join("dev") .join("self_signed_certs") .join("certificate.pem") } pub fn certificate_buff() -> String { std::fs::read_to_string(certificate()).unwrap() } pub fn private_key() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("..") .join("..") .join("etc") .join("dev") .join("self_signed_certs") .join("private_key.pem") } pub fn private_key_buff() -> Vec<u8> { std::fs::read(private_key()).unwrap() } pub fn temp_dir() -> tempfile::TempDir { tempfile::TempDir::new().unwrap() }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_test/src/kvsd.rs
crates/synd_test/src/kvsd.rs
use std::{future::pending, path::PathBuf, time::Duration}; use futures_util::TryFutureExt; use tokio::net::{TcpListener, TcpStream}; pub async fn run_kvsd( kvsd_host: String, kvsd_port: u16, kvsd_username: String, kvsd_password: String, root_dir: PathBuf, ) -> anyhow::Result<kvsd::client::tcp::Client<TcpStream>> { let mut config = kvsd::config::Config::default(); // Setup user credential. config.kvsd.users = vec![kvsd::core::UserEntry { username: kvsd_username, password: kvsd_password, }]; config.server.set_disable_tls(&mut Some(true)); // Test Server listen addr let addr = (kvsd_host, kvsd_port); let mut initializer = kvsd::config::Initializer::from_config(config); initializer.set_root_dir(root_dir); initializer.set_listener(TcpListener::bind(addr.clone()).await.unwrap()); initializer.init_dir().await.unwrap(); let _server_handler = tokio::spawn(initializer.run_kvsd(pending::<()>())); let handshake = async { loop { match kvsd::client::tcp::UnauthenticatedClient::insecure_from_addr(&addr.0, addr.1) .and_then(|client| client.authenticate("test", "test")) .await { Ok(client) => break client, Err(_) => tokio::time::sleep(Duration::from_millis(500)).await, } } }; let client = tokio::time::timeout(Duration::from_secs(5), handshake).await?; Ok(client) }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_test/src/jwt.rs
crates/synd_test/src/jwt.rs
use std::{ ops::{Add, Sub}, time::Duration, }; use chrono::{DateTime, Utc}; use synd_auth::jwt; use crate::{TEST_EMAIL, private_key_buff}; pub(super) const DUMMY_GOOGLE_JWT_KEY_ID: &str = "dummy-google-jwt-kid-1"; pub const DUMMY_GOOGLE_CLIENT_ID: &str = "dummy_google_client_id"; pub(super) fn google_test_jwt() -> String { let header = jsonwebtoken::Header { typ: Some("JST".into()), // google use Allgorithm::RS256, but our testing private key use ECDSA alg: jsonwebtoken::Algorithm::ES256, kid: Some(DUMMY_GOOGLE_JWT_KEY_ID.to_owned()), ..Default::default() }; let encoding_key = jsonwebtoken::EncodingKey::from_ec_pem(private_key_buff().as_slice()).unwrap(); let claims = jwt::google::Claims { iss: "https://accounts.google.com".into(), azp: DUMMY_GOOGLE_CLIENT_ID.to_owned(), aud: DUMMY_GOOGLE_CLIENT_ID.to_owned(), sub: "123456789".into(), email: TEST_EMAIL.to_owned(), email_verified: true, iat: Utc::now().timestamp(), exp: Utc::now().add(Duration::from_secs(60 * 60)).timestamp(), }; jsonwebtoken::encode(&header, &claims, &encoding_key).unwrap() } /// Return encoded expired jwt and `expired_at` pub fn google_expired_jwt() -> (String, DateTime<Utc>) { let header = jsonwebtoken::Header { typ: Some("JST".into()), // google use Allgorithm::RS256, but our testing private key use ECDSA alg: jsonwebtoken::Algorithm::ES256, kid: Some(DUMMY_GOOGLE_JWT_KEY_ID.to_owned()), ..Default::default() }; let encoding_key = jsonwebtoken::EncodingKey::from_ec_pem(private_key_buff().as_slice()).unwrap(); let iat = Utc::now().sub(Duration::from_secs(60 * 60 * 24)); let exp = Utc::now() .sub(Duration::from_secs(60 * 60 * 24)) .add(Duration::from_secs(60 * 60)); let claims = jwt::google::Claims { iss: "https://accounts.google.com".into(), azp: DUMMY_GOOGLE_CLIENT_ID.to_owned(), aud: DUMMY_GOOGLE_CLIENT_ID.to_owned(), sub: "123456789".into(), email: TEST_EMAIL.to_owned(), email_verified: true, iat: iat.timestamp(), exp: exp.timestamp(), }; ( jsonwebtoken::encode(&header, &claims, &encoding_key).unwrap(), exp, ) }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_test/src/mock/feed.rs
crates/synd_test/src/mock/feed.rs
use axum::{ extract::Path, http::StatusCode, response::{IntoResponse, Response}, }; use serde::Deserialize; #[derive(Deserialize)] pub(super) struct FeedParams { feed: String, } pub(super) async fn feed(Path(FeedParams { feed }): Path<FeedParams>) -> impl IntoResponse { let content = match feed.as_str() { "twir_atom" => include_str!("feeddata/twir_atom.xml"), "o11y_news" => include_str!("feeddata/o11y_news_rss.xml"), _ => unreachable!("undefined feed fixture posted"), }; content.into_response() } #[derive(Deserialize)] pub(super) struct FeedErrorParams { error: String, } pub(super) async fn feed_error(Path(FeedErrorParams { error }): Path<FeedErrorParams>) -> Response { match error.as_str() { "internal" => StatusCode::INTERNAL_SERVER_ERROR.into_response(), "malformed" => "malformed xml".into_response(), _ => unreachable!("undefined feed fixture posted"), } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_test/src/mock/mod.rs
crates/synd_test/src/mock/mod.rs
use std::{collections::HashMap, sync::atomic::AtomicUsize, time::Duration}; use axum::{ Form, Json, Router, http::{HeaderMap, StatusCode}, response::{IntoResponse, Response}, routing::{get, patch, post, put}, }; use headers::{Authorization, Header, authorization::Bearer}; use serde::Serialize; use synd_auth::device_flow::{ DeviceAccessTokenErrorResponse, DeviceAccessTokenRequest, DeviceAccessTokenResponse, DeviceAuthorizationRequest, DeviceAuthorizationResponse, provider::google::DeviceAccessTokenRequest as GoogleDeviceAccessTokenRequest, }; use tokio::net::TcpListener; use crate::{GITHUB_INVALID_TOKEN, TEST_EMAIL, certificate_buff, jwt::DUMMY_GOOGLE_JWT_KEY_ID}; mod feed; pub mod github; async fn github_device_authorization( Form(DeviceAuthorizationRequest { scope, .. }): Form<DeviceAuthorizationRequest<'static>>, ) -> Result<Json<DeviceAuthorizationResponse>, StatusCode> { tracing::debug!(%scope, "Handle device authorization request"); if scope != "user:email" { return Err(StatusCode::BAD_REQUEST); } let res = DeviceAuthorizationResponse { device_code: "DC001".into(), user_code: "UC123456".into(), verification_uri: Some("https://syndicationd.ymgyt.io/test".parse().unwrap()), verification_url: None, verification_uri_complete: None, expires_in: 3600, interval: Some(1), // for test speed }; Ok(Json(res)) } async fn google_device_authorization( Form(DeviceAuthorizationRequest { scope, .. }): Form<DeviceAuthorizationRequest<'static>>, ) -> Result<Json<DeviceAuthorizationResponse>, StatusCode> { tracing::debug!(%scope, "Handle device authorization request"); if scope != "email" { return Err(StatusCode::BAD_REQUEST); } let res = DeviceAuthorizationResponse { device_code: "DCGGL1".into(), user_code: "UCGGL1".into(), verification_uri: Some("https://syndicationd.ymgyt.io/test".parse().unwrap()), verification_url: None, verification_uri_complete: None, expires_in: 3600, interval: Some(1), // for test speed }; Ok(Json(res)) } async fn github_device_access_token( Form(DeviceAccessTokenRequest { device_code, .. }): Form<DeviceAccessTokenRequest<'static>>, ) -> Response { // Check error handling static TRY: AtomicUsize = AtomicUsize::new(0); let count = TRY.fetch_add(1, std::sync::atomic::Ordering::Relaxed); tracing::debug!("Handle device access token request"); if device_code != "DC001" { return StatusCode::BAD_REQUEST.into_response(); } match count { 0 => ( StatusCode::BAD_REQUEST, Json(DeviceAccessTokenErrorResponse { error: synd_auth::device_flow::DeviceAccessTokenErrorCode::AuthorizationPending, error_description: None, error_uri: None, }), ) .into_response(), 1 => ( StatusCode::PRECONDITION_REQUIRED, Json(DeviceAccessTokenErrorResponse { error: synd_auth::device_flow::DeviceAccessTokenErrorCode::SlowDown, error_description: None, error_uri: None, }), ) .into_response(), _ => { let res = DeviceAccessTokenResponse { access_token: "gh_dummy_access_token".into(), token_type: String::new(), expires_in: None, refresh_token: None, id_token: None, }; Json(res).into_response() } } } async fn google_device_access_token( Form(GoogleDeviceAccessTokenRequest { code, .. }): Form< GoogleDeviceAccessTokenRequest<'static>, >, ) -> Result<Json<DeviceAccessTokenResponse>, StatusCode> { tracing::debug!("Handle device access token request"); if code != "DCGGL1" { return Err(StatusCode::BAD_REQUEST); } // mock user input duration tokio::time::sleep(Duration::from_secs(1)).await; // Generate jwt let jwt = crate::jwt::google_test_jwt(); let res = DeviceAccessTokenResponse { access_token: "gh_dummy_access_token".into(), token_type: String::new(), expires_in: Some(600), refresh_token: Some("dummy_refresh_token".into()), id_token: Some(jwt), }; Ok(Json(res)) } async fn github_graphql_viewer( headers: HeaderMap, _query: String, ) -> Result<Json<serde_json::Value>, StatusCode> { let auth = headers.get(Authorization::<Bearer>::name()).unwrap(); let auth = Authorization::<Bearer>::decode(&mut std::iter::once(auth)).unwrap(); let token = auth.token(); tracing::debug!("Got token: `{token}`"); if token == GITHUB_INVALID_TOKEN { Err(StatusCode::UNAUTHORIZED) } else { let response = serde_json::json!({ "data": { "viewer": { "email": TEST_EMAIL, } } }); Ok(Json(response)) } } // mock https://www.googleapis.com/oauth2/v1/certs async fn google_jwt_pem() -> Json<HashMap<String, String>> { let key_id = DUMMY_GOOGLE_JWT_KEY_ID.to_owned(); let cert = certificate_buff(); Json([(key_id, cert)].into_iter().collect()) } #[derive(Serialize)] struct GoogleOauth2TokenResponse { expires_in: i64, id_token: String, } // mock https://oauth2.googleapis.com/token async fn google_oauth2_token() -> Json<GoogleOauth2TokenResponse> { let id_token = crate::jwt::google_test_jwt(); let expires_in = 60 * 30; Json(GoogleOauth2TokenResponse { expires_in, id_token, }) } pub async fn serve(listener: TcpListener) -> anyhow::Result<()> { let case_1 = Router::new() .route( "/github/login/device/code", post(github_device_authorization), ) .route( "/github/login/oauth/access_token", post(github_device_access_token), ) .route( "/google/login/device/code", post(google_device_authorization), ) .route( "/google/login/oauth/access_token", post(google_device_access_token), ); let router = Router::new() .nest("/case1", case_1) .route("/github/graphql", post(github_graphql_viewer)) .route( "/github/rest/notifications", get(github::notifications::list), ) .route( "/github/rest/notifications/threads/{thread}", patch(github::notifications::mark_as_done), ) .route( "/github/rest/notifications/threads/{thread}/subscription", put(github::notifications::unsubscribe_thread), ) .route("/github/rest/graphql", post(github::gql::graphql)) .route("/google/oauth2/v1/certs", get(google_jwt_pem)) .route("/google/oauth2/token", post(google_oauth2_token)) .route("/feed/error/{error}", get(feed::feed_error)) .route("/feed/{feed}", get(feed::feed)) .layer(axum::middleware::from_fn(debug_mw)); let addr = listener.local_addr().ok(); tracing::info!(?addr, "Serving..."); axum::serve(listener, router).await?; Ok(()) } async fn debug_mw( req: axum::extract::Request, next: axum::middleware::Next, ) -> axum::response::Response { tracing::debug!("Incoming {req:?}"); next.run(req).await }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_test/src/mock/github.rs
crates/synd_test/src/mock/github.rs
use serde::Deserialize; use serde_json::json; pub mod notifications { use std::{ops::Sub, sync::LazyLock}; #[allow(clippy::wildcard_imports)] use super::*; use axum::{ Json, extract::{Path, Query}, http::StatusCode, response::{IntoResponse, Response}, }; use chrono::{DateTime, Duration, TimeZone, Utc}; use serde::Serialize; use serde_json::Value; #[allow(unused)] #[derive(Deserialize, Debug)] pub struct Notifications { all: bool, participating: bool, per_page: u8, page: u8, } pub static NOW: LazyLock<DateTime<Utc>> = LazyLock::new(|| Utc::with_ymd_and_hms(&Utc, 2024, 7, 5, 8, 0, 0).unwrap()); pub async fn list(Query(n): Query<Notifications>) -> Response { if n.page == 1 { let notifications = json!({ "items": [ { "id": 1, "repository": repo_a(), "subject": { "title": "title AA1", "url": "https://api.ymgyt.io/repos/sakura/repo-1/issues/1", "type": "issue", }, "reason": "mention", "unread": true, "updated_at": NOW.sub(Duration::hours(1)), "url": "https://api.ymgyt.io/notifications/threads/1", }, { "id": 2, "repository": repo_a(), "subject": { "title": "title AA2", "url": "https://api.ymgyt.io/repos/sakura/repo-a/pulls/1", "type": "pullrequest", }, "reason": "mention", "unread": true, "updated_at": NOW.sub(Duration::hours(2)), "url": "https://api.ymgyt.io/notifications/threads/2", }, { "id": 3, "repository": repo_private(), "subject": { "title": "Add feature foo", "url": "https://api.ymgyt.io/repos/sakura/repo-private/pulls/2", "type": "pullrequest", }, "reason": "subscribed", "unread": true, "updated_at": NOW.sub(Duration::hours(3)), "url": "https://api.ymgyt.io/notifications/threads/3", }, { "id": 4, "repository": repo_private(), "subject": { "title": "Request Review", "url": "https://api.ymgyt.io/repos/sakura/repo-private/pulls/3", "type": "pullrequest", }, "reason": "review_requested", "unread": true, "updated_at": NOW.sub(Duration::hours(4)), "url": "https://api.ymgyt.io/notifications/threads/4", } ], }); notifications.to_string().into_response() } else { json!({ "items": [], }) .to_string() .into_response() } } fn repo_a() -> Value { json!({ "id": 1, "name": "repo-a", "full_name": "sakura/repo-a", "private": false, "url": "https://github.ymgyt.io/sakura/repo-a/", }) } fn repo_private() -> Value { json!({ "id": 2, "name": "repo-private", "full_name": "sakura/repo-private", "private": true, "url": "https://github.ymgyt.io/sakura/repo-private/", }) } #[derive(Deserialize)] pub struct MarkAsDoneParams { thread: u64, } pub async fn mark_as_done( Path(MarkAsDoneParams { thread }): Path<MarkAsDoneParams>, ) -> impl IntoResponse { tracing::info!("Mark as done thread: {thread}"); StatusCode::OK } #[derive(Deserialize)] pub struct UnsubscribeThreadParams { thread: u64, } #[derive(Serialize)] pub struct UnsubscribeThreadResponse {} pub async fn unsubscribe_thread( Path(UnsubscribeThreadParams { thread }): Path<UnsubscribeThreadParams>, ) -> Json<UnsubscribeThreadResponse> { tracing::info!("Unsubscribe thread: {thread}"); Json(UnsubscribeThreadResponse {}) } } pub mod gql { use axum::{ Json, response::{IntoResponse, Response}, }; use serde::Deserialize; use serde_json::Value; #[derive(Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Payload { operation_name: String, _query: String, variables: Value, } pub async fn graphql(Json(payload): Json<Payload>) -> Response { match payload.operation_name.as_str() { "IssueQuery" => { let issue = payload.variables["issueNumber"].as_u64().unwrap(); let repo_owner = payload.variables["repositoryOwner"].as_str().unwrap(); let repo_name = payload.variables["repositoryName"].as_str().unwrap(); let fixture = format!("{repo_owner}_{repo_name}_issues_{issue}"); match fixture.as_str() { "sakura_repo-a_issues_1" => { include_str!("./githubdata/sakura_repo-a_issues_1.json").into_response() } _ => panic!("Unexpected issue fixture: {fixture}"), } } "PullRequestQuery" => { let pr = payload.variables["pullRequestNumber"].as_u64().unwrap(); let repo_owner = payload.variables["repositoryOwner"].as_str().unwrap(); let repo_name = payload.variables["repositoryName"].as_str().unwrap(); let fixture = format!("{repo_owner}_{repo_name}_prs_{pr}"); match fixture.as_str() { "sakura_repo-a_prs_1" => { include_str!("./githubdata/sakura_repo-a_prs_1.json").into_response() } "sakura_repo-private_prs_2" => { include_str!("./githubdata/sakura_repo-private_prs_2.json").into_response() } "sakura_repo-private_prs_3" => { include_str!("./githubdata/sakura_repo-private_prs_3.json").into_response() } _ => panic!("Unexpected pr fixture: {fixture}"), } } unexpected => panic!("Unexpected operation: {unexpected}"), } } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_stdx/src/prelude.rs
crates/synd_stdx/src/prelude.rs
pub use tracing::{debug, error, info, trace, warn};
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_stdx/src/lib.rs
crates/synd_stdx/src/lib.rs
#[cfg(feature = "byte")] pub mod byte; #[cfg(feature = "conf")] pub mod conf; pub mod fs; pub mod io; pub mod prelude; pub mod time;
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_stdx/src/time/mod.rs
crates/synd_stdx/src/time/mod.rs
#[cfg(feature = "humantime")] pub mod humantime;
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_stdx/src/time/humantime/parse.rs
crates/synd_stdx/src/time/humantime/parse.rs
use std::time::Duration; pub type DurationError = humantime::DurationError; /// Parse the string representation of a duration, such as "30s". pub fn parse_duration(s: &str) -> Result<Duration, DurationError> { humantime::parse_duration(s) }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_stdx/src/time/humantime/mod.rs
crates/synd_stdx/src/time/humantime/mod.rs
mod parse; pub use parse::{DurationError, parse_duration}; pub mod de;
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_stdx/src/time/humantime/de.rs
crates/synd_stdx/src/time/humantime/de.rs
use std::time::Duration; use serde::{Deserialize, Deserializer}; use crate::time::humantime; pub fn parse_duration_opt<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error> where D: Deserializer<'de>, { match Option::<String>::deserialize(deserializer)? { Some(duration) => match humantime::parse_duration(&duration) { Ok(duration) => Ok(Some(duration)), Err(err) => Err(serde::de::Error::custom(err)), }, None => Ok(None), } } #[cfg(test)] mod tests { use super::*; #[test] fn should_parse() { #[derive(Deserialize)] struct Data { #[serde(default, deserialize_with = "parse_duration_opt")] d: Option<Duration>, } let s = r#"{"d": "30sec" }"#; let data: Data = serde_json::from_str(s).unwrap(); assert_eq!(data.d, Some(Duration::from_secs(30))); let s = r#"{"d": null }"#; let data: Data = serde_json::from_str(s).unwrap(); assert_eq!(data.d, None); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_stdx/src/byte/mod.rs
crates/synd_stdx/src/byte/mod.rs
pub type Byte = byte_unit::Byte; #[cfg(test)] mod tests { use super::*; #[test] fn parse() { assert_eq!(4_u64 * 1024 * 1024, Byte::parse_str("4MiB", true).unwrap()); assert_eq!(4_u64 * 1000 * 1000, Byte::parse_str("4MB", true).unwrap()); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_stdx/src/io/mod.rs
crates/synd_stdx/src/io/mod.rs
#[cfg(feature = "color")] pub mod color;
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_stdx/src/io/color/support.rs
crates/synd_stdx/src/io/color/support.rs
#[derive(PartialEq, Eq)] pub enum ColorSupport { Supported, NotSupported, } /// Return whether or not the current environment supports ANSI color output. pub fn is_color_supported() -> ColorSupport { use supports_color::Stream; if supports_color::on(Stream::Stdout).is_some() { ColorSupport::Supported } else { ColorSupport::NotSupported } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_stdx/src/io/color/mod.rs
crates/synd_stdx/src/io/color/mod.rs
mod support; pub use support::{ColorSupport, is_color_supported};
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_stdx/src/conf/mod.rs
crates/synd_stdx/src/conf/mod.rs
/// `Entry` holds candidates for the final value for the configuration. #[derive(Debug)] pub struct Entry<T> { flag: Option<T>, file: Option<T>, default: T, } impl<T> Entry<T> { pub fn with_default(default: T) -> Self { Self { flag: None, file: None, default, } } #[must_use] pub fn with_file(self, file: Option<T>) -> Self { Self { file, ..self } } #[must_use] pub fn with_flag(self, flag: Option<T>) -> Self { Self { flag, ..self } } pub fn resolve_ref(&self) -> &T { self.flag .as_ref() .or(self.file.as_ref()) .unwrap_or(&self.default) } } impl<T> Entry<T> where T: Copy, { pub fn resolve(&self) -> T { *self.resolve_ref() } } #[cfg(test)] mod tests { use super::*; #[test] fn resolve_order() { let flag = 10; let file = 9; let default = 8; let e = Entry { flag: Some(flag), file: Some(file), default, }; assert_eq!(e.resolve(), flag, "flag should have highest priority"); let e = Entry { flag: None, file: Some(file), default, }; assert_eq!( e.resolve(), file, "file should have higher priority over default" ); let e = Entry { flag: None, file: None, default, }; assert_eq!(e.resolve(), default); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_stdx/src/fs/mod.rs
crates/synd_stdx/src/fs/mod.rs
use std::{fs::File, io, path::Path}; pub mod fsimpl; #[cfg_attr(feature = "mock", mockall::automock)] pub trait FileSystem { #[cfg_attr(feature = "mock", mockall::concretize)] fn create_dir_all<P: AsRef<Path>>(&self, path: P) -> io::Result<()>; #[cfg_attr(feature = "mock", mockall::concretize)] fn create_file<P: AsRef<Path>>(&self, path: P) -> io::Result<File>; #[cfg_attr(feature = "mock", mockall::concretize)] fn open_file<P: AsRef<Path>>(&self, path: P) -> io::Result<File>; #[cfg_attr(feature = "mock", mockall::concretize)] fn remove_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()>; }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_stdx/src/fs/fsimpl.rs
crates/synd_stdx/src/fs/fsimpl.rs
use std::{fs::File, io, path::Path}; #[derive(Debug, Clone, Default)] pub struct FileSystem {} impl FileSystem { pub fn new() -> Self { Self {} } } impl super::FileSystem for FileSystem { fn create_dir_all<P: AsRef<Path>>(&self, path: P) -> std::io::Result<()> { std::fs::create_dir_all(path) } fn create_file<P: AsRef<Path>>(&self, path: P) -> io::Result<File> { std::fs::File::create(path) } fn open_file<P: AsRef<Path>>(&self, path: P) -> io::Result<File> { std::fs::File::open(path) } fn remove_file<P: AsRef<Path>>(&self, path: P) -> std::io::Result<()> { std::fs::remove_file(path) } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_auth/src/config.rs
crates/synd_auth/src/config.rs
pub(crate) mod github { pub(crate) const CLIENT_ID: &str = "6652e5931c88e528a851"; } pub(crate) mod google { pub(crate) const CLIENT_ID: &str = concat!( "387487893172-", "u28ebbv8lbl157jjeb7blsts8b5impio", ".apps.googleusercontent.com" ); // This value is distributed as binary anyway, so it cannot be secret pub(crate) const CLIENT_ID2: &str = concat!("GOCSPX-", "igWWNOqW7hsV_", "08qdDx1P2s8YqlG"); }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_auth/src/lib.rs
crates/synd_auth/src/lib.rs
//! syndicationd authentication crate providing features //! related OAuth and JWT. #![warn(rustdoc::broken_intra_doc_links)] mod config; pub mod device_flow; pub mod jwt; const USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_auth/src/jwt/mod.rs
crates/synd_auth/src/jwt/mod.rs
pub mod google;
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_auth/src/jwt/google.rs
crates/synd_auth/src/jwt/google.rs
use std::{ borrow::Cow, collections::HashMap, sync::{Arc, RwLock}, time::Duration, }; use chrono::{DateTime, TimeZone, Utc}; use jsonwebtoken::{Algorithm, DecodingKey, Validation}; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use thiserror::Error; use crate::{USER_AGENT, config}; type Kid = String; #[derive(Debug, Error)] pub enum JwtError { #[error("fetch pem: {0}")] FetchPem(#[from] reqwest::Error), #[error("decoding key pem not found")] DecodingKeyPemNotFound, #[error("decode id token: {0}")] Decode(#[from] jsonwebtoken::errors::Error), #[error("invalid jwt header: {0}")] InvalidHeader(String), #[error("refresh id token: {0}")] RefreshToken(reqwest::Error), #[error("unexpected algorithm: {0:?}")] UnexpectedAlgorithm(Algorithm), } #[allow(dead_code)] #[derive(Debug, Serialize, Deserialize)] pub struct Claims { pub iss: String, pub azp: String, pub aud: String, pub sub: String, pub email: String, pub email_verified: bool, pub iat: i64, pub exp: i64, } impl Claims { /// Return `DateTime` at when `Claims` expire pub fn expired_at(&self) -> DateTime<Utc> { Utc.timestamp_opt(self.exp, 0) .single() .unwrap_or_else(Utc::now) } } #[derive(Clone)] pub struct JwtService { client: Client, client_id: Cow<'static, str>, client_secret: Cow<'static, str>, pem_endpoint: Url, token_endpoint: Url, key_cache: Arc<RwLock<HashMap<Kid, Arc<DecodingKey>>>>, } impl Default for JwtService { fn default() -> Self { Self::new(config::google::CLIENT_ID, config::google::CLIENT_ID2) } } impl JwtService { const PEM_ENDPOINT: &'static str = "https://www.googleapis.com/oauth2/v1/certs"; const TOKEN_ENDPOINT: &'static str = "https://oauth2.googleapis.com/token"; const ISSUERS: &'static [&'static str] = &["https://accounts.google.com", "accounts.google.com"]; pub fn new( client_id: impl Into<Cow<'static, str>>, client_secret: impl Into<Cow<'static, str>>, ) -> Self { let client = reqwest::ClientBuilder::new() .user_agent(USER_AGENT) .connect_timeout(Duration::from_secs(10)) .timeout(Duration::from_secs(10)) .build() .unwrap(); Self { client, client_id: client_id.into(), client_secret: client_secret.into(), pem_endpoint: Url::parse(Self::PEM_ENDPOINT).unwrap(), token_endpoint: Url::parse(Self::TOKEN_ENDPOINT).unwrap(), key_cache: Arc::new(RwLock::default()), } } #[must_use] pub fn with_pem_endpoint(self, pem_endpoint: Url) -> Self { Self { pem_endpoint, ..self } } #[must_use] pub fn with_token_endpoint(self, token_endpoint: Url) -> Self { Self { token_endpoint, ..self } } /// Decode and validate JWT id token pub async fn decode_id_token(&self, id_token: &str) -> Result<Claims, JwtError> { // decode header to get kid let header = jsonwebtoken::decode_header(id_token).map_err(JwtError::Decode)?; let kid = header .kid .ok_or_else(|| JwtError::InvalidHeader("kid not found".into()))?; let decoding_key = self.lookup_decoding_pem(&kid, header.alg).await?; let validation = { let mut v = Validation::new(header.alg); v.set_audience(&[self.client_id.as_ref()]); v.set_issuer(Self::ISSUERS); v.set_required_spec_claims(&["exp"]); v.validate_exp = true; v }; jsonwebtoken::decode(id_token, &decoding_key, &validation) .map_err(JwtError::Decode) .map(|data| data.claims) } /// Decode JWT id token without signature validation pub fn decode_id_token_insecure( &self, id_token: &str, validate_exp: bool, ) -> Result<Claims, JwtError> { let decoding_key = DecodingKey::from_secret(&[]); let validation = { let mut v = Validation::default(); v.insecure_disable_signature_validation(); v.set_audience(&[self.client_id.as_ref()]); v.set_issuer(Self::ISSUERS); v.set_required_spec_claims(&["exp"]); v.validate_exp = validate_exp; v }; jsonwebtoken::decode(id_token, &decoding_key, &validation) .map_err(JwtError::Decode) .map(|data| data.claims) } async fn lookup_decoding_pem( &self, kid: &str, alg: Algorithm, ) -> Result<Arc<DecodingKey>, JwtError> { if let Some(key) = self.key_cache.read().unwrap().get(kid) { return Ok(key.clone()); } self.refresh_key_cache(alg).await?; self.key_cache .read() .unwrap() .get(kid) .cloned() .ok_or(JwtError::DecodingKeyPemNotFound) } async fn refresh_key_cache(&self, alg: Algorithm) -> Result<(), JwtError> { let keys = self .fetch_decoding_key_pem() .await? .into_iter() .filter_map(|key| { let result = match alg { Algorithm::ES256 => DecodingKey::from_ec_pem(key.pem.as_bytes()), Algorithm::RS256 | Algorithm::RS384 | Algorithm::RS512 => { DecodingKey::from_rsa_pem(key.pem.as_bytes()) } _ => { let err = JwtError::UnexpectedAlgorithm(alg); tracing::error!("{err:?}"); return None; } }; match result { Ok(de_key) => Some((key.kid, Arc::new(de_key))), Err(err) => { tracing::warn!("failed to create jwt decoding key from pem: {err}"); None } } }); let mut cache = self.key_cache.write().unwrap(); keys.for_each(|(kid, de_key)| { cache.insert(kid, de_key); }); Ok(()) } async fn fetch_decoding_key_pem(&self) -> Result<Vec<DecodingKeyPem>, JwtError> { async fn call( client: &Client, endpoint: Url, ) -> Result<HashMap<String, String>, reqwest::Error> { let payload = client .get(endpoint) .header(http::header::ACCEPT, "application/json") .send() .await? .error_for_status()? .json::<HashMap<String, String>>() .await?; Ok(payload) } let payload = call(&self.client, self.pem_endpoint.clone()) .await .map_err(JwtError::FetchPem)?; Ok(payload .into_iter() .map(|(kid, pem)| DecodingKeyPem { kid, pem }) .collect()) } /// Refresh id token /// <https://developers.google.com/identity/gsi/web/guides/devices#obtain_an_id_token_and_refresh_token> pub async fn refresh_id_token(&self, refresh_token: &str) -> Result<String, JwtError> { #[derive(Serialize)] struct Request<'s> { client_id: &'s str, client_secret: &'s str, refresh_token: &'s str, grant_type: &'static str, } #[derive(Deserialize)] struct Response { #[allow(dead_code)] expires_in: i64, id_token: String, } async fn call( client: &Client, endpoint: Url, payload: &Request<'_>, ) -> Result<Response, reqwest::Error> { client .post(endpoint) .header(http::header::ACCEPT, "application/json") .form(payload) .send() .await? .error_for_status()? .json() .await } // https://developers.google.com/identity/protocols/oauth2/limited-input-device#offline let request = &Request { client_id: self.client_id.as_ref(), client_secret: self.client_secret.as_ref(), refresh_token, grant_type: "refresh_token", }; let response = call(&self.client, self.token_endpoint.clone(), request) .await .map_err(JwtError::RefreshToken)?; Ok(response.id_token) } } struct DecodingKeyPem { kid: String, pem: String, }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_auth/src/device_flow/mod.rs
crates/synd_auth/src/device_flow/mod.rs
use std::{borrow::Cow, time::Duration}; use http::{StatusCode, Uri}; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use tracing::debug; use crate::USER_AGENT; pub mod provider; pub trait Provider: private::Sealed { type DeviceAccessTokenRequest<'d>: Serialize + Send where Self: 'd; fn device_authorization_endpoint(&self) -> Url; fn token_endpoint(&self) -> Url; fn device_authorization_request(&'_ self) -> DeviceAuthorizationRequest<'_>; fn device_access_token_request<'d, 'p: 'd>( &'p self, device_code: &'d str, ) -> Self::DeviceAccessTokenRequest<'d>; } mod private { use crate::device_flow::provider; pub trait Sealed {} impl Sealed for provider::Github {} impl Sealed for provider::Google {} } #[derive(Clone)] pub struct DeviceFlow<P> { provider: P, client: Client, } impl<P> DeviceFlow<P> { pub fn new(provider: P) -> Self { let client = reqwest::ClientBuilder::new() .user_agent(USER_AGENT) .connect_timeout(Duration::from_secs(10)) .timeout(Duration::from_secs(10)) .build() .unwrap(); Self { provider, client } } } impl<P: Provider> DeviceFlow<P> { #[tracing::instrument(skip(self))] pub async fn device_authorize_request(&self) -> anyhow::Result<DeviceAuthorizationResponse> { let response = self .client .post(self.provider.device_authorization_endpoint()) .header(http::header::ACCEPT, "application/json") .form(&self.provider.device_authorization_request()) .send() .await? .error_for_status()? .json::<DeviceAuthorizationResponse>() .await?; Ok(response) } pub async fn poll_device_access_token( &self, device_code: String, interval: Option<i64>, ) -> anyhow::Result<DeviceAccessTokenResponse> { // poll to check if user authorized the device macro_rules! continue_or_abort { ( $response_bytes:ident ) => {{ let err_response = serde_json::from_slice::<DeviceAccessTokenErrorResponse>(&$response_bytes)?; if err_response.error.should_continue_to_poll() { debug!(error_code=?err_response.error,interval, "Continue to poll"); let interval = interval.unwrap_or(5); #[allow(clippy::cast_sign_loss)] tokio::time::sleep(Duration::from_secs(interval as u64)).await; } else { anyhow::bail!( "authorization server or oidc provider respond with {err_response:?}" ) } }}; } let response = loop { let response = self .client .post(self.provider.token_endpoint()) .header(http::header::ACCEPT, "application/json") .form(&self.provider.device_access_token_request(&device_code)) .send() .await?; match response.status() { StatusCode::OK => { let full = response.bytes().await?; if let Ok(response) = serde_json::from_slice::<DeviceAccessTokenResponse>(&full) { break response; } continue_or_abort!(full); } // Google return 428(Precondition required) StatusCode::BAD_REQUEST | StatusCode::PRECONDITION_REQUIRED => { let full = response.bytes().await?; continue_or_abort!(full); } other => { let error_msg = response.text().await.unwrap_or_default(); anyhow::bail!( "Failed to authenticate. authorization server respond with {other} {error_msg}" ) } } }; Ok(response) } } /// <https://datatracker.ietf.org/doc/html/rfc8628#section-3.1> #[derive(Serialize, Deserialize, Debug)] pub struct DeviceAuthorizationRequest<'s> { pub client_id: Cow<'s, str>, pub scope: Cow<'s, str>, } /// <https://datatracker.ietf.org/doc/html/rfc8628#section-3.2> #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DeviceAuthorizationResponse { /// device verification code pub device_code: String, /// end user verification code pub user_code: String, /// end user verification uri on the authorization server #[serde(with = "http_serde_ext::uri::option", default)] pub verification_uri: Option<Uri>, /// Google use verification_"url" #[serde(with = "http_serde_ext::uri::option", default)] pub verification_url: Option<Uri>, /// a verification uri that includes `user_code` which is designed for non-textual transmission. #[allow(unused)] #[serde(with = "http_serde_ext::uri::option", default)] pub verification_uri_complete: Option<Uri>, /// the lifetime in seconds of the `device_code` and `user_code` #[allow(unused)] pub expires_in: i64, /// the minimum amount of time in seconds that the client should wait between polling requests to the token endpoint /// if no value is provided, clients must use 5 as the default pub interval: Option<i64>, } impl DeviceAuthorizationResponse { pub fn verification_uri(&self) -> &Uri { self.verification_uri .as_ref() .or(self.verification_url.as_ref()) .expect("verification uri or url not found") } } #[derive(Serialize, Deserialize)] pub struct DeviceAccessTokenRequest<'s> { /// Value MUST be set to "urn:ietf:params:oauth:grant-type:device_code" grant_type: Cow<'static, str>, /// The device verification code, `device_code` from the device authorization response pub device_code: Cow<'s, str>, pub client_id: Cow<'s, str>, } impl<'s> DeviceAccessTokenRequest<'s> { const GRANT_TYPE: &'static str = "urn:ietf:params:oauth:grant-type:device_code"; #[must_use] pub fn new(device_code: impl Into<Cow<'s, str>>, client_id: &'s str) -> Self { Self { grant_type: Self::GRANT_TYPE.into(), device_code: device_code.into(), client_id: client_id.into(), } } } /// Successful Response /// <https://datatracker.ietf.org/doc/html/rfc6749#section-5.1> #[derive(Serialize, Deserialize, Debug, Clone)] pub struct DeviceAccessTokenResponse { /// the access token issued by the authorization server pub access_token: String, pub token_type: String, /// the lifetime in seconds of the access token pub expires_in: Option<i64>, // OIDC usecase pub refresh_token: Option<String>, pub id_token: Option<String>, } /// <https://datatracker.ietf.org/doc/html/rfc6749#section-5.2> #[derive(Serialize, Deserialize, Debug)] pub struct DeviceAccessTokenErrorResponse { pub error: DeviceAccessTokenErrorCode, #[allow(unused)] pub error_description: Option<String>, // error if there is no field on deserializing, maybe bug on http_serde_ext crate ? #[allow(unused)] #[serde(with = "http_serde_ext::uri::option", skip_deserializing)] pub error_uri: Option<Uri>, } #[derive(PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum DeviceAccessTokenErrorCode { AuthorizationPending, SlowDown, AccessDenied, ExpiredToken, InvalidRequest, InvalidClient, InvalidGrant, UnauthorizedClient, UnsupportedGrantType, InvalidScope, IncorrectDeviceCode, } impl DeviceAccessTokenErrorCode { /// The `authorization_pending` and `slow_down` error codes define particularly unique behavior, as they indicate that the OAuth client should continue to poll the token endpoint by repeating the token request (implementing the precise behavior defined above) pub fn should_continue_to_poll(&self) -> bool { use DeviceAccessTokenErrorCode::{AuthorizationPending, SlowDown}; *self == AuthorizationPending || *self == SlowDown } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_auth/src/device_flow/provider/mod.rs
crates/synd_auth/src/device_flow/provider/mod.rs
pub mod github; pub mod google; pub use {github::Github, google::Google};
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_auth/src/device_flow/provider/google.rs
crates/synd_auth/src/device_flow/provider/google.rs
use std::borrow::Cow; use reqwest::Url; use serde::{Deserialize, Serialize}; use crate::{ config, device_flow::{DeviceAuthorizationRequest, Provider}, }; #[derive(Clone)] pub struct Google { client_id: Cow<'static, str>, client_secret: Cow<'static, str>, device_authorization_endpoint: Url, token_endpoint: Url, } impl Default for Google { fn default() -> Self { Self::new(config::google::CLIENT_ID, config::google::CLIENT_ID2) } } impl Google { const DEVICE_AUTHORIZATION_ENDPOINT: &'static str = "https://oauth2.googleapis.com/device/code"; const TOKEN_ENDPOINT: &'static str = "https://oauth2.googleapis.com/token"; /// <https://developers.google.com/identity/gsi/web/guides/devices#obtain_an_id_token_and_refresh_token> const GRANT_TYPE: &'static str = "http://oauth.net/grant_type/device/1.0"; /// <https://developers.google.com/identity/gsi/web/guides/devices#obtain_a_user_code_and_verification_url> const SCOPE: &'static str = "email"; pub fn new( client_id: impl Into<Cow<'static, str>>, client_secret: impl Into<Cow<'static, str>>, ) -> Self { Self { client_id: client_id.into(), client_secret: client_secret.into(), device_authorization_endpoint: Url::parse(Self::DEVICE_AUTHORIZATION_ENDPOINT).unwrap(), token_endpoint: Url::parse(Self::TOKEN_ENDPOINT).unwrap(), } } #[must_use] pub fn with_device_authorization_endpoint(self, endpoint: Url) -> Self { Self { device_authorization_endpoint: endpoint, ..self } } #[must_use] pub fn with_token_endpoint(self, endpoint: Url) -> Self { Self { token_endpoint: endpoint, ..self } } } #[derive(Serialize, Deserialize)] pub struct DeviceAccessTokenRequest<'s> { grant_type: Cow<'static, str>, pub code: Cow<'s, str>, pub client_id: Cow<'s, str>, pub client_secret: Cow<'s, str>, } impl Provider for Google { type DeviceAccessTokenRequest<'d> = DeviceAccessTokenRequest<'d>; fn device_authorization_endpoint(&self) -> Url { self.device_authorization_endpoint.clone() } fn token_endpoint(&self) -> Url { self.token_endpoint.clone() } fn device_authorization_request(&'_ self) -> DeviceAuthorizationRequest<'_> { DeviceAuthorizationRequest { client_id: self.client_id.clone(), scope: Self::SCOPE.into(), } } fn device_access_token_request<'d, 'p: 'd>( &'p self, device_code: &'d str, ) -> DeviceAccessTokenRequest<'d> { DeviceAccessTokenRequest { grant_type: Self::GRANT_TYPE.into(), code: device_code.into(), client_id: self.client_id.clone(), client_secret: self.client_secret.clone(), } } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_auth/src/device_flow/provider/github.rs
crates/synd_auth/src/device_flow/provider/github.rs
use std::borrow::Cow; use reqwest::Url; use crate::{ config, device_flow::{DeviceAccessTokenRequest, DeviceAuthorizationRequest, Provider}, }; #[derive(Clone)] pub struct Github { client_id: Cow<'static, str>, device_authorization_endpoint: Url, token_endpoint: Url, } impl Default for Github { fn default() -> Self { Self::new(config::github::CLIENT_ID) } } impl Github { const DEVICE_AUTHORIZATION_ENDPOINT: &'static str = "https://github.com/login/device/code"; const TOKEN_ENDPOINT: &'static str = "https://github.com/login/oauth/access_token"; // https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps const SCOPE: &'static str = "user:email"; pub fn new(client_id: impl Into<Cow<'static, str>>) -> Self { Self { client_id: client_id.into(), device_authorization_endpoint: Url::parse(Self::DEVICE_AUTHORIZATION_ENDPOINT).unwrap(), token_endpoint: Url::parse(Self::TOKEN_ENDPOINT).unwrap(), } } #[must_use] pub fn with_device_authorization_endpoint(self, endpoint: Url) -> Self { Self { device_authorization_endpoint: endpoint, ..self } } #[must_use] pub fn with_token_endpoint(self, endpoint: Url) -> Self { Self { token_endpoint: endpoint, ..self } } } impl Provider for Github { type DeviceAccessTokenRequest<'d> = DeviceAccessTokenRequest<'d>; fn device_authorization_endpoint(&self) -> Url { self.device_authorization_endpoint.clone() } fn token_endpoint(&self) -> reqwest::Url { self.token_endpoint.clone() } fn device_authorization_request(&'_ self) -> DeviceAuthorizationRequest<'_> { DeviceAuthorizationRequest { client_id: self.client_id.clone(), scope: Self::SCOPE.into(), } } fn device_access_token_request<'d, 'p: 'd>( &'p self, device_code: &'d str, ) -> DeviceAccessTokenRequest<'d> { DeviceAccessTokenRequest::new(device_code, self.client_id.as_ref()) } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_o11y/src/lib.rs
crates/synd_o11y/src/lib.rs
//! syndicationd observability crate providing features //! related to tracing, opentelemetry, and other observability //! functionalities. #![warn(rustdoc::broken_intra_doc_links)] use ::opentelemetry::KeyValue; pub mod health_check; pub mod opentelemetry; pub mod tracing_subscriber; pub use opentelemetry::OpenTelemetryGuard; pub use tracing_subscriber::opentelemetry_layer; /// Request id key for opentelemetry baggage pub const REQUEST_ID_KEY: &str = "request.id"; /// Generate random request id pub fn request_id() -> String { // https://stackoverflow.com/questions/54275459/how-do-i-create-a-random-string-by-sampling-from-alphanumeric-characters use rand::distr::{Alphanumeric, SampleString}; Alphanumeric.sample_string(&mut rand::rng(), 10) } /// Generate random request id key value pub fn request_id_key_value() -> KeyValue { KeyValue::new(REQUEST_ID_KEY, request_id()) }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_o11y/src/health_check.rs
crates/synd_o11y/src/health_check.rs
//! RFC Draft Health Check Response Format for HTTP APIs implementation //! [RFC Draft](https://datatracker.ietf.org/doc/html/draft-inadarei-api-health-check) use core::fmt; use std::borrow::Cow; use serde::{Deserialize, Serialize}; /// Indicates whether the service status is acceptable or not. #[derive(Default, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Status { /// healthy #[default] Pass, /// Unhealthy Fail, /// healthy, with some concerns Warn, } impl fmt::Display for Status { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Status::Pass => f.write_str("pass"), Status::Fail => f.write_str("fail"), Status::Warn => f.write_str("warn"), } } } /// Represents Api Health #[derive(Default, Debug, Serialize, Deserialize)] pub struct Health { pub status: Status, pub version: Option<Cow<'static, str>>, pub description: Option<Cow<'static, str>>, } impl Health { /// [RFC API Health Response](https://datatracker.ietf.org/doc/html/draft-inadarei-api-health-check#name-api-health-response) pub const CONTENT_TYPE: &'static str = "application/health+json"; pub fn pass() -> Self { Self { status: Status::Pass, ..Default::default() } } #[must_use] pub fn with_version(self, version: impl Into<Cow<'static, str>>) -> Self { Self { version: Some(version.into()), ..self } } #[must_use] pub fn with_description(self, description: impl Into<Cow<'static, str>>) -> Self { Self { description: Some(description.into()), ..self } } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_o11y/src/opentelemetry/resource.rs
crates/synd_o11y/src/opentelemetry/resource.rs
use opentelemetry::KeyValue; use opentelemetry_sdk::resource::EnvResourceDetector; use opentelemetry_semantic_conventions::{ SCHEMA_URL, resource::{SERVICE_NAME, SERVICE_NAMESPACE, SERVICE_VERSION}, }; use std::borrow::Cow; pub use opentelemetry_sdk::Resource; /// Return the [`Resource`] of opentelemetry. /// Check and merge the environment variables specified in the specification. pub fn resource( service_name: impl Into<Cow<'static, str>>, service_version: impl Into<Cow<'static, str>>, ) -> Resource { Resource::builder() .with_schema_url( [ (SERVICE_NAME, service_name.into()), (SERVICE_VERSION, service_version.into()), (SERVICE_NAMESPACE, "syndicationd".into()), ] .into_iter() .map(|(key, value)| KeyValue::new(key, value)), SCHEMA_URL, ) .with_detectors(&[Box::new(EnvResourceDetector::new())]) .build() }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_o11y/src/opentelemetry/guard.rs
crates/synd_o11y/src/opentelemetry/guard.rs
use opentelemetry_sdk::{ logs::SdkLoggerProvider, metrics::SdkMeterProvider, trace::SdkTracerProvider, }; use tracing::warn; #[expect(clippy::struct_field_names)] /// `OpenTelemetry` terminination process handler pub struct OpenTelemetryGuard { pub(crate) tracer_provider: SdkTracerProvider, pub(crate) meter_provider: SdkMeterProvider, pub(crate) logger_provider: SdkLoggerProvider, } impl Drop for OpenTelemetryGuard { fn drop(&mut self) { // https://github.com/open-telemetry/opentelemetry-rust/blob/main/docs/migration_0.28.md#tracing-shutdown-changes if let Err(err) = self.tracer_provider.shutdown() { warn!("{err}"); } if let Err(err) = self.meter_provider.shutdown() { warn!("{err}"); } if let Err(err) = self.logger_provider.shutdown() { warn!("{err}"); } } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_o11y/src/opentelemetry/propagation.rs
crates/synd_o11y/src/opentelemetry/propagation.rs
use opentelemetry::propagation::TextMapCompositePropagator; use opentelemetry_sdk::propagation::{BaggagePropagator, TraceContextPropagator}; pub mod http { use crate::opentelemetry::extension::*; use opentelemetry_http::{HeaderExtractor, HeaderInjector}; /// Inject current opentelemetry context into given headers pub fn inject(cx: &opentelemetry::Context, headers: &mut reqwest::header::HeaderMap) { opentelemetry::global::get_text_map_propagator(|propagator| { propagator.inject_context(cx, &mut HeaderInjector(headers)); }); } pub fn inject_with_baggage<T, I>( cx: &opentelemetry::Context, headers: &mut reqwest::header::HeaderMap, baggage: T, ) where T: IntoIterator<Item = I>, I: Into<opentelemetry::baggage::KeyValueMetadata>, { inject(&cx.with_baggage(baggage), headers); } pub fn extract(headers: &axum::http::HeaderMap) -> opentelemetry::Context { opentelemetry::global::get_text_map_propagator(|propagator| { propagator.extract(&HeaderExtractor(headers)) }) } } /// Configure `TraceContext` and Baggage propagator then set as global propagator pub fn init_propagation() { let trace_propagator = TraceContextPropagator::new(); let baggage_propagator = BaggagePropagator::new(); let composite_propagator = TextMapCompositePropagator::new(vec![ Box::new(trace_propagator), Box::new(baggage_propagator), ]); opentelemetry::global::set_text_map_propagator(composite_propagator); }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_o11y/src/opentelemetry/mod.rs
crates/synd_o11y/src/opentelemetry/mod.rs
mod resource; pub use resource::{Resource, resource}; mod propagation; pub use propagation::{http, init_propagation}; pub use opentelemetry::KeyValue; mod guard; pub use guard::OpenTelemetryGuard; pub mod extension { pub use opentelemetry::baggage::BaggageExt as _; pub use tracing_opentelemetry::OpenTelemetrySpanExt as _; }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_o11y/src/tracing_subscriber/initializer.rs
crates/synd_o11y/src/tracing_subscriber/initializer.rs
use crate::{ OpenTelemetryGuard, opentelemetry::init_propagation, opentelemetry_layer, tracing_subscriber::{audit, otel_metrics::metrics_event_filter}, }; const LOG_DIRECTIVE_ENV: &str = "SYND_LOG"; const DEFAULT_LOG_DIRECTIVE: &str = "info"; pub struct TracingInitializer { app_name: Option<&'static str>, app_version: Option<&'static str>, otlp_endpoint: Option<String>, trace_sampler_ratio: f64, enable_ansi: bool, show_code_location: bool, show_target: bool, log_directive_env: Option<&'static str>, } impl Default for TracingInitializer { fn default() -> Self { Self { app_name: None, app_version: None, otlp_endpoint: None, trace_sampler_ratio: 1., enable_ansi: true, show_code_location: false, show_target: true, log_directive_env: None, } } } impl TracingInitializer { /// Initialize tracing Subscriber with layers pub fn init(self) -> Option<OpenTelemetryGuard> { use tracing_subscriber::{ Layer as _, Registry, filter::EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt as _, }; let Self { app_name: Some(app_name), app_version: Some(app_version), otlp_endpoint, trace_sampler_ratio, enable_ansi, show_code_location, show_target, log_directive_env, } = self else { panic!() }; let (otel_layer, otel_guard) = match otlp_endpoint .as_deref() .filter(|s| !s.is_empty()) .map(|endpoint| { opentelemetry_layer(endpoint, app_name, app_version, trace_sampler_ratio) }) { Some((otel_layer, otel_guard)) => (Some(otel_layer), Some(otel_guard)), _ => (None, None), }; Registry::default() .with( fmt::Layer::new() .with_ansi(enable_ansi) .with_timer(fmt::time::ChronoLocal::rfc_3339()) .with_file(show_code_location) .with_line_number(show_code_location) .with_target(show_target) .with_filter(metrics_event_filter()) .and_then(otel_layer) .with_filter( EnvFilter::try_from_env(log_directive_env.unwrap_or(LOG_DIRECTIVE_ENV)) .or_else(|_| EnvFilter::try_new(DEFAULT_LOG_DIRECTIVE)) .unwrap() .add_directive(audit::Audit::directive()), ), ) .with(audit::layer()) .init(); // Set text map propagator globally init_propagation(); otel_guard } } impl TracingInitializer { #[must_use] pub fn app_name(self, app_name: &'static str) -> Self { Self { app_name: Some(app_name), ..self } } #[must_use] pub fn app_version(self, app_version: &'static str) -> Self { Self { app_version: Some(app_version), ..self } } #[must_use] pub fn otlp_endpoint(self, otlp_endpoint: Option<String>) -> Self { Self { otlp_endpoint, ..self } } #[must_use] pub fn trace_sampler_ratio(self, trace_sampler_ratio: f64) -> Self { Self { trace_sampler_ratio, ..self } } #[must_use] pub fn enable_ansi(self, enable_ansi: bool) -> Self { Self { enable_ansi, ..self } } #[must_use] pub fn show_code_location(self, show_code_location: bool) -> Self { Self { show_code_location, ..self } } #[must_use] pub fn show_target(self, show_target: bool) -> Self { Self { show_target, ..self } } #[must_use] pub fn log_directive_env(self, log_directive_env: &'static str) -> Self { Self { log_directive_env: Some(log_directive_env), ..self } } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_o11y/src/tracing_subscriber/mod.rs
crates/synd_o11y/src/tracing_subscriber/mod.rs
use std::{borrow::Cow, time::Duration}; use opentelemetry_sdk::{logs, trace}; use tracing::Subscriber; use tracing_subscriber::{Layer, registry::LookupSpan}; use crate::{OpenTelemetryGuard, tracing_subscriber::otel_metrics::metrics_event_filter}; pub mod audit; pub mod initializer; pub mod otel_log; pub mod otel_metrics; pub mod otel_trace; /// Return a composed layer that exports traces, metrics, and logs of opentelemetry. /// The exported telemetry will be accompanied by a `Resource`. pub fn opentelemetry_layer<S>( endpoint: impl Into<String>, service_name: impl Into<Cow<'static, str>>, service_version: impl Into<Cow<'static, str>>, trace_sampler_ratio: f64, ) -> (impl Layer<S>, OpenTelemetryGuard) where S: Subscriber + for<'span> LookupSpan<'span>, { let endpoint = endpoint.into(); let resource = crate::opentelemetry::resource(service_name, service_version); let (trace_layer, tracer_provider) = { let trace_batch_config = trace::BatchConfigBuilder::default().build(); otel_trace::layer( endpoint.clone(), resource.clone(), trace_sampler_ratio, trace_batch_config, ) }; let (metrics_layer, meter_provider) = { let metrics_reader_interval = Duration::from_secs(60); otel_metrics::layer(endpoint.clone(), resource.clone(), metrics_reader_interval) }; let (log_layer, logger_provider) = { let log_batch_config = logs::BatchConfigBuilder::default().build(); otel_log::layer(endpoint.clone(), resource.clone(), log_batch_config) }; // Since metrics events are handled by the metrics layer and are not needed as logs, set a filter for them. let log_layer = log_layer.with_filter(metrics_event_filter()); let guard = OpenTelemetryGuard { tracer_provider, meter_provider, logger_provider, }; ( trace_layer.and_then(metrics_layer).and_then(log_layer), guard, ) }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_o11y/src/tracing_subscriber/otel_trace/mod.rs
crates/synd_o11y/src/tracing_subscriber/otel_trace/mod.rs
use opentelemetry::{global, trace::TracerProvider}; use opentelemetry_otlp::WithExportConfig; use opentelemetry_sdk::{ Resource, trace::{BatchConfig, BatchSpanProcessor, Sampler, SdkTracerProvider, Tracer}, }; use tracing::Subscriber; use tracing_opentelemetry::OpenTelemetryLayer; use tracing_subscriber::{Layer, registry::LookupSpan}; pub fn layer<S>( endpoint: impl Into<String>, resource: Resource, sampler_ratio: f64, batch_config: BatchConfig, ) -> (impl Layer<S>, SdkTracerProvider) where S: Subscriber + for<'span> LookupSpan<'span>, { let (tracer, provider) = init_tracer(endpoint, resource, sampler_ratio, batch_config); (OpenTelemetryLayer::new(tracer), provider) } fn init_tracer( endpoint: impl Into<String>, resource: Resource, sampler_ratio: f64, // TODO: how to use BatchConfig after 0.27 ? batch_config: BatchConfig, ) -> (Tracer, SdkTracerProvider) { let exporter = opentelemetry_otlp::SpanExporter::builder() .with_tonic() .with_endpoint(endpoint) .build() .unwrap(); let batch_processor = BatchSpanProcessor::builder(exporter) .with_batch_config(batch_config) .build(); let provider = SdkTracerProvider::builder() .with_resource(resource) .with_sampler(Sampler::ParentBased(Box::new(Sampler::TraceIdRatioBased( sampler_ratio, )))) .with_span_processor(batch_processor) .build(); // > It would now be the responsibility of users to set it by calling global::set_tracer_provider(tracer_provider.clone()); // https://github.com/open-telemetry/opentelemetry-rust/blob/main/opentelemetry-otlp/CHANGELOG.md#v0170 global::set_tracer_provider(provider.clone()); (provider.tracer("tracing-opentelemetry"), provider) } #[cfg(test)] mod tests { use std::{net::SocketAddr, time::Duration}; use opentelemetry::KeyValue; use opentelemetry_proto::tonic::{ collector::trace::v1::{ ExportTraceServiceRequest, ExportTraceServiceResponse, trace_service_server::{TraceService, TraceServiceServer}, }, trace::v1::{Status, span::SpanKind, status::StatusCode}, }; use opentelemetry_sdk::trace::BatchConfigBuilder; use tokio::sync::mpsc::UnboundedSender; use tonic::transport::Server; use tracing::dispatcher; use tracing_subscriber::{Registry, layer::SubscriberExt}; use super::*; type Request = tonic::Request<ExportTraceServiceRequest>; struct DumpTraces { tx: UnboundedSender<Request>, } #[tonic::async_trait] impl TraceService for DumpTraces { async fn export( &self, request: tonic::Request<ExportTraceServiceRequest>, ) -> Result<tonic::Response<ExportTraceServiceResponse>, tonic::Status> { self.tx.send(request).unwrap(); Ok(tonic::Response::new(ExportTraceServiceResponse { partial_success: None, // means success })) } } #[tracing::instrument(fields( otel.name = "f1_custom", otel.kind = "Client", ) )] fn f1() { f2(); } #[tracing::instrument(fields( otel.name = "f2_custom", otel.kind = "Server", ))] fn f2() { tracing::error!("error_f2"); } #[tokio::test(flavor = "multi_thread")] async fn layer_test() { let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); let dump = TraceServiceServer::new(DumpTraces { tx }); let addr: SocketAddr = ([127, 0, 0, 1], 48100).into(); let server = Server::builder().add_service(dump).serve(addr); let _server = tokio::task::spawn(server); let resource = resource(); let config = BatchConfigBuilder::default() // The default interval is 5 seconds, which slows down the test .with_scheduled_delay(Duration::from_millis(10)) .build(); let (layer, _provider) = layer("https://localhost:48100", resource.clone(), 1.0, config); let subscriber = Registry::default().with(layer); let dispatcher = tracing::Dispatch::new(subscriber); dispatcher::with_default(&dispatcher, || { f1(); }); let req = rx.recv().await.unwrap().into_inner(); assert_eq!(req.resource_spans.len(), 1); let resource_span = req.resource_spans[0].clone(); insta::with_settings!({ description => "trace resource", }, { insta::assert_yaml_snapshot!("layer_test_trace_resource", req.resource_spans[0].resource, { ".attributes" => insta::sorted_redaction(), }); }); let [f2_span, f1_span] = resource_span.scope_spans[0].spans.as_slice() else { panic!() }; assert_eq!(&f2_span.name, "f2_custom"); assert_eq!(&f1_span.name, "f1_custom"); assert_eq!(f2_span.parent_span_id, f1_span.span_id); assert_eq!(f2_span.trace_id, f1_span.trace_id); assert_eq!(f2_span.kind, SpanKind::Server as i32); assert_eq!(f1_span.kind, SpanKind::Client as i32); assert_eq!( f2_span.status, Some(Status { message: String::new(), code: StatusCode::Error as i32, }) ); assert_eq!( f1_span.status, Some(Status { message: String::new(), code: StatusCode::Unset as i32, }) ); assert_eq!(f2_span.events.len(), 1); assert_eq!(f2_span.attributes.len(), 7); } fn resource() -> Resource { Resource::builder() .with_attributes([KeyValue::new("service.name", "test")]) .build() } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_o11y/src/tracing_subscriber/otel_metrics/macros.rs
crates/synd_o11y/src/tracing_subscriber/otel_metrics/macros.rs
#[macro_export] macro_rules! metric { ($($tt:tt)* ) => { ::tracing::event!( target: $crate::tracing_subscriber::otel_metrics::METRICS_EVENT_TARGET, ::tracing::Level::INFO, $($tt)* );} }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_o11y/src/tracing_subscriber/otel_metrics/mod.rs
crates/synd_o11y/src/tracing_subscriber/otel_metrics/mod.rs
use std::time::Duration; use opentelemetry::global; use opentelemetry_otlp::WithExportConfig; use opentelemetry_sdk::{ Resource, metrics::{Instrument, PeriodicReader, SdkMeterProvider, Stream, View}, }; use tracing::{Metadata, Subscriber}; use tracing_opentelemetry::MetricsLayer; use tracing_subscriber::{Layer, filter::filter_fn, layer::Filter, registry::LookupSpan}; pub mod macros; pub const METRICS_EVENT_TARGET: &str = "metrics"; pub fn metrics_event_filter<S: Subscriber>() -> impl Filter<S> { filter_fn(|metadata: &Metadata<'_>| metadata.target() != METRICS_EVENT_TARGET) } pub fn layer<S>( endpoint: impl Into<String>, resource: Resource, interval: Duration, ) -> (impl Layer<S>, SdkMeterProvider) where S: Subscriber + for<'span> LookupSpan<'span>, { let provider = init_meter_provider(endpoint, resource, interval); (MetricsLayer::new(provider.clone()), provider) } fn init_meter_provider( endpoint: impl Into<String>, resource: Resource, interval: Duration, ) -> SdkMeterProvider { // Currently OtelpMetricPipeline does not provide a way to set up views. let exporter = opentelemetry_otlp::MetricExporter::builder() .with_tonic() .with_endpoint(endpoint) .build() .unwrap(); let reader = PeriodicReader::builder(exporter) .with_interval(interval) .build(); let view = view(); let meter_provider_builder = SdkMeterProvider::builder() .with_resource(resource) .with_reader(reader) .with_view(view); #[cfg(feature = "opentelemetry-stdout")] let stdout_reader = { let exporter = opentelemetry_stdout::MetricExporterBuilder::default().build(); PeriodicReader::builder(exporter) .with_interval(Duration::from_secs(60)) .build() }; #[cfg(feature = "opentelemetry-stdout")] let meter_provider_builder = meter_provider_builder.with_reader(stdout_reader); let meter_provider = meter_provider_builder.build(); global::set_meter_provider(meter_provider.clone()); meter_provider } fn view() -> impl View { |instrument: &Instrument| -> Option<Stream> { tracing::debug!("{instrument:?}"); match instrument.name.as_ref() { "graphql.duration" => Some( Stream::new() .name(instrument.name.clone()) .description("graphql response duration") // Currently we could not ingest metrics with Arregation::Base2ExponentialHistogram in grafanacloud .aggregation( opentelemetry_sdk::metrics::Aggregation::ExplicitBucketHistogram { // https://opentelemetry.io/docs/specs/semconv/http/http-metrics/#http-server boundaries: vec![ 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0, ], record_min_max: false, }, ) // https://opentelemetry.io/docs/specs/semconv/general/metrics/#instrument-units .unit("s"), ), name => { tracing::debug!(name, "There is no explicit view"); None } } } } #[cfg(test)] mod tests { use std::{net::SocketAddr, time::Duration}; use opentelemetry::KeyValue; use opentelemetry_proto::tonic::{ collector::metrics::v1::{ ExportMetricsServiceRequest, ExportMetricsServiceResponse, metrics_service_server::{MetricsService, MetricsServiceServer}, }, metrics::v1::{AggregationTemporality, metric::Data, number_data_point::Value}, }; use tokio::sync::mpsc::UnboundedSender; use tonic::transport::Server; use tracing::dispatcher; use tracing_subscriber::{Registry, layer::SubscriberExt}; use super::*; type Request = tonic::Request<ExportMetricsServiceRequest>; struct DumpMetrics { tx: UnboundedSender<Request>, } #[tonic::async_trait] impl MetricsService for DumpMetrics { async fn export( &self, request: tonic::Request<ExportMetricsServiceRequest>, ) -> Result<tonic::Response<ExportMetricsServiceResponse>, tonic::Status> { self.tx.send(request).unwrap(); Ok(tonic::Response::new(ExportMetricsServiceResponse { partial_success: None, // means success })) } } fn f1() { tracing::info!(monotonic_counter.f1 = 1, key1 = "val1"); } fn f2() { tracing::info!(histogram.graphql.duration = 0.5); } #[tokio::test(flavor = "multi_thread")] async fn layer_test() { let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); let dump = MetricsServiceServer::new(DumpMetrics { tx }); let addr: SocketAddr = ([127, 0, 0, 1], 48101).into(); let server = Server::builder().add_service(dump).serve(addr); let _server = tokio::task::spawn(server); let resource = resource(); // The default interval is 60 seconds, which slows down the test let interval = Duration::from_millis(100); let (layer, _provider) = layer("https://localhost:48101", resource.clone(), interval); let subscriber = Registry::default().with(layer); let dispatcher = tracing::Dispatch::new(subscriber); dispatcher::with_default(&dispatcher, || { f1(); }); let req = rx.recv().await.unwrap().into_inner(); assert_eq!(req.resource_metrics.len(), 1); let metric1 = req.resource_metrics[0].clone(); insta::with_settings!({ description => " metric 1 resource", }, { insta::assert_yaml_snapshot!("layer_test_metric_1_resource", metric1.resource, { ".attributes" => insta::sorted_redaction(), }); }); let metric1 = metric1.scope_metrics[0].metrics[0].clone(); assert_eq!(&metric1.name, "f1"); let Some(Data::Sum(sum)) = metric1.data else { panic!("metric1 data is not sum") }; assert!(sum.is_monotonic); assert_eq!( sum.aggregation_temporality, AggregationTemporality::Cumulative as i32 ); let data = sum.data_points[0].clone(); assert_eq!(data.value, Some(Value::AsInt(1))); insta::with_settings!({ description => " metric 1 datapoint attributes", }, { insta::assert_yaml_snapshot!("layer_test_metric_1_datapoint_attributes", data.attributes); }); dispatcher::with_default(&dispatcher, || { f2(); }); let req = rx.recv().await.unwrap().into_inner(); insta::with_settings!({ description => "graphql duration histogram metrics", }, { insta::assert_yaml_snapshot!("layer_test_metrics_graphql_histogram", req, { ".**.startTimeUnixNano" => "[UNIX_TIMESTAMP]", ".**.timeUnixNano" => "[UNIX_TIMESTAMP]", ".**.scope.version" => "[INSTRUMENT_LIB_VERSION]", ".**.attributes" => insta::sorted_redaction(), }); }); } fn resource() -> Resource { Resource::builder() .with_attributes([KeyValue::new("service.name", "test")]) .build() } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_o11y/src/tracing_subscriber/audit/mod.rs
crates/synd_o11y/src/tracing_subscriber/audit/mod.rs
use tracing::{ Event, Level, Metadata, Subscriber, field, span::{self, Attributes}, subscriber::Interest, }; use tracing_subscriber::{ Layer, filter::{Directive, Filtered}, layer::{self, Context}, registry::LookupSpan, }; mod macros { #[macro_export] macro_rules! audit_span { () => { ::tracing::info_span!( target: $crate::tracing_subscriber::audit::Audit::TARGET, $crate::tracing_subscriber::audit::Audit::SPAN_ROOT_NAME) }; } #[macro_export] macro_rules! audit { ($($arg:tt)*) => { ::tracing::event!( name: $crate::tracing_subscriber::audit::Audit::EVENT_NAME, target: $crate::tracing_subscriber::audit::Audit::TARGET, ::tracing::Level::TRACE, $($arg)*) }; } } pub struct Audit; impl Audit { pub const TARGET: &'static str = "__audit"; pub const SPAN_ROOT_NAME: &'static str = "audit.root"; pub const EVENT_NAME: &'static str = "audit.event"; const EMIT_TARGET: &'static str = "audit"; const EMIT_EVENT_NAME: &'static str = "audit"; // follow opentelemetry semantic conventions pub const USER_ID: &'static str = opentelemetry_semantic_conventions::attribute::USER_ID; pub const OPERATION: &'static str = "operation"; pub const RESULT: &'static str = "result"; /// # Panics /// panic when directive is invalid pub fn directive() -> Directive { let directive = format!("{emit}=info", emit = Self::EMIT_TARGET); directive.parse().expect("Invalid directive") } } /// Create `AuditLayer` pub fn layer<S>() -> impl Layer<S> where S: Subscriber + for<'span> LookupSpan<'span>, { let layer = AuditLayer::new(); let filter = AuditFilter::new(); Filtered::new(layer, filter) } pub struct AuditFilter; impl AuditFilter { fn new() -> Self { Self {} } fn is_enabled(meta: &Metadata<'_>) -> bool { meta.target() == Audit::TARGET } } impl<S> layer::Filter<S> for AuditFilter { fn enabled(&self, meta: &Metadata<'_>, _cx: &Context<'_, S>) -> bool { Self::is_enabled(meta) } fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest { if Self::is_enabled(meta) { Interest::always() } else { Interest::never() } } } pub struct AuditLayer {} impl AuditLayer { fn new() -> Self { Self {} } } struct AuditEventVisitor<'a> { ctx: &'a mut AuditContext, } impl field::Visit for AuditEventVisitor<'_> { fn record_debug(&mut self, _field: &field::Field, _value: &dyn std::fmt::Debug) { // do nothing } fn record_str(&mut self, field: &field::Field, value: &str) { match field.name() { Audit::USER_ID => self.ctx.user_id = Some(value.to_owned()), Audit::OPERATION => self.ctx.operation = Some(value.to_string()), Audit::RESULT => self.ctx.result = Some(value.to_string()), _ => {} } } } struct AuditContext { user_id: Option<String>, operation: Option<String>, result: Option<String>, } impl AuditContext { fn new() -> Self { Self { user_id: None, operation: None, result: None, } } } impl<S> Layer<S> for AuditLayer where S: Subscriber + for<'span> LookupSpan<'span>, { /// If new span is audit root span, create `AuditContext` and insert to extensions. fn on_new_span(&self, attrs: &Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) { if attrs.metadata().name() != Audit::SPAN_ROOT_NAME { return; } let span = ctx.span(id).expect("Span not found, this is a bug"); let mut extensions = span.extensions_mut(); extensions.insert(AuditContext::new()); } /// If event is in audit span, visit event and store audit information to extensions fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) { if event.metadata().name() != Audit::EVENT_NAME { return; } // traverse span tree to find audit context let Some(span) = ctx.lookup_current() else { return; }; let Some(audit_span) = span .scope() .from_root() .find(|span| span.metadata().name() == Audit::SPAN_ROOT_NAME) else { return; }; let mut extension = audit_span.extensions_mut(); let Some(audit_ctx) = extension.get_mut::<AuditContext>() else { return; }; event.record(&mut AuditEventVisitor { ctx: audit_ctx }); } /// If audit root span is closed, write a audit log fn on_close(&self, id: span::Id, ctx: Context<'_, S>) { let span = ctx.span(&id).expect("Span not found, this is a bug"); if span.metadata().name() != Audit::SPAN_ROOT_NAME { return; } let mut extensions = span.extensions_mut(); let Some(AuditContext { user_id, operation, result, }) = extensions.remove::<AuditContext>() else { return; }; let user_id = user_id.as_deref().unwrap_or("?"); let operation = operation.as_deref().unwrap_or("?"); let result = result.as_deref().unwrap_or("?"); tracing::event!( name: Audit::EMIT_EVENT_NAME, target: Audit::EMIT_TARGET, Level::INFO, { Audit::USER_ID } = user_id, { Audit::OPERATION } = operation, { Audit::RESULT } = result, ); } } #[cfg(test)] mod tests { use std::sync::{Arc, Mutex}; use tracing::{info, info_span}; use tracing_subscriber::prelude::__tracing_subscriber_SubscriberExt; use super::*; struct TestLayer<F> { on_event: F, } impl<S, F> Layer<S> for TestLayer<F> where S: Subscriber + for<'span> LookupSpan<'span>, F: Fn(&Event<'_>) + 'static, { fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) { (self.on_event)(event); } } // Mock audit layer usecase mod usecase_authorize_scenario { use tracing::info_span; use crate::{audit, audit_span, tracing_subscriber::audit::Audit}; pub fn root() { let span = audit_span!(); let _enter = span.enter(); usecase(); } fn usecase() { let span = info_span!("usecase"); let _enter = span.enter(); authorize(); ops(); audit!( { Audit::OPERATION } = "create_foo", { Audit::RESULT } = "success", ); } fn authorize() { let span = info_span!("authorize"); let _enter = span.enter(); audit!({ Audit::USER_ID } = "user-a",); } fn ops() { let span = info_span!("ops"); let _enter = span.enter(); } } #[test] fn usecase_authorize_scenario() { let ctx = Arc::new(Mutex::new(AuditContext::new())); let ctx2 = Arc::clone(&ctx); let on_event = move |event: &Event<'_>| { if event.metadata().name() == Audit::EMIT_EVENT_NAME { let mut ctx = ctx2.lock().unwrap(); event.record(&mut AuditEventVisitor { ctx: &mut ctx }); } }; let test_layer = TestLayer { on_event }; let subscriber = tracing_subscriber::registry() .with(layer()) .with(test_layer); tracing::subscriber::with_default(subscriber, || { usecase_authorize_scenario::root(); }); let ctx = Arc::into_inner(ctx).unwrap().into_inner().unwrap(); assert_eq!(ctx.user_id.as_deref(), Some("user-a")); assert_eq!(ctx.operation.as_deref(), Some("create_foo")); assert_eq!(ctx.result.as_deref(), Some("success")); } #[test] fn no_audit_span() { let on_event = |event: &Event<'_>| { assert_ne!(event.metadata().name(), Audit::EMIT_EVENT_NAME); }; let test_layer = TestLayer { on_event }; let subscriber = tracing_subscriber::registry() .with(layer()) .with(test_layer); tracing::subscriber::with_default(subscriber, || { let span = info_span!("ignore"); let _enter = span.enter(); info!("ignore"); }); } #[test] fn emit_target_dose_not_equal_target() { assert!(Audit::TARGET != Audit::EMIT_TARGET); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_o11y/src/tracing_subscriber/otel_log/mod.rs
crates/synd_o11y/src/tracing_subscriber/otel_log/mod.rs
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge; use opentelemetry_otlp::WithExportConfig; use opentelemetry_sdk::{ Resource, logs::{BatchConfig, SdkLoggerProvider}, }; use tracing::Subscriber; use tracing_subscriber::{Layer, registry::LookupSpan}; pub fn layer<S>( endpoint: impl Into<String>, resource: Resource, // TODO: how to use BatchConfig after 0.27 ? _batch_config: BatchConfig, ) -> (impl Layer<S>, SdkLoggerProvider) where S: Subscriber + for<'span> LookupSpan<'span>, { let exporter = opentelemetry_otlp::LogExporter::builder() .with_tonic() .with_endpoint(endpoint) .build() .unwrap(); let provider = SdkLoggerProvider::builder() .with_resource(resource) .with_batch_exporter(exporter) .build(); (OpenTelemetryTracingBridge::new(&provider), provider) } #[cfg(test)] mod tests { use std::{net::SocketAddr, time::Duration}; use opentelemetry::KeyValue; use opentelemetry_proto::tonic::collector::logs::v1::{ ExportLogsServiceRequest, ExportLogsServiceResponse, logs_service_server::{LogsService, LogsServiceServer}, }; use opentelemetry_sdk::logs::BatchConfigBuilder; use tokio::sync::mpsc::UnboundedSender; use tonic::transport::Server; use tracing::dispatcher; use tracing_subscriber::{Registry, layer::SubscriberExt}; use super::*; type Request = tonic::Request<ExportLogsServiceRequest>; struct Dumplogs { tx: UnboundedSender<Request>, } #[tonic::async_trait] impl LogsService for Dumplogs { async fn export( &self, request: tonic::Request<ExportLogsServiceRequest>, ) -> Result<tonic::Response<ExportLogsServiceResponse>, tonic::Status> { self.tx.send(request).unwrap(); Ok(tonic::Response::new(ExportLogsServiceResponse { partial_success: None, // means success })) } } fn f1() { tracing::info!("f1_message"); } #[tokio::test(flavor = "multi_thread")] async fn layer_test() { let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); let dump = LogsServiceServer::new(Dumplogs { tx }); let addr: SocketAddr = ([127, 0, 0, 1], 48102).into(); let server = Server::builder().add_service(dump).serve(addr); let _server = tokio::task::spawn(server); let resource = resource(); // The default interval is 1 seconds, which slows down the test let config = BatchConfigBuilder::default() .with_scheduled_delay(Duration::from_millis(100)) .build(); let (layer, provider) = layer("https://localhost:48102", resource.clone(), config); let subscriber = Registry::default().with(layer); let dispatcher = tracing::Dispatch::new(subscriber); dispatcher::with_default(&dispatcher, || { f1(); }); provider.shutdown().unwrap(); let req = rx.recv().await.unwrap().into_inner(); assert_eq!(req.resource_logs.len(), 1); let log1 = req.resource_logs[0].clone(); insta::with_settings!({ description => " log 1 resource", }, { insta::assert_yaml_snapshot!("layer_test_log_1_resource", log1.resource,{ ".attributes" => insta::sorted_redaction(), }); }); let record = log1.scope_logs[0].log_records[0].clone(); insta::with_settings!({ description => " log 1 record", }, { insta::assert_yaml_snapshot!("layer_test_log_1_record", record, { ".observedTimeUnixNano" => "[OBSERVED_TIME_UNIX_NANO]", }); }); } fn resource() -> Resource { Resource::builder() .with_attributes([KeyValue::new("service.name", "test")]) .build() } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_feed/src/lib.rs
crates/synd_feed/src/lib.rs
#![allow(clippy::new_without_default)] #![warn(rustdoc::broken_intra_doc_links)] pub mod feed; pub mod types;
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_feed/src/types/feed_type.rs
crates/synd_feed/src/types/feed_type.rs
#[derive(Clone, Copy, Debug, Eq, PartialEq)] #[cfg_attr(feature = "graphql", derive(async_graphql::Enum))] #[cfg_attr(feature = "fake", derive(fake::Dummy))] pub enum FeedType { Atom, #[allow(clippy::upper_case_acronyms)] JSON, RSS0, RSS1, RSS2, } impl From<feed_rs::model::FeedType> for FeedType { fn from(typ: feed_rs::model::FeedType) -> Self { match typ { feed_rs::model::FeedType::Atom => FeedType::Atom, feed_rs::model::FeedType::JSON => FeedType::JSON, feed_rs::model::FeedType::RSS0 => FeedType::RSS0, feed_rs::model::FeedType::RSS1 => FeedType::RSS1, feed_rs::model::FeedType::RSS2 => FeedType::RSS2, } } } #[cfg(test)] mod tests { use super::*; #[test] fn feed_rs_compatible() { assert_eq!( FeedType::from(feed_rs::model::FeedType::Atom), FeedType::Atom ); assert_eq!( FeedType::from(feed_rs::model::FeedType::JSON), FeedType::JSON ); assert_eq!( FeedType::from(feed_rs::model::FeedType::RSS0), FeedType::RSS0 ); assert_eq!( FeedType::from(feed_rs::model::FeedType::RSS1), FeedType::RSS1 ); assert_eq!( FeedType::from(feed_rs::model::FeedType::RSS2), FeedType::RSS2 ); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_feed/src/types/url.rs
crates/synd_feed/src/types/url.rs
use std::{borrow::Borrow, fmt}; use serde::{Deserialize, Serialize}; use thiserror::Error; use url::Url; use crate::types::macros::impl_sqlx_encode_decode; #[derive(Error, Debug)] pub enum FeedUrlError { #[error("invalid url: {0}")] InvalidUrl(url::ParseError), } /// Feed Url which serve rss or atom #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))] pub struct FeedUrl(Url); impl Borrow<Url> for FeedUrl { fn borrow(&self) -> &Url { &self.0 } } impl TryFrom<&str> for FeedUrl { type Error = FeedUrlError; fn try_from(s: &str) -> Result<Self, Self::Error> { Url::parse(s).map(FeedUrl).map_err(FeedUrlError::InvalidUrl) } } impl AsRef<str> for FeedUrl { fn as_ref(&self) -> &str { self.0.as_str() } } impl From<Url> for FeedUrl { fn from(url: Url) -> Self { Self(url) } } impl From<FeedUrl> for Url { fn from(url: FeedUrl) -> Self { url.0 } } impl fmt::Display for FeedUrl { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } impl FeedUrl { pub fn into_inner(self) -> Url { self.0 } pub fn as_str(&self) -> &str { self.0.as_str() } pub fn parse(input: &str) -> Result<Self, url::ParseError> { Url::parse(input).map(FeedUrl) } } #[cfg(feature = "graphql")] #[async_graphql::Scalar] impl async_graphql::ScalarType for FeedUrl { fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> { let async_graphql::Value::String(s) = value else { return Err(async_graphql::InputValueError::expected_type(value)); }; match Url::parse(&s) { Ok(url) => Ok(FeedUrl::from(url)), Err(err) => Err(async_graphql::InputValueError::custom(err)), } } fn to_value(&self) -> async_graphql::Value { // Is this clone avoidable? async_graphql::Value::String(self.0.clone().into()) } } #[cfg(feature = "fake")] impl fake::Dummy<fake::Faker> for FeedUrl { fn dummy_with_rng<R: rand::Rng + ?Sized>(_config: &fake::Faker, _rng: &mut R) -> Self { Url::parse("https://fake.ymgyt.io").unwrap().into() } } impl_sqlx_encode_decode!(FeedUrl as String); #[cfg(test)] mod tests { use super::*; #[test] fn backward_compatible() { let org = "https://blog.ymgyt.io/atom.xml"; let u = FeedUrl::parse(org).unwrap(); assert_eq!(u.as_str(), org); assert_eq!(format!("{u}").as_str(), org); } #[test] fn deserialize_from_strings() { let data = vec![ "https://blog.ymgyt.io/atom.xml", "https://blog.ymgyt.io/atom2.xml", ]; let serialized = serde_json::to_string(&data).unwrap(); let deserialized: Vec<FeedUrl> = serde_json::from_str(&serialized).unwrap(); assert_eq!( deserialized, vec![ FeedUrl::parse("https://blog.ymgyt.io/atom.xml").unwrap(), FeedUrl::parse("https://blog.ymgyt.io/atom2.xml").unwrap(), ], ); } #[test] fn url() { let u = FeedUrl::parse("https://blog.ymgyt.io/atom.xml").unwrap(); assert_eq!(Borrow::<Url>::borrow(&u), &Url::from(u.clone())); } #[test] #[cfg(feature = "graphql")] fn scalar() { use async_graphql::ScalarType; assert!(<FeedUrl as ScalarType>::parse(async_graphql::Value::Null).is_err()); assert!( <FeedUrl as ScalarType>::parse(async_graphql::Value::String("invalid".into())).is_err() ); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_feed/src/types/category.rs
crates/synd_feed/src/types/category.rs
use std::{ borrow::Cow, fmt::{self, Display}, }; use serde::{Deserialize, Serialize}; use thiserror::Error; #[derive(Error, Debug, PartialEq, Eq)] pub enum CategoryError { #[error("not empty validation is violated")] NotEmptyViolated, #[error("len max validation is violated")] LenMaxViolated, } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))] pub struct Category<'a>(Cow<'a, str>); impl<'a> Category<'a> { const MAX_LEN: usize = 30; pub fn new(c: impl Into<Cow<'a, str>>) -> Result<Self, CategoryError> { let c = c.into().trim().to_ascii_lowercase(); match c.len() { 0 => return Err(CategoryError::NotEmptyViolated), n if n > Self::MAX_LEN => return Err(CategoryError::LenMaxViolated), _ => {} } Ok(Self(c.into())) } pub fn as_str(&self) -> &str { self.0.as_ref() } pub fn into_inner(self) -> Cow<'a, str> { self.0 } } impl<'s> TryFrom<&'s str> for Category<'s> { type Error = CategoryError; fn try_from(value: &'s str) -> Result<Self, Self::Error> { Self::new(value) } } impl Display for Category<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad(self.0.as_ref()) } } #[cfg(feature = "graphql")] #[async_graphql::Scalar] impl async_graphql::ScalarType for Category<'_> { fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> { let async_graphql::Value::String(s) = value else { return Err(async_graphql::InputValueError::expected_type(value)); }; match Category::new(s) { Ok(c) => Ok(c), Err(err) => Err(async_graphql::InputValueError::custom(err)), } } fn to_value(&self) -> async_graphql::Value { // Is this clone avoidable? async_graphql::Value::String(self.0.clone().into_owned()) } } #[cfg(feature = "fake")] impl fake::Dummy<fake::Faker> for Category<'_> { fn dummy_with_rng<R: rand::Rng + ?Sized>(_config: &fake::Faker, rng: &mut R) -> Self { let category: String = fake::Fake::fake_with_rng(&(1..31), rng); Self::new(category).unwrap() } } #[cfg(feature = "sqlx")] impl sqlx::Type<sqlx::Sqlite> for Category<'static> { fn type_info() -> sqlx::sqlite::SqliteTypeInfo { <String as sqlx::Type<sqlx::Sqlite>>::type_info() } } #[cfg(feature = "sqlx")] impl<'q> sqlx::Encode<'q, sqlx::Sqlite> for Category<'static> { fn encode_by_ref( &self, buf: &mut Vec<sqlx::sqlite::SqliteArgumentValue<'q>>, ) -> Result<sqlx::encode::IsNull, Box<dyn std::error::Error + Send + Sync>> { self.to_string().encode_by_ref(buf) } } #[cfg(feature = "sqlx")] impl<'r> sqlx::Decode<'r, sqlx::Sqlite> for Category<'static> { fn decode(value: sqlx::sqlite::SqliteValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> { let s = <String as sqlx::Decode<sqlx::Sqlite>>::decode(value)?; Self::new(Cow::Owned(s)).map_err(Into::into) } } #[cfg(test)] mod tests { use super::*; #[test] fn category_spec() { assert_eq!(Category::new(""), Err(CategoryError::NotEmptyViolated)); assert_eq!( Category::new("a".repeat(Category::MAX_LEN + 1)), Err(CategoryError::LenMaxViolated) ); assert!(Category::new("a".repeat(Category::MAX_LEN) + " ").is_ok(),); assert_eq!( Category::new("rust").unwrap().into_inner(), format!("{}", Category::new("rust").unwrap()), ); } #[test] #[cfg(feature = "graphql")] fn scalar() { use async_graphql::ScalarType; assert!(Category::parse(async_graphql::Value::Null).is_err()); assert!( Category::parse(async_graphql::Value::String( "a".repeat(Category::MAX_LEN + 1) )) .is_err() ); } #[test] #[cfg(feature = "fake")] fn fake() { use fake::Fake; let c: Category = fake::Faker.fake(); assert!(!c.as_str().is_empty()); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_feed/src/types/macros.rs
crates/synd_feed/src/types/macros.rs
macro_rules! impl_sqlx_encode_decode { ($ty:ty as String) => { #[cfg(feature = "sqlx")] impl sqlx::Type<sqlx::Sqlite> for $ty { fn type_info() -> sqlx::sqlite::SqliteTypeInfo { <String as sqlx::Type<sqlx::Sqlite>>::type_info() } } #[cfg(feature = "sqlx")] impl<'q> sqlx::Encode<'q, sqlx::Sqlite> for $ty { fn encode_by_ref( &self, buf: &mut Vec<sqlx::sqlite::SqliteArgumentValue<'q>>, ) -> Result<sqlx::encode::IsNull, Box<dyn std::error::Error + Send + Sync>> { self.to_string().encode_by_ref(buf) } } #[cfg(feature = "sqlx")] impl<'r> sqlx::Decode<'r, sqlx::Sqlite> for $ty { fn decode( value: sqlx::sqlite::SqliteValueRef<'r>, ) -> Result<Self, sqlx::error::BoxDynError> { let s = <String as sqlx::Decode<sqlx::Sqlite>>::decode(value)?; Self::try_from(s.as_str()).map_err(Into::into) } } }; } pub(crate) use impl_sqlx_encode_decode;
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_feed/src/types/mod.rs
crates/synd_feed/src/types/mod.rs
use std::{borrow::Cow, fmt::Display}; use chrono::{DateTime, Utc}; use feed_rs::model::{self as feedrs, Generator, Link, Person, Text}; pub type Time = DateTime<Utc>; mod requirement; pub use requirement::Requirement; mod category; pub use category::Category; mod url; pub use url::FeedUrl; mod feed_type; pub use feed_type::FeedType; mod macros; #[derive(PartialEq, Eq, Debug, Clone)] pub struct EntryId<'a>(Cow<'a, str>); impl<'a, T> From<T> for EntryId<'a> where T: Into<Cow<'a, str>>, { fn from(value: T) -> Self { Self(value.into()) } } impl Display for EntryId<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.0.as_ref()) } } #[derive(Debug, Clone)] pub struct Entry(feedrs::Entry); impl Entry { pub fn id(&self) -> EntryId<'static> { EntryId(Cow::Owned(self.0.id.clone())) } pub fn id_ref(&self) -> EntryId<'_> { EntryId(Cow::Borrowed(self.0.id.as_str())) } pub fn title(&self) -> Option<&str> { self.0.title.as_ref().map(|text| text.content.as_str()) } pub fn updated(&self) -> Option<Time> { self.0.updated } pub fn published(&self) -> Option<Time> { self.0.published } pub fn summary(&self) -> Option<&str> { self.0.summary.as_ref().map(|text| text.content.as_str()) } pub fn content(&self) -> Option<&str> { self.0 .content .as_ref() .and_then(|content| content.body.as_deref()) } pub fn website_url(&self, feed_type: FeedType) -> Option<&str> { link::find_website_url(feed_type, &self.0.links) } /// Return approximate entry bytes size pub fn approximate_size(&self) -> usize { let content_size = self .0 .content .as_ref() .and_then(|content| content.body.as_deref()) .map_or(0, str::len); let summary_size = self .0 .summary .as_ref() .map_or(0, |summary| summary.content.len()); content_size + summary_size } } #[derive(Debug, Clone)] pub struct FeedMeta { url: FeedUrl, // feed_rs models feed_type: FeedType, title: Option<Text>, updated: Option<Time>, authors: Vec<Person>, description: Option<Text>, links: Vec<Link>, generator: Option<Generator>, published: Option<Time>, } #[derive(Debug, Clone)] pub struct Annotated<T> { pub feed: T, pub requirement: Option<Requirement>, pub category: Option<Category<'static>>, } impl<T> Annotated<T> { pub fn project<U>(&self, f: impl Fn(&T) -> U) -> Annotated<U> { Annotated { feed: f(&self.feed), requirement: self.requirement, category: self.category.clone(), } } } impl<T> Annotated<T> { pub fn new(feed: T) -> Self { Self { feed, requirement: None, category: None, } } } impl FeedMeta { pub fn r#type(&self) -> FeedType { self.feed_type } pub fn url(&self) -> &FeedUrl { &self.url } pub fn title(&self) -> Option<&str> { self.title.as_ref().map(|text| text.content.as_str()) } pub fn updated(&self) -> Option<Time> { self.updated.or(self.published) } pub fn authors(&self) -> impl Iterator<Item = &str> { self.authors.iter().map(|person| person.name.as_str()) } pub fn description(&self) -> Option<&str> { self.description.as_ref().map(|text| text.content.as_str()) } pub fn links(&self) -> impl Iterator<Item = &feedrs::Link> { self.links.iter() } /// Return website link to which feed syndicate pub fn website_url(&self) -> Option<&str> { link::find_website_url(self.r#type(), &self.links) } pub fn generator(&self) -> Option<&str> { self.generator.as_ref().map(|g| g.content.as_str()) } } impl<'a> From<&'a FeedMeta> for Cow<'a, FeedMeta> { fn from(value: &'a FeedMeta) -> Self { Cow::Borrowed(value) } } impl From<FeedMeta> for Cow<'static, FeedMeta> { fn from(value: FeedMeta) -> Self { Cow::Owned(value) } } #[derive(Debug, Clone)] pub struct Feed { meta: FeedMeta, entries: Vec<Entry>, } impl Feed { pub fn parts(self) -> (FeedMeta, Vec<Entry>) { (self.meta, self.entries) } pub fn meta(&self) -> &FeedMeta { &self.meta } pub fn entries(&self) -> impl Iterator<Item = &Entry> { self.entries.iter() } /// Return approximate Feed byte size pub fn approximate_size(&self) -> usize { self.entries().map(Entry::approximate_size).sum() } } impl From<(FeedUrl, feed_rs::model::Feed)> for Feed { fn from((url, feed): (FeedUrl, feedrs::Feed)) -> Self { let feed_rs::model::Feed { feed_type, title, updated, authors, description, links, generator, published, entries, .. } = feed; let meta = FeedMeta { url, feed_type: feed_type.into(), title, updated, authors, description, links, generator, published, }; let entries = entries.into_iter().map(Entry).collect(); Feed { meta, entries } } } mod link { use feed_rs::model::Link; use crate::types::FeedType; pub fn find_website_url<'a>( feed_type: FeedType, links: impl IntoIterator<Item = &'a Link>, ) -> Option<&'a str> { let mut links = links.into_iter(); match feed_type { // Find rel == alternate link FeedType::Atom => links .find(|link| link.rel.as_deref() == Some("alternate")) .map(|link| link.href.as_str()), // how to detect homepage(website) url? // ignore .json extension link FeedType::JSON => links .find(|link| { !std::path::Path::new(link.href.as_str()) .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("json")) }) .map(|link| link.href.as_str()), FeedType::RSS0 => { tracing::warn!("RSS0 is used! {:?}", links.collect::<Vec<_>>()); None } // Use the first link whose rel is not "self" FeedType::RSS1 | FeedType::RSS2 => links .find(|link| link.rel.as_deref() != Some("self")) .map(|link| link.href.as_str()), } } #[cfg(test)] mod tests { use super::*; #[test] fn rss_ignore_rel_self() { let links = vec![ Link { href: "https://syndicationd.ymgyt.io/".into(), title: None, rel: None, media_type: None, href_lang: None, length: None, }, Link { href: "https://syndicationd.ymgyt.io/atom.xml".into(), title: None, rel: Some("self".into()), media_type: None, href_lang: None, length: None, }, ]; assert_eq!( find_website_url(FeedType::RSS1, &links), Some("https://syndicationd.ymgyt.io/") ); assert_eq!( find_website_url(FeedType::RSS2, &links), Some("https://syndicationd.ymgyt.io/") ); } #[test] fn atom_use_rel_alternate() { let links = vec![ Link { href: "https://syndicationd.ymgyt.io/atom.xml".into(), title: None, rel: Some("self".into()), media_type: None, href_lang: None, length: None, }, Link { href: "https://syndicationd.ymgyt.io/".into(), title: None, rel: Some("alternate".into()), media_type: None, href_lang: None, length: None, }, ]; assert_eq!( find_website_url(FeedType::Atom, &links), Some("https://syndicationd.ymgyt.io/") ); } #[test] fn json_ignore_json_ext() { let links = vec![ Link { href: "https://kubernetes.io/docs/reference/issues-security/official-cve-feed/index.json".into(), title: None, rel: None, media_type: None, href_lang: None, length: None, }, Link { href: "https://kubernetes.io".into(), title: None, rel: None, media_type: None, href_lang: None, length: None, }, ]; assert_eq!( find_website_url(FeedType::JSON, &links), Some("https://kubernetes.io") ); } } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_feed/src/types/requirement.rs
crates/synd_feed/src/types/requirement.rs
use serde::{Deserialize, Serialize}; use std::{ fmt::{self, Display}, str::FromStr, }; use crate::types::macros::impl_sqlx_encode_decode; /// `Requirement` expresses how important the feed is /// using an analogy to [RFC2119](https://datatracker.ietf.org/doc/html/rfc2119) #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "graphql", derive(async_graphql::Enum))] #[cfg_attr(feature = "fake", derive(fake::Dummy))] #[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))] pub enum Requirement { /// `Must` indicates it must be read Must = 2, /// `Should` suggests it should be read unless there is a special reason not to Should = 1, /// `May` implies it is probably worth reading May = 0, } impl FromStr for Requirement { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { _ if s.eq_ignore_ascii_case("MUST") => Ok(Requirement::Must), _ if s.eq_ignore_ascii_case("SHOULD") => Ok(Requirement::Should), _ if s.eq_ignore_ascii_case("MAY") => Ok(Requirement::May), _ => Err("invalid requirement, should be one of ['must', 'should', 'may']"), } } } impl<'a> TryFrom<&'a str> for Requirement { type Error = &'static str; fn try_from(s: &'a str) -> Result<Self, Self::Error> { s.parse() } } impl Display for Requirement { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result { match self { Requirement::Must => f.pad("MUST"), Requirement::Should => f.pad("SHOULD"), Requirement::May => f.pad("MAY"), } } } impl Requirement { #[must_use] pub fn up(self) -> Self { Requirement::from_num((self as isize).saturating_add(1)) } #[must_use] pub fn down(self) -> Self { #[allow(clippy::match_same_arms)] let n = self as isize; Requirement::from_num(n.saturating_sub(1)) } pub fn is_satisfied(self, condition: Requirement) -> bool { (self as isize) >= (condition as isize) } fn from_num(n: isize) -> Self { match n { 2.. => Requirement::Must, 1 => Requirement::Should, _ => Requirement::May, } } } impl_sqlx_encode_decode!(Requirement as String); #[cfg(test)] mod tests { use super::*; #[test] fn parse() { assert_eq!("must".parse(), Ok(Requirement::Must)); assert_eq!("should".parse(), Ok(Requirement::Should)); assert_eq!("may".parse(), Ok(Requirement::May)); assert!("unexpected".parse::<Requirement>().is_err()); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_feed/src/feed/service.rs
crates/synd_feed/src/feed/service.rs
use std::{sync::Arc, time::Duration}; use async_trait::async_trait; use feed_rs::parser::{ParseErrorKind, ParseFeedError, Parser}; use crate::types::{Feed, FeedUrl}; pub type FetchFeedResult<T> = std::result::Result<T, FetchFeedError>; #[derive(Debug, thiserror::Error)] pub enum FetchFeedError { #[error("fetch failed")] Fetch(#[from] reqwest::Error), #[error("response size limit exceeded")] ResponseLimitExceed, #[error("invalid feed: {0}")] InvalidFeed(ParseErrorKind), #[error("io error: {0}")] Io(#[from] std::io::Error), #[error("json format error: {0}")] JsonFormat(#[from] serde_json::Error), #[error("unsupported json version: {0}")] JsonUnsupportedVersion(String), #[error("xml format error: {0}")] XmlFormat(String), #[error(transparent)] Other(#[from] anyhow::Error), } impl From<ParseFeedError> for FetchFeedError { fn from(err: ParseFeedError) -> Self { match err { ParseFeedError::ParseError(kind) => FetchFeedError::InvalidFeed(kind), ParseFeedError::IoError(io_err) => FetchFeedError::Io(io_err), ParseFeedError::JsonSerde(json_err) => FetchFeedError::JsonFormat(json_err), ParseFeedError::JsonUnsupportedVersion(version) => { FetchFeedError::JsonUnsupportedVersion(version) } ParseFeedError::XmlReader(xml_err) => FetchFeedError::XmlFormat(format!("{xml_err}")), } } } #[async_trait] pub trait FetchFeed: Send + Sync { async fn fetch_feed(&self, url: FeedUrl) -> FetchFeedResult<Feed>; } #[async_trait] impl<T> FetchFeed for Arc<T> where T: FetchFeed, { async fn fetch_feed(&self, url: FeedUrl) -> FetchFeedResult<Feed> { self.fetch_feed(url).await } } /// Feed Process entry point #[derive(Clone)] pub struct FeedService { http: reqwest::Client, buff_limit: usize, } #[async_trait] impl FetchFeed for FeedService { async fn fetch_feed(&self, url: FeedUrl) -> FetchFeedResult<Feed> { use futures_util::StreamExt; let mut stream = self .http .get(url.clone().into_inner()) .send() .await .map_err(FetchFeedError::Fetch)? .error_for_status() .map_err(FetchFeedError::Fetch)? .bytes_stream(); let mut buff = Vec::new(); while let Some(chunk) = stream.next().await { let chunk = chunk.map_err(FetchFeedError::Fetch)?; if buff.len() + chunk.len() > self.buff_limit { return Err(FetchFeedError::ResponseLimitExceed); } buff.extend(chunk); } self.parse(url, buff.as_slice()) } } impl FeedService { pub fn new(user_agent: &str, buff_limit: usize) -> Self { let http = reqwest::ClientBuilder::new() .user_agent(user_agent) .timeout(Duration::from_secs(10)) .connect_timeout(Duration::from_secs(10)) .build() .unwrap(); Self { http, buff_limit } } pub fn parse<S>(&self, url: FeedUrl, source: S) -> FetchFeedResult<Feed> where S: std::io::Read, { let parser = Self::build_parser(&url); parser .parse(source) .map(|feed| Feed::from((url, feed))) .map_err(FetchFeedError::from) } fn build_parser(base_uri: impl AsRef<str>) -> Parser { feed_rs::parser::Builder::new() .base_uri(Some(base_uri)) .build() } } #[cfg(test)] mod tests { use super::*; #[test] fn from_feed_rs_parse_feed_error() { assert!(matches!( FetchFeedError::from(ParseFeedError::ParseError(ParseErrorKind::NoFeedRoot)), FetchFeedError::InvalidFeed(_) )); assert!(matches!( FetchFeedError::from(ParseFeedError::IoError(std::io::Error::from( std::io::ErrorKind::UnexpectedEof ))), FetchFeedError::Io(_) )); assert!(matches!( FetchFeedError::from(ParseFeedError::JsonUnsupportedVersion("dummy".into())), FetchFeedError::JsonUnsupportedVersion(_) )); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_feed/src/feed/mod.rs
crates/synd_feed/src/feed/mod.rs
pub mod cache; pub mod service;
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_feed/src/feed/cache/periodic_refresher.rs
crates/synd_feed/src/feed/cache/periodic_refresher.rs
use std::{sync::Arc, time::Duration}; use synd_o11y::metric; use tokio_util::sync::CancellationToken; use tracing::{info, warn}; use crate::feed::service::FetchFeed; use super::Cache; pub struct PeriodicRefresher<S> { service: S, cache: Cache, emit_metrics: bool, } impl<S> PeriodicRefresher<S> { pub fn new(service: S, cache: Cache) -> Self { Self { service, cache, emit_metrics: false, } } #[must_use] pub fn with_emit_metrics(self, emit_metrics: bool) -> Self { Self { emit_metrics, ..self } } fn emit_metrics(&self, prev: &Metrics) -> Metrics { // Should call cache.run_pending_tasks() ? let current = Metrics { cache_count: self.cache.entry_count().try_into().unwrap_or(0), cache_size: self.cache.weighted_size().try_into().unwrap_or(0), }; metric!(counter.cache.feed.count = current.cache_count - prev.cache_count); metric!(counter.cache.feed.size = current.cache_size - prev.cache_size); current } } impl<S> PeriodicRefresher<S> where S: FetchFeed + Clone + 'static, { #[tracing::instrument(skip_all, name = "feed::cache::refresh")] async fn refresh(&self) { // It is safe to insert while iterating to cache. for (feed_url, _) in &self.cache { let feed_url = Arc::unwrap_or_clone(feed_url); match self.service.fetch_feed(feed_url.clone()).await { Ok(new_feed) => { self.cache.insert(feed_url, Arc::new(new_feed)).await; } Err(err) => { warn!( url = feed_url.as_str(), "Failed to refresh feed cache: {err}" ); } } } } pub async fn run(self, interval: Duration, ct: CancellationToken) { info!(?interval, "Run periodic feed cache refresher"); let mut interval = tokio::time::interval(interval); let mut prev = Metrics::default(); // Consume initial tick which return ready immediately interval.tick().await; loop { tokio::select! { biased; () = ct.cancelled() => break, _ = interval.tick() => {}, } if self.emit_metrics { prev = self.emit_metrics(&prev); } self.refresh().await; info!("Refreshed feed cache"); } } } #[derive(Default)] struct Metrics { cache_count: i64, cache_size: i64, } #[cfg(test)] mod tests { use async_trait::async_trait; use url::Url; use crate::{ feed::service::FetchFeedResult, types::{Feed, FeedUrl}, }; use super::*; #[derive(Clone)] struct Fetcher {} #[async_trait] impl FetchFeed for Fetcher { async fn fetch_feed(&self, url: FeedUrl) -> FetchFeedResult<Feed> { if url.as_str().ends_with("bad") { Err(crate::feed::service::FetchFeedError::Other( anyhow::anyhow!("error"), )) } else { let (_, feed) = feed(); Ok(feed) } } } #[tokio::test] async fn refresher() { let cache = { let cache = Cache::new(1024); let (url, feed) = feed(); cache.insert(url.clone(), Arc::new(feed.clone())).await; let url2: Url = url.into(); let url2 = url2.join("bad").unwrap(); let url2: FeedUrl = url2.into(); cache.insert(url2, Arc::new(feed)).await; cache }; let fetcher = Fetcher {}; let refresher = PeriodicRefresher::new(fetcher, cache).with_emit_metrics(true); let ct = CancellationToken::new(); ct.cancel(); refresher.run(Duration::from_nanos(1), ct).await; } fn feed() -> (FeedUrl, Feed) { let url = FeedUrl::parse("https://example.ymgyt.io/atom.xml").unwrap(); let feed = feed_rs::model::Feed { feed_type: feed_rs::model::FeedType::RSS1, id: "ID".into(), title: None, updated: None, authors: Vec::new(), description: None, links: Vec::new(), categories: Vec::new(), contributors: Vec::new(), generator: None, icon: None, language: None, logo: None, published: None, rating: None, rights: None, ttl: None, entries: Vec::new(), }; let feed = (url.clone(), feed).into(); (url, feed) } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false