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
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/components/subscription.rs
crates/synd_term/src/ui/components/subscription.rs
use std::borrow::Cow; use itertools::Itertools; use ratatui::{ prelude::{Alignment, Buffer, Constraint, Layout, Rect}, style::{Modifier, Style, Stylize}, text::{Line, Span}, widgets::{ Block, BorderType, Borders, Cell, Padding, Paragraph, Row, Table as RatatuiTable, Tabs, Widget, }, }; use synd_feed::types::{FeedType, FeedUrl}; use crate::{ application::{Direction, Populate}, client::synd_api::query::subscription::SubscriptionOutput, types::{self, EntryMeta, Feed, RequirementExt, TimeExt}, ui::{ self, Context, components::{collections::FilterableVec, filter::FeedFilterer}, extension::RectExt, widgets::{scrollbar::Scrollbar, table::Table}, }, }; pub struct Subscription { feeds: FilterableVec<types::Feed, FeedFilterer>, unsubscribe_popup: UnsubscribePopup, } #[derive(Clone, Copy, PartialEq, Eq)] pub enum UnsubscribeSelection { Yes, No, } impl UnsubscribeSelection { fn toggle(self) -> Self { match self { UnsubscribeSelection::Yes => UnsubscribeSelection::No, UnsubscribeSelection::No => UnsubscribeSelection::Yes, } } } struct UnsubscribePopup { selection: UnsubscribeSelection, selected_feed: Option<types::Feed>, } impl Subscription { pub(crate) fn new() -> Self { Self { feeds: FilterableVec::new(), unsubscribe_popup: UnsubscribePopup { selection: UnsubscribeSelection::Yes, selected_feed: None, }, } } pub(crate) fn has_subscription(&self) -> bool { !self.feeds.is_empty() } pub(crate) fn is_already_subscribed(&self, url: &FeedUrl) -> bool { self.feeds.iter().any(|feed| &feed.url == url) } pub(crate) fn selected_feed(&self) -> Option<&types::Feed> { self.feeds.selected() } pub(crate) fn toggle_unsubscribe_popup(&mut self, show: bool) { if show { self.unsubscribe_popup.selected_feed = self.selected_feed().cloned(); } else { self.unsubscribe_popup.selected_feed = None; } } pub(crate) fn unsubscribe_popup_selection( &self, ) -> (UnsubscribeSelection, Option<&types::Feed>) { ( self.unsubscribe_popup.selection, self.unsubscribe_popup.selected_feed.as_ref(), ) } pub(crate) fn update_subscription( &mut self, populate: Populate, subscription: SubscriptionOutput, ) { let feeds = subscription .feeds .nodes .into_iter() .map(types::Feed::from) .collect(); FilterableVec::update(&mut self.feeds, populate, feeds); } pub(crate) fn update_filterer(&mut self, filterer: FeedFilterer) { self.feeds.update_filter(filterer); } pub(crate) fn upsert_subscribed_feed(&mut self, feed: types::Feed) { let url = feed.url.clone(); self.feeds.upsert_first(feed, |x| x.url == url); } pub(crate) fn remove_unsubscribed_feed(&mut self, url: &FeedUrl) { self.feeds.retain(|feed| &feed.url != url); } pub(crate) fn move_selection(&mut self, direction: Direction) { self.feeds.move_selection(direction); } pub(crate) fn move_first(&mut self) { self.feeds.move_first(); } pub(crate) fn move_last(&mut self) { self.feeds.move_first(); } pub(crate) fn move_unsubscribe_popup_selection(&mut self, direction: Direction) { if matches!(direction, Direction::Left | Direction::Right) { self.unsubscribe_popup.selection = self.unsubscribe_popup.selection.toggle(); } } } impl Subscription { pub fn render(&self, area: Rect, buf: &mut Buffer, cx: &Context<'_>) { let vertical = Layout::vertical([Constraint::Fill(2), Constraint::Fill(1)]); let [feeds_area, feed_detail_area] = vertical.areas(area); self.render_feeds(feeds_area, buf, cx); self.render_feed_detail(feed_detail_area, buf, cx); if let Some(feed) = self.unsubscribe_popup.selected_feed.as_ref() { self.render_unsubscribe_popup(area, buf, cx, feed); } } fn render_feeds(&self, area: Rect, buf: &mut Buffer, cx: &Context<'_>) { let feeds_area = Block::new().padding(Padding::top(1)).inner(area); let (header, widths, rows) = self.feed_rows(cx); Table::builder() .header(header) .widths(widths) .rows(rows) .theme(&cx.theme.entries) .selected_idx(self.feeds.selected_index()) .highlight_modifier(cx.table_highlight_modifier()) .build() .render(feeds_area, buf); let header_rows = 2; #[allow(clippy::cast_possible_truncation)] let scrollbar_area = Rect { y: area.y + header_rows, height: area .height .saturating_sub(header_rows) .min(self.feeds.len() as u16), ..area }; Scrollbar { content_length: self.feeds.len(), position: self.feeds.selected_index(), } .render(scrollbar_area, buf, cx); } fn feed_rows<'a>( &'a self, cx: &'a Context<'_>, ) -> ( Row<'a>, impl IntoIterator<Item = Constraint>, impl IntoIterator<Item = Row<'a>>, ) { let (n, m) = { if self.feeds.is_empty() { (Cow::Borrowed("-"), Cow::Borrowed("-")) } else { ( Cow::Owned((self.feeds.selected_index() + 1).to_string()), Cow::Owned(self.feeds.len().to_string()), ) } }; let header = Row::new([ Cell::from("Updated"), Cell::from(format!("Feed {n}/{m}")), Cell::from("URL"), Cell::from("Description"), Cell::from("Req"), ]); let constraints = [ Constraint::Length(10), Constraint::Fill(1), Constraint::Fill(1), Constraint::Fill(2), Constraint::Length(4), ]; let row = |feed_meta: &'a Feed| { let title = feed_meta.title.as_deref().unwrap_or(ui::UNKNOWN_SYMBOL); let updated = feed_meta .updated .as_ref() .or(feed_meta .entries .first() .and_then(|entry| entry.published.as_ref().or(entry.updated.as_ref()))) .map_or_else(|| ui::UNKNOWN_SYMBOL.to_string(), TimeExt::local_ymd); let website_url = feed_meta .website_url .as_deref() .unwrap_or(ui::UNKNOWN_SYMBOL); let desc = feed_meta.description.as_deref().unwrap_or(""); let requirement = feed_meta.requirement().label(&cx.theme.requirement); let category = feed_meta.category(); let icon = cx .categories .icon(category) .unwrap_or_else(|| ui::default_icon()); Row::new([ Cell::from(Span::from(updated)), Cell::from(Line::from(vec![ Span::from(icon.symbol()).fg(icon.color().unwrap_or(cx.theme.default_icon_fg)), Span::from(" "), Span::from(title), ])), Cell::from(Span::from( website_url .trim_start_matches("http://") .trim_start_matches("https://") .trim_end_matches('/'), )), Cell::from(Span::from(desc)), Cell::from(Line::from(vec![requirement, Span::from(" ")])), ]) }; (header, constraints, self.feeds.iter().map(row)) } #[allow(clippy::too_many_lines)] fn render_feed_detail(&self, area: Rect, buf: &mut Buffer, cx: &Context<'_>) { let block = Block::new() .padding(Padding { left: 2, right: 2, top: 0, bottom: 0, }) .borders(Borders::TOP) .border_type(BorderType::Plain); let inner = block.inner(area); Widget::render(block, area, buf); let Some(feed) = self.selected_feed() else { return; }; let vertical = Layout::vertical([Constraint::Length(3), Constraint::Min(0)]); let [meta_area, entries_area] = vertical.areas(inner); let entries_area = Block::new().padding(Padding::top(1)).inner(entries_area); let widths = [ Constraint::Length(11), Constraint::Fill(1), Constraint::Fill(2), ]; let meta_rows = vec![ Row::new([ Cell::new(Span::styled( "󰚼 Authors", Style::default().add_modifier(Modifier::BOLD), )), Cell::new(Span::from(if feed.authors.is_empty() { Cow::Borrowed(ui::UNKNOWN_SYMBOL) } else { Cow::Owned(feed.authors.iter().join(", ")) })), Cell::new(Line::from(vec![ Span::styled("󰗀 Src ", Style::default().add_modifier(Modifier::BOLD)), Span::from(feed.url.as_str()), ])), ]), Row::new([ Cell::new(Span::styled( " Generator", Style::default().add_modifier(Modifier::BOLD), )), Cell::new(Span::from( feed.generator.as_deref().unwrap_or(ui::UNKNOWN_SYMBOL), )), Cell::new(Line::from(vec![ Span::styled("󰈙 Type ", Style::default().add_modifier(Modifier::BOLD)), Span::from(match feed.feed_type { Some(FeedType::RSS0) => "RSS 0", Some(FeedType::RSS1) => "RSS 1", Some(FeedType::RSS2) => "RSS 2", Some(FeedType::Atom) => "Atom", Some(FeedType::JSON) => "JSON Feed", None => ui::UNKNOWN_SYMBOL, }), ])), ]), Row::new([ Cell::new(Span::styled( " Category", Style::default().add_modifier(Modifier::BOLD), )), Cell::new(Span::from(feed.category().as_str())), Cell::new(Line::from(vec![ Span::styled(" Req ", Style::default().add_modifier(Modifier::BOLD)), Span::from(feed.requirement().to_string()), ])), ]), ]; let table = RatatuiTable::new(meta_rows, widths) .column_spacing(1) .style(cx.theme.subscription.background); Widget::render(table, meta_area, buf); let entry = |entry: &EntryMeta| { let title = entry.title.as_deref().unwrap_or(ui::UNKNOWN_SYMBOL); let published = entry .published .as_ref() .or(entry.updated.as_ref()) .map_or_else(|| ui::UNKNOWN_SYMBOL.to_string(), TimeExt::local_ymd); let summary = entry.summary_text(100).unwrap_or(ui::UNKNOWN_SYMBOL.into()); Row::new([ Cell::new(Span::from(published)), Cell::new(Span::from(title.to_string())), Cell::new(Span::from(summary)), ]) }; let header = Row::new([ Cell::new(Span::from("Published")), Cell::new(Span::from("Entry")), Cell::new(Span::from("Summary")), ]); let rows = feed.entries.iter().map(entry); let table = RatatuiTable::new(rows, widths) .header(header.style(cx.theme.subscription.header)) .column_spacing(1) .style(cx.theme.subscription.background); Widget::render(table, entries_area, buf); } fn render_unsubscribe_popup( &self, area: Rect, buf: &mut Buffer, cx: &Context<'_>, feed: &types::Feed, ) { let area = { let area = RectExt::centered(area, 60, 60); let vertical = Layout::vertical([ Constraint::Fill(1), Constraint::Min(12), Constraint::Fill(2), ]); let [_, area, _] = vertical.areas(area); area.reset(buf); area }; let block = Block::new() .title_top("Unsubscribe") .title_alignment(Alignment::Center) .title_style(Style::new().add_modifier(Modifier::BOLD)) .padding(Padding { left: 1, right: 1, top: 1, bottom: 1, }) .borders(Borders::ALL) .style(cx.theme.base); let inner_area = block.inner(area); let vertical = Layout::vertical([Constraint::Length(6), Constraint::Fill(1)]); let [info_area, selection_area] = vertical.areas(inner_area); block.render(area, buf); // for align line let feed_n = "Feed: ".len() + feed.title.as_deref().unwrap_or("-").len(); let url_n = "URL : ".len() + feed.url.as_str().len(); Paragraph::new(vec![ Line::from("Do you unsubscribe from this feed?"), Line::from(""), Line::from(vec![ Span::from("Feed: "), Span::from(feed.title.as_deref().unwrap_or("-")).bold(), Span::from(" ".repeat(url_n.saturating_sub(feed_n))), ]), Line::from(vec![ Span::from("URL : "), Span::from(feed.url.to_string()).bold(), Span::from(" ".repeat(feed_n.saturating_sub(url_n))), ]), ]) .alignment(Alignment::Center) .block( Block::new() .borders(Borders::BOTTOM) .border_type(BorderType::Plain) .border_style(Style::new().add_modifier(Modifier::DIM)), ) .render(info_area, buf); // align center let horizontal = Layout::horizontal([Constraint::Fill(1), Constraint::Min(1), Constraint::Fill(1)]); let [_, selection_area, _] = horizontal.areas(selection_area); Tabs::new([" Yes ", " No "]) .style(cx.theme.tabs) .divider("") .padding(" ", " ") .select(match self.unsubscribe_popup.selection { UnsubscribeSelection::Yes => 0, UnsubscribeSelection::No => 1, }) .highlight_style(cx.theme.selection_popup.highlight) .render(selection_area, buf); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/components/mod.rs
crates/synd_term/src/ui/components/mod.rs
use crate::{ application::Features, auth::AuthenticationProvider, ui::components::{ authentication::Authentication, entries::Entries, filter::Filter, gh_notifications::GhNotifications, status::StatusLine, subscription::Subscription, tabs::Tabs, }, }; pub(crate) mod authentication; pub(crate) mod entries; pub(crate) mod filter; pub(crate) mod gh_notifications; pub(crate) mod root; pub(crate) mod status; pub(crate) mod subscription; pub(crate) mod tabs; mod collections; pub(crate) struct Components { pub tabs: Tabs, pub filter: Filter, pub prompt: StatusLine, pub subscription: Subscription, pub entries: Entries, pub gh_notifications: GhNotifications, pub auth: Authentication, } impl Components { pub fn new(features: &'_ Features) -> Self { Self { tabs: Tabs::new(features), filter: Filter::new(), prompt: StatusLine::new(), subscription: Subscription::new(), entries: Entries::new(), gh_notifications: GhNotifications::new(), auth: Authentication::new(vec![ AuthenticationProvider::Github, AuthenticationProvider::Google, ]), } } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/components/authentication.rs
crates/synd_term/src/ui/components/authentication.rs
use ratatui::{ prelude::{Alignment, Buffer, Constraint, Layout, Rect}, style::{Modifier, Style}, text::{Line, Span, Text}, widgets::{ Block, Borders, HighlightSpacing, List, ListItem, ListState, Paragraph, StatefulWidget, Widget, }, }; use synd_auth::device_flow::DeviceAuthorizationResponse; use tui_widgets::big_text::{BigText, PixelSize}; use crate::{ application::Direction, auth::AuthenticationProvider, ui::{self, Context, extension::RectExt, icon}, }; /// Handle user authentication #[expect(clippy::large_enum_variant)] #[derive(PartialEq, Eq)] pub(crate) enum AuthenticateState { NotAuthenticated, DeviceFlow(DeviceAuthorizationResponse), Authenticated, } pub(crate) struct Authentication { state: AuthenticateState, providers: Vec<AuthenticationProvider>, selected_provider_index: usize, } impl Authentication { pub fn new(providers: Vec<AuthenticationProvider>) -> Self { debug_assert!(!providers.is_empty()); Self { state: AuthenticateState::NotAuthenticated, providers, selected_provider_index: 0, } } pub fn state(&self) -> &AuthenticateState { &self.state } pub fn selected_provider(&self) -> AuthenticationProvider { self.providers[self.selected_provider_index] } pub fn move_selection(&mut self, direction: Direction) { self.selected_provider_index = direction.apply( self.selected_provider_index, self.providers.len(), crate::application::IndexOutOfRange::Wrapping, ); } pub fn authenticated(&mut self) { self.state = AuthenticateState::Authenticated; } pub fn set_device_authorization_response(&mut self, response: DeviceAuthorizationResponse) { self.state = AuthenticateState::DeviceFlow(response); } pub(super) fn should_render(&self) -> bool { matches!( self.state, AuthenticateState::NotAuthenticated | AuthenticateState::DeviceFlow(_) ) } } impl Authentication { pub(super) fn render(&self, area: Rect, buf: &mut Buffer, cx: &Context<'_>) { match self.state { AuthenticateState::NotAuthenticated => self.render_login(area, buf, cx), AuthenticateState::DeviceFlow(ref res) => Self::render_device_flow(area, buf, cx, res), AuthenticateState::Authenticated => unreachable!(), } } fn render_login(&self, area: Rect, buf: &mut Buffer, cx: &Context<'_>) { let area = RectExt::centered(area, 40, 50); let vertical = Layout::vertical([ Constraint::Length(9), Constraint::Length(2), Constraint::Min(2), ]); let [big_text_area, title_area, methods_area] = vertical.areas(area); // Render big "syndicationd" BigText::builder() .pixel_size(PixelSize::HalfWidth) .style(cx.theme.base) .alignment(Alignment::Center) .lines(vec!["Syndicationd".into()]) .build() .render(big_text_area, buf); let title = Self::login_title(cx); let methods = { let items = self .providers .iter() .map(|provider| match provider { AuthenticationProvider::Github => Text::from(concat!(icon!(github), " GitHub")), AuthenticationProvider::Google => Text::from(concat!(icon!(google), " Google")), }) .map(ListItem::new); List::new(items) .highlight_symbol(ui::TABLE_HIGHLIGHT_SYMBOL) .highlight_style(cx.theme.login.selected_auth_provider_item) .highlight_spacing(HighlightSpacing::Always) }; let mut methods_state = ListState::default().with_selected(Some(self.selected_provider_index)); Widget::render(title, title_area, buf); StatefulWidget::render(methods, methods_area, buf, &mut methods_state); } fn render_device_flow( area: Rect, buf: &mut Buffer, cx: &Context<'_>, res: &DeviceAuthorizationResponse, ) { let area = RectExt::centered(area, 40, 50); let vertical = Layout::vertical([Constraint::Length(2), Constraint::Min(1)]); let [title_area, device_flow_area] = vertical.areas(area); let title = Self::login_title(cx); let device_flow = Paragraph::new(vec![ Line::from("Open the following URL and Enter the code"), Line::from(""), Line::from(vec![ Span::styled("URL: ", Style::default()), Span::styled( res.verification_uri().to_string(), Style::default().add_modifier(Modifier::BOLD), ), ]), Line::from(vec![ Span::styled("Code: ", Style::default()), Span::styled( &res.user_code, Style::default().add_modifier(Modifier::BOLD), ), ]), ]); Widget::render(title, title_area, buf); Widget::render(device_flow, device_flow_area, buf); } fn login_title(cx: &Context<'_>) -> Paragraph<'static> { Paragraph::new(Span::styled("Login", cx.theme.login.title)) .alignment(Alignment::Center) .block(Block::default().borders(Borders::BOTTOM)) } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/components/filter/feed.rs
crates/synd_term/src/ui/components/filter/feed.rs
use synd_feed::types::Requirement; use crate::{ types, ui::components::filter::{ CategoryFilterer, ComposedFilterer, FilterResult, Filterable, MatcherFilterer, category::CategoriesState, composed::Composable, }, }; #[derive(Debug)] pub(crate) struct FeedHandler { pub(super) requirement: Requirement, pub(super) categories_state: CategoriesState, } impl FeedHandler { const INITIAL_REQUIREMENT: Requirement = Requirement::May; pub(super) fn new() -> Self { Self { requirement: Self::INITIAL_REQUIREMENT, categories_state: CategoriesState::new(), } } } #[derive(Clone, Debug)] pub(crate) struct RequirementFilterer { requirement: Requirement, } impl Default for RequirementFilterer { fn default() -> Self { Self::new(FeedHandler::INITIAL_REQUIREMENT) } } impl Composable for RequirementFilterer {} impl RequirementFilterer { pub(super) fn new(requirement: Requirement) -> Self { Self { requirement } } } impl Filterable<types::Entry> for RequirementFilterer { fn filter(&self, entry: &types::Entry) -> FilterResult { if entry.requirement().is_satisfied(self.requirement) { FilterResult::Use } else { FilterResult::Discard } } } impl Filterable<types::Feed> for RequirementFilterer { fn filter(&self, feed: &types::Feed) -> FilterResult { if feed.requirement().is_satisfied(self.requirement) { FilterResult::Use } else { FilterResult::Discard } } } pub(crate) type FeedFilterer = ComposedFilterer<ComposedFilterer<RequirementFilterer, CategoryFilterer>, MatcherFilterer>;
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/components/filter/category.rs
crates/synd_term/src/ui/components/filter/category.rs
use std::collections::{HashMap, HashSet}; use synd_feed::types::Category; use crate::{ application::Populate, config::{Categories, Icon}, types::{self, github::Notification}, ui::{ self, components::filter::{Composable, FilterResult, Filterable}, }, }; #[allow(dead_code)] static LABELS: &[char] = &[ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ]; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum FilterCategoryState { Active, Inactive, } impl FilterCategoryState { pub(super) fn toggle(self) -> Self { match self { FilterCategoryState::Active => FilterCategoryState::Inactive, FilterCategoryState::Inactive => FilterCategoryState::Active, } } pub(super) fn is_active(self) -> bool { self == FilterCategoryState::Active } } #[derive(Debug)] pub(super) struct CategoryState { pub(super) label: char, pub(super) state: FilterCategoryState, pub(super) icon: Icon, } #[derive(Debug)] pub(super) struct CategoriesState { // TODO: make private pub(super) categories: Vec<Category<'static>>, pub(super) state: HashMap<Category<'static>, CategoryState>, } impl CategoriesState { pub(super) fn new() -> Self { Self { categories: Vec::new(), state: HashMap::new(), } } pub(super) fn update( &mut self, config: &Categories, populate: Populate, categories: impl IntoIterator<Item = Category<'static>>, ) { let new = categories.into_iter().collect::<HashSet<_>>(); let mut prev = self.categories.drain(..).collect::<HashSet<_>>(); let mut new_categories = match populate { Populate::Replace => { let should_remove = prev.difference(&new); let should_create = new.difference(&prev); for c in should_remove { self.state.remove(c); } for c in should_create { self.state.insert( c.clone(), CategoryState { label: ' ', icon: config.icon(c).unwrap_or_else(|| ui::default_icon()).clone(), state: FilterCategoryState::Active, }, ); } new.into_iter().collect::<Vec<_>>() } Populate::Append => { let should_create = new.difference(&prev); for c in should_create { self.state.insert( c.clone(), CategoryState { label: ' ', icon: config.icon(c).unwrap_or_else(|| ui::default_icon()).clone(), state: FilterCategoryState::Active, }, ); } prev.extend(new); prev.into_iter().collect::<Vec<_>>() } }; new_categories.sort_unstable(); self.categories = new_categories; self.assigine_category_labels(); } fn assigine_category_labels(&mut self) { self.categories .iter() .zip(LABELS) .for_each(|(category, label)| { self.state.get_mut(category).unwrap().label = *label; }); } pub(super) fn clear(&mut self) { self.categories.clear(); self.state.clear(); } } #[derive(Default, Clone, Debug)] pub(crate) struct CategoryFilterer { state: HashMap<Category<'static>, FilterCategoryState>, } impl Composable for CategoryFilterer {} impl CategoryFilterer { pub(crate) fn new(state: HashMap<Category<'static>, FilterCategoryState>) -> Self { Self { state } } fn filter_by_category(&self, category: &Category<'_>) -> FilterResult { match self.state.get(category) { Some(FilterCategoryState::Inactive) => FilterResult::Discard, _ => FilterResult::Use, } } } impl Filterable<types::Entry> for CategoryFilterer { fn filter(&self, entry: &types::Entry) -> super::FilterResult { self.filter_by_category(entry.category()) } } impl Filterable<types::Feed> for CategoryFilterer { fn filter(&self, feed: &types::Feed) -> super::FilterResult { self.filter_by_category(feed.category()) } } impl Filterable<Notification> for CategoryFilterer { fn filter(&self, n: &Notification) -> super::FilterResult { if !self.state.is_empty() && n.categories() .filter_map(|c| self.state.get(c)) .all(|state| !state.is_active()) { FilterResult::Discard } else { FilterResult::Use } } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/components/filter/mod.rs
crates/synd_term/src/ui/components/filter/mod.rs
use std::{cell::RefCell, collections::HashMap, rc::Rc}; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use itertools::Itertools; use ratatui::{ buffer::Buffer, layout::{Constraint, Layout, Rect}, style::Stylize, text::{Line, Span}, widgets::{Block, Padding, Widget}, }; use synd_feed::types::{Category, Requirement}; use crate::{ application::{Direction, Populate}, client::github::{FetchNotificationInclude, FetchNotificationParticipating}, command::Command, config::Categories, keymap::{KeyTrie, Keymap}, matcher::Matcher, types::{ self, RequirementExt, github::{PullRequestState, Reason, RepoVisibility}, }, ui::{ Context, components::{ filter::{ category::{CategoriesState, FilterCategoryState}, feed::RequirementFilterer, github::GhNotificationHandler, }, gh_notifications::GhNotificationFilterOptions, tabs::Tab, }, icon, widgets::prompt::{Prompt, RenderCursor}, }, }; mod feed; pub(crate) use feed::{FeedFilterer, FeedHandler}; mod github; mod category; pub(crate) use category::CategoryFilterer; mod composed; pub(crate) use composed::{Composable, ComposedFilterer}; mod matcher; pub(crate) use matcher::MatcherFilterer; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum FilterLane { Feed, GhNotification, } impl From<Tab> for FilterLane { fn from(tab: Tab) -> Self { match tab { Tab::Entries | Tab::Feeds => FilterLane::Feed, Tab::GitHub => FilterLane::GhNotification, } } } pub(crate) type CategoryAndMatcherFilterer = ComposedFilterer<CategoryFilterer, MatcherFilterer>; #[derive(Clone, Debug)] pub(crate) enum Filterer { Feed(FeedFilterer), GhNotification(CategoryAndMatcherFilterer), } pub(crate) trait Filterable<T> { fn filter(&self, item: &T) -> FilterResult; } #[derive(Clone, Debug, Copy, PartialEq, Eq)] pub(crate) enum FilterResult { Use, Discard, } #[derive(Debug)] pub(crate) struct Filter { state: State, feed: FeedHandler, gh_notification: GhNotificationHandler, prompt: Rc<RefCell<Prompt>>, matcher: Matcher, } #[derive(Debug, PartialEq, Eq)] enum State { Normal, CategoryFiltering(FilterLane), SearchFiltering, } impl Filter { pub fn new() -> Self { Self { state: State::Normal, prompt: Rc::new(RefCell::new(Prompt::new())), feed: FeedHandler::new(), gh_notification: GhNotificationHandler::new(), matcher: Matcher::new(), } } #[must_use] pub fn activate_search_filtering(&mut self) -> Rc<RefCell<Prompt>> { self.state = State::SearchFiltering; self.prompt.clone() } pub fn is_search_active(&self) -> bool { self.state == State::SearchFiltering } #[must_use] pub fn activate_category_filtering(&mut self, lane: FilterLane) -> Keymap { self.state = State::CategoryFiltering(lane); let mut map = self.categories_state_from_lane(lane).state.iter().fold( HashMap::new(), |mut map, (category, state)| { let key = KeyEvent::new(KeyCode::Char(state.label), KeyModifiers::NONE); let command = Command::ToggleFilterCategory { lane, category: category.clone(), }; map.insert(key, KeyTrie::Command(command)); map }, ); map.insert( KeyEvent::new(KeyCode::Char('+'), KeyModifiers::NONE), KeyTrie::Command(Command::ActivateAllFilterCategories { lane }), ); map.insert( KeyEvent::new(KeyCode::Char('-'), KeyModifiers::NONE), KeyTrie::Command(Command::DeactivateAllFilterCategories { lane }), ); Keymap::from_map(crate::keymap::KeymapId::CategoryFiltering, map) } fn categories_state_from_lane(&self, lane: FilterLane) -> &CategoriesState { match lane { FilterLane::Feed => &self.feed.categories_state, FilterLane::GhNotification => &self.gh_notification.categories_state, } } fn categories_state_from_lane_mut(&mut self, lane: FilterLane) -> &mut CategoriesState { match lane { FilterLane::Feed => &mut self.feed.categories_state, FilterLane::GhNotification => &mut self.gh_notification.categories_state, } } pub fn deactivate_filtering(&mut self) { self.state = State::Normal; } #[must_use] pub fn move_requirement(&mut self, direction: Direction) -> Filterer { self.feed.requirement = match direction { Direction::Left => { if self.feed.requirement == Requirement::Must { Requirement::May } else { self.feed.requirement.up() } } Direction::Right => { if self.feed.requirement == Requirement::May { Requirement::Must } else { self.feed.requirement.down() } } _ => self.feed.requirement, }; Filterer::Feed(self.feed_filterer()) } #[must_use] pub fn toggle_category_state( &mut self, category: &Category<'static>, lane: FilterLane, ) -> Filterer { if let Some(category_state) = self .categories_state_from_lane_mut(lane) .state .get_mut(category) { category_state.state = category_state.state.toggle(); } self.filterer(lane) } #[must_use] pub fn activate_all_categories_state(&mut self, lane: FilterLane) -> Filterer { self.categories_state_from_lane_mut(lane) .state .iter_mut() .for_each(|(_, state)| state.state = FilterCategoryState::Active); self.filterer(lane) } #[must_use] pub fn deactivate_all_categories_state(&mut self, lane: FilterLane) -> Filterer { self.categories_state_from_lane_mut(lane) .state .iter_mut() .for_each(|(_, state)| state.state = FilterCategoryState::Inactive); self.filterer(lane) } #[must_use] pub(crate) fn filterer(&self, lane: FilterLane) -> Filterer { match lane { FilterLane::Feed => Filterer::Feed(self.feed_filterer()), FilterLane::GhNotification => Filterer::GhNotification(self.gh_notification_filterer()), } } #[must_use] fn feed_filterer(&self) -> FeedFilterer { RequirementFilterer::new(self.feed.requirement) .and_then(Self::category_filterer(&self.feed.categories_state)) .and_then(self.matcher_filterer()) } #[must_use] fn gh_notification_filterer(&self) -> CategoryAndMatcherFilterer { Self::category_filterer(&self.gh_notification.categories_state) .and_then(self.matcher_filterer()) } #[must_use] fn category_filterer(categories: &CategoriesState) -> CategoryFilterer { CategoryFilterer::new( categories .state .iter() .map(|(c, state)| (c.clone(), state.state)) .collect(), ) } #[must_use] fn matcher_filterer(&self) -> MatcherFilterer { let mut matcher = self.matcher.clone(); matcher.update_needle(self.prompt.borrow().line()); MatcherFilterer::new(matcher) } pub fn update_categories( &mut self, config: &Categories, populate: Populate, entries: &[types::Entry], ) { self.feed.categories_state.update( config, populate, entries.iter().map(types::Entry::category).cloned(), ); } pub fn update_gh_notification_categories( &mut self, config: &Categories, populate: Populate, categories: impl IntoIterator<Item = Category<'static>>, ) { self.gh_notification .categories_state .update(config, populate, categories); } pub(crate) fn clear_gh_notifications_categories(&mut self) { self.gh_notification.categories_state.clear(); } } pub(super) struct FilterContext<'a> { pub(super) ui: &'a Context<'a>, pub(super) gh_options: &'a GhNotificationFilterOptions, } impl Filter { pub(super) fn render(&self, area: Rect, buf: &mut Buffer, cx: &FilterContext<'_>) { let area = Block::new() .padding(Padding { left: 2, right: 1, top: 0, bottom: 0, }) .inner(area); let vertical = Layout::vertical([Constraint::Length(2), Constraint::Length(1)]); let [filter_area, search_area] = vertical.areas(area); let lane = cx.ui.tab.into(); self.render_filter(filter_area, buf, cx, lane); self.render_search(search_area, buf, cx.ui, lane); } #[allow(unstable_name_collisions)] fn render_filter( &self, area: Rect, buf: &mut Buffer, cx: &FilterContext<'_>, lane: FilterLane, ) { let mut spans = vec![Span::from(concat!(icon!(filter), " Filter")).dim()]; match lane { FilterLane::Feed => { let mut r = self.feed.requirement.label(&cx.ui.theme.requirement); if r.content == "MAY" { r = r.dim(); } spans.extend([Span::from(" "), r, Span::from(" ")]); } FilterLane::GhNotification => { let options = cx.gh_options; let mut unread = Span::from("Unread"); if options.include == FetchNotificationInclude::All { unread = unread.dim(); } let mut participating = Span::from("Participating"); if options.participating == FetchNotificationParticipating::All { participating = participating.dim(); } let visibility = match options.visibility { Some(RepoVisibility::Public) => Some(Span::from("Public")), Some(RepoVisibility::Private) => Some(Span::from("Private")), None => None, }; spans.extend([ Span::from(" "), unread, Span::from(" "), participating, Span::from(" "), ]); if let Some(visibility) = visibility { spans.extend([visibility, Span::from(" ")]); } let pr_conditions = options .pull_request_conditions .iter() .map(|cond| match cond { PullRequestState::Open => Span::from("Open"), PullRequestState::Merged => Span::from("Merged"), PullRequestState::Closed => Span::from("Closed"), }) .collect::<Vec<_>>(); if !pr_conditions.is_empty() { spans.extend(pr_conditions.into_iter().intersperse(Span::from(" "))); spans.push(Span::from(" ")); } let reasons = options .reasons .iter() .filter_map(|reason| match reason { Reason::Mention | Reason::TeamMention => Some(Span::from("Mentioned")), Reason::ReviewRequested => Some(Span::from("ReviewRequested")), _ => None, }) .collect::<Vec<_>>(); if !reasons.is_empty() { spans.extend(reasons.into_iter().intersperse(Span::from(" "))); spans.push(Span::from(" ")); } } } let status_line = Line::from(spans); #[allow(clippy::cast_possible_truncation)] let horizontal = Layout::horizontal([ Constraint::Length(status_line.width() as u16), Constraint::Fill(1), ]); let [status_area, categories_area] = horizontal.areas(area); status_line.render(status_area, buf); let (categories, categories_state) = match lane { FilterLane::Feed => ( &self.feed.categories_state.categories, &self.feed.categories_state.state, ), FilterLane::GhNotification => ( &self.gh_notification.categories_state.categories, &self.gh_notification.categories_state.state, ), }; let mut spans = vec![]; let is_active = matches!(self.state, State::CategoryFiltering(active) if active == lane); for c in categories { let state = categories_state .get(c) .expect("CategoryState is not found. THIS IS A BUG"); let mut icon_span = Span::from(state.icon.symbol()); if let Some(fg) = state.icon.color() { icon_span = icon_span.fg(fg); } if state.state == FilterCategoryState::Inactive { icon_span = icon_span.dim(); } spans.push(icon_span); if is_active { spans.push(Span::from(" ")); let mut s = Span::from(state.label.to_string()); if state.state == FilterCategoryState::Active { s = s.underlined(); } else { s = s.dim(); } spans.push(s); spans.push(Span::from(" ")); } else { spans.push(Span::from(" ")); } } if is_active { spans.push(Span::from("(Esc/+/-)").dim()); } Line::from(spans).render(categories_area, buf); } fn render_search(&self, area: Rect, buf: &mut Buffer, _cx: &Context<'_>, lane: FilterLane) { let mut spans = vec![]; let mut label = Span::from(concat!(icon!(search), " Search")); if self.state != State::SearchFiltering { label = label.dim(); } spans.push(label); { let padding = match lane { FilterLane::Feed => " ", FilterLane::GhNotification => " ", }; spans.push(Span::from(padding)); } let search = Line::from(spans); let margin = search.width() + 1; search.render(area, buf); let prompt_area = Rect { #[allow(clippy::cast_possible_truncation)] x: area.x + margin as u16, ..area }; let render_cursor = if self.state == State::SearchFiltering { RenderCursor::Enable } else { RenderCursor::Disable }; self.prompt.borrow().render(prompt_area, buf, render_cursor); } } #[cfg(test)] mod tests { use fake::{Fake, Faker}; use crate::types::Feed; use super::*; #[test] fn filter_match_feed_url() { let mut matcher = Matcher::new(); matcher.update_needle("ymgyt"); let filter = RequirementFilterer::new(Requirement::May) .and_then(CategoryFilterer::new(HashMap::new())) .and_then(MatcherFilterer::new(matcher)); let mut feed: Feed = Faker.fake(); // title does not match needle feed.title = Some("ABC".into()); feed.website_url = Some("https://blog.ymgyt.io".into()); assert_eq!(filter.filter(&feed), FilterResult::Use); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/components/filter/github.rs
crates/synd_term/src/ui/components/filter/github.rs
use crate::ui::components::filter::category::CategoriesState; #[derive(Debug)] pub(super) struct GhNotificationHandler { pub(super) categories_state: CategoriesState, } impl GhNotificationHandler { pub(crate) fn new() -> Self { Self { categories_state: CategoriesState::new(), } } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/components/filter/composed.rs
crates/synd_term/src/ui/components/filter/composed.rs
use crate::ui::components::filter::{FilterResult, Filterable}; #[derive(Default, Debug, Clone)] pub(crate) struct ComposedFilterer<L, R> { left: L, right: R, } impl<L, R> ComposedFilterer<L, R> { pub(crate) fn new(left: L, right: R) -> Self { Self { left, right } } pub(crate) fn update_left(&mut self, left: L) { self.left = left; } pub(crate) fn update_right(&mut self, right: R) { self.right = right; } pub(crate) fn and_then<F>(self, right: F) -> ComposedFilterer<Self, F> { ComposedFilterer::new(self, right) } pub(crate) fn right(&self) -> &R { &self.right } } impl<L, R, T> Filterable<T> for ComposedFilterer<L, R> where L: Filterable<T>, R: Filterable<T>, { fn filter(&self, item: &T) -> super::FilterResult { if self.left.filter(item) == FilterResult::Use && self.right.filter(item) == FilterResult::Use { FilterResult::Use } else { FilterResult::Discard } } } pub(crate) trait Composable { fn and_then<F>(self, right: F) -> ComposedFilterer<Self, F> where Self: Sized, { ComposedFilterer::new(self, right) } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/components/filter/matcher.rs
crates/synd_term/src/ui/components/filter/matcher.rs
use crate::{ matcher::Matcher, types::{self, github::Notification}, ui::components::filter::{FilterResult, Filterable}, }; #[derive(Default, Clone, Debug)] pub(crate) struct MatcherFilterer { matcher: Matcher, } impl MatcherFilterer { pub(crate) fn new(matcher: Matcher) -> Self { Self { matcher } } } impl Filterable<types::Entry> for MatcherFilterer { fn filter(&self, entry: &types::Entry) -> super::FilterResult { if self .matcher .r#match(entry.title.as_deref().unwrap_or_default()) || self .matcher .r#match(entry.feed_title.as_deref().unwrap_or_default()) { FilterResult::Use } else { FilterResult::Discard } } } impl Filterable<types::Feed> for MatcherFilterer { fn filter(&self, feed: &types::Feed) -> super::FilterResult { if self .matcher .r#match(feed.title.as_deref().unwrap_or_default()) || self .matcher .r#match(feed.website_url.as_deref().unwrap_or_default()) { FilterResult::Use } else { FilterResult::Discard } } } impl Filterable<Notification> for MatcherFilterer { fn filter(&self, n: &Notification) -> super::FilterResult { if self.matcher.r#match(n.title()) || self.matcher.r#match(&n.repository.owner) || self.matcher.r#match(&n.repository.name) { FilterResult::Use } else { FilterResult::Discard } } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/components/gh_notifications/mod.rs
crates/synd_term/src/ui/components/gh_notifications/mod.rs
use std::{borrow::Cow, collections::HashMap, fmt::Debug, ops::ControlFlow}; use chrono_humanize::{Accuracy, HumanTime, Tense}; use itertools::Itertools; use ratatui::{ buffer::Buffer, layout::{Alignment, Constraint, Layout, Rect}, style::{Modifier, Style, Styled, Stylize}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Cell, Padding, Paragraph, Row, Widget, Wrap}, }; use serde::{Deserialize, Serialize}; use crate::{ application::{Direction, Populate}, client::github::{ FetchNotificationInclude, FetchNotificationParticipating, FetchNotificationsParams, }, command::Command, config::{self, Categories}, types::{ TimeExt, github::{ Comment, IssueContext, Notification, NotificationId, PullRequestContext, PullRequestState, Reason, RepoVisibility, SubjectContext, SubjectType, }, }, ui::{ Context, components::{ collections::FilterableVec, filter::{CategoryFilterer, ComposedFilterer, MatcherFilterer}, }, extension::RectExt, icon, widgets::{scrollbar::Scrollbar, table::Table}, }, }; mod filter_popup; use filter_popup::{FilterPopup, OptionFilterer}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum NotificationStatus { MarkingAsDone, } #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum GhNotificationFilterOptionsState { Unchanged, Changed(GhNotificationFilterOptions), } #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub(crate) struct GhNotificationFilterOptions { pub(crate) include: FetchNotificationInclude, pub(crate) participating: FetchNotificationParticipating, pub(crate) visibility: Option<RepoVisibility>, pub(crate) pull_request_conditions: Vec<PullRequestState>, pub(crate) reasons: Vec<Reason>, } impl Default for GhNotificationFilterOptions { fn default() -> Self { Self { include: FetchNotificationInclude::OnlyUnread, participating: FetchNotificationParticipating::All, visibility: None, pull_request_conditions: Vec::new(), reasons: Vec::new(), } } } impl GhNotificationFilterOptions { fn toggle_pull_request_condition(&mut self, pr_state: PullRequestState) { if let Some(idx) = self .pull_request_conditions .iter() .position(|cond| cond == &pr_state) { self.pull_request_conditions.swap_remove(idx); } else { self.pull_request_conditions.push(pr_state); } } fn toggle_reason(&mut self, reason: &Reason) { if let Some(idx) = self.reasons.iter().position(|r| r == reason) { self.reasons.swap_remove(idx); } else { self.reasons.push(reason.clone()); } } } #[allow(clippy::struct_excessive_bools, clippy::struct_field_names)] #[derive(Debug, Clone, Default)] pub(crate) struct GhNotificationFilterUpdater { pub(crate) toggle_include: bool, pub(crate) toggle_participating: bool, pub(crate) toggle_visilibty_public: bool, pub(crate) toggle_visilibty_private: bool, pub(crate) toggle_pull_request_condition: Option<PullRequestState>, pub(crate) toggle_reason: Option<Reason>, } type CategoryAndMatcherFilterer = ComposedFilterer<CategoryFilterer, MatcherFilterer>; #[allow(clippy::struct_field_names)] pub(crate) struct GhNotifications { max_repository_name: usize, notifications: FilterableVec<Notification, ComposedFilterer<CategoryAndMatcherFilterer, OptionFilterer>>, #[allow(clippy::zero_sized_map_values)] status: HashMap<NotificationId, NotificationStatus>, limit: usize, next_page: Option<u8>, filter_popup: FilterPopup, } impl GhNotifications { pub(crate) fn new() -> Self { Self::with_filter_options(GhNotificationFilterOptions::default()) } pub(crate) fn with_filter_options(filter_options: GhNotificationFilterOptions) -> Self { let filterer = CategoryAndMatcherFilterer::default().and_then(OptionFilterer::new(filter_options)); Self { notifications: FilterableVec::from_filter(filterer), max_repository_name: 0, #[allow(clippy::zero_sized_map_values)] status: HashMap::new(), limit: config::github::NOTIFICATION_PER_PAGE as usize, next_page: Some(config::github::INITIAL_PAGE_NUM), filter_popup: FilterPopup::new(), } } pub(crate) fn filter_options(&self) -> &GhNotificationFilterOptions { self.notifications.filter().right().options() } pub(crate) fn update_filter_options(&mut self, updater: &GhNotificationFilterUpdater) { let current = self.filter_options().clone(); self.filter_popup.update_options(updater, &current); } pub(crate) fn update_filterer(&mut self, filterer: CategoryAndMatcherFilterer) { self.notifications .with_filter(|composed| composed.update_left(filterer)); } pub(crate) fn update_notifications( &mut self, populate: Populate, notifications: Vec<Notification>, ) -> Option<Command> { if notifications.is_empty() { self.next_page = None; return None; } match populate { Populate::Replace => self.next_page = Some(config::github::INITIAL_PAGE_NUM + 1), Populate::Append => self.next_page = self.next_page.map(|next| next.saturating_add(1)), } let contexts = notifications .iter() .filter_map(Notification::context) .collect(); self.max_repository_name = self.max_repository_name.max( notifications .iter() .map(|n| n.repository.name.as_str().len()) .max() .unwrap_or(0) .min(30), ); self.notifications.update(populate, notifications); Some(Command::FetchGhNotificationDetails { contexts }) } pub(crate) fn fetch_next_if_needed(&self) -> Option<Command> { match self.next_page { Some(page) if self.notifications.len() < self.limit => { tracing::debug!( "Should fetch more. notifications: {} next_page {page}", self.notifications.len(), ); Some(Command::FetchGhNotifications { populate: Populate::Append, params: self.next_fetch_params(page), }) } _ => { tracing::debug!( "Nothing to fetch. notifications: {} next_page {:?}", self.notifications.len(), self.next_page ); None } } } pub(crate) fn reload(&mut self) -> FetchNotificationsParams { self.next_page = Some(config::github::INITIAL_PAGE_NUM); self.next_fetch_params(config::github::INITIAL_PAGE_NUM) } fn next_fetch_params(&self, page: u8) -> FetchNotificationsParams { let options = self.filter_options(); FetchNotificationsParams { page, include: options.include, participating: options.participating, } } pub(crate) fn update_issue( &mut self, notification_id: NotificationId, issue: IssueContext, config: &Categories, ) -> Option<&Notification> { let mut issue = Some(issue); self.notifications.with_mut(|n| { if n.id == notification_id { n.subject_context = Some(SubjectContext::Issue(issue.take().unwrap())); n.update_categories(config); ControlFlow::Break(()) } else { ControlFlow::Continue(()) } }) } pub(crate) fn update_pull_request( &mut self, notification_id: NotificationId, pull_request: PullRequestContext, config: &Categories, ) -> Option<&Notification> { let mut pull_request = Some(pull_request); self.notifications.with_mut(|n| { if n.id == notification_id { n.subject_context = Some(SubjectContext::PullRequest(pull_request.take().unwrap())); n.update_categories(config); ControlFlow::Break(()) } else { ControlFlow::Continue(()) } }) } pub(crate) fn marking_as_done(&mut self) -> Option<NotificationId> { let id = self.selected_notification()?.id; self.status.insert(id, NotificationStatus::MarkingAsDone); Some(id) } pub(crate) fn marking_as_done_all(&mut self) -> Vec<NotificationId> { let ids: Vec<NotificationId> = self.notifications.iter().map(|n| n.id).collect(); for &id in &ids { self.status.insert(id, NotificationStatus::MarkingAsDone); } ids } pub(crate) fn marked_as_done(&mut self, id: NotificationId) { self.notifications.retain(|n| n.id != id); } pub(crate) fn move_selection(&mut self, direction: Direction) { self.notifications.move_selection(direction); } pub(crate) fn move_first(&mut self) { self.notifications.move_first(); } pub(crate) fn move_last(&mut self) { self.notifications.move_last(); } pub(crate) fn open_filter_popup(&mut self) { self.filter_popup.is_active = true; } #[must_use] pub(crate) fn close_filter_popup(&mut self) -> Option<Command> { self.filter_popup.is_active = false; match self.filter_popup.commit() { GhNotificationFilterOptionsState::Changed(new_options) => { (&new_options != self.filter_options()).then(|| { self.apply_filter_options(new_options); Command::FetchGhNotifications { populate: Populate::Replace, params: self.reload(), } }) } GhNotificationFilterOptionsState::Unchanged => None, } } fn apply_filter_options(&mut self, options: GhNotificationFilterOptions) { let filterer = OptionFilterer::new(options); self.notifications .with_filter(|composed| composed.update_right(filterer)); } pub(crate) fn selected_notification(&self) -> Option<&Notification> { self.notifications.selected() } } impl GhNotifications { pub(crate) fn render(&self, area: Rect, buf: &mut Buffer, cx: &Context<'_>) { let vertical = Layout::vertical([Constraint::Fill(2), Constraint::Fill(1)]); let [notifications_area, detail_area] = vertical.areas(area); self.render_notifications(notifications_area, buf, cx); self.render_detail(detail_area, buf, cx); if self.filter_popup.is_active { self.render_filter_popup(area, buf, cx); } } fn render_notifications(&self, area: Rect, buf: &mut Buffer, cx: &Context<'_>) { let notifications_area = Block::new().padding(Padding::top(1)).inner(area); let (header, widths, rows) = self.notification_rows(cx); Table::builder() .header(header) .widths(widths) .rows(rows) .theme(&cx.theme.entries) .selected_idx(self.notifications.selected_index()) .highlight_modifier(cx.table_highlight_modifier()) .build() .render(notifications_area, buf); let header_rows = 2; #[allow(clippy::cast_possible_truncation)] let scrollbar_area = Rect { y: area.y + header_rows, height: area .height .saturating_sub(header_rows) .min(self.notifications.len() as u16), ..area }; Scrollbar { content_length: self.notifications.len(), position: self.notifications.selected_index(), } .render(scrollbar_area, buf, cx); } fn notification_rows<'a>( &'a self, cx: &'a Context<'_>, ) -> ( Row<'a>, impl IntoIterator<Item = Constraint>, impl IntoIterator<Item = Row<'a>>, ) { let (n, m) = { if self.notifications.is_empty() { (Cow::Borrowed("-"), Cow::Borrowed("-")) } else { ( Cow::Owned((self.notifications.selected_index() + 1).to_string()), Cow::Owned(self.notifications.len().to_string()), ) } }; let header = Row::new([ Cell::from("Updated"), Cell::from(format!("Title {n}/{m}")), Cell::from("Repository"), Cell::from("Reason"), ]); let constraints = [ Constraint::Length(8), Constraint::Fill(1), Constraint::Max(self.max_repository_name.try_into().unwrap_or(30)), Constraint::Length(10), ]; let row = |n: &'a Notification| { let updated_at = HumanTime::from(n.updated_at.signed_duration_since(cx.now)) .to_text_en(Accuracy::Rough, Tense::Past); let updated_at = short_human_time(&updated_at); let subject = n.title(); let subject_icon = n.subject_icon(); let repo = n.repository.name.as_str(); let reason = reason_label(&n.reason); let is_marking_as_done = self .status .get(&n.id) .is_some_and(|s| *s == NotificationStatus::MarkingAsDone); let modifier = if is_marking_as_done { Modifier::CROSSED_OUT | Modifier::DIM } else { Modifier::empty() }; Row::new([ Cell::from(Span::from(updated_at).add_modifier(modifier)), Cell::from( Line::from(vec![subject_icon, Span::from(" "), Span::from(subject)]) .add_modifier(modifier), ), Cell::from(Span::from(repo).add_modifier(modifier)), Cell::from(Span::from(reason).add_modifier(modifier)), ]) }; (header, constraints, self.notifications.iter().map(row)) } #[allow(clippy::too_many_lines)] fn render_detail(&self, area: Rect, buf: &mut Buffer, cx: &Context<'_>) { let block = Block::new() .padding(Padding { left: 2, right: 2, top: 0, bottom: 0, }) .borders(Borders::TOP) .border_type(BorderType::Plain); let inner = block.inner(area); Widget::render(block, area, buf); let Some(notification) = self.selected_notification() else { return; }; let vertical = Layout::vertical([ Constraint::Length(1), Constraint::Length(1), Constraint::Length(1), Constraint::Fill(1), ]); let [subject_area, title_area, updated_at_area, content_area] = vertical.areas(inner); Line::from(vec![ notification.subject_icon().bold(), Span::from(" Subject").bold(), Span::from(" "), Span::from(format!( "{} / {} ", notification.repository.owner.as_str(), notification.repository.name.as_str(), )), { let id = match notification.subject_type() { Some(SubjectType::Issue) => { format!( "#{}", notification .issue_id() .map(|id| id.to_string()) .unwrap_or_default() ) } Some(SubjectType::PullRequest) => { format!( "#{}", notification .pull_request_id() .map(|id| id.to_string()) .unwrap_or_default() ) } Some(SubjectType::Ci) => "ci".to_owned(), Some(SubjectType::Release) => "release".to_owned(), Some(SubjectType::Discussion) => "discussion".to_owned(), None => String::new(), }; Span::from(id) }, ]) .render(subject_area, buf); Line::from(vec![ Span::from(concat!(icon!(entry), " Title")).bold(), Span::from(" "), Span::from(notification.title()), ]) .render(title_area, buf); Line::from(vec![ Span::from(concat!(icon!(calendar), " UpdatedAt")).bold(), Span::from(" "), Span::from(notification.updated_at.local_ymd_hm()), { if let Some(last_read) = notification.last_read_at { Span::from(format!( " last read {}", HumanTime::from(last_read.signed_duration_since(cx.now)) .to_text_en(Accuracy::Rough, Tense::Past) )) .dim() } else { Span::from("") } }, ]) .render(updated_at_area, buf); let (label, padding) = match notification.subject_type() { Some(SubjectType::Issue) => ("Issue", " "), Some(SubjectType::PullRequest) => ("PR", " "), _ => ("Body", " "), }; let body = Line::from(vec![ Span::from(format!("{} {label}", icon!(summary))) .bold() .underlined(), Span::from(padding), { if let Some(author) = notification.author() { Span::from(format!(" @{author}")).dim() } else { Span::from("") } }, ]); let body_para = Paragraph::new(notification.body().unwrap_or_default()) .wrap(Wrap { trim: true }) .alignment(Alignment::Left); let last_comment = notification.last_comment(); // Render labels if exists let content_area = { let labels = notification.labels().map(|labels| { #[allow(unstable_name_collisions)] let labels = labels .map(|label| { let span = Span::from(&label.name); if let Some(color) = label.color { span.set_style( Style::default().bg(color).fg( // Depending on the background color of the label // the foreground may become difficult to read cx.theme .contrast_fg_from_luminance(label.luminance.unwrap_or(0.5)), ), ) } else { span } }) .intersperse(Span::from(" ")); let mut line = vec![ Span::from(concat!(icon!(label), " Labels")).bold(), Span::from(" "), ]; line.extend(labels); Line::from(line) }); match labels { None => content_area, Some(labels) => { let vertical = Layout::vertical([Constraint::Length(1), Constraint::Fill(1)]); let [labels_area, content_area] = vertical.areas(content_area); labels.render(labels_area, buf); content_area } } }; if last_comment.is_none() { let vertical = Layout::vertical([Constraint::Length(1), Constraint::Fill(1)]); let [body_header_area, body_area] = vertical.areas(content_area); body.render(body_header_area, buf); body_para.render(body_area, buf); } else { let vertical = Layout::vertical([ Constraint::Length(1), Constraint::Fill(1), Constraint::Length(1), Constraint::Fill(1), ]); let [ body_header_area, body_area, comment_header_area, comment_area, ] = vertical.areas(content_area); body.render(body_header_area, buf); body_para.render(body_area, buf); #[expect(clippy::unnecessary_unwrap)] let Comment { author, body } = last_comment.unwrap(); Line::from(vec![ Span::from(concat!(icon!(comment), " Comment")) .bold() .underlined(), Span::from(" "), Span::from(format!(" @{author}")).dim(), ]) .render(comment_header_area, buf); Paragraph::new(body) .wrap(Wrap { trim: true }) .alignment(Alignment::Left) .render(comment_area, buf); } } fn render_filter_popup(&self, area: Rect, buf: &mut Buffer, cx: &Context<'_>) { let area = { let vertical = Layout::vertical([ Constraint::Fill(1), Constraint::Length(9), Constraint::Fill(2), ]); let [_, area, _] = vertical.areas(area); let area = RectExt::centered(area, 70, 100); area.reset(buf); area }; self.filter_popup .render(area, buf, cx, self.filter_options()); } } fn reason_label(reason: &Reason) -> &str { match reason { Reason::Assign => "assigned", Reason::Author => "author", Reason::CiActivity => "ci", Reason::ManuallySubscribed => "manual", Reason::Mention => "mentioned", Reason::TeamMention => "team mentioned", Reason::ReviewRequested => "review", Reason::WatchingRepo => "subscribed", Reason::Other(other) => other, } } // 3 days ago => "_3d ago" fn short_human_time(s: &str) -> String { if s == "now" { return s.to_owned(); } let mut seg = s.splitn(3, ' '); let (Some(n), Some(u)) = (seg.next(), seg.next()) else { return s.to_owned(); }; let u = match u { "seconds" | "second" => "s", "minutes" | "minute" => "m", "hours" | "hour" => "h", "days" | "day" => "d", "weeks" | "week" => "w", "months" | "month" => "mo", "years" | "year" => "y", _ => "", }; let n = match n { "an" | "a" => "1", n => n, }; if u == "mo" { format!("{n}{u} ago") } else { format!("{n: >2}{u} ago") } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/components/gh_notifications/filter_popup.rs
crates/synd_term/src/ui/components/gh_notifications/filter_popup.rs
use ratatui::{ buffer::Buffer, layout::{Alignment, Constraint, Layout, Rect}, style::{Modifier, Style, Stylize}, text::{Line, Span}, widgets::{Block, Borders, Padding, Widget}, }; use crate::{ client::github::{FetchNotificationInclude, FetchNotificationParticipating}, types::github::{Notification, PullRequestState, Reason, RepoVisibility, SubjectContext}, ui::{ Context, components::{ filter::{FilterResult, Filterable}, gh_notifications::{ GhNotificationFilterOptions, GhNotificationFilterOptionsState, GhNotificationFilterUpdater, }, }, icon, }, }; #[derive(Clone, Debug, Default)] pub(super) struct OptionFilterer { options: GhNotificationFilterOptions, } impl OptionFilterer { pub(super) fn new(options: GhNotificationFilterOptions) -> Self { Self { options } } pub(super) fn options(&self) -> &GhNotificationFilterOptions { &self.options } } impl Filterable<Notification> for OptionFilterer { fn filter(&self, n: &Notification) -> FilterResult { // unread and participating are handled in rest api if let Some(visibility) = self.options.visibility && visibility != n.repository.visibility { return FilterResult::Discard; } if !self.options.pull_request_conditions.is_empty() { match n.subject_context.as_ref() { Some(SubjectContext::PullRequest(pr)) => { if !self.options.pull_request_conditions.contains(&pr.state) { return FilterResult::Discard; } } _ => return FilterResult::Discard, } } if !self.options.reasons.is_empty() { let mut ok = false; for reason in &self.options.reasons { if (reason == &Reason::Mention && (n.reason == Reason::TeamMention || n.reason == Reason::Mention)) || reason == &n.reason { ok = true; } } if !ok { return FilterResult::Discard; } } FilterResult::Use } } pub(super) struct FilterPopup { pub(super) is_active: bool, pending_options: Option<GhNotificationFilterOptions>, } impl FilterPopup { pub(super) fn new() -> Self { Self { is_active: false, pending_options: None, } } pub(super) fn commit(&mut self) -> GhNotificationFilterOptionsState { match self.pending_options.take() { Some(options) => GhNotificationFilterOptionsState::Changed(options), None => GhNotificationFilterOptionsState::Unchanged, } } pub(super) fn update_options( &mut self, new: &GhNotificationFilterUpdater, current: &GhNotificationFilterOptions, ) { let mut pending = self .pending_options .take() .unwrap_or_else(|| current.clone()); if new.toggle_include { pending.include = match pending.include { FetchNotificationInclude::OnlyUnread => FetchNotificationInclude::All, FetchNotificationInclude::All => FetchNotificationInclude::OnlyUnread, }; } if new.toggle_participating { pending.participating = match pending.participating { FetchNotificationParticipating::OnlyParticipating => { FetchNotificationParticipating::All } FetchNotificationParticipating::All => { FetchNotificationParticipating::OnlyParticipating } }; } if new.toggle_visilibty_public { pending.visibility = match pending.visibility { Some(RepoVisibility::Public) => None, Some(RepoVisibility::Private) | None => Some(RepoVisibility::Public), }; } if new.toggle_visilibty_private { pending.visibility = match pending.visibility { Some(RepoVisibility::Private) => None, Some(RepoVisibility::Public) | None => Some(RepoVisibility::Private), }; } if let Some(pr_state) = new.toggle_pull_request_condition { pending.toggle_pull_request_condition(pr_state); } if let Some(reason) = new.toggle_reason.as_ref() { pending.toggle_reason(reason); } self.pending_options = Some(pending); } } impl FilterPopup { #[allow(clippy::too_many_lines)] pub(super) fn render( &self, area: Rect, buf: &mut Buffer, cx: &Context<'_>, current: &GhNotificationFilterOptions, ) { let area = { let block = Block::new() .title_top("Filter") .title_alignment(Alignment::Center) .title_style(Style::new().add_modifier(Modifier::BOLD)) .padding(Padding { left: 3, right: 2, top: 1, bottom: 1, }) .borders(Borders::ALL) .style(cx.theme.base); let inner_area = block.inner(area); block.render(area, buf); inner_area }; let vertical = Layout::vertical([ Constraint::Length(1), Constraint::Length(1), Constraint::Length(1), Constraint::Length(1), Constraint::Length(1), // Constraint::Fill(1), ]); let [ status_area, participating_area, visibility_area, pull_request_area, reason_area, ] = vertical.areas(area); let options = self.pending_options.as_ref().unwrap_or(current); let keyword = cx.theme.entries.selected_entry; // Render status { let mut spans = vec![ Span::from(concat!(icon!(unread), " Status")).bold(), Span::from(" "), ]; let mut unread1 = Span::styled("Un", keyword).italic().bold(); let mut unread2 = Span::from("read").bold(); if options.include == FetchNotificationInclude::All { unread1 = unread1.dim(); unread2 = unread2.dim(); } spans.push(unread1); spans.push(unread2); Line::from(spans).render(status_area, buf); } // Render participating { let mut spans = vec![ Span::from(concat!(icon!(chat), " Participating")).bold(), Span::from(" "), ]; let mut par1 = Span::styled("Pa", keyword).italic().bold(); let mut par2 = Span::from("rticipating").bold(); if options.participating == FetchNotificationParticipating::All { par1 = par1.dim(); par2 = par2.dim(); } spans.extend([par1, par2]); Line::from(spans).render(participating_area, buf); } // Render repository visibility { let mut spans = vec![ Span::from(concat!(icon!(repository), " Repository")).bold(), Span::from(" "), ]; let mut pub1 = Span::styled("Pu", keyword).italic().bold(); let mut pub2 = Span::from("blic").bold(); let mut pri1 = Span::styled("Pr", keyword).italic().bold(); let mut pri2 = Span::from("ivate").bold(); match options.visibility { Some(RepoVisibility::Public) => { pri1 = pri1.dim(); pri2 = pri2.dim(); } Some(RepoVisibility::Private) => { pub1 = pub1.dim(); pub2 = pub2.dim(); } None => { pri1 = pri1.dim(); pri2 = pri2.dim(); pub1 = pub1.dim(); pub2 = pub2.dim(); } } spans.extend([pub1, pub2, Span::from(" "), pri1, pri2]); Line::from(spans).render(visibility_area, buf); } // Render pull request conditions { let mut spans = vec![ Span::from(concat!(icon!(pullrequest), " PullRequest")).bold(), Span::from(" "), ]; // dim then bold approach does not work :( let mut open1 = Span::styled("Op", keyword).italic().bold(); let mut open2 = Span::from("en").bold(); let mut merged1 = Span::styled("M", keyword).italic().bold(); let mut merged2 = Span::from("e").bold(); let mut merged3 = Span::styled("r", keyword).italic().bold(); let mut merged4 = Span::from("ged").bold(); let mut closed1 = Span::styled("Cl", keyword).italic().bold(); let mut closed2 = Span::from("osed").bold(); let mut disable_open = true; let mut disable_merged = true; let mut disable_closed = true; for cond in &options.pull_request_conditions { match cond { PullRequestState::Open => { disable_open = false; } PullRequestState::Merged => { disable_merged = false; } PullRequestState::Closed => disable_closed = false, } } if disable_open { open1 = open1.dim(); open2 = open2.dim(); } if disable_merged { merged1 = merged1.dim(); merged2 = merged2.dim(); merged3 = merged3.dim(); merged4 = merged4.dim(); } if disable_closed { closed1 = closed1.dim(); closed2 = closed2.dim(); } spans.extend([ open1, open2, Span::from(" "), merged1, merged2, merged3, merged4, Span::from(" "), closed1, closed2, ]); Line::from(spans).render(pull_request_area, buf); } // Render reasons { let mut spans = vec![ Span::from(concat!(icon!(chat), " Reason")).bold(), Span::from(" "), ]; let mut mentioned1 = Span::styled("Me", keyword).italic().bold(); let mut mentioned2 = Span::from("ntioned").bold(); let mut review1 = Span::styled("Re", keyword).italic().bold(); let mut review2 = Span::from("viewRequested").bold(); let mut disable_mentioned = true; let mut disable_review = true; for reason in &options.reasons { match reason { Reason::Mention | Reason::TeamMention => { disable_mentioned = false; } Reason::ReviewRequested => { disable_review = false; } _ => {} } } if disable_mentioned { mentioned1 = mentioned1.dim(); mentioned2 = mentioned2.dim(); } if disable_review { review1 = review1.dim(); review2 = review2.dim(); } spans.extend([ mentioned1, mentioned2, Span::from(" "), review1, review2, ]); Line::from(spans).render(reason_area, buf); } } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/components/collections/filterable.rs
crates/synd_term/src/ui/components/collections/filterable.rs
use std::ops::ControlFlow; use crate::{ application::{Direction, IndexOutOfRange, Populate}, ui::components::filter::{FilterResult, Filterable}, }; pub(crate) struct FilterableVec<T, F> { items: Vec<T>, effective_items: Vec<usize>, selected_item_index: usize, filterer: F, } impl<T, F> FilterableVec<T, F> where F: Default, { pub(crate) fn new() -> Self { Self::from_filter(F::default()) } pub(crate) fn from_filter(filterer: F) -> Self { Self { items: Vec::new(), effective_items: Vec::new(), selected_item_index: 0, filterer, } } } impl<T, F> FilterableVec<T, F> { pub(crate) fn selected(&self) -> Option<&T> { self.effective_items .get(self.selected_item_index) .map(|&idx| &self.items[idx]) } pub(crate) fn selected_index(&self) -> usize { self.selected_item_index } pub(crate) fn len(&self) -> usize { self.effective_items.len() } pub(crate) fn is_empty(&self) -> bool { self.effective_items.is_empty() } pub(crate) fn move_selection(&mut self, direction: Direction) { self.selected_item_index = direction.apply( self.selected_item_index, self.effective_items.len(), IndexOutOfRange::Wrapping, ); } pub(crate) fn move_first(&mut self) { self.selected_item_index = 0; } pub(crate) fn move_last(&mut self) { if !self.items.is_empty() { self.selected_item_index = self.effective_items.len() - 1; } } pub(crate) fn iter(&self) -> impl Iterator<Item = &T> { self.effective_items .iter() .map(move |&idx| &self.items[idx]) } pub(crate) fn as_unfiltered_slice(&self) -> &[T] { self.items.as_slice() } pub(crate) fn filter(&self) -> &F { &self.filterer } } impl<T, F> FilterableVec<T, F> where F: Filterable<T>, { pub(crate) fn update(&mut self, populate: Populate, items: Vec<T>) { match populate { Populate::Append => self.items.extend(items), Populate::Replace => self.items = items, } self.refresh(); } pub(crate) fn upsert_first<C>(&mut self, item: T, should_update: C) where C: Fn(&T) -> bool, { match self.items.iter_mut().find(|item| should_update(item)) { Some(old) => *old = item, None => self.items.insert(0, item), } self.refresh(); } pub(crate) fn with_mut<F2>(&mut self, mut f: F2) -> Option<&T> where F2: FnMut(&mut T) -> ControlFlow<()>, { let mut found = None; for (idx, item) in self.items.iter_mut().enumerate() { match f(item) { ControlFlow::Break(()) => { found = Some(idx); break; } ControlFlow::Continue(()) => (), } } if let Some(idx) = found { self.refresh(); self.items.get(idx) } else { None } } pub(crate) fn update_filter(&mut self, filterer: F) { self.filterer = filterer; self.refresh(); } pub(crate) fn with_filter<With>(&mut self, f: With) where With: FnOnce(&mut F), { f(&mut self.filterer); self.refresh(); } pub(crate) fn retain<C>(&mut self, cond: C) where C: Fn(&T) -> bool, { self.items.retain(cond); self.refresh(); } pub(crate) fn refresh(&mut self) { self.effective_items = self .items .iter() .enumerate() .filter(|(_idx, item)| self.filterer.filter(item) == FilterResult::Use) .map(|(idx, _)| idx) .collect(); // prevent selection from out of index self.selected_item_index = self .selected_item_index .min(self.effective_items.len().saturating_sub(1)); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/components/collections/mod.rs
crates/synd_term/src/ui/components/collections/mod.rs
mod filterable; pub(super) use filterable::FilterableVec;
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/widgets/throbber.rs
crates/synd_term/src/ui/widgets/throbber.rs
// Currently throbber-widgets-tui dependes ratatui 0.24 // https://github.com/arkbig/throbber-widgets-tui/blob/cd6d1e1e1f38e221d8462df66172dcc370582bbd/Cargo.toml#L20 use ratatui::{ prelude::{Buffer, Rect}, style::Style, text::Span, widgets::StatefulWidget, }; #[derive(Debug, Clone, Default)] pub struct ThrobberState { index: i8, } impl ThrobberState { pub fn calc_step(&mut self, step: i8) { self.index = self.index.saturating_add(step); } #[allow(clippy::cast_possible_truncation)] pub fn normalize(&mut self, throbber: &Throbber) { let len = throbber.throbber_set.symbols.len() as i8; if len <= 0 { //ng but it's not used, so it stays. } else { self.index %= len; if self.index < 0 { // Negative numbers are indexed from the tail self.index += len; } } } } #[allow(clippy::struct_field_names)] #[derive(Debug, Clone)] pub struct Throbber<'a> { label: Option<Span<'a>>, style: Style, throbber_style: Style, throbber_set: throbber::Set, use_type: throbber::WhichUse, } impl Default for Throbber<'_> { fn default() -> Self { Self { label: None, style: Style::default(), throbber_style: Style::default(), throbber_set: throbber::BRAILLE_EIGHT_DOUBLE, use_type: throbber::WhichUse::Spin, } } } impl<'a> Throbber<'a> { #[must_use] pub fn label<T>(mut self, label: T) -> Self where T: Into<Span<'a>>, { self.label = Some(label.into()); self } #[must_use] pub fn throbber_set(mut self, set: throbber::Set) -> Self { self.throbber_set = set; self } #[must_use] pub fn use_type(mut self, use_type: throbber::WhichUse) -> Self { self.use_type = use_type; self } } #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] impl StatefulWidget for Throbber<'_> { type State = ThrobberState; /// Render specified index symbols. fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { buf.set_style(area, self.style); let throbber_area = area; if throbber_area.height < 1 { return; } // render a symbol. let symbol = match self.use_type { throbber::WhichUse::Spin => { state.normalize(&self); let len = self.throbber_set.symbols.len() as i8; if 0 <= state.index && state.index < len { self.throbber_set.symbols[state.index as usize] } else { self.throbber_set.empty } } }; let symbol_span = Span::styled(format!("{symbol} "), self.throbber_style); let (col, row) = buf.set_span( throbber_area.left(), throbber_area.top(), &symbol_span, symbol_span.width() as u16, ); // render a label. if let Some(label) = self.label { if throbber_area.right() <= col { return; } buf.set_span(col, row, &label, label.width() as u16); } } } #[allow(clippy::module_inception, clippy::doc_link_with_quotes)] pub mod throbber { /// A set of symbols to be rendered by throbber. #[derive(Debug, Clone)] pub struct Set { pub empty: &'static str, pub symbols: &'static [&'static str], } /// Rendering object. /// /// If Spin is specified, ThrobberState.index is used. #[derive(Debug, Clone)] pub enum WhichUse { Spin, } #[cfg(not(feature = "integration"))] pub const BRAILLE_EIGHT_DOUBLE: Set = Set { empty: " ", symbols: &["⣧", "⣏", "⡟", "⠿", "⢻", "⣹", "⣼", "⣶"], }; #[cfg(feature = "integration")] pub const BRAILLE_EIGHT_DOUBLE: Set = Set { empty: " ", symbols: &["⣧", "⣧", "⣧", "⣧", "⣧", "⣧", "⣧", "⣧"], }; }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/widgets/table.rs
crates/synd_term/src/ui/widgets/table.rs
use ratatui::{ buffer::Buffer, layout::{Constraint, Rect}, style::Modifier, widgets::{Row, StatefulWidget, TableState}, }; use crate::ui::{self, theme::EntriesTheme}; pub(crate) struct TableBuilder<H, R, C, T, S, M> { header: H, rows: R, widths: C, theme: T, selected_idx: S, highlight_modifier: M, } impl Default for TableBuilder<(), (), (), (), (), ()> { fn default() -> Self { Self { header: (), rows: (), widths: (), theme: (), selected_idx: (), highlight_modifier: (), } } } impl<R, C, T, S, M> TableBuilder<(), R, C, T, S, M> { pub(crate) fn header(self, header: Row<'_>) -> TableBuilder<Row<'_>, R, C, T, S, M> { TableBuilder { header, rows: self.rows, widths: self.widths, theme: self.theme, selected_idx: self.selected_idx, highlight_modifier: self.highlight_modifier, } } } impl<H, C, T, S, M> TableBuilder<H, (), C, T, S, M> { pub(crate) fn rows<'a, Rows>(self, rows: Rows) -> TableBuilder<H, Vec<Row<'a>>, C, T, S, M> where Rows: IntoIterator, Rows::Item: Into<Row<'a>>, { TableBuilder { header: self.header, rows: rows.into_iter().map(Into::into).collect(), widths: self.widths, theme: self.theme, selected_idx: self.selected_idx, highlight_modifier: self.highlight_modifier, } } } impl<H, R, T, S, M> TableBuilder<H, R, (), T, S, M> { pub(crate) fn widths<C>(self, widths: C) -> TableBuilder<H, R, Vec<Constraint>, T, S, M> where C: IntoIterator, C::Item: Into<Constraint>, { TableBuilder { header: self.header, rows: self.rows, widths: widths.into_iter().map(Into::into).collect(), theme: self.theme, selected_idx: self.selected_idx, highlight_modifier: self.highlight_modifier, } } } impl<H, R, C, S, M> TableBuilder<H, R, C, (), S, M> { pub(crate) fn theme(self, theme: &EntriesTheme) -> TableBuilder<H, R, C, &EntriesTheme, S, M> where C: IntoIterator, C::Item: Into<Constraint>, { TableBuilder { header: self.header, rows: self.rows, widths: self.widths, theme, selected_idx: self.selected_idx, highlight_modifier: self.highlight_modifier, } } } impl<H, R, C, T, M> TableBuilder<H, R, C, T, (), M> { pub(crate) fn selected_idx(self, selected_idx: usize) -> TableBuilder<H, R, C, T, usize, M> { TableBuilder { header: self.header, rows: self.rows, widths: self.widths, theme: self.theme, selected_idx, highlight_modifier: self.highlight_modifier, } } } impl<H, R, C, T, S> TableBuilder<H, R, C, T, S, ()> { pub(crate) fn highlight_modifier( self, highlight_modifier: Modifier, ) -> TableBuilder<H, R, C, T, S, Modifier> { TableBuilder { header: self.header, rows: self.rows, widths: self.widths, theme: self.theme, selected_idx: self.selected_idx, highlight_modifier, } } } impl<'a> TableBuilder<Row<'a>, Vec<Row<'a>>, Vec<Constraint>, &'a EntriesTheme, usize, Modifier> { pub(crate) fn build(self) -> Table<'a> { let TableBuilder { header, rows, widths, theme, selected_idx, highlight_modifier, } = self; let table = ratatui::widgets::Table::new(rows, widths) .header(header.style(theme.header)) .column_spacing(2) .highlight_symbol(ui::TABLE_HIGHLIGHT_SYMBOL) .row_highlight_style(theme.selected_entry.add_modifier(highlight_modifier)) .highlight_spacing(ratatui::widgets::HighlightSpacing::Always); let state = TableState::new().with_offset(0).with_selected(selected_idx); Table { table, state } } } pub(crate) struct Table<'a> { table: ratatui::widgets::Table<'a>, state: TableState, } impl Table<'_> { pub(crate) fn builder() -> TableBuilder<(), (), (), (), (), ()> { TableBuilder::default() } pub(crate) fn render(mut self, area: Rect, buf: &mut Buffer) { StatefulWidget::render(self.table, area, buf, &mut self.state); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/widgets/prompt.rs
crates/synd_term/src/ui/widgets/prompt.rs
use crossterm::event::{KeyCode, KeyEvent}; use ratatui::{ buffer::Buffer, layout::Rect, style::Stylize, text::{Line, Span}, widgets::Widget, }; use unicode_segmentation::GraphemeCursor; use crate::{application::event::KeyEventResult, command::Command}; #[derive(Debug, Clone, Copy)] enum Move { BackwardChar(usize), } #[derive(Debug)] pub(crate) struct Prompt { line: String, cursor: usize, } impl Prompt { pub fn new() -> Self { Self { line: String::new(), cursor: 0, } } pub fn line(&self) -> &str { self.line.as_str() } fn insert_char(&mut self, c: char) { self.line.insert(self.cursor, c); let mut cursor = GraphemeCursor::new(self.cursor, self.line.len(), true); if let Ok(Some(pos)) = cursor.next_boundary(&self.line, 0) { self.cursor = pos; } } } #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum RenderCursor { Enable, Disable, } impl Prompt { pub fn handle_key_event(&mut self, event: &KeyEvent) -> KeyEventResult { match event { KeyEvent { code: KeyCode::Backspace, .. } => { let pos = self.move_cursor(Move::BackwardChar(1)); self.line.replace_range(pos..self.cursor, ""); self.cursor = pos; KeyEventResult::consumed(Command::PromptChanged).should_render(true) } KeyEvent { code: KeyCode::Char(c), .. } => { self.insert_char(*c); KeyEventResult::consumed(Command::PromptChanged).should_render(true) } _ => KeyEventResult::Ignored, } } fn move_cursor(&self, m: Move) -> usize { match m { Move::BackwardChar(n) => { let mut position = self.cursor; for _ in 0..n { let mut cursor = GraphemeCursor::new(position, self.line.len(), true); if let Ok(Some(pos)) = cursor.prev_boundary(&self.line, 0) { position = pos; } else { break; } } position } } } pub fn render(&self, area: Rect, buf: &mut Buffer, cursor: RenderCursor) { let mut spans = vec![Span::from(&self.line)]; if cursor == RenderCursor::Enable { spans.push(Span::from(" ").reversed()); } Line::from(spans).render(area, buf); } } #[cfg(test)] mod tests { use super::*; #[test] fn prompt_ascii() { let mut p = Prompt::new(); assert!(matches!( p.handle_key_event(&KeyEvent::from(KeyCode::Char('a'))), KeyEventResult::Consumed { .. } )); p.handle_key_event(&KeyEvent::from(KeyCode::Char('b'))); p.handle_key_event(&KeyEvent::from(KeyCode::Char('c'))); assert_eq!(p.line(), "abc"); assert!(matches!( p.handle_key_event(&KeyEvent::from(KeyCode::Enter)), KeyEventResult::Ignored )); } #[test] fn prompt_grapheme() { let mut p = Prompt::new(); // insert multi byte p.handle_key_event(&KeyEvent::from(KeyCode::Char('山'))); p.handle_key_event(&KeyEvent::from(KeyCode::Char('口'))); p.handle_key_event(&KeyEvent::from(KeyCode::Backspace)); assert_eq!(p.line(), "山"); p.handle_key_event(&KeyEvent::from(KeyCode::Backspace)); assert_eq!(p.line(), ""); p.handle_key_event(&KeyEvent::from(KeyCode::Backspace)); p.handle_key_event(&KeyEvent::from(KeyCode::Backspace)); p.handle_key_event(&KeyEvent::from(KeyCode::Backspace)); assert_eq!(p.line(), ""); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/widgets/mod.rs
crates/synd_term/src/ui/widgets/mod.rs
pub(crate) mod prompt; pub(crate) mod scrollbar; pub(crate) mod table; pub(crate) mod throbber;
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/ui/widgets/scrollbar.rs
crates/synd_term/src/ui/widgets/scrollbar.rs
use ratatui::{ buffer::Buffer, layout::Rect, widgets::{ScrollbarOrientation, ScrollbarState, StatefulWidget}, }; use crate::ui::Context; pub(in crate::ui) struct Scrollbar { pub(in crate::ui) content_length: usize, pub(in crate::ui) position: usize, } impl Scrollbar { pub(in crate::ui) fn render(self, area: Rect, buf: &mut Buffer, cx: &Context<'_>) { let mut state = ScrollbarState::default() .content_length(self.content_length) .position(self.position); ratatui::widgets::Scrollbar::default() .orientation(ScrollbarOrientation::VerticalRight) .begin_symbol(None) .end_symbol(None) .track_symbol(Some(" ")) .thumb_symbol("▐") .style(cx.theme.base) .render(area, buf, &mut state); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/interact/process.rs
crates/synd_term/src/interact/process.rs
use std::{ io::{self, ErrorKind}, path::PathBuf, process::{Command, Stdio}, }; use itertools::Itertools; use url::Url; use crate::interact::{Interact, OpenBrowserError, OpenEditor, OpenTextBrowser, OpenWebBrowser}; pub struct ProcessInteractor { text_browser: TextBrowserInteractor, } impl ProcessInteractor { pub fn new(text_browser: TextBrowserInteractor) -> Self { Self { text_browser } } } impl OpenWebBrowser for ProcessInteractor { fn open_browser(&self, url: url::Url) -> Result<(), super::OpenBrowserError> { open::that(url.as_str()).map_err(OpenBrowserError::from) } } impl OpenTextBrowser for ProcessInteractor { fn open_text_browser(&self, url: Url) -> Result<(), super::OpenBrowserError> { self.text_browser.open_text_browser(url) } } impl OpenEditor for ProcessInteractor { fn open_editor(&self, initial_content: &str) -> Result<String, super::OpenEditorError> { edit::edit(initial_content).map_err(|err| super::OpenEditorError { message: err.to_string(), }) } } impl Interact for ProcessInteractor {} pub struct TextBrowserInteractor { command: PathBuf, args: Vec<String>, } impl TextBrowserInteractor { pub fn new(command: PathBuf, args: Vec<String>) -> Self { Self { command, args } } } impl OpenTextBrowser for TextBrowserInteractor { #[tracing::instrument(skip(self))] fn open_text_browser(&self, url: Url) -> Result<(), OpenBrowserError> { let status = Command::new(self.command.as_os_str()) .args(self.args.iter()) .arg(url.as_str()) .stdin(Stdio::inherit()) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .output() .map_err(|err| { if err.kind() == ErrorKind::NotFound { OpenBrowserError::CommandNotFound { command: self.command.clone(), } } else { err.into() } })? .status; if status.success() { Ok(()) } else { let full_command = if self.args.is_empty() { format!("{} {}", self.command.display(), url,) } else { format!( "{} {} {}", self.command.display(), self.args.iter().join(" "), url, ) }; Err(io::Error::other(full_command).into()) } } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/interact/mod.rs
crates/synd_term/src/interact/mod.rs
use std::{io, path::PathBuf}; #[cfg(feature = "integration")] pub mod mock; mod process; pub use process::{ProcessInteractor, TextBrowserInteractor}; use thiserror::Error; use url::Url; pub trait Interact: OpenWebBrowser + OpenTextBrowser + OpenEditor {} #[derive(Debug, Error)] pub enum OpenBrowserError { #[error("io: {0}")] Io(#[from] io::Error), #[error("command `{command}` not found")] CommandNotFound { command: PathBuf }, } pub trait OpenWebBrowser { fn open_browser(&self, url: Url) -> Result<(), OpenBrowserError>; } pub trait OpenTextBrowser { fn open_text_browser(&self, url: Url) -> Result<(), OpenBrowserError>; } #[derive(Debug, Error)] #[error("failed to open editor: {message}")] pub struct OpenEditorError { message: String, } pub trait OpenEditor { fn open_editor(&self, initial_content: &str) -> Result<String, OpenEditorError>; }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/src/interact/mock.rs
crates/synd_term/src/interact/mock.rs
use std::cell::RefCell; use url::Url; use crate::interact::{ Interact, OpenBrowserError, OpenEditor, OpenEditorError, OpenTextBrowser, OpenWebBrowser, }; pub struct MockInteractor { editor_buffer: RefCell<Vec<String>>, browser_urls: RefCell<Vec<String>>, } impl MockInteractor { pub fn new() -> Self { Self { editor_buffer: RefCell::new(Vec::new()), browser_urls: RefCell::new(Vec::new()), } } #[must_use] pub fn with_buffer(mut self, editor_buffer: Vec<String>) -> Self { self.editor_buffer = RefCell::new(editor_buffer); self } } impl OpenWebBrowser for MockInteractor { fn open_browser(&self, url: url::Url) -> Result<(), OpenBrowserError> { self.browser_urls.borrow_mut().push(url.to_string()); Ok(()) } } impl OpenTextBrowser for MockInteractor { fn open_text_browser(&self, url: Url) -> Result<(), OpenBrowserError> { self.browser_urls.borrow_mut().push(url.to_string()); Ok(()) } } impl OpenEditor for MockInteractor { fn open_editor(&self, _initial_content: &str) -> Result<String, OpenEditorError> { Ok(self.editor_buffer.borrow_mut().remove(0)) } } impl Interact for MockInteractor {}
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/tests/integration.rs
crates/synd_term/tests/integration.rs
#[cfg(feature = "integration")] mod test { use std::path::{Path, PathBuf}; use std::sync::Once; use synd_term::{ application::{Config, Features}, auth::Credential, key, shift, }; use synd_test::temp_dir; mod helper; use crate::test::helper::{ TestCase, focus_gained_event, focus_lost_event, resize_event, test_config, }; static INIT: Once = Once::new(); fn ensure_init() { INIT.call_once(|| { // Initialize rustls crypto provider for all integration tests let _ = rustls::crypto::ring::default_provider().install_default(); }); } #[tokio::test(flavor = "multi_thread")] async fn login_with_github() -> anyhow::Result<()> { helper::init_tracing(); let test_case = TestCase { mock_port: 6000, synd_api_port: 6001, kvsd_port: 47379, terminal_col_row: (120, 30), device_flow_case: "case1", cache_dir: temp_dir().keep(), ..Default::default() }; let mut application = test_case.init_app().await?; let (tx, mut event_stream) = helper::event_stream(); { application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "initial login prompt", }, { insta::assert_debug_snapshot!("initial_login", application.buffer()); }); } { // push enter => start auth flow tx.send(key!(enter)); let _ = application.event_loop_until_idle(&mut event_stream).await; insta::with_settings!({ description => "show device flow code", },{ insta::assert_debug_snapshot!("device_flow_prompt", application.buffer()); }); } { // polling device access token complete application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "initial landing entries", },{ insta::assert_debug_snapshot!("landing_entries", application.buffer()); }); } { // Rotate theme tx.send_multi([ shift!('t'), shift!('t'), shift!('t'), shift!('t'), shift!('t'), ]); application .wait_until_jobs_completed(&mut event_stream) .await; } Ok(()) } #[tokio::test(flavor = "multi_thread")] async fn login_with_google() -> anyhow::Result<()> { helper::init_tracing(); let test_case = TestCase { mock_port: 6010, synd_api_port: 6011, kvsd_port: 47389, terminal_col_row: (120, 30), device_flow_case: "case1", cache_dir: temp_dir().keep(), ..Default::default() }; let mut application = test_case.init_app().await?; let (tx, mut event_stream) = helper::event_stream(); { // push enter => start auth flow // Select google then select tx.send_multi([key!('j'), key!(enter)]); let _ = application.event_loop_until_idle(&mut event_stream).await; insta::with_settings!({ description => "show google device flow code", },{ insta::assert_debug_snapshot!("google_device_flow_prompt", application.buffer()); }); } { // polling device access token complete application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "initial landing entries after google login", },{ insta::assert_debug_snapshot!("google_landing_entries", application.buffer()); }); } Ok(()) } #[tokio::test(flavor = "multi_thread")] async fn refresh_expired_google_jwt() -> anyhow::Result<()> { ensure_init(); let (expired_jwt, expired_at) = synd_test::jwt::google_expired_jwt(); let test_case = TestCase { mock_port: 6040, synd_api_port: 6041, kvsd_port: 6042, terminal_col_row: (120, 30), device_flow_case: "case1", cache_dir: temp_dir().keep(), ..Default::default() } .with_credential(Credential::Google { id_token: expired_jwt, refresh_token: "dummy".into(), expired_at, }); let mut application = test_case.init_app().await?; let (_tx, mut event_stream) = helper::event_stream(); { application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "after_refreshing_expired_google_jwt", },{ insta::assert_debug_snapshot!("refresh_expired_google_jwt_landing", application.buffer()); }); } Ok(()) } #[tokio::test(flavor = "multi_thread")] #[allow(clippy::too_many_lines)] async fn subscribe_then_unsubscribe() -> anyhow::Result<()> { helper::init_tracing(); let test_case = TestCase { mock_port: 6020, synd_api_port: 6021, kvsd_port: 47399, terminal_col_row: (120, 30), interactor_buffer_fn: Some(|case: &TestCase| { vec![ format!( "should rust http://localhost:{mock_port}/feed/twir_atom", mock_port = case.mock_port ), // edit requirement from should to must format!( "must rust http://localhost:{mock_port}/feed/twir_atom", mock_port = case.mock_port ), // internal error format!( "may rust http://localhost:{mock_port}/feed/error/internal", mock_port = case.mock_port ), format!( "may rust http://localhost:{mock_port}/feed/error/malformed", mock_port = case.mock_port ), ] }), ..Default::default() } .already_logined(); let mut application = test_case.init_app().await?; let (tx, mut event_stream) = helper::event_stream(); { // Move tab to feeds tx.send(key!(tab)); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "after feeds tab move", },{ insta::assert_debug_snapshot!("subscribe_then_unsubscribe_landing_feeds", application.buffer()); }); } { // Subscribe tx.send(key!('a')); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "after parsing editor buffer for subscribe", },{ insta::assert_debug_snapshot!("subscribe_then_unsubscribe_after_editor_parse", application.buffer()); }); } { // Open feed. TODO: assert interactor tx.send(key!(enter)); application .wait_until_jobs_completed(&mut event_stream) .await; } { // Edit feed tx.send(key!('e')); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "after edit requirement from should to must", },{ insta::assert_debug_snapshot!("subscribe_then_unsubscribe_after_edit", application.buffer()); }); } { // Prompt unsubscribe popup and move selection tx.send_multi([key!('d'), key!('l'), key!('h')]); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "unsubscribe popup", },{ insta::assert_debug_snapshot!("subscribe_then_unsubscribe_unsubscribe_popup", application.buffer()); }); } { // Select Yes (assuming Yes is selected) tx.send(key!(enter)); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "after unsubscribe", },{ insta::assert_debug_snapshot!("subscribe_then_unsubscribe_unsubscribed", application.buffer()); }); } { // Handle the case that the server of the feed user tried to subscribe to is returning a internal error. tx.send(key!('a')); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "handle internal error of the feed server", },{ insta::assert_debug_snapshot!("subscribe_then_unsubscribe_feed_server_internal_error", application.buffer()); }); } { // Handle the case that the server of the feed user tried to subscribe to is returning a internal error. tx.send(key!('a')); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "handle malformed xml error ", },{ insta::assert_debug_snapshot!("subscribe_then_unsubscribe_malformed_xml_error", application.buffer()); }); } Ok(()) } #[tokio::test(flavor = "multi_thread")] #[allow(clippy::too_many_lines)] async fn filter_entries() -> anyhow::Result<()> { helper::init_tracing(); let test_case = TestCase { // this port is hard coded in fixtures mock_port: 6030, synd_api_port: 6031, kvsd_port: 47409, kvsd_root_dir: PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("tests/fixtures/kvsd/20240609"), terminal_col_row: (120, 30), config: Config { // To test pagination entries_per_pagination: 1, feeds_per_pagination: 1, ..test_config() }, ..Default::default() } .already_logined(); let mut application = test_case.init_app().await?; let (tx, mut event_stream) = helper::event_stream(); // Initial fetch { application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "filter entries after initial fetch", },{ insta::assert_debug_snapshot!("filter_entries_initial_fetch", application.buffer()); }); // Cover move tx.send_multi([key!('j'), key!('g'), key!('e'), key!('g'), key!('g')]); } // Move Feed tab { tx.send(key!(tab)); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "feed tab after initial fetch", },{ insta::assert_debug_snapshot!("filter_entries_initial_fetch_feed", application.buffer()); }); // Cover move_last and move_first tx.send_multi([key!('g'), key!('e'), key!('g'), key!('g')]); // Move back tx.send(key!(tab)); } { // Open entry. TODO: assert interactor tx.send(key!(enter)); application .wait_until_jobs_completed(&mut event_stream) .await; } // Filter by requirement { // Change requirement to MUST tx.send_multi([key!('h'), key!('h')]); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "entris after changing requirement to must", },{ insta::assert_debug_snapshot!("filter_entries_req_must_entries", application.buffer()); }); // Change requirement to MAY tx.send_multi([key!('l'), key!('l')]); } // Filter by category { // Enable category filter and activate first category tx.send_multi([key!('c'), key!('-'), key!('a')]); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "entris after enable category filter", },{ insta::assert_debug_snapshot!("filter_entries_category_filter_entries", application.buffer()); }); // Enable all category tx.send_multi([key!('+'), key!(esc)]); } // Filter by keyword { // Enter keyword 'rust 549' tx.send_multi([ key!('/'), key!('r'), key!('u'), key!('s'), key!('t'), key!(' '), key!('5'), key!('4'), key!('9'), ]); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "entris after keyword search", },{ insta::assert_debug_snapshot!("filter_entries_keyword_search_entries", application.buffer()); }); // Clear keyword tx.send_multi([ key!(backspace), key!(backspace), key!(backspace), key!(backspace), key!(backspace), key!(backspace), key!(backspace), key!(backspace), key!(esc), ]); } Ok(()) } #[tokio::test(flavor = "multi_thread")] async fn terminal_events() -> anyhow::Result<()> { ensure_init(); let (mut col, mut row) = (120, 30); let test_case = TestCase { mock_port: 6050, synd_api_port: 6051, kvsd_port: 6052, terminal_col_row: (col, row), ..Default::default() } .already_logined(); let mut application = test_case.init_app().await?; let (tx, mut event_stream) = helper::event_stream(); // Focus { tx.send(focus_gained_event()); tx.send(focus_lost_event()); application .wait_until_jobs_completed(&mut event_stream) .await; } // Resize loop { col /= 2; row /= 2; if col == 0 && row == 0 { break; } // Assert that app do not panic tx.send(resize_event(col, row)); application .wait_until_jobs_completed(&mut event_stream) .await; } Ok(()) } #[tokio::test(flavor = "multi_thread")] async fn unauthorized() -> anyhow::Result<()> { ensure_init(); let test_case = TestCase { mock_port: 6060, synd_api_port: 6061, kvsd_port: 6062, terminal_col_row: (120, 30), ..Default::default() } .with_credential(Credential::Github { // Use invalid token to mock unauthorized access_token: synd_test::GITHUB_INVALID_TOKEN.to_owned(), }); let mut application = test_case.init_app().await?; let (_tx, mut event_stream) = helper::event_stream(); // Assert unauthorized error message { application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "unauthorized error message(port is ignorable)", },{ insta::assert_debug_snapshot!("unauthorized_error_message", application.buffer()); }); } Ok(()) } #[tokio::test(flavor = "multi_thread")] async fn github_notifications() -> anyhow::Result<()> { helper::init_tracing(); let test_case = TestCase { mock_port: 6070, synd_api_port: 6071, kvsd_port: 6072, terminal_col_row: (120, 30), // Enable github notification features config: Config { features: Features { enable_github_notification: true, }, ..test_config() }, now: Some(*synd_test::mock::github::notifications::NOW), ..Default::default() } .already_logined(); let mut application = test_case.init_app().await?; let (tx, mut event_stream) = helper::event_stream(); { application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "github notifications initial", },{ insta::assert_debug_snapshot!("gh_notifications_init", application.buffer()); }); } { // Filter tx.send(key!('f')); // Enable private repo tx.send_multi([key!('p'), key!('r'), key!(enter)]); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "github notifications enable private repo filter", },{ insta::assert_debug_snapshot!("gh_notifications_filter_private_repo", application.buffer()); }); // Disable private and enable PR closed tx.send_multi([ key!('f'), key!('p'), key!('r'), key!('c'), key!('l'), key!(enter), ]); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "github notifications enable pr closed filter", },{ insta::assert_debug_snapshot!("gh_notifications_filter_pr_closed", application.buffer()); }); // Disable PR closed and enable review requested tx.send_multi([ key!('f'), key!('c'), key!('l'), key!('r'), key!('e'), key!(enter), ]); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "github notifications enable review requested filter", },{ insta::assert_debug_snapshot!("gh_notifications_filter_reason_review_requested", application.buffer()); }); // Clear filter conditions tx.send_multi([key!('f'), key!('r'), key!('e'), key!(enter)]); } { // Done tx.send(key!('d')); application .wait_until_jobs_completed(&mut event_stream) .await; // Unsubscribe tx.send(key!('u')); application .wait_until_jobs_completed(&mut event_stream) .await; // Done all tx.send(key!('D')); application .wait_until_jobs_completed(&mut event_stream) .await; insta::with_settings!({ description => "github notifications mark as done all", },{ insta::assert_debug_snapshot!("gh_notifications_mark_as_done_all", application.buffer()); }); } Ok(()) } #[tokio::test(flavor = "multi_thread")] async fn cli_commands() -> anyhow::Result<()> { helper::init_tracing(); let test_case = TestCase { // If the mock server on port 7000 is not functioning properly on macOS // it might be due to the AirPlay Receiver. // try uncheking System Preferences > AirPlay Receiver > On to resolve the issue. mock_port: 7000, synd_api_port: 7001, kvsd_port: 7002, cache_dir: temp_dir().keep(), ..Default::default() } .already_logined(); test_case.init_app().await?; check_command_test(test_case.synd_api_port); export_command_test(test_case.synd_api_port, &test_case.cache_dir); term_command_test(&test_case.cache_dir, &test_case.log_path); // Exec clean last clean_command_test(&test_case.cache_dir); Ok(()) } fn check_command_test(api_port: u16) { #[expect(deprecated)] let mut cmd = assert_cmd::Command::cargo_bin("synd").unwrap(); cmd.args([ "check", "--endpoint", &format!("https://localhost:{api_port}"), ]) .assert() .success(); cmd.arg("--format=json").assert().success(); } fn export_command_test(api_port: u16, cache_dir: &Path) { #[expect(deprecated)] let mut cmd = assert_cmd::Command::cargo_bin("synd").unwrap(); cmd.args([ "export", "--endpoint", &format!("https://localhost:{api_port}"), "--cache-dir", &cache_dir.display().to_string(), ]) .assert() .success(); cmd.arg("--print-schema").assert().success(); } fn clean_command_test(cache_dir: &Path) { #[expect(deprecated)] let mut cmd = assert_cmd::Command::cargo_bin("synd").unwrap(); cmd.args(["clean", "--cache-dir", &cache_dir.display().to_string()]) .assert() .success(); } fn term_command_test(cache_dir: &Path, log_path: &Path) { #[expect(deprecated)] let mut cmd = assert_cmd::Command::cargo_bin("synd").unwrap(); // Nix do not allow to create log file in user directory cmd.args([ "--dry-run", "--cache-dir", &cache_dir.display().to_string(), "--log", &log_path.display().to_string(), ]) .assert() .success(); } }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/tests/test/helper.rs
crates/synd_term/tests/test/helper.rs
use std::{path::PathBuf, sync::Once, time::Duration}; use chrono::{DateTime, Utc}; use futures_util::future; use octocrab::Octocrab; use ratatui::backend::TestBackend; use synd_api::{ cli::{CacheOptions, ServeOptions, TlsOptions}, client::github::GithubClient, dependency::Dependency, repository::{SubscriptionRepository, sqlite::DbPool, types::FeedSubscription}, shutdown::Shutdown, }; use synd_auth::{ device_flow::{DeviceFlow, provider}, jwt, }; use synd_feed::types::{Category, Requirement}; pub use synd_term::integration::event_stream; use synd_term::{ application::{ Application, Authenticator, Cache, Clock, Config, DeviceFlows, JwtService, SystemClock, }, auth::Credential, client::{github::GithubClient as TermGithubClient, synd_api::Client}, config::Categories, interact::mock::MockInteractor, terminal::Terminal, types::Time, ui::theme::Theme, }; use synd_test::temp_dir; use tokio::net::TcpListener; use tokio_util::sync::CancellationToken; use tracing_subscriber::EnvFilter; use url::Url; struct DummyClock(Time); impl Clock for DummyClock { fn now(&self) -> DateTime<Utc> { self.0 } } #[derive(Clone)] pub struct TestCase { pub mock_port: u16, pub synd_api_port: u16, pub kvsd_port: u16, pub kvsd_root_dir: PathBuf, pub terminal_col_row: (u16, u16), pub config: Config, pub device_flow_case: &'static str, pub cache_dir: PathBuf, pub log_path: PathBuf, pub now: Option<Time>, pub login_credential: Option<Credential>, pub interactor_buffer_fn: Option<fn(&TestCase) -> Vec<String>>, } pub fn test_config() -> Config { Config::default().with_idle_timer_interval(Duration::from_millis(1000)) } impl Default for TestCase { fn default() -> Self { Self { mock_port: 0, synd_api_port: 0, kvsd_port: 0, kvsd_root_dir: synd_test::temp_dir().keep(), terminal_col_row: (120, 30), config: test_config(), device_flow_case: "case1", cache_dir: temp_dir().keep(), log_path: temp_dir().keep().join("synd.log"), now: None, login_credential: None, interactor_buffer_fn: None, } } } impl TestCase { pub fn already_logined(self) -> Self { let cred = Credential::Github { access_token: "dummy_gh_token".into(), }; self.with_credential(cred) } pub fn with_credential(mut self, cred: Credential) -> Self { self.login_credential = Some(cred); self } pub async fn run_api(&self) -> anyhow::Result<()> { let TestCase { mock_port, synd_api_port, kvsd_port, kvsd_root_dir, .. } = self.clone(); // Start mock server { let addr = ("127.0.0.1", mock_port); let listener = TcpListener::bind(addr).await?; tokio::spawn(synd_test::mock::serve(listener)); } // Start synd api server { serve_api(mock_port, synd_api_port, kvsd_port, kvsd_root_dir).await?; } Ok(()) } pub async fn init_app(&self) -> anyhow::Result<Application> { let TestCase { mock_port, synd_api_port, terminal_col_row: (term_col, term_row), config, device_flow_case, cache_dir, login_credential, interactor_buffer_fn, now, .. } = self.clone(); self.run_api().await?; // Configure application let application = { let endpoint = format!("https://localhost:{synd_api_port}/graphql") .parse() .unwrap(); let terminal = new_test_terminal(term_col, term_row); let client = Client::new(endpoint, Duration::from_secs(10)).unwrap(); let device_flows = DeviceFlows { github: DeviceFlow::new( provider::Github::new("dummy") .with_device_authorization_endpoint(Url::parse(&format!( "http://localhost:{mock_port}/{device_flow_case}/github/login/device/code", )).unwrap()) .with_token_endpoint( Url::parse(&format!("http://localhost:{mock_port}/{device_flow_case}/github/login/oauth/access_token")).unwrap()), ), google: DeviceFlow::new(provider::Google::new("dummy", "dummy") .with_device_authorization_endpoint(Url::parse(&format!("http://localhost:{mock_port}/{device_flow_case}/google/login/device/code")).unwrap()) .with_token_endpoint(Url::parse(&format!("http://localhost:{mock_port}/{device_flow_case}/google/login/oauth/access_token")).unwrap()) ), }; let jwt_service = { // client_id is used for verify jwt let google_jwt_service = jwt::google::JwtService::new( synd_test::jwt::DUMMY_GOOGLE_CLIENT_ID, synd_test::jwt::DUMMY_GOOGLE_CLIENT_ID, ) .with_token_endpoint( Url::parse(&format!("http://localhost:{mock_port}/google/oauth2/token")) .unwrap(), ); JwtService::new().with_google_jwt_service(google_jwt_service) }; let authenticator = Authenticator::new() .with_device_flows(device_flows) .with_jwt_service(jwt_service); // to isolate the state for each test let cache = Cache::new(cache_dir); let mut should_reload = false; // Configure logined state if let Some(cred) = login_credential { cache .persist_credential(cred) .expect("failed to save credential to cache"); should_reload = true; } let interactor = { let buffer = if let Some(f) = interactor_buffer_fn { f(self) } else { Vec::new() }; Box::new(MockInteractor::new().with_buffer(buffer)) }; let github_client = { let octo = Octocrab::builder() .base_uri(format!("http://localhost:{mock_port}/github/rest"))? .personal_token("dummpy_gh_pat".to_owned()) .build() .unwrap(); TermGithubClient::with(octo) }; let clock: Box<dyn Clock> = { match now { Some(now) => Box::new(DummyClock(now)), None => Box::new(SystemClock), } }; let mut app = Application::builder() .terminal(terminal) .client(client) .categories(Categories::default_toml()) .config(config) .cache(cache) .theme(Theme::default()) .authenticator(authenticator) .interactor(interactor) .github_client(github_client) .clock(clock) .build(); if should_reload { app.reload_cache().await.unwrap(); } app }; Ok(application) } } pub fn init_tracing() { static INIT_SUBSCRIBER: Once = Once::new(); INIT_SUBSCRIBER.call_once(|| { // Initialize rustls crypto provider for integration tests let _ = rustls::crypto::ring::default_provider().install_default(); let show_code_location = std::env::var("SYND_LOG_LOCATION").ok().is_some(); tracing_subscriber::fmt() .with_env_filter(EnvFilter::from_default_env()) .with_line_number(show_code_location) .with_file(show_code_location) .with_target(true) .without_time() .init(); }); } pub fn new_test_terminal(width: u16, height: u16) -> Terminal { let backend = TestBackend::new(width, height); let terminal = ratatui::Terminal::new(backend).unwrap(); Terminal::with(terminal) } pub async fn serve_api( oauth_provider_port: u16, api_port: u16, kvsd_port: u16, kvsd_root_dir: PathBuf, ) -> anyhow::Result<()> { let db = { let db = DbPool::connect(kvsd_root_dir.join(format!("{kvsd_port}_synd.db"))).await?; db.migrate().await?; if api_port == 6031 { // setup fixtures let test_user_id = "899cf3fa5afc0aa1"; db.put_feed_subscription(FeedSubscription { user_id: test_user_id.into(), url: "http://localhost:6030/feed/twir_atom".try_into().unwrap(), requirement: Some(Requirement::Must), category: Some(Category::new("rust").unwrap()), }) .await?; tokio::time::sleep(Duration::from_secs(1)).await; db.put_feed_subscription(FeedSubscription { user_id: test_user_id.into(), url: "http://localhost:6030/feed/o11y_news".try_into().unwrap(), requirement: Some(Requirement::Should), category: Some(Category::new("opentelemetry").unwrap()), }) .await?; } db }; let tls_options = TlsOptions { certificate: synd_test::certificate(), private_key: synd_test::private_key(), }; let serve_options = ServeOptions { timeout: Duration::from_secs(10), body_limit_bytes: 1024 * 2, concurrency_limit: 100, }; let cache_options = CacheOptions { feed_cache_size_mb: 1, feed_cache_ttl: Duration::from_secs(60), feed_cache_refresh_interval: Duration::from_secs(3600), }; let mut dep = Dependency::new( db, tls_options, serve_options, cache_options, CancellationToken::new(), ) .await .unwrap(); { let github_endpoint: &'static str = format!("http://localhost:{oauth_provider_port}/github/graphql").leak(); let github_client = GithubClient::new()?.with_endpoint(github_endpoint); let google_jwt = jwt::google::JwtService::new("dummy_google_client_id", "dummy_google_client_secret") .with_pem_endpoint( Url::parse(&format!( "http://localhost:{oauth_provider_port}/google/oauth2/v1/certs" )) .unwrap(), ); dep.authenticator = dep .authenticator .with_github_client(github_client) .with_google_jwt(google_jwt); } let listener = TcpListener::bind(("localhost", api_port)).await?; tokio::spawn(synd_api::serve::serve( listener, dep, Shutdown::watch_signal(future::pending(), || {}), )); Ok(()) } pub fn resize_event(columns: u16, rows: u16) -> crossterm::event::Event { crossterm::event::Event::Resize(columns, rows) } pub fn focus_gained_event() -> crossterm::event::Event { crossterm::event::Event::FocusGained } pub fn focus_lost_event() -> crossterm::event::Event { crossterm::event::Event::FocusLost }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/benches/render.rs
crates/synd_term/benches/render.rs
use criterion::Criterion; use pprof::criterion::{Output, PProfProfiler}; mod bench { use criterion::Criterion; use synd_term::{integration, key}; mod helper; pub(super) fn render(c: &mut Criterion) { c.bench_function("render", move |b| { b.to_async(runtime()).iter_batched( || { let app = helper::init_app(); let (tx, event_stream) = integration::event_stream(); for _ in 0..100 { tx.send(key!('j')); } (app, event_stream) }, |(mut app, mut event_stream)| async move { app.wait_until_jobs_completed(&mut event_stream).await; }, criterion::BatchSize::SmallInput, ); }); } fn runtime() -> tokio::runtime::Runtime { tokio::runtime::Builder::new_multi_thread() .enable_all() .build() .expect("Failed building the Runtime") } } pub fn benches() { let mut criterion: Criterion<_> = Criterion::default() .with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))) .configure_from_args(); bench::render(&mut criterion); } fn main() { benches(); criterion::Criterion::default() .configure_from_args() .final_summary(); }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
ymgyt/syndicationd
https://github.com/ymgyt/syndicationd/blob/956bec58fcb6dbd9e8740d925649772b1670ead9/crates/synd_term/benches/bench/helper.rs
crates/synd_term/benches/bench/helper.rs
use std::time::Duration; use ratatui::backend::TestBackend; use synd_term::{ application::{Application, Cache, Config}, client::synd_api::Client, config::Categories, interact::mock::MockInteractor, terminal::Terminal, ui::theme::Theme, }; use url::Url; pub fn init_app() -> Application { let terminal = { let backend = TestBackend::new(120, 40); let terminal = ratatui::Terminal::new(backend).unwrap(); Terminal::with(terminal) }; let client = { Client::new( Url::parse("http://dummy.ymgyt.io").unwrap(), Duration::from_secs(10), ) .unwrap() }; let config = { Config::default().with_idle_timer_interval(Duration::from_micros(1)) }; let cache = { Cache::new(tempfile::TempDir::new().unwrap().keep()) }; Application::builder() .terminal(terminal) .client(client) .categories(Categories::default_toml()) .config(config) .cache(cache) .theme(Theme::default()) .interactor(Box::new(MockInteractor::new())) .build() }
rust
Apache-2.0
956bec58fcb6dbd9e8740d925649772b1670ead9
2026-01-04T20:11:26.769763Z
false
rust-ux/uX
https://github.com/rust-ux/uX/blob/9df9b3aa307a31fce57ee4a3529c2ae20427ef39/src/lib.rs
src/lib.rs
//! # uX - non-standard-width integers types //! //! When non-standard-width integers is required in an applications, the norm is to use a larger container and make sure the value is within range after manipulation. uX aims to take care of this once and for all by: //! //! - Providing `u1`-`u127` and `i1`-`i127` types that should behave as similar as possible to the built in rust types //! - The methods of the defined types are the same as for the built in types (far from all is implemented at this point but fill out an issue or create a PR if something essential for you is missing) //! - Overflow will panic in debug and wrap in release. //! - All possible infallible conversions is possible by using `From` and all fallible conversion by using `TryFrom`. //! //! The uX types take up as much space as the smallest integer type that can contain them; //! the compiler can not yet be made aware of further optimization potential, //! and thus does not use it: //! an `Option<u7>` still takes up two bytes. #![cfg_attr(not(feature = "std"), no_std)] mod lib { pub use core; } mod conversion; use lib::core::ops::{ BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, Shl, ShlAssign, Shr, ShrAssign, }; use lib::core::fmt::{Binary, Display, Formatter, LowerHex, Octal, UpperHex}; macro_rules! define_unsigned { ($name:ident, $bits:expr, $type:ident) => {define_unsigned!(#[doc=""], $name, $bits, $type);}; (#[$doc:meta], $name:ident, $bits:expr, $type:ident) => { #[$doc] #[allow(non_camel_case_types)] #[derive(Default, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct $name($type); impl $name { pub const MAX: Self = $name(((1 as $type) << $bits) -1 ); pub const MIN: Self = $name(0); pub const BITS: u32 = $bits; fn mask(self) -> Self { $name(self.0 & ( ((1 as $type) << $bits).overflowing_sub(1).0)) } } implement_common!($name, $bits, $type); } } macro_rules! define_signed { ($name:ident, $bits:expr, $type:ident) => {define_signed!(#[doc=""], $name, $bits, $type);}; (#[$doc:meta], $name:ident, $bits:expr, $type:ident) => { #[$doc] #[allow(non_camel_case_types)] #[derive(Default, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct $name($type); #[$doc] impl $name { pub const MAX: Self = $name(((1 as $type) << ($bits - 1)) - 1); pub const MIN: Self = $name(-((1 as $type) << ($bits - 1))); pub const BITS: u32 = $bits; fn mask(self) -> Self { if ( self.0 & (1<<($bits-1)) ) == 0 { $name(self.0 & ( ((1 as $type) << $bits).overflowing_sub(1).0)) } else { $name(self.0 | !( ((1 as $type) << $bits).overflowing_sub(1).0)) } } } implement_common!($name, $bits, $type); } } macro_rules! implement_common { ($name:ident, $bits:expr, $type:ident) => { impl $name { /// Returns the smallest value that can be represented by this integer type. pub fn min_value() -> $name { $name::MIN } /// Returns the largest value that can be represented by this integer type. pub fn max_value() -> $name { $name::MAX } /// Crates a new variable /// /// This function mainly exists as there is currently not a better way to construct these types. /// May be deprecated or removed if a better way to construct these types becomes available. /// /// # Examples /// /// Basic usage: /// /// ``` /// use ux::*; /// /// assert_eq!(u31::new(64), u31::from(64u8)); /// /// ``` /// /// # Panic /// /// This function will panic if `value` is not representable by this type pub const fn new(value: $type) -> $name { assert!(value <= $name::MAX.0 && value >= $name::MIN.0); $name(value) } /// Wrapping (modular) subtraction. Computes `self - other`, /// wrapping around at the boundary of the type. /// /// # Examples /// /// Basic usage: /// /// ``` /// use ux::*; /// /// assert_eq!(i5::MIN.wrapping_sub(i5::new(1)), i5::MAX); /// /// assert_eq!(i5::new(-10).wrapping_sub(i5::new(5)), i5::new(-15)); /// assert_eq!(i5::new(-15).wrapping_sub(i5::new(5)), i5::new(12)); /// ``` pub fn wrapping_sub(self, rhs: Self) -> Self { $name(self.0.wrapping_sub(rhs.0)).mask() } /// Wrapping (modular) addition. Computes `self + other`, /// wrapping around at the boundary of the type. /// /// # Examples /// /// Basic usage: /// /// ``` /// use ux::*; /// /// assert_eq!(i5::MAX.wrapping_add(i5::new(1)), i5::MIN); /// /// assert_eq!(i5::new(10).wrapping_add(i5::new(5)), i5::new(15)); /// assert_eq!(i5::new(15).wrapping_add(i5::new(5)), i5::new(-12)); /// ``` pub fn wrapping_add(self, rhs: Self) -> Self { $name(self.0.wrapping_add(rhs.0)).mask() } } // Implement formating functions impl Display for $name { fn fmt(&self, f: &mut Formatter) -> Result<(), lib::core::fmt::Error> { let $name(ref value) = self; <$type as Display>::fmt(value, f) } } impl UpperHex for $name { fn fmt(&self, f: &mut Formatter) -> Result<(), lib::core::fmt::Error> { let $name(ref value) = self; <$type as UpperHex>::fmt(value, f) } } impl LowerHex for $name { fn fmt(&self, f: &mut Formatter) -> Result<(), lib::core::fmt::Error> { let $name(ref value) = self; <$type as LowerHex>::fmt(value, f) } } impl Octal for $name { fn fmt(&self, f: &mut Formatter) -> Result<(), lib::core::fmt::Error> { let $name(ref value) = self; <$type as Octal>::fmt(value, f) } } impl Binary for $name { fn fmt(&self, f: &mut Formatter) -> Result<(), lib::core::fmt::Error> { let $name(ref value) = self; <$type as Binary>::fmt(value, f) } } impl<T> Shr<T> for $name where $type: Shr<T, Output = $type>, { type Output = $name; fn shr(self, rhs: T) -> $name { $name(self.0.shr(rhs)) } } impl<T> Shl<T> for $name where $type: Shl<T, Output = $type>, { type Output = $name; fn shl(self, rhs: T) -> $name { $name(self.0.shl(rhs)).mask() } } impl<T> ShrAssign<T> for $name where $type: ShrAssign<T>, { fn shr_assign(&mut self, rhs: T) { self.0.shr_assign(rhs); } } impl<T> ShlAssign<T> for $name where $type: ShlAssign<T>, { fn shl_assign(&mut self, rhs: T) { self.0.shl_assign(rhs); *self = self.mask(); } } impl BitOr<$name> for $name { type Output = $name; fn bitor(self, rhs: $name) -> Self::Output { $name(self.0.bitor(rhs.0)) } } impl<'a> BitOr<&'a $name> for $name { type Output = <$name as BitOr<$name>>::Output; fn bitor(self, rhs: &'a $name) -> Self::Output { $name(self.0.bitor(rhs.0)) } } impl<'a> BitOr<$name> for &'a $name { type Output = <$name as BitOr<$name>>::Output; fn bitor(self, rhs: $name) -> Self::Output { $name(self.0.bitor(rhs.0)) } } impl<'a> BitOr<&'a $name> for &'a $name { type Output = <$name as BitOr<$name>>::Output; fn bitor(self, rhs: &'a $name) -> Self::Output { $name(self.0.bitor(rhs.0)) } } impl BitOrAssign<$name> for $name { fn bitor_assign(&mut self, other: $name) { self.0.bitor_assign(other.0) } } impl BitXor<$name> for $name { type Output = $name; fn bitxor(self, rhs: $name) -> Self::Output { $name(self.0.bitxor(rhs.0)) } } impl<'a> BitXor<&'a $name> for $name { type Output = <$name as BitOr<$name>>::Output; fn bitxor(self, rhs: &'a $name) -> Self::Output { $name(self.0.bitxor(rhs.0)) } } impl<'a> BitXor<$name> for &'a $name { type Output = <$name as BitOr<$name>>::Output; fn bitxor(self, rhs: $name) -> Self::Output { $name(self.0.bitxor(rhs.0)) } } impl<'a> BitXor<&'a $name> for &'a $name { type Output = <$name as BitOr<$name>>::Output; fn bitxor(self, rhs: &'a $name) -> Self::Output { $name(self.0.bitxor(rhs.0)) } } impl BitXorAssign<$name> for $name { fn bitxor_assign(&mut self, other: $name) { self.0.bitxor_assign(other.0) } } impl Not for $name { type Output = $name; fn not(self) -> $name { $name(self.0.not()).mask() } } impl<'a> Not for &'a $name { type Output = <$name as Not>::Output; fn not(self) -> $name { $name(self.0.not()).mask() } } impl BitAnd<$name> for $name { type Output = $name; fn bitand(self, rhs: $name) -> Self::Output { $name(self.0.bitand(rhs.0)) } } impl<'a> BitAnd<&'a $name> for $name { type Output = <$name as BitOr<$name>>::Output; fn bitand(self, rhs: &'a $name) -> Self::Output { $name(self.0.bitand(rhs.0)) } } impl<'a> BitAnd<$name> for &'a $name { type Output = <$name as BitOr<$name>>::Output; fn bitand(self, rhs: $name) -> Self::Output { $name(self.0.bitand(rhs.0)) } } impl<'a> BitAnd<&'a $name> for &'a $name { type Output = <$name as BitOr<$name>>::Output; fn bitand(self, rhs: &'a $name) -> Self::Output { $name(self.0.bitand(rhs.0)) } } impl BitAndAssign<$name> for $name { fn bitand_assign(&mut self, other: $name) { self.0.bitand_assign(other.0) } } impl lib::core::ops::Add<$name> for $name { type Output = $name; #[allow(unused_comparisons)] fn add(self, other: $name) -> $name { if self.0 > 0 && other.0 > 0 { debug_assert!(Self::MAX.0 - other.0 >= self.0); } else if self.0 < 0 && other.0 < 0 { debug_assert!(Self::MIN.0 - other.0 <= self.0); } self.wrapping_add(other) } } impl lib::core::ops::Sub<$name> for $name { type Output = $name; #[allow(unused_comparisons)] fn sub(self, other: $name) -> $name { if self > other { debug_assert!(Self::MAX.0 + other.0 >= self.0); } else if self < other { debug_assert!(Self::MIN.0 + other.0 <= self.0); } self.wrapping_sub(other) } } }; } define_unsigned!(#[doc="The 1-bit unsigned integer type."], u1, 1, u8); define_unsigned!(#[doc="The 2-bit unsigned integer type."], u2, 2, u8); define_unsigned!(#[doc="The 3-bit unsigned integer type."], u3, 3, u8); define_unsigned!(#[doc="The 4-bit unsigned integer type."], u4, 4, u8); define_unsigned!(#[doc="The 5-bit unsigned integer type."], u5, 5, u8); define_unsigned!(#[doc="The 6-bit unsigned integer type."], u6, 6, u8); define_unsigned!(#[doc="The 7-bit unsigned integer type."], u7, 7, u8); define_unsigned!(#[doc="The 9-bit unsigned integer type."], u9, 9, u16); define_unsigned!(#[doc="The 10-bit unsigned integer type."], u10, 10, u16); define_unsigned!(#[doc="The 11-bit unsigned integer type."], u11, 11, u16); define_unsigned!(#[doc="The 12-bit unsigned integer type."], u12, 12, u16); define_unsigned!(#[doc="The 13-bit unsigned integer type."], u13, 13, u16); define_unsigned!(#[doc="The 14-bit unsigned integer type."], u14, 14, u16); define_unsigned!(#[doc="The 15-bit unsigned integer type."], u15, 15, u16); define_unsigned!(#[doc="The 17-bit unsigned integer type."], u17, 17, u32); define_unsigned!(#[doc="The 18-bit unsigned integer type."], u18, 18, u32); define_unsigned!(#[doc="The 19-bit unsigned integer type."], u19, 19, u32); define_unsigned!(#[doc="The 20-bit unsigned integer type."], u20, 20, u32); define_unsigned!(#[doc="The 21-bit unsigned integer type."], u21, 21, u32); define_unsigned!(#[doc="The 22-bit unsigned integer type."], u22, 22, u32); define_unsigned!(#[doc="The 23-bit unsigned integer type."], u23, 23, u32); define_unsigned!(#[doc="The 24-bit unsigned integer type."], u24, 24, u32); define_unsigned!(#[doc="The 25-bit unsigned integer type."], u25, 25, u32); define_unsigned!(#[doc="The 26-bit unsigned integer type."], u26, 26, u32); define_unsigned!(#[doc="The 27-bit unsigned integer type."], u27, 27, u32); define_unsigned!(#[doc="The 28-bit unsigned integer type."], u28, 28, u32); define_unsigned!(#[doc="The 29-bit unsigned integer type."], u29, 29, u32); define_unsigned!(#[doc="The 30-bit unsigned integer type."], u30, 30, u32); define_unsigned!(#[doc="The 31-bit unsigned integer type."], u31, 31, u32); define_unsigned!(#[doc="The 33-bit unsigned integer type."], u33, 33, u64); define_unsigned!(#[doc="The 34-bit unsigned integer type."], u34, 34, u64); define_unsigned!(#[doc="The 35-bit unsigned integer type."], u35, 35, u64); define_unsigned!(#[doc="The 36-bit unsigned integer type."], u36, 36, u64); define_unsigned!(#[doc="The 37-bit unsigned integer type."], u37, 37, u64); define_unsigned!(#[doc="The 38-bit unsigned integer type."], u38, 38, u64); define_unsigned!(#[doc="The 39-bit unsigned integer type."], u39, 39, u64); define_unsigned!(#[doc="The 40-bit unsigned integer type."], u40, 40, u64); define_unsigned!(#[doc="The 41-bit unsigned integer type."], u41, 41, u64); define_unsigned!(#[doc="The 42-bit unsigned integer type."], u42, 42, u64); define_unsigned!(#[doc="The 43-bit unsigned integer type."], u43, 43, u64); define_unsigned!(#[doc="The 44-bit unsigned integer type."], u44, 44, u64); define_unsigned!(#[doc="The 45-bit unsigned integer type."], u45, 45, u64); define_unsigned!(#[doc="The 46-bit unsigned integer type."], u46, 46, u64); define_unsigned!(#[doc="The 47-bit unsigned integer type."], u47, 47, u64); define_unsigned!(#[doc="The 48-bit unsigned integer type."], u48, 48, u64); define_unsigned!(#[doc="The 49-bit unsigned integer type."], u49, 49, u64); define_unsigned!(#[doc="The 50-bit unsigned integer type."], u50, 50, u64); define_unsigned!(#[doc="The 51-bit unsigned integer type."], u51, 51, u64); define_unsigned!(#[doc="The 52-bit unsigned integer type."], u52, 52, u64); define_unsigned!(#[doc="The 53-bit unsigned integer type."], u53, 53, u64); define_unsigned!(#[doc="The 54-bit unsigned integer type."], u54, 54, u64); define_unsigned!(#[doc="The 55-bit unsigned integer type."], u55, 55, u64); define_unsigned!(#[doc="The 56-bit unsigned integer type."], u56, 56, u64); define_unsigned!(#[doc="The 57-bit unsigned integer type."], u57, 57, u64); define_unsigned!(#[doc="The 58-bit unsigned integer type."], u58, 58, u64); define_unsigned!(#[doc="The 59-bit unsigned integer type."], u59, 59, u64); define_unsigned!(#[doc="The 60-bit unsigned integer type."], u60, 60, u64); define_unsigned!(#[doc="The 61-bit unsigned integer type."], u61, 61, u64); define_unsigned!(#[doc="The 62-bit unsigned integer type."], u62, 62, u64); define_unsigned!(#[doc="The 63-bit unsigned integer type."], u63, 63, u64); define_unsigned!(#[doc="The 65-bit unsigned integer type."], u65, 65, u128); define_unsigned!(#[doc="The 66-bit unsigned integer type."], u66, 66, u128); define_unsigned!(#[doc="The 67-bit unsigned integer type."], u67, 67, u128); define_unsigned!(#[doc="The 68-bit unsigned integer type."], u68, 68, u128); define_unsigned!(#[doc="The 69-bit unsigned integer type."], u69, 69, u128); define_unsigned!(#[doc="The 70-bit unsigned integer type."], u70, 70, u128); define_unsigned!(#[doc="The 71-bit unsigned integer type."], u71, 71, u128); define_unsigned!(#[doc="The 72-bit unsigned integer type."], u72, 72, u128); define_unsigned!(#[doc="The 73-bit unsigned integer type."], u73, 73, u128); define_unsigned!(#[doc="The 74-bit unsigned integer type."], u74, 74, u128); define_unsigned!(#[doc="The 75-bit unsigned integer type."], u75, 75, u128); define_unsigned!(#[doc="The 76-bit unsigned integer type."], u76, 76, u128); define_unsigned!(#[doc="The 77-bit unsigned integer type."], u77, 77, u128); define_unsigned!(#[doc="The 78-bit unsigned integer type."], u78, 78, u128); define_unsigned!(#[doc="The 79-bit unsigned integer type."], u79, 79, u128); define_unsigned!(#[doc="The 80-bit unsigned integer type."], u80, 80, u128); define_unsigned!(#[doc="The 81-bit unsigned integer type."], u81, 81, u128); define_unsigned!(#[doc="The 82-bit unsigned integer type."], u82, 82, u128); define_unsigned!(#[doc="The 83-bit unsigned integer type."], u83, 83, u128); define_unsigned!(#[doc="The 84-bit unsigned integer type."], u84, 84, u128); define_unsigned!(#[doc="The 85-bit unsigned integer type."], u85, 85, u128); define_unsigned!(#[doc="The 86-bit unsigned integer type."], u86, 86, u128); define_unsigned!(#[doc="The 87-bit unsigned integer type."], u87, 87, u128); define_unsigned!(#[doc="The 88-bit unsigned integer type."], u88, 88, u128); define_unsigned!(#[doc="The 89-bit unsigned integer type."], u89, 89, u128); define_unsigned!(#[doc="The 90-bit unsigned integer type."], u90, 90, u128); define_unsigned!(#[doc="The 91-bit unsigned integer type."], u91, 91, u128); define_unsigned!(#[doc="The 92-bit unsigned integer type."], u92, 92, u128); define_unsigned!(#[doc="The 93-bit unsigned integer type."], u93, 93, u128); define_unsigned!(#[doc="The 94-bit unsigned integer type."], u94, 94, u128); define_unsigned!(#[doc="The 95-bit unsigned integer type."], u95, 95, u128); define_unsigned!(#[doc="The 96-bit unsigned integer type."], u96, 96, u128); define_unsigned!(#[doc="The 97-bit unsigned integer type."], u97, 97, u128); define_unsigned!(#[doc="The 98-bit unsigned integer type."], u98, 98, u128); define_unsigned!(#[doc="The 99-bit unsigned integer type."], u99, 99, u128); define_unsigned!(#[doc="The 100-bit unsigned integer type."], u100, 100, u128); define_unsigned!(#[doc="The 101-bit unsigned integer type."], u101, 101, u128); define_unsigned!(#[doc="The 102-bit unsigned integer type."], u102, 102, u128); define_unsigned!(#[doc="The 103-bit unsigned integer type."], u103, 103, u128); define_unsigned!(#[doc="The 104-bit unsigned integer type."], u104, 104, u128); define_unsigned!(#[doc="The 105-bit unsigned integer type."], u105, 105, u128); define_unsigned!(#[doc="The 106-bit unsigned integer type."], u106, 106, u128); define_unsigned!(#[doc="The 107-bit unsigned integer type."], u107, 107, u128); define_unsigned!(#[doc="The 108-bit unsigned integer type."], u108, 108, u128); define_unsigned!(#[doc="The 109-bit unsigned integer type."], u109, 109, u128); define_unsigned!(#[doc="The 110-bit unsigned integer type."], u110, 110, u128); define_unsigned!(#[doc="The 111-bit unsigned integer type."], u111, 111, u128); define_unsigned!(#[doc="The 112-bit unsigned integer type."], u112, 112, u128); define_unsigned!(#[doc="The 113-bit unsigned integer type."], u113, 113, u128); define_unsigned!(#[doc="The 114-bit unsigned integer type."], u114, 114, u128); define_unsigned!(#[doc="The 115-bit unsigned integer type."], u115, 115, u128); define_unsigned!(#[doc="The 116-bit unsigned integer type."], u116, 116, u128); define_unsigned!(#[doc="The 117-bit unsigned integer type."], u117, 117, u128); define_unsigned!(#[doc="The 118-bit unsigned integer type."], u118, 118, u128); define_unsigned!(#[doc="The 119-bit unsigned integer type."], u119, 119, u128); define_unsigned!(#[doc="The 120-bit unsigned integer type."], u120, 120, u128); define_unsigned!(#[doc="The 121-bit unsigned integer type."], u121, 121, u128); define_unsigned!(#[doc="The 122-bit unsigned integer type."], u122, 122, u128); define_unsigned!(#[doc="The 123-bit unsigned integer type."], u123, 123, u128); define_unsigned!(#[doc="The 124-bit unsigned integer type."], u124, 124, u128); define_unsigned!(#[doc="The 125-bit unsigned integer type."], u125, 125, u128); define_unsigned!(#[doc="The 126-bit unsigned integer type."], u126, 126, u128); define_unsigned!(#[doc="The 127-bit unsigned integer type."], u127, 127, u128); define_signed!(#[doc="The 1-bit signed integer type."], i1, 1, i8); define_signed!(#[doc="The 2-bit signed integer type."], i2, 2, i8); define_signed!(#[doc="The 3-bit signed integer type."], i3, 3, i8); define_signed!(#[doc="The 4-bit signed integer type."], i4, 4, i8); define_signed!(#[doc="The 5-bit signed integer type."], i5, 5, i8); define_signed!(#[doc="The 6-bit signed integer type."], i6, 6, i8); define_signed!(#[doc="The 7-bit signed integer type."], i7, 7, i8); define_signed!(#[doc="The 9-bit signed integer type."], i9, 9, i16); define_signed!(#[doc="The 10-bit signed integer type."], i10, 10, i16); define_signed!(#[doc="The 11-bit signed integer type."], i11, 11, i16); define_signed!(#[doc="The 12-bit signed integer type."], i12, 12, i16); define_signed!(#[doc="The 13-bit signed integer type."], i13, 13, i16); define_signed!(#[doc="The 14-bit signed integer type."], i14, 14, i16); define_signed!(#[doc="The 15-bit signed integer type."], i15, 15, i16); define_signed!(#[doc="The 17-bit signed integer type."], i17, 17, i32); define_signed!(#[doc="The 18-bit signed integer type."], i18, 18, i32); define_signed!(#[doc="The 19-bit signed integer type."], i19, 19, i32); define_signed!(#[doc="The 20-bit signed integer type."], i20, 20, i32); define_signed!(#[doc="The 21-bit signed integer type."], i21, 21, i32); define_signed!(#[doc="The 22-bit signed integer type."], i22, 22, i32); define_signed!(#[doc="The 23-bit signed integer type."], i23, 23, i32); define_signed!(#[doc="The 24-bit signed integer type."], i24, 24, i32); define_signed!(#[doc="The 25-bit signed integer type."], i25, 25, i32); define_signed!(#[doc="The 26-bit signed integer type."], i26, 26, i32); define_signed!(#[doc="The 27-bit signed integer type."], i27, 27, i32); define_signed!(#[doc="The 28-bit signed integer type."], i28, 28, i32); define_signed!(#[doc="The 29-bit signed integer type."], i29, 29, i32); define_signed!(#[doc="The 30-bit signed integer type."], i30, 30, i32); define_signed!(#[doc="The 31-bit signed integer type."], i31, 31, i32); define_signed!(#[doc="The 33-bit signed integer type."], i33, 33, i64); define_signed!(#[doc="The 34-bit signed integer type."], i34, 34, i64); define_signed!(#[doc="The 35-bit signed integer type."], i35, 35, i64); define_signed!(#[doc="The 36-bit signed integer type."], i36, 36, i64); define_signed!(#[doc="The 37-bit signed integer type."], i37, 37, i64); define_signed!(#[doc="The 38-bit signed integer type."], i38, 38, i64); define_signed!(#[doc="The 39-bit signed integer type."], i39, 39, i64); define_signed!(#[doc="The 40-bit signed integer type."], i40, 40, i64); define_signed!(#[doc="The 41-bit signed integer type."], i41, 41, i64); define_signed!(#[doc="The 42-bit signed integer type."], i42, 42, i64); define_signed!(#[doc="The 43-bit signed integer type."], i43, 43, i64); define_signed!(#[doc="The 44-bit signed integer type."], i44, 44, i64); define_signed!(#[doc="The 45-bit signed integer type."], i45, 45, i64); define_signed!(#[doc="The 46-bit signed integer type."], i46, 46, i64); define_signed!(#[doc="The 47-bit signed integer type."], i47, 47, i64); define_signed!(#[doc="The 48-bit signed integer type."], i48, 48, i64); define_signed!(#[doc="The 49-bit signed integer type."], i49, 49, i64); define_signed!(#[doc="The 50-bit signed integer type."], i50, 50, i64); define_signed!(#[doc="The 51-bit signed integer type."], i51, 51, i64); define_signed!(#[doc="The 52-bit signed integer type."], i52, 52, i64); define_signed!(#[doc="The 53-bit signed integer type."], i53, 53, i64); define_signed!(#[doc="The 54-bit signed integer type."], i54, 54, i64); define_signed!(#[doc="The 55-bit signed integer type."], i55, 55, i64); define_signed!(#[doc="The 56-bit signed integer type."], i56, 56, i64); define_signed!(#[doc="The 57-bit signed integer type."], i57, 57, i64); define_signed!(#[doc="The 58-bit signed integer type."], i58, 58, i64); define_signed!(#[doc="The 59-bit signed integer type."], i59, 59, i64); define_signed!(#[doc="The 60-bit signed integer type."], i60, 60, i64); define_signed!(#[doc="The 61-bit signed integer type."], i61, 61, i64); define_signed!(#[doc="The 62-bit signed integer type."], i62, 62, i64); define_signed!(#[doc="The 63-bit signed integer type."], i63, 63, i64); define_signed!(#[doc="The 65-bit signed integer type."], i65, 65, i128); define_signed!(#[doc="The 66-bit signed integer type."], i66, 66, i128); define_signed!(#[doc="The 67-bit signed integer type."], i67, 67, i128); define_signed!(#[doc="The 68-bit signed integer type."], i68, 68, i128); define_signed!(#[doc="The 69-bit signed integer type."], i69, 69, i128); define_signed!(#[doc="The 70-bit signed integer type."], i70, 70, i128); define_signed!(#[doc="The 71-bit signed integer type."], i71, 71, i128); define_signed!(#[doc="The 72-bit signed integer type."], i72, 72, i128); define_signed!(#[doc="The 73-bit signed integer type."], i73, 73, i128); define_signed!(#[doc="The 74-bit signed integer type."], i74, 74, i128); define_signed!(#[doc="The 75-bit signed integer type."], i75, 75, i128); define_signed!(#[doc="The 76-bit signed integer type."], i76, 76, i128); define_signed!(#[doc="The 77-bit signed integer type."], i77, 77, i128); define_signed!(#[doc="The 78-bit signed integer type."], i78, 78, i128); define_signed!(#[doc="The 79-bit signed integer type."], i79, 79, i128); define_signed!(#[doc="The 80-bit signed integer type."], i80, 80, i128); define_signed!(#[doc="The 81-bit signed integer type."], i81, 81, i128); define_signed!(#[doc="The 82-bit signed integer type."], i82, 82, i128); define_signed!(#[doc="The 83-bit signed integer type."], i83, 83, i128); define_signed!(#[doc="The 84-bit signed integer type."], i84, 84, i128); define_signed!(#[doc="The 85-bit signed integer type."], i85, 85, i128); define_signed!(#[doc="The 86-bit signed integer type."], i86, 86, i128); define_signed!(#[doc="The 87-bit signed integer type."], i87, 87, i128); define_signed!(#[doc="The 88-bit signed integer type."], i88, 88, i128); define_signed!(#[doc="The 89-bit signed integer type."], i89, 89, i128); define_signed!(#[doc="The 90-bit signed integer type."], i90, 90, i128); define_signed!(#[doc="The 91-bit signed integer type."], i91, 91, i128); define_signed!(#[doc="The 92-bit signed integer type."], i92, 92, i128); define_signed!(#[doc="The 93-bit signed integer type."], i93, 93, i128); define_signed!(#[doc="The 94-bit signed integer type."], i94, 94, i128); define_signed!(#[doc="The 95-bit signed integer type."], i95, 95, i128); define_signed!(#[doc="The 96-bit signed integer type."], i96, 96, i128); define_signed!(#[doc="The 97-bit signed integer type."], i97, 97, i128); define_signed!(#[doc="The 98-bit signed integer type."], i98, 98, i128); define_signed!(#[doc="The 99-bit signed integer type."], i99, 99, i128); define_signed!(#[doc="The 100-bit signed integer type."], i100, 100, i128); define_signed!(#[doc="The 101-bit signed integer type."], i101, 101, i128); define_signed!(#[doc="The 102-bit signed integer type."], i102, 102, i128); define_signed!(#[doc="The 103-bit signed integer type."], i103, 103, i128); define_signed!(#[doc="The 104-bit signed integer type."], i104, 104, i128); define_signed!(#[doc="The 105-bit signed integer type."], i105, 105, i128); define_signed!(#[doc="The 106-bit signed integer type."], i106, 106, i128); define_signed!(#[doc="The 107-bit signed integer type."], i107, 107, i128); define_signed!(#[doc="The 108-bit signed integer type."], i108, 108, i128); define_signed!(#[doc="The 109-bit signed integer type."], i109, 109, i128); define_signed!(#[doc="The 110-bit signed integer type."], i110, 110, i128); define_signed!(#[doc="The 111-bit signed integer type."], i111, 111, i128); define_signed!(#[doc="The 112-bit signed integer type."], i112, 112, i128); define_signed!(#[doc="The 113-bit signed integer type."], i113, 113, i128); define_signed!(#[doc="The 114-bit signed integer type."], i114, 114, i128); define_signed!(#[doc="The 115-bit signed integer type."], i115, 115, i128); define_signed!(#[doc="The 116-bit signed integer type."], i116, 116, i128); define_signed!(#[doc="The 117-bit signed integer type."], i117, 117, i128); define_signed!(#[doc="The 118-bit signed integer type."], i118, 118, i128); define_signed!(#[doc="The 119-bit signed integer type."], i119, 119, i128); define_signed!(#[doc="The 120-bit signed integer type."], i120, 120, i128); define_signed!(#[doc="The 121-bit signed integer type."], i121, 121, i128); define_signed!(#[doc="The 122-bit signed integer type."], i122, 122, i128); define_signed!(#[doc="The 123-bit signed integer type."], i123, 123, i128); define_signed!(#[doc="The 124-bit signed integer type."], i124, 124, i128); define_signed!(#[doc="The 125-bit signed integer type."], i125, 125, i128); define_signed!(#[doc="The 126-bit signed integer type."], i126, 126, i128); define_signed!(#[doc="The 127-bit signed integer type."], i127, 127, i128); #[cfg(test)] mod tests { use super::*; #[test] fn test_masking() { assert_eq!(u4(0b11000110).mask().0, 0b00000110); assert_eq!(u4(0b00001000).mask().0, 0b00001000); assert_eq!(u4(0b00001110).mask().0, 0b00001110); assert_eq!(i4(0b11000110u8 as i8).mask().0, 0b00000110u8 as i8); assert_eq!(i4(0b00001000u8 as i8).mask().0, 0b11111000u8 as i8); assert_eq!(i4(0b00001110u8 as i8).mask().0, 0b11111110u8 as i8); } #[test] fn min_max_values() { assert_eq!(u1::MAX, u1(1)); assert_eq!(u2::MAX, u2(3)); assert_eq!(u3::MAX, u3(7)); assert_eq!(u7::MAX, u7(127)); assert_eq!(u9::MAX, u9(511)); assert_eq!(i1::MAX, i1(0)); assert_eq!(i2::MAX, i2(1)); assert_eq!(i3::MAX, i3(3)); assert_eq!(i7::MAX, i7(63)); assert_eq!(i9::MAX, i9(255)); assert_eq!(u1::MIN, u1(0)); assert_eq!(u2::MIN, u2(0)); assert_eq!(u3::MIN, u3(0)); assert_eq!(u7::MIN, u7(0)); assert_eq!(u9::MIN, u9(0)); assert_eq!(u127::MIN, u127(0)); assert_eq!(i1::MIN, i1(-1)); assert_eq!(i2::MIN, i2(-2)); assert_eq!(i3::MIN, i3(-4)); assert_eq!(i7::MIN, i7(-64)); assert_eq!(i9::MIN, i9(-256)); } #[test] fn test_bits_values() { assert_eq!(u1::BITS, 1); assert_eq!(i7::BITS, 7); assert_eq!(u127::BITS, 127); } #[test] fn test_wrapping_add() { assert_eq!(u1::MAX.wrapping_add(u1(1)), u1(0)); assert_eq!(u1::MAX.wrapping_add(u1(0)), u1(1)); assert_eq!(u5::MAX.wrapping_add(u5(1)), u5(0)); assert_eq!(u5::MAX.wrapping_add(u5(4)), u5(3)); assert_eq!(u127::MAX.wrapping_add(u127(100)), u127(99));
rust
Apache-2.0
9df9b3aa307a31fce57ee4a3529c2ae20427ef39
2026-01-04T20:20:28.114552Z
true
rust-ux/uX
https://github.com/rust-ux/uX/blob/9df9b3aa307a31fce57ee4a3529c2ae20427ef39/src/conversion.rs
src/conversion.rs
use crate::*; /// The error type returned when a checked integral type conversion fails. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct TryFromIntError(pub(crate) ()); impl From<lib::core::num::TryFromIntError> for TryFromIntError { fn from(_: lib::core::num::TryFromIntError) -> TryFromIntError { TryFromIntError(()) } } impl From<lib::core::convert::Infallible> for TryFromIntError { fn from(_: lib::core::convert::Infallible) -> TryFromIntError { TryFromIntError(()) } } impl Display for TryFromIntError { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "out of range integral type conversion attempted") } } #[cfg(feature = "std")] impl std::error::Error for TryFromIntError {} // Only implement if $from can be converted into $name lossless macro_rules! implement_from { {[$($name:ident),*], [$($from:ident),*] } => {$(implement_from!($name, $from);)*}; {$name:ident, [$($from:ident),*] } => {$(implement_from!($name, $from);)*}; {[$($name:ident),*], $from:ident } => {$(implement_from!($name, $from);)*}; {$name:ident, $from:ty} => { impl From<$from> for $name { fn from(x: $from) -> $name { $name(x.into()) } } }; } macro_rules! implement_try_from { {[$($name:ident),*], [$($from:ident),*] } => {$(implement_try_from!($name, $from);)*}; {$name:ident, [$($from:ident),*] } => {$(implement_try_from!($name, $from);)*}; {[$($name:ident),*], $from:ident } => {$(implement_try_from!($name, $from);)*}; {$name:ident, $from:ty} => { impl TryFrom<$from> for $name { type Error = TryFromIntError; fn try_from(x: $from) -> Result<$name, Self::Error> { // First get the value into the correct type let value = x.try_into()?; if value <= $name::MAX.into() && value >= $name::MIN.into() { Ok($name(value)) } else { Err(TryFromIntError(())) } } } }; } // Only implement if $type can be converted from $name lossless macro_rules! implement_into { {[$($name:ident),*], $from:ident } => {$(implement_into!($name, $from);)*}; {$name:ident, $into:ident} => { impl From<$name> for $into { fn from(x: $name) -> $into { $into::from(x.0) } } }; } macro_rules! implement_try_into { {[$($name:ident),*], $from:ident } => {$(implement_try_into!($name, $from);)*}; {$name:ident, $into:ident} => { impl TryFrom<$name> for $into { type Error = TryFromIntError; fn try_from(x: $name) -> Result<$into, Self::Error> { Ok($into::try_from(x.0)?) } } }; } // Implement From for all unsigned integers implement_try_from!([u1, u2, u3, u4, u5, u6, u7], u8); implement_from!([u9, u10, u11, u12, u13, u14, u15], u8); implement_from!([u17, u18, u19, u20, u21, u22, u23, u24], u8); implement_from!([u25, u26, u27, u28, u29, u30, u31], u8); implement_from!([u33, u34, u35, u36, u37, u38, u39, u40], u8); implement_from!([u41, u42, u43, u44, u45, u46, u47, u48], u8); implement_from!([u49, u50, u51, u52, u53, u54, u55, u56], u8); implement_from!([u57, u58, u59, u60, u61, u62, u63], u8); implement_into!([u1, u2, u3, u4, u5, u6, u7], u8); implement_try_into!([u9, u10, u11, u12, u13, u14, u15], u8); implement_try_into!([u17, u18, u19, u20, u21, u22, u23, u24], u8); implement_try_into!([u25, u26, u27, u28, u29, u30, u31], u8); implement_try_into!([u33, u34, u35, u36, u37, u38, u39, u40], u8); implement_try_into!([u41, u42, u43, u44, u45, u46, u47, u48], u8); implement_try_into!([u49, u50, u51, u52, u53, u54, u55, u56], u8); implement_try_into!([u57, u58, u59, u60, u61, u62, u63], u8); implement_try_from!([u1, u2, u3, u4, u5, u6, u7], u16); implement_try_from!([u9, u10, u11, u12, u13, u14, u15], u16); implement_from!([u17, u18, u19, u20, u21, u22, u23, u24], u16); implement_from!([u25, u26, u27, u28, u29, u30, u31], u16); implement_from!([u33, u34, u35, u36, u37, u38, u39, u40], u16); implement_from!([u41, u42, u43, u44, u45, u46, u47, u48], u16); implement_from!([u49, u50, u51, u52, u53, u54, u55, u56], u16); implement_from!([u57, u58, u59, u60, u61, u62, u63], u16); implement_into!([u1, u2, u3, u4, u5, u6, u7], u16); implement_into!([u9, u10, u11, u12, u13, u14, u15], u16); implement_try_into!([u17, u18, u19, u20, u21, u22, u23, u24], u16); implement_try_into!([u25, u26, u27, u28, u29, u30, u31], u16); implement_try_into!([u33, u34, u35, u36, u37, u38, u39, u40], u16); implement_try_into!([u41, u42, u43, u44, u45, u46, u47, u48], u16); implement_try_into!([u49, u50, u51, u52, u53, u54, u55, u56], u16); implement_try_into!([u57, u58, u59, u60, u61, u62, u63], u16); implement_try_from!([u1, u2, u3, u4, u5, u6, u7], u32); implement_try_from!([u9, u10, u11, u12, u13, u14, u15], u32); implement_try_from!([u17, u18, u19, u20, u21, u22, u23, u24], u32); implement_try_from!([u25, u26, u27, u28, u29, u30, u31], u32); implement_from!([u33, u34, u35, u36, u37, u38, u39, u40], u32); implement_from!([u41, u42, u43, u44, u45, u46, u47, u48], u32); implement_from!([u49, u50, u51, u52, u53, u54, u55, u56], u32); implement_from!([u57, u58, u59, u60, u61, u62, u63], u32); implement_into!([u1, u2, u3, u4, u5, u6, u7], u32); implement_into!([u9, u10, u11, u12, u13, u14, u15], u32); implement_into!([u17, u18, u19, u20, u21, u22, u23, u24], u32); implement_into!([u25, u26, u27, u28, u29, u30, u31], u32); implement_try_into!([u33, u34, u35, u36, u37, u38, u39, u40], u32); implement_try_into!([u41, u42, u43, u44, u45, u46, u47, u48], u32); implement_try_into!([u49, u50, u51, u52, u53, u54, u55, u56], u32); implement_try_into!([u57, u58, u59, u60, u61, u62, u63], u32); implement_try_from!([u1, u2, u3, u4, u5, u6, u7], u64); implement_try_from!([u9, u10, u11, u12, u13, u14, u15], u64); implement_try_from!([u17, u18, u19, u20, u21, u22, u23, u24], u64); implement_try_from!([u25, u26, u27, u28, u29, u30, u31], u64); implement_try_from!([u33, u34, u35, u36, u37, u38, u39, u40], u64); implement_try_from!([u41, u42, u43, u44, u45, u46, u47, u48], u64); implement_try_from!([u49, u50, u51, u52, u53, u54, u55, u56], u64); implement_try_from!([u57, u58, u59, u60, u61, u62, u63], u64); implement_into!([u1, u2, u3, u4, u5, u6, u7], u64); implement_into!([u9, u10, u11, u12, u13, u14, u15], u64); implement_into!([u17, u18, u19, u20, u21, u22, u23, u24], u64); implement_into!([u25, u26, u27, u28, u29, u30, u31], u64); implement_into!([u33, u34, u35, u36, u37, u38, u39, u40], u64); implement_into!([u41, u42, u43, u44, u45, u46, u47, u48], u64); implement_into!([u49, u50, u51, u52, u53, u54, u55, u56], u64); implement_into!([u57, u58, u59, u60, u61, u62, u63], u64); implement_try_into!([u1, u2, u3, u4, u5, u6, u7], usize); implement_try_into!([u9, u10, u11, u12, u13, u14, u15], usize); implement_try_into!([u17, u18, u19, u20, u21, u22, u23, u24], usize); implement_try_into!([u25, u26, u27, u28, u29, u30, u31], usize); implement_try_into!([u33, u34, u35, u36, u37, u38, u39, u40], usize); implement_try_into!([u41, u42, u43, u44, u45, u46, u47, u48], usize); implement_try_into!([u49, u50, u51, u52, u53, u54, u55, u56], usize); implement_try_into!([u57, u58, u59, u60, u61, u62, u63], usize); implement_try_from!( u1, [ u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!(u2, [u1]); implement_try_from!( u2, [ u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!(u3, [u2, u1]); implement_try_from!( u3, [ u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!(u4, [u1, u2, u3]); implement_try_from!( u4, [ u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!(u5, [u1, u2, u3, u4]); implement_try_from!( u5, [ u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!(u6, [u1, u2, u3, u4, u5]); implement_try_from!( u6, [ u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!(u7, [u1, u2, u3, u4, u5, u6]); implement_try_from!( u7, [ u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!(u9, [u1, u2, u3, u4, u5, u6, u7]); implement_try_from!( u9, [ u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!(u10, [u1, u2, u3, u4, u5, u6, u7, u9]); implement_try_from!( u10, [ u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!(u11, [u1, u2, u3, u4, u5, u6, u7, u9, u10]); implement_try_from!( u11, [ u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!(u12, [u1, u2, u3, u4, u5, u6, u7, u9, u10, u11]); implement_try_from!( u12, [ u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!(u13, [u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12]); implement_try_from!( u13, [ u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!(u14, [u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13]); implement_try_from!( u14, [ u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u15, [u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14] ); implement_try_from!( u15, [ u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u17, [u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15] ); implement_try_from!( u17, [ u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u18, [u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17] ); implement_try_from!( u18, [ u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u19, [u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18] ); implement_try_from!( u19, [ u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u20, [u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19] ); implement_try_from!( u20, [ u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u21, [u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20] ); implement_try_from!( u21, [ u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u22, [u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21] ); implement_try_from!( u22, [ u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u23, [u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22] ); implement_try_from!( u23, [ u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u24, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23 ] ); implement_try_from!( u24, [ u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u25, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24 ] ); implement_try_from!( u25, [ u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u26, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25 ] ); implement_try_from!( u26, [ u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u27, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26 ] ); implement_try_from!( u27, [ u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u28, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27 ] ); implement_try_from!( u28, [ u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u29, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28 ] ); implement_try_from!( u29, [ u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u30, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29 ] ); implement_try_from!( u30, [ u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u31, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30 ] ); implement_try_from!( u31, [ u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u33, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31 ] ); implement_try_from!( u33, [ u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u34, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33 ] ); implement_try_from!( u34, [ u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u35, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34 ] ); implement_try_from!( u35, [ u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u36, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35 ] ); implement_try_from!( u36, [ u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u37, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36 ] ); implement_try_from!( u37, [ u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u38, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37 ] ); implement_try_from!( u38, [ u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u39, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38 ] ); implement_try_from!( u39, [ u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u40, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39 ] ); implement_try_from!( u40, [ u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u41, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40 ] ); implement_try_from!( u41, [ u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u42, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41 ] ); implement_try_from!( u42, [ u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u43, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42 ] ); implement_try_from!( u43, [ u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u44, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43 ] ); implement_try_from!( u44, [ u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u45, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44 ] ); implement_try_from!( u45, [ u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize ] ); implement_from!( u46, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45 ] ); implement_try_from!( u46, [u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize] ); implement_from!( u47, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46 ] ); implement_try_from!( u47, [u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize] ); implement_from!( u48, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47 ] ); implement_try_from!( u48, [u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize] ); implement_from!( u49, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48 ] ); implement_try_from!( u49, [u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize] ); implement_from!( u50, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49 ] ); implement_try_from!( u50, [u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize] ); implement_from!( u51, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50 ] ); implement_try_from!( u51, [u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize] ); implement_from!( u52, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51 ] ); implement_try_from!( u52, [u53, u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize] ); implement_from!( u53, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52 ] ); implement_try_from!( u53, [u54, u55, u56, u57, u58, u59, u60, u61, u62, u63, usize] ); implement_from!( u54, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53 ] ); implement_try_from!(u54, [u55, u56, u57, u58, u59, u60, u61, u62, u63, usize]); implement_from!( u55, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54 ] ); implement_try_from!(u55, [u56, u57, u58, u59, u60, u61, u62, u63, usize]); implement_from!( u56, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55 ] ); implement_try_from!(u56, [u57, u58, u59, u60, u61, u62, u63, usize]); implement_from!( u57, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56 ] ); implement_try_from!(u57, [u58, u59, u60, u61, u62, u63, usize]); implement_from!( u58, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57 ] ); implement_try_from!(u58, [u59, u60, u61, u62, u63, usize]); implement_from!( u59, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58 ] ); implement_try_from!(u59, [u60, u61, u62, u63, usize]); implement_from!( u60, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59 ] ); implement_try_from!(u60, [u61, u62, u63, usize]); implement_from!( u61, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60 ] ); implement_try_from!(u61, [u62, u63, usize]); implement_from!( u62, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61 ] ); implement_from!( u63, [ u1, u2, u3, u4, u5, u6, u7, u9, u10, u11, u12, u13, u14, u15, u17, u18, u19, u20, u21, u22, u23, u24, u25, u26, u27, u28, u29, u30, u31, u33, u34, u35, u36, u37, u38, u39, u40, u41, u42, u43, u44, u45, u46, u47, u48, u49, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u60, u61, u62 ] ); // Implement From for all signed integer implement_try_from!([i2, i3, i4, i5, i6, i7], i8); implement_from!([i9, i10, i11, i12, i13, i14, i15], i8); implement_from!([i17, i18, i19, i20, i21, i22, i23, i24], i8); implement_from!([i25, i26, i27, i28, i29, i30, i31], i8); implement_from!([i33, i34, i35, i36, i37, i38, i39, i40], i8); implement_from!([i41, i42, i43, i44, i45, i46, i47, i48], i8); implement_from!([i49, i50, i51, i52, i53, i54, i55, i56], i8); implement_from!([i57, i58, i59, i60, i61, i62, i63], i8); implement_into!([i2, i3, i4, i5, i6, i7], i8); implement_try_into!([i9, i10, i11, i12, i13, i14, i15], i8); implement_try_into!([i17, i18, i19, i20, i21, i22, i23, i24], i8); implement_try_into!([i25, i26, i27, i28, i29, i30, i31], i8); implement_try_into!([i33, i34, i35, i36, i37, i38, i39, i40], i8); implement_try_into!([i41, i42, i43, i44, i45, i46, i47, i48], i8); implement_try_into!([i49, i50, i51, i52, i53, i54, i55, i56], i8); implement_try_into!([i57, i58, i59, i60, i61, i62, i63], i8); implement_try_from!([i2, i3, i4, i5, i6, i7], i16); implement_try_from!([i9, i10, i11, i12, i13, i14, i15], i16); implement_from!([i17, i18, i19, i20, i21, i22, i23, i24], i16); implement_from!([i25, i26, i27, i28, i29, i30, i31], i16); implement_from!([i33, i34, i35, i36, i37, i38, i39, i40], i16); implement_from!([i41, i42, i43, i44, i45, i46, i47, i48], i16); implement_from!([i49, i50, i51, i52, i53, i54, i55, i56], i16);
rust
Apache-2.0
9df9b3aa307a31fce57ee4a3529c2ae20427ef39
2026-01-04T20:20:28.114552Z
true
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/examples/rust/src/main.rs
examples/rust/src/main.rs
use auto_traffic_control::v1::atc_service_client::AtcServiceClient; use auto_traffic_control::v1::GetVersionRequest; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let mut atc_service = AtcServiceClient::connect("http://localhost:4747").await?; let response = atc_service.get_version(GetVersionRequest {}).await?; let version_field = response.into_inner().version; if let Some(version) = version_field { let mut version_string = format!("{}.{}.{}", version.major, version.minor, version.patch); if !version.pre.is_empty() { version_string.push('-'); version_string.push_str(&version.pre); } println!("Auto Traffic Control is running version '{version_string}'"); } else { panic!("Requesting the version returned an empty response."); } Ok(()) }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/utilities/test-server/src/main.rs
utilities/test-server/src/main.rs
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use semver::Version as SemVer; use tonic::transport::{Error, Server}; use tonic::{Request, Response, Status}; use auto_traffic_control::v1::atc_service_server::AtcServiceServer; use auto_traffic_control::v1::{GetVersionRequest, GetVersionResponse, Version}; struct AtcService; #[tonic::async_trait] impl auto_traffic_control::v1::atc_service_server::AtcService for AtcService { async fn get_version( &self, _request: Request<GetVersionRequest>, ) -> Result<Response<GetVersionResponse>, Status> { let semver = SemVer::parse(env!("CARGO_PKG_VERSION")).unwrap(); let version = Version { major: semver.major, minor: semver.minor, patch: semver.patch, pre: semver.pre.to_string(), }; Ok(Response::new(GetVersionResponse { version: Some(version), })) } } #[tokio::main] async fn main() -> Result<(), Error> { Server::builder() .add_service(AtcServiceServer::new(AtcService)) .serve(SocketAddr::V4(SocketAddrV4::new( Ipv4Addr::new(0, 0, 0, 0), 4747, ))) .await }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/utilities/debug-client/src/main.rs
utilities/debug-client/src/main.rs
use tokio_stream::StreamExt; use auto_traffic_control::v1::event_service_client::EventServiceClient; use auto_traffic_control::v1::stream_response::Event; use auto_traffic_control::v1::StreamRequest; fn should_print(event: &Event) -> bool { match event { Event::AirplaneCollided(_) => true, Event::AirplaneDetected(_) => true, Event::AirplaneLanded(_) => true, Event::AirplaneMoved(_) => false, Event::FlightPlanUpdated(_) => false, Event::LandingAborted(_) => true, Event::GameStarted(_) => true, Event::GameStopped(_) => true, } } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let mut client = EventServiceClient::connect("http://localhost:4747").await?; let mut stream = client.stream(StreamRequest {}).await.unwrap().into_inner(); while let Some(message) = stream.next().await { let event = message.unwrap().event.unwrap(); if !should_print(&event) { continue; } match event { Event::AirplaneCollided(collision) => { println!( "Airplane {} collided with airplane {}", collision.id1, collision.id2 ); } Event::AirplaneDetected(airplane_detected) => { let airplane = airplane_detected.airplane.unwrap(); let point = airplane.point.unwrap(); println!( "Airplane detected: {} at {}:{}", airplane.id, point.x, point.y ); } Event::AirplaneLanded(airplane_landed) => { println!("Airplane landed: {}", airplane_landed.id); } Event::AirplaneMoved(airplane_moved) => { let airplane_id = airplane_moved.id; let point = airplane_moved.point.unwrap(); println!("Airplane moved: {} to {}:{}", airplane_id, point.x, point.y); } Event::FlightPlanUpdated(flight_plan_updated) => { let airplane_id = flight_plan_updated.id; let flight_plan = flight_plan_updated.flight_plan; println!( "Flight plan updated for {}: {}", airplane_id, flight_plan .iter() .map(|node| format!("{}:{}", node.longitude, node.latitude)) .collect::<Vec<String>>() .join(", ") ); } Event::LandingAborted(landing_aborted) => { println!( "Landing aborted: Airplane {} has the wrong tag", landing_aborted.id ); } Event::GameStarted(_) => { println!("Game started"); } Event::GameStopped(_) => { println!("Game stopped"); } } } Ok(()) }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/rendering.rs
game/src/rendering.rs
use bevy::prelude::*; pub const FONT_COLOR: Color = Color::BLACK; pub enum RenderLayer { Landscape, Decoration, RoutingGrid, Airport, Airplane, Ui, } impl RenderLayer { pub fn z(&self) -> f32 { match self { RenderLayer::Landscape => 0.0, RenderLayer::Decoration => 1.0, RenderLayer::RoutingGrid => 2.0, RenderLayer::Airport => 3.0, RenderLayer::Airplane => 4.0, RenderLayer::Ui => 5.0, } } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/main.rs
game/src/main.rs
use std::sync::Arc; use bevy::prelude::*; use tokio::sync::broadcast::channel; use crate::api::Api; use crate::command::{Command, CommandReceiver, CommandSender}; use crate::event::{Event, EventReceiver, EventSender}; use crate::scene::{GameOverPlugin, GamePlugin, MainMenuPlugin}; use crate::store::{Store, StoreWatcher}; use crate::systems::*; mod api; mod command; mod components; mod event; mod map; mod rendering; mod resources; mod scene; mod store; mod systems; /// The height of the game's window const SCREEN_HEIGHT: f32 = 640.0; /// The width of the game's window const SCREEN_WIDTH: f32 = 800.0; /// The dimension of a tile /// /// Tiles must have the same size as the textures that are used to render them. This game uses /// textures with a size of 32 by 32 pixels, and thus tiles must be 32 pixels high and wide as well. const TILE_SIZE: i32 = 32; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub enum AppState { MainMenu, Game, GameOver, } #[tokio::main] async fn main() { let (command_sender, command_receiver) = channel::<Command>(1024); let command_sender = CommandSender::new(command_sender); let command_receiver = CommandReceiver::new(command_receiver); let (event_sender, event_receiver) = channel::<Event>(1024); let event_sender = EventSender::new(event_sender); let event_receiver = EventReceiver::new(event_receiver); let store = Arc::new(Store::new()); let mut store_watcher = StoreWatcher::new(event_receiver, store.clone()); let _api_join_handle = tokio::spawn(Api::serve( command_sender.clone(), event_sender.clone(), store, )); let _drainer_join_handle = tokio::spawn(async move { drain_queue(command_receiver).await }); let _store_join_handle = tokio::spawn(async move { store_watcher.connect().await }); App::new() // Must be added before the DefaultPlugins .insert_resource(ClearColor(Color::BLACK)) .add_plugins(DefaultPlugins.set(WindowPlugin { window: WindowDescriptor { title: "Auto Traffic Control".to_string(), width: SCREEN_WIDTH, height: SCREEN_HEIGHT, resizable: false, ..Default::default() }, ..Default::default() })) .insert_resource(command_sender) .insert_resource(event_sender) .add_state(AppState::MainMenu) .add_plugin(GamePlugin) .add_plugin(GameOverPlugin) .add_plugin(MainMenuPlugin) .add_startup_system(setup_cameras) .add_system(change_app_state) .run(); } async fn drain_queue(mut receiver: CommandReceiver) { while (receiver.get_mut().recv().await).is_ok() {} }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/command/sender.rs
game/src/command/sender.rs
use bevy::prelude::*; use tokio::sync::broadcast::Sender; use crate::command::{Command, CommandReceiver}; #[derive(Clone, Debug, Resource)] pub struct CommandSender(Sender<Command>); impl CommandSender { pub fn new(sender: Sender<Command>) -> Self { Self(sender) } pub fn get(&self) -> &Sender<Command> { &self.0 } pub fn subscribe(&self) -> CommandReceiver { CommandReceiver::new(self.0.subscribe()) } } #[cfg(test)] mod tests { use super::*; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<CommandSender>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<CommandSender>(); } #[test] fn trait_unpin() { fn assert_unpin<T: Unpin>() {} assert_unpin::<CommandSender>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/command/mod.rs
game/src/command/mod.rs
use crate::components::{AirplaneId, FlightPlan}; pub use self::bus::CommandBus; pub use self::receiver::CommandReceiver; pub use self::sender::CommandSender; mod bus; mod receiver; mod sender; #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub enum Command { StartGame, UpdateFlightPlan(AirplaneId, FlightPlan), } #[cfg(test)] mod test { use super::CommandBus; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<CommandBus>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<CommandBus>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/command/bus.rs
game/src/command/bus.rs
use bevy::prelude::*; use crate::command::{CommandReceiver, CommandSender}; #[derive(Debug)] pub struct CommandBus { receiver: CommandReceiver, } impl CommandBus { pub fn receiver(&mut self) -> &mut CommandReceiver { &mut self.receiver } } impl FromWorld for CommandBus { fn from_world(world: &mut World) -> Self { let sender = world.resource::<CommandSender>(); Self { receiver: sender.subscribe(), } } } #[cfg(test)] mod tests { use super::CommandBus; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<CommandBus>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<CommandBus>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/command/receiver.rs
game/src/command/receiver.rs
use bevy::prelude::*; use tokio::sync::broadcast::Receiver; use crate::command::Command; #[derive(Debug, Resource)] pub struct CommandReceiver(Receiver<Command>); impl CommandReceiver { pub fn new(receiver: Receiver<Command>) -> Self { Self(receiver) } pub fn get_mut(&mut self) -> &mut Receiver<Command> { &mut self.0 } } #[cfg(test)] mod tests { use super::*; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<CommandReceiver>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<CommandReceiver>(); } #[test] fn trait_unpin() { fn assert_unpin<T: Unpin>() {} assert_unpin::<CommandReceiver>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/store/watcher.rs
game/src/store/watcher.rs
use std::sync::Arc; use auto_traffic_control::v1::get_game_state_response::GameState; use auto_traffic_control::v1::Airplane; use crate::api::AsApi; use crate::components::{AirplaneId, FlightPlan, Location, Tag}; use crate::event::EventReceiver; use crate::map::Map; use crate::{Event, Store}; #[derive(Debug)] pub struct StoreWatcher { event_bus: EventReceiver, store: Arc<Store>, } impl StoreWatcher { pub fn new(event_bus: EventReceiver, store: Arc<Store>) -> Self { Self { event_bus, store } } pub async fn connect(&mut self) { while let Ok(event) = self.event_bus.get_mut().recv().await { match event { Event::AirplaneDetected(id, location, flight_plan, tag) => { self.insert_airplane(id, location, flight_plan, tag) } Event::AirplaneLanded(id) => self.remove_airplane(id), Event::AirplaneMoved(id, location) => self.move_airplane(id, location), Event::FlightPlanUpdated(id, flight_plan) => { self.update_flight_plan(id, flight_plan) } Event::GameStarted(map) => self.start_game(map), Event::GameStopped(_) => self.reset(), _ => {} } } } fn insert_airplane( &self, id: AirplaneId, location: Location, flight_plan: FlightPlan, tag: Tag, ) { self.store.airplanes().insert( id.get().into(), Airplane { id: id.as_api(), point: Some(location.as_api()), flight_plan: flight_plan.as_api(), tag: tag.as_api().into(), }, ); } fn remove_airplane(&self, id: AirplaneId) { self.store.airplanes().remove(id.get()); } fn move_airplane(&self, id: AirplaneId, location: Location) { if let Some(mut airplane) = self.store.airplanes().get_mut(id.get()) { airplane.point = Some(location.as_api()); } } fn update_flight_plan(&self, id: AirplaneId, flight_plan: FlightPlan) { if let Some(mut airplane) = self.store.airplanes().get_mut(id.get()) { airplane.flight_plan = flight_plan.as_api(); } } fn start_game(&self, map: Map) { let mut game_started = self.store.game_state().lock(); *game_started = GameState::Running; let mut map_guard = self.store.map().lock(); *map_guard = map; } fn reset(&self) { self.store.airplanes().clear(); let mut game_started = self.store.game_state().lock(); *game_started = GameState::Ready; } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/store/mod.rs
game/src/store/mod.rs
use std::sync::Arc; use dashmap::DashMap; use parking_lot::Mutex; use auto_traffic_control::v1::get_game_state_response::GameState; use auto_traffic_control::v1::Airplane; use crate::map::Map; pub use self::watcher::StoreWatcher; mod watcher; pub type SharedGameState = Arc<Mutex<GameState>>; pub type SharedMap = Arc<Mutex<Map>>; #[derive(Clone, Debug)] pub struct Store { airplanes: DashMap<String, Airplane>, game_state: SharedGameState, map: SharedMap, } impl Store { pub fn new() -> Self { Self::default() } // TODO: Hide implementation details (DashMap) and provide query interface for airplanes pub fn airplanes(&self) -> &DashMap<String, Airplane> { &self.airplanes } pub fn game_state(&self) -> &SharedGameState { &self.game_state } pub fn map(&self) -> &SharedMap { &self.map } } impl Default for Store { fn default() -> Self { Self { airplanes: DashMap::new(), game_state: Arc::new(Mutex::new(GameState::Ready)), map: Arc::new(Mutex::new(Map::new())), } } } #[cfg(test)] mod tests { use super::Store; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<Store>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Store>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/components/airplane_id.rs
game/src/components/airplane_id.rs
use bevy::prelude::*; use crate::api::AsApi; #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Component)] pub struct AirplaneId(String); impl AirplaneId { pub fn new(id: String) -> Self { Self(id) } #[allow(dead_code)] // TODO: Remove when the id is read pub fn get(&self) -> &str { &self.0 } } impl AsApi for AirplaneId { type ApiType = String; fn as_api(&self) -> Self::ApiType { self.0.clone() } } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)] pub struct AirplaneIdGenerator { last_id: u32, } impl AirplaneIdGenerator { pub fn generate(&mut self) -> AirplaneId { self.last_id += 1; AirplaneId(format!("AT-{:0width$}", self.last_id, width = 4)) } } #[cfg(test)] mod tests { use crate::api::AsApi; use super::{AirplaneId, AirplaneIdGenerator}; #[test] fn get() { let id = "test"; let airplane_id = AirplaneId(String::from(id)); assert_eq!(id, airplane_id.get()); } #[test] fn generate() { let mut generator = AirplaneIdGenerator::default(); assert_eq!("AT-0001", generator.generate().get()); assert_eq!("AT-0002", generator.generate().get()); } #[test] fn trait_as_api() { let id = String::from("test"); let airplane_id = AirplaneId(id.clone()); assert_eq!(id, airplane_id.as_api()); } #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<AirplaneId>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<AirplaneId>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/components/collider.rs
game/src/components/collider.rs
use bevy::prelude::*; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Component)] pub struct Collider; #[cfg(test)] mod tests { use super::Collider; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<Collider>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Collider>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/components/travelled_route.rs
game/src/components/travelled_route.rs
use bevy::prelude::*; use crate::map::Node; #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Component)] pub struct TravelledRoute(Vec<Node>); impl TravelledRoute { pub fn new(route: Vec<Node>) -> Self { Self(route) } pub fn get(&self) -> &Vec<Node> { &self.0 } pub fn get_mut(&mut self) -> &mut Vec<Node> { &mut self.0 } } #[cfg(test)] mod tests { use super::TravelledRoute; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<TravelledRoute>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<TravelledRoute>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/components/landing.rs
game/src/components/landing.rs
use bevy::prelude::*; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Component)] pub struct Landing; #[cfg(test)] mod tests { use super::Landing; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<Landing>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Landing>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/components/speed.rs
game/src/components/speed.rs
use bevy::prelude::*; #[derive(Copy, Clone, PartialEq, PartialOrd, Debug, Component)] pub struct Speed(f32); impl Speed { pub fn new(speed: f32) -> Self { Self(speed) } pub fn get(&self) -> f32 { self.0 } } #[cfg(test)] mod tests { use super::Speed; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<Speed>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Speed>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/components/mod.rs
game/src/components/mod.rs
pub use self::airplane::*; pub use self::airplane_id::*; pub use self::collider::*; pub use self::flight_plan::*; pub use self::landing::*; pub use self::location::*; pub use self::speed::*; pub use self::tag::*; pub use self::travelled_route::*; mod airplane; mod airplane_id; mod collider; mod flight_plan; mod landing; mod location; mod speed; mod tag; mod travelled_route;
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/components/location.rs
game/src/components/location.rs
use std::fmt::{Display, Formatter}; use bevy::prelude::*; use geo::Point; use auto_traffic_control::v1::Point as ApiPoint; use crate::api::AsApi; use crate::map::Node; use crate::TILE_SIZE; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Component)] pub struct Location { x: i32, y: i32, } impl Location { #[cfg(test)] pub fn new(x: i32, y: i32) -> Self { Location { x, y } } #[allow(dead_code)] // TODO: Remove when the value is read pub fn x(&self) -> i32 { self.x } #[allow(dead_code)] // TODO: Remove when the value is read pub fn y(&self) -> i32 { self.y } } impl From<&Point<f32>> for Location { fn from(point: &Point<f32>) -> Self { Self { x: point.x() as i32, y: point.y() as i32, } } } impl From<&Node> for Location { fn from(tile: &Node) -> Self { Self { x: tile.longitude() * TILE_SIZE, y: tile.latitude() * TILE_SIZE, } } } impl From<&Mut<'_, bevy::prelude::Transform>> for Location { fn from(transform: &Mut<'_, bevy::prelude::Transform>) -> Self { Self { x: transform.translation.x as i32, y: transform.translation.y as i32, } } } impl From<&Vec3> for Location { fn from(vec3: &Vec3) -> Self { Self { x: vec3.x as i32, y: vec3.y as i32, } } } impl Display for Location { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "Location {{ x: {}, y: {} }}", self.x, self.y) } } impl AsApi for Location { type ApiType = ApiPoint; fn as_api(&self) -> Self::ApiType { ApiPoint { x: self.x, y: self.y, } } } #[cfg(test)] mod tests { use super::Location; #[test] fn trait_display() { let location = Location { x: 1, y: 2 }; assert_eq!("Location { x: 1, y: 2 }", &location.to_string()); } #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<Location>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Location>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/components/tag.rs
game/src/components/tag.rs
use bevy::prelude::*; use auto_traffic_control::v1::Tag as ApiTag; use crate::api::AsApi; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Component)] pub enum Tag { Blue, Red, } impl AsApi for Tag { type ApiType = ApiTag; fn as_api(&self) -> Self::ApiType { match self { Tag::Blue => ApiTag::Blue, Tag::Red => ApiTag::Red, } } } #[cfg(test)] mod tests { use super::Tag; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<Tag>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Tag>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/components/flight_plan.rs
game/src/components/flight_plan.rs
use bevy::prelude::*; use auto_traffic_control::v1::update_flight_plan_error::ValidationError; use auto_traffic_control::v1::Node as ApiNode; use crate::api::AsApi; use crate::map::{Node, MAP_HEIGHT_RANGE, MAP_WIDTH_RANGE}; #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Component)] pub struct FlightPlan(Vec<Node>); impl FlightPlan { pub fn new(flight_plan: Vec<Node>) -> Self { Self(flight_plan) } pub fn next(&self) -> Option<&Node> { self.0.last() } pub fn get(&self) -> &Vec<Node> { &self.0 } pub fn get_mut(&mut self) -> &mut Vec<Node> { &mut self.0 } pub fn validate( &self, previous_flight_plan: &FlightPlan, routing_grid: &[Node], ) -> Result<(), Vec<ValidationError>> { let errors: Vec<ValidationError> = vec![ self.is_within_map_bounds(), self.is_in_logical_order(), self.has_invalid_first_node(previous_flight_plan), self.has_sharp_turns(), self.has_restricted_nodes(routing_grid), ] .iter() .filter_map(|result| result.err()) .collect(); if !errors.is_empty() { Err(errors) } else { Ok(()) } } fn is_within_map_bounds(&self) -> Result<(), ValidationError> { for node in self.0.iter() { if !MAP_WIDTH_RANGE.contains(&node.longitude()) { return Err(ValidationError::NodeOutsideMap); } if !MAP_HEIGHT_RANGE.contains(&node.latitude()) { return Err(ValidationError::NodeOutsideMap); } } Ok(()) } fn is_in_logical_order(&self) -> Result<(), ValidationError> { for window in self.0.windows(2) { let previous = window[0]; let next = window[1]; if !previous.is_neighbor(&next) { return Err(ValidationError::InvalidStep); } } Ok(()) } fn has_invalid_first_node( &self, previous_flight_plan: &FlightPlan, ) -> Result<(), ValidationError> { if self.0.last() == previous_flight_plan.get().last() { Ok(()) } else { Err(ValidationError::InvalidStart) } } fn has_sharp_turns(&self) -> Result<(), ValidationError> { for window in self.0.windows(3) { let previous = window[0]; let next = window[2]; if previous == next { return Err(ValidationError::SharpTurn); } } Ok(()) } fn has_restricted_nodes(&self, routing_grid: &[Node]) -> Result<(), ValidationError> { for node in self.0.iter() { if !routing_grid.contains(node) { return Err(ValidationError::RestrictedNode); } } Ok(()) } } impl From<&Vec<auto_traffic_control::v1::Node>> for FlightPlan { fn from(api_flight_plan: &Vec<auto_traffic_control::v1::Node>) -> Self { let tiles = api_flight_plan .iter() .rev() .map(|node| Node::unrestricted(node.longitude, node.latitude)) .collect(); FlightPlan(tiles) } } impl AsApi for FlightPlan { type ApiType = Vec<ApiNode>; fn as_api(&self) -> Self::ApiType { self.0.iter().rev().map(|node| node.as_api()).collect() } } #[cfg(test)] mod tests { use auto_traffic_control::v1::update_flight_plan_error::ValidationError; use crate::map::{Node, MAP_HEIGHT_RANGE, MAP_WIDTH_RANGE}; use super::FlightPlan; fn routing_grid() -> Vec<Node> { let mut nodes = Vec::new(); for y in -3..=3 { for x in -3..=3 { nodes.push(Node::unrestricted(x, y)); } } nodes } #[test] fn validate_with_valid_plan() { let previous_flight_plan = FlightPlan(vec![ Node::unrestricted(2, 0), Node::unrestricted(1, 0), Node::unrestricted(0, 0), ]); let new_flight_plan = FlightPlan(vec![ Node::unrestricted(1, 1), Node::unrestricted(1, 0), Node::unrestricted(0, 0), ]); let result = new_flight_plan.validate(&previous_flight_plan, &routing_grid()); assert!(result.is_ok()); } #[test] fn validate_with_invalid_plan() { let x = *MAP_WIDTH_RANGE.start(); let y = *MAP_HEIGHT_RANGE.start(); let previous_flight_plan = FlightPlan(vec![Node::unrestricted(0, 0), Node::unrestricted(x, y)]); let new_flight_plan = FlightPlan(vec![ Node::unrestricted(x - 1, y - 1), Node::unrestricted(0, 0), ]); let result = new_flight_plan.validate(&previous_flight_plan, &routing_grid()); assert_eq!( vec![ ValidationError::NodeOutsideMap, ValidationError::InvalidStep, ValidationError::InvalidStart, ValidationError::RestrictedNode, ], result.err().unwrap() ); } #[test] fn is_within_map_bounds_with_valid_plan() { let flight_plan = FlightPlan(vec![ Node::unrestricted(0, 0), Node::unrestricted(1, 0), Node::unrestricted(2, 0), ]); let result = flight_plan.is_within_map_bounds(); assert!(result.is_ok()); } #[test] fn is_within_map_bounds_with_invalid_plan() { let x = MAP_WIDTH_RANGE.start() - 1; let y = MAP_HEIGHT_RANGE.start() - 1; let flight_plan = FlightPlan(vec![Node::unrestricted(x, y)]); let result = flight_plan.is_within_map_bounds(); assert!(result.is_err()); } #[test] fn is_in_logical_order_with_valid_plan() { let flight_plan = FlightPlan(vec![ Node::unrestricted(0, 0), Node::unrestricted(1, 0), Node::unrestricted(2, 0), ]); let result = flight_plan.is_in_logical_order(); assert!(result.is_ok()); } #[test] fn is_in_logical_order_with_invalid_plan() { let flight_plan = FlightPlan(vec![Node::unrestricted(0, 0), Node::unrestricted(3, 3)]); let result = flight_plan.is_in_logical_order(); assert!(result.is_err()); } #[test] fn has_invalid_first_node_with_valid_plan() { let previous_flight_plan = FlightPlan(vec![Node::unrestricted(1, 0), Node::unrestricted(0, 0)]); let new_flight_plan = FlightPlan(vec![Node::unrestricted(0, 1), Node::unrestricted(0, 0)]); let result = new_flight_plan.has_invalid_first_node(&previous_flight_plan); assert!(result.is_ok()); } #[test] fn has_invalid_first_node_with_invalid_plan() { let previous_flight_plan = FlightPlan(vec![Node::unrestricted(0, 0), Node::unrestricted(1, 0)]); let new_flight_plan = FlightPlan(vec![Node::unrestricted(1, 0), Node::unrestricted(0, 0)]); let result = new_flight_plan.has_invalid_first_node(&previous_flight_plan); assert!(result.is_err()); } #[test] fn has_sharp_turns_without_turns() { let flight_plan = FlightPlan(vec![ Node::unrestricted(0, 0), Node::unrestricted(1, 0), Node::unrestricted(1, 1), ]); let result = flight_plan.has_sharp_turns(); assert!(result.is_ok()); } #[test] fn has_sharp_turns_with_turns() { let flight_plan = FlightPlan(vec![ Node::unrestricted(0, 0), Node::unrestricted(1, 0), Node::unrestricted(0, 0), ]); let result = flight_plan.has_sharp_turns(); assert!(result.is_err()); } #[test] fn has_restricted_nodes_without_restricted_nodes() { let flight_plan = FlightPlan(vec![Node::unrestricted(0, 0)]); let routing_grid = vec![Node::unrestricted(0, 0)]; let result = flight_plan.has_restricted_nodes(&routing_grid); assert!(result.is_ok()); } #[test] fn has_restricted_nodes_with_restricted_nodes() { let flight_plan = FlightPlan(vec![Node::unrestricted(1, 1)]); let routing_grid = vec![Node::unrestricted(0, 0)]; let result = flight_plan.has_restricted_nodes(&routing_grid); assert!(result.is_err()); } #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<FlightPlan>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<FlightPlan>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/components/airplane.rs
game/src/components/airplane.rs
use bevy::prelude::*; pub const AIRPLANE_SIZE: f32 = 24.0; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Component)] pub struct Airplane; #[cfg(test)] mod tests { use super::Airplane; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<Airplane>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Airplane>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/scene/main_menu.rs
game/src/scene/main_menu.rs
use bevy::prelude::*; use crate::rendering::RenderLayer; use crate::{setup_landscape, AppState}; pub struct MainMenuPlugin; impl Plugin for MainMenuPlugin { fn build(&self, app: &mut App) { app.add_system_set( SystemSet::on_enter(AppState::MainMenu) .with_system(setup_landscape) .with_system(spawn), ) .add_system_set(SystemSet::on_update(AppState::MainMenu)) .add_system_set(SystemSet::on_exit(AppState::MainMenu).with_system(despawn)); } } fn spawn(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(SpriteBundle { transform: Transform::from_xyz(0.0, 0.0, RenderLayer::Ui.z()), texture: asset_server.load("sprites/logo.png"), ..Default::default() }); commands.spawn(SpriteBundle { transform: Transform::from_xyz(0.0, -128.0, RenderLayer::Ui.z()), texture: asset_server.load("sprites/instructions.png"), ..Default::default() }); } fn despawn(mut commands: Commands, query: Query<Entity, Without<Camera>>) { for entity in query.iter() { commands.entity(entity).despawn_recursive(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/scene/game_over.rs
game/src/scene/game_over.rs
use bevy::prelude::*; use crate::rendering::FONT_COLOR; use crate::AppState; pub struct GameOverPlugin; impl Plugin for GameOverPlugin { fn build(&self, app: &mut App) { app.add_system_set(SystemSet::on_enter(AppState::GameOver).with_system(spawn)) .add_system_set(SystemSet::on_update(AppState::GameOver)) .add_system_set(SystemSet::on_exit(AppState::GameOver).with_system(despawn)); } } fn spawn(mut commands: Commands, asset_server: Res<AssetServer>) { commands .spawn(NodeBundle { style: Style { size: Size::new(Val::Percent(100.0), Val::Percent(100.0)), align_items: AlignItems::Center, justify_content: JustifyContent::SpaceBetween, flex_direction: FlexDirection::ColumnReverse, ..Default::default() }, ..Default::default() }) .with_children(|parent| { parent.spawn(TextBundle { text: Text::from_section( "Game Over", TextStyle { font: asset_server.load("font/JetBrainsMono-Regular.ttf"), font_size: 48.0, color: FONT_COLOR, }, ), ..Default::default() }); parent.spawn(TextBundle { style: Style { margin: UiRect::all(Val::Px(24.0)), ..Default::default() }, text: Text::from_section( "Two planes got too close to each other. The simulation was aborted.", TextStyle { font: asset_server.load("font/JetBrainsMono-Regular.ttf"), font_size: 24.0, color: FONT_COLOR, }, ), ..Default::default() }); }); } fn despawn(mut commands: Commands, query: Query<Entity, Without<Camera>>) { for entity in query.iter() { commands.entity(entity).despawn_recursive(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/scene/game.rs
game/src/scene/game.rs
use bevy::prelude::*; use crate::event::{Event, EventBus}; use crate::map::Map; use crate::rendering::FONT_COLOR; use crate::resources::Score; use crate::systems::{ despawn_airplane, detect_collision, follow_flight_plan, generate_flight_plan, land_airplane, rotate_airplane, setup_airport, setup_grid, setup_landscape, spawn_airplane, update_flight_plan, SpawnTimer, }; use crate::AppState; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Resource)] pub struct ScoreOverlay(Entity); pub struct GamePlugin; impl Plugin for GamePlugin { fn build(&self, app: &mut App) { app.insert_resource(SpawnTimer::new(Timer::from_seconds( 2.0, TimerMode::Repeating, ))) .insert_resource(Map::new()) .add_system_set( SystemSet::on_enter(AppState::Game) .with_system(start_game) .with_system(setup_airport) .with_system(setup_grid) .with_system(setup_landscape) .with_system(setup_score), ) .add_system_set( SystemSet::on_update(AppState::Game) .with_system(follow_flight_plan.label("move")) .with_system(despawn_airplane) .with_system(detect_collision) .with_system(generate_flight_plan) .with_system(land_airplane) .with_system(rotate_airplane) .with_system(spawn_airplane) .with_system(update_flight_plan) .with_system(update_score), ) .add_system_set(SystemSet::on_exit(AppState::Game).with_system(end_game)); } } fn start_game(mut commands: Commands, map: Res<Map>, event_bus: Local<EventBus>) { commands.insert_resource(Score::new()); let map = map.into_inner().clone(); event_bus .sender() .get() .send(Event::GameStarted(map)) .expect("failed to send event"); // TODO: Handle error } fn end_game(score: Res<Score>, event_bus: Local<EventBus>) { event_bus .sender() .get() .send(Event::GameStopped(*score)) .expect("failed to send event"); // TODO: Handle error } fn setup_score(mut commands: Commands, asset_server: Res<AssetServer>) { let overlay_id = commands .spawn(TextBundle { text: Text { sections: vec![ TextSection { value: "Score: ".to_string(), style: TextStyle { font: asset_server.load("font/JetBrainsMono-Regular.ttf"), font_size: 24.0, color: FONT_COLOR, }, }, TextSection { value: "".to_string(), style: TextStyle { font: asset_server.load("font/JetBrainsMono-Regular.ttf"), font_size: 24.0, color: FONT_COLOR, }, }, ], ..Default::default() }, style: Style { position_type: PositionType::Absolute, position: UiRect { top: Val::Px(8.0), left: Val::Px(8.0), ..Default::default() }, ..Default::default() }, ..Default::default() }) .id(); commands.insert_resource(ScoreOverlay(overlay_id)); } fn update_score(score: Res<Score>, mut query: Query<&mut Text>) { let mut text = query.single_mut(); text.sections[1].value = format!("{}", score.get()); }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/scene/mod.rs
game/src/scene/mod.rs
pub use self::game::GamePlugin; pub use self::game_over::GameOverPlugin; pub use self::main_menu::MainMenuPlugin; mod game; mod game_over; mod main_menu;
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/api/event.rs
game/src/api/event.rs
use std::pin::Pin; use tokio_stream::wrappers::BroadcastStream; use tokio_stream::StreamExt; use tonic::codegen::futures_core::Stream; use tonic::{Request, Response, Status}; use auto_traffic_control::v1::{StreamRequest, StreamResponse}; use crate::api::AsApi; use crate::event::EventSender; #[derive(Clone, Debug)] pub struct EventService { event_sender: EventSender, } impl EventService { pub fn new(event_sender: EventSender) -> Self { Self { event_sender } } } #[tonic::async_trait] impl auto_traffic_control::v1::event_service_server::EventService for EventService { type StreamStream = Pin<Box<dyn Stream<Item = Result<StreamResponse, Status>> + Send + Sync + 'static>>; async fn stream( &self, _request: Request<StreamRequest>, ) -> Result<Response<Self::StreamStream>, Status> { let stream = BroadcastStream::new(self.event_sender.subscribe().into()).filter_map(|event| { let event = match event { Ok(event) => Some(event.as_api()), Err(_) => None, }; event.map(|event| Ok(StreamResponse { event: Some(event) })) }); Ok(Response::new(Box::pin(stream) as Self::StreamStream)) } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/api/atc.rs
game/src/api/atc.rs
use semver::Version as SemVer; use tonic::{Request, Response, Status}; use auto_traffic_control::v1::{GetVersionRequest, GetVersionResponse, Version}; pub struct AtcService; #[tonic::async_trait] impl auto_traffic_control::v1::atc_service_server::AtcService for AtcService { async fn get_version( &self, _request: Request<GetVersionRequest>, ) -> Result<Response<GetVersionResponse>, Status> { let semver = SemVer::parse(env!("CARGO_PKG_VERSION")).unwrap(); let version = Version { major: semver.major, minor: semver.minor, patch: semver.patch, pre: semver.pre.to_string(), }; Ok(Response::new(GetVersionResponse { version: Some(version), })) } } #[cfg(test)] mod tests { use tonic::Request; use auto_traffic_control::v1::atc_service_server::AtcService as ServiceTrait; use auto_traffic_control::v1::GetVersionRequest; use super::AtcService; #[tokio::test] async fn get_version() { let response = AtcService .get_version(Request::new(GetVersionRequest {})) .await .unwrap(); let version = response.into_inner().version.unwrap(); assert_eq!( env!("CARGO_PKG_VERSION_MAJOR").parse::<u64>().unwrap(), version.major ); assert_eq!( env!("CARGO_PKG_VERSION_MINOR").parse::<u64>().unwrap(), version.minor ); assert_eq!( env!("CARGO_PKG_VERSION_PATCH").parse::<u64>().unwrap(), version.patch ); assert_eq!(env!("CARGO_PKG_VERSION_PRE"), version.pre); } #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<AtcService>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<AtcService>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/api/map.rs
game/src/api/map.rs
use std::sync::Arc; use tonic::{Request, Response, Status}; use auto_traffic_control::v1::{ GetMapRequest, GetMapResponse, NodeToPointRequest, NodeToPointResponse, Point, }; use crate::api::AsApi; use crate::map::Node; use crate::store::Store; #[derive(Clone, Debug, Default)] pub struct MapService { store: Arc<Store>, } impl MapService { pub fn new(store: Arc<Store>) -> Self { Self { store } } } #[tonic::async_trait] impl auto_traffic_control::v1::map_service_server::MapService for MapService { async fn get_map( &self, _request: Request<GetMapRequest>, ) -> Result<Response<GetMapResponse>, Status> { let map = Some(self.store.map().lock().as_api()); Ok(Response::new(GetMapResponse { map })) } async fn node_to_point( &self, request: Request<NodeToPointRequest>, ) -> Result<Response<NodeToPointResponse>, Status> { if let Some(api_node) = request.into_inner().node { let node = Node::unrestricted(api_node.longitude, api_node.latitude); let point = node.to_location(); Ok(Response::new(NodeToPointResponse { point: Some(Point { x: point.0, y: point.1, }), })) } else { Err(Status::invalid_argument("must provide a Node")) } } } #[cfg(test)] mod tests { use std::sync::Arc; use tonic::Request; use auto_traffic_control::v1::map_service_server::MapService as ServiceTrait; use auto_traffic_control::v1::{Airport, GetMapRequest, Node, NodeToPointRequest, Tag}; use crate::store::Store; use super::MapService; fn setup() -> (Arc<Store>, MapService) { let store = Arc::new(Store::new()); let service = MapService::new(store.clone()); (store, service) } #[tokio::test] async fn get_map() { let (_, service) = setup(); let request = Request::new(GetMapRequest {}); let response = service.get_map(request).await.unwrap(); let map = response.into_inner().map.unwrap(); assert_eq!( vec![ Airport { node: Some(Node { longitude: -2, latitude: -2, restricted: false }), tag: Tag::Red.into() }, Airport { node: Some(Node { longitude: 1, latitude: 4, restricted: false }), tag: Tag::Blue.into() } ], map.airports ); } #[tokio::test] async fn node_to_location_with_center() { let (_, service) = setup(); let request = Request::new(NodeToPointRequest { node: Some(Node { longitude: 0, latitude: 0, restricted: false, }), }); let response = service.node_to_point(request).await.unwrap(); let location = response.into_inner().point.unwrap(); assert_eq!(0, location.x); assert_eq!(0, location.y); } #[tokio::test] async fn node_to_location() { let (_, service) = setup(); let request = Request::new(NodeToPointRequest { node: Some(Node { longitude: 1, latitude: 2, restricted: false, }), }); let response = service.node_to_point(request).await.unwrap(); let location = response.into_inner().point.unwrap(); assert_eq!(32, location.x); assert_eq!(64, location.y); } #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<MapService>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<MapService>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/api/game.rs
game/src/api/game.rs
use std::sync::Arc; use tonic::{Request, Response, Status}; use auto_traffic_control::v1::{ GetGameStateRequest, GetGameStateResponse, StartGameRequest, StartGameResponse, }; use crate::command::{Command, CommandSender}; use crate::store::{SharedGameState, Store}; #[derive(Clone, Debug)] pub struct GameService { command_bus: CommandSender, game_state: SharedGameState, } impl GameService { pub fn new(command_bus: CommandSender, store: Arc<Store>) -> Self { Self { command_bus, game_state: store.game_state().clone(), } } } #[tonic::async_trait] impl auto_traffic_control::v1::game_service_server::GameService for GameService { async fn get_game_state( &self, _request: Request<GetGameStateRequest>, ) -> Result<Response<GetGameStateResponse>, Status> { let game_state = self.game_state.lock(); Ok(Response::new(GetGameStateResponse { game_state: (*game_state).into(), })) } async fn start_game( &self, _request: Request<StartGameRequest>, ) -> Result<Response<StartGameResponse>, Status> { if self.command_bus.get().send(Command::StartGame).is_err() { return Err(Status::internal("failed to queue command")); } Ok(Response::new(StartGameResponse {})) } } #[cfg(test)] mod tests { use std::sync::Arc; use tokio::sync::broadcast::channel; use tonic::{Code, Request}; use auto_traffic_control::v1::game_service_server::GameService as ServiceTrait; use auto_traffic_control::v1::get_game_state_response::GameState; use auto_traffic_control::v1::{GetGameStateRequest, StartGameRequest}; use crate::command::{Command, CommandReceiver, CommandSender}; use crate::Store; use super::GameService; fn setup() -> (CommandReceiver, GameService) { let (command_sender, command_receiver) = channel::<Command>(1024); let command_sender = CommandSender::new(command_sender); let command_receiver = CommandReceiver::new(command_receiver); let store = Arc::new(Store::new()); let service = GameService::new(command_sender, store); (command_receiver, service) } #[tokio::test] async fn get_game_state() { let (_command_bus, service) = setup(); let request = Request::new(GetGameStateRequest {}); let response = service.get_game_state(request).await.unwrap(); assert_eq!(GameState::Ready, response.into_inner().game_state()); } #[tokio::test] async fn start_game_fails_to_queue_command() { let (command_bus, service) = setup(); std::mem::drop(command_bus); let request = Request::new(StartGameRequest {}); let status = service.start_game(request).await.unwrap_err(); assert_eq!(status.code(), Code::Internal); } #[tokio::test] async fn start_game_queues_command() { let (mut command_bus, service) = setup(); let request = Request::new(StartGameRequest {}); assert!(service.start_game(request).await.is_ok()); let command = command_bus.get_mut().try_recv().unwrap(); assert_eq!(Command::StartGame, command); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/api/mod.rs
game/src/api/mod.rs
use std::net::{IpAddr, SocketAddr}; use std::str::FromStr; use std::sync::Arc; use tonic::transport::{Error, Server as GrpcServer}; use ::auto_traffic_control::v1::airplane_service_server::AirplaneServiceServer; use ::auto_traffic_control::v1::atc_service_server::AtcServiceServer; use ::auto_traffic_control::v1::event_service_server::EventServiceServer; use ::auto_traffic_control::v1::game_service_server::GameServiceServer; use ::auto_traffic_control::v1::map_service_server::MapServiceServer; use crate::command::CommandSender; use crate::event::EventSender; use crate::store::Store; use self::airplane::AirplaneService; use self::atc::AtcService; use self::event::EventService; use self::game::GameService; use self::map::MapService; mod airplane; mod atc; mod event; mod game; mod map; const INTERFACE_VARIABLE: &str = "AUTO_TRAFFIC_CONTROL_INTERFACE"; pub struct Api; impl Api { pub async fn serve( command_sender: CommandSender, event_sender: EventSender, store: Arc<Store>, ) -> Result<(), Error> { GrpcServer::builder() .add_service(AirplaneServiceServer::new(AirplaneService::new( command_sender.clone(), store.clone(), ))) .add_service(AtcServiceServer::new(AtcService)) .add_service(EventServiceServer::new(EventService::new(event_sender))) .add_service(GameServiceServer::new(GameService::new( command_sender, store.clone(), ))) .add_service(MapServiceServer::new(MapService::new(store))) .serve(Self::address_or_default()) .await } fn address_or_default() -> SocketAddr { if let Ok(address_string) = std::env::var(INTERFACE_VARIABLE) { if let Ok(address) = SocketAddr::from_str(&address_string) { return address; } } SocketAddr::new(IpAddr::from([0, 0, 0, 0]), 4747) } } pub trait AsApi { type ApiType; fn as_api(&self) -> Self::ApiType; }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/api/airplane.rs
game/src/api/airplane.rs
use std::sync::Arc; use tonic::{Request, Response, Status}; use auto_traffic_control::v1::update_flight_plan_response::Payload; use auto_traffic_control::v1::{ GetAirplaneRequest, GetAirplaneResponse, UpdateFlightPlanError, UpdateFlightPlanRequest, UpdateFlightPlanResponse, UpdateFlightPlanSuccess, }; use crate::command::CommandSender; use crate::components::{AirplaneId, FlightPlan}; use crate::map::Map; use crate::store::Store; use crate::Command; #[derive(Clone, Debug)] pub struct AirplaneService { command_bus: CommandSender, map: Map, store: Arc<Store>, } impl AirplaneService { pub fn new(command_bus: CommandSender, store: Arc<Store>) -> Self { Self { command_bus, map: Map::new(), store, } } } #[tonic::async_trait] impl auto_traffic_control::v1::airplane_service_server::AirplaneService for AirplaneService { async fn get_airplane( &self, request: Request<GetAirplaneRequest>, ) -> Result<Response<GetAirplaneResponse>, Status> { let id = request.into_inner().id; if let Some(airplane) = self.store.airplanes().get(&id) { Ok(Response::new(GetAirplaneResponse { airplane: Some(airplane.clone()), })) } else { Err(Status::not_found(format!( "No airplane with id {id} was found" ))) } } async fn update_flight_plan( &self, request: Request<UpdateFlightPlanRequest>, ) -> Result<Response<UpdateFlightPlanResponse>, Status> { let request = request.into_inner(); let id = request.id; let airplane = match self.store.airplanes().get(&id) { Some(airplane) => airplane, None => { return Err(Status::not_found(format!( "No airplane with id {id} was found" ))); } }; let previous_flight_plan = (&airplane.flight_plan).into(); let new_flight_plan: FlightPlan = (&request.flight_plan).into(); if let Err(errors) = new_flight_plan.validate(&previous_flight_plan, self.map.routing_grid()) { let errors = errors.iter().map(|error| (*error).into()).collect(); return Ok(Response::new(UpdateFlightPlanResponse { payload: Some(Payload::Error(UpdateFlightPlanError { errors })), })); }; if self .command_bus .get() .send(Command::UpdateFlightPlan( AirplaneId::new(id), new_flight_plan, )) .is_err() { return Err(Status::internal("failed to queue command")); } Ok(Response::new(UpdateFlightPlanResponse { payload: Some(Payload::Success(UpdateFlightPlanSuccess {})), })) } } #[cfg(test)] mod tests { use std::sync::Arc; use tokio::sync::broadcast::channel; use tonic::{Code, Request}; use auto_traffic_control::v1::airplane_service_server::AirplaneService as ServiceTrait; use auto_traffic_control::v1::update_flight_plan_error::ValidationError; use auto_traffic_control::v1::update_flight_plan_response::Payload; use auto_traffic_control::v1::{Airplane, GetAirplaneRequest, UpdateFlightPlanRequest}; use crate::api::airplane::AirplaneService; use crate::api::AsApi; use crate::command::{CommandReceiver, CommandSender}; use crate::components::{AirplaneId, FlightPlan, Location, Tag}; use crate::map::{Node, MAP_HEIGHT_RANGE, MAP_WIDTH_RANGE}; use crate::{Command, Store}; fn setup() -> (CommandReceiver, Arc<Store>, AirplaneService) { let (command_sender, command_receiver) = channel::<Command>(1024); let command_sender = CommandSender::new(command_sender); let command_receiver = CommandReceiver::new(command_receiver); let store = Arc::new(Store::new()); let service = AirplaneService::new(command_sender, store.clone()); (command_receiver, store, service) } fn init_airplane(id: &str, store: &Arc<Store>) -> (AirplaneId, Location, FlightPlan) { let id = AirplaneId::new(id.into()); let location = Location::new(0, 0); let flight_plan = FlightPlan::new(vec![Node::unrestricted(0, 0)]); let airplane = Airplane { id: id.as_api(), point: Some(location.as_api()), flight_plan: flight_plan.as_api(), tag: Tag::Red.as_api().into(), }; store.airplanes().insert("AT-4321".into(), airplane); (id, location, flight_plan) } #[tokio::test] async fn get_airplane_with_wrong_id() { let (_command_bus, _store, service) = setup(); let request = Request::new(GetAirplaneRequest { id: "AT-4321".into(), }); let status = service.get_airplane(request).await.unwrap_err(); assert_eq!(status.code(), Code::NotFound); } #[tokio::test] async fn get_airplane_for_existing_plane() { let (_command_bus, store, service) = setup(); let (_id, _location, _flight_plan) = init_airplane("AT-4321", &store); let request = Request::new(GetAirplaneRequest { id: "AT-4321".into(), }); let response = service.get_airplane(request).await.unwrap(); let payload = response.into_inner(); let airplane = payload.airplane.unwrap(); assert_eq!("AT-4321", &airplane.id); } #[tokio::test] async fn update_flight_plan_with_wrong_id() { let (_command_bus, _store, service) = setup(); let request = Request::new(UpdateFlightPlanRequest { id: "AT-4321".into(), flight_plan: vec![Node::unrestricted(0, 0).as_api()], }); let status = service.update_flight_plan(request).await.unwrap_err(); assert_eq!(status.code(), Code::NotFound); } #[tokio::test] async fn update_flight_plan_with_invalid_plan() { let (mut command_bus, store, service) = setup(); let (_id, _location, _flight_plan) = init_airplane("AT-4321", &store); let request = Request::new(UpdateFlightPlanRequest { id: "AT-4321".into(), flight_plan: vec![ Node::unrestricted(1, 0).as_api(), Node::unrestricted(3, 0).as_api(), Node::unrestricted(1, 0).as_api(), Node::unrestricted(MAP_WIDTH_RANGE.start() - 1, MAP_HEIGHT_RANGE.start() - 1) .as_api(), ], }); let response = service.update_flight_plan(request).await.unwrap(); let actual_errors = match response.into_inner().payload.unwrap() { Payload::Error(error) => error.errors, _ => panic!("unexpected payload"), }; let expected_errors: Vec<i32> = vec![ ValidationError::NodeOutsideMap.into(), ValidationError::InvalidStep.into(), ValidationError::InvalidStart.into(), ValidationError::SharpTurn.into(), ValidationError::RestrictedNode.into(), ]; assert_eq!(expected_errors, actual_errors); assert!(command_bus.get_mut().try_recv().is_err()); } #[tokio::test] async fn update_flight_plan_fails_to_queue_command() { let (command_bus, store, service) = setup(); std::mem::drop(command_bus); let id = AirplaneId::new("AT-4321".into()); let location = Location::new(0, 0); let flight_plan = FlightPlan::new(vec![Node::unrestricted(0, 0)]); let airplane = Airplane { id: id.as_api(), point: Some(location.as_api()), flight_plan: flight_plan.as_api(), tag: Tag::Red.as_api().into(), }; store.airplanes().insert("AT-4321".into(), airplane); let request = Request::new(UpdateFlightPlanRequest { id: "AT-4321".into(), flight_plan: vec![Node::unrestricted(0, 0).as_api()], }); let status = service.update_flight_plan(request).await.unwrap_err(); assert_eq!(status.code(), Code::Internal); } #[tokio::test] async fn update_flight_plan_with_valid_plan() { let (mut command_bus, store, service) = setup(); let id = AirplaneId::new("AT-4321".into()); let location = Location::new(0, 0); let flight_plan = FlightPlan::new(vec![Node::unrestricted(0, 0)]); let airplane = Airplane { id: id.as_api(), point: Some(location.as_api()), flight_plan: flight_plan.as_api(), tag: Tag::Red.as_api().into(), }; store.airplanes().insert("AT-4321".into(), airplane); let new_flight_plan = FlightPlan::new(vec![Node::unrestricted(-1, 0), Node::unrestricted(0, 0)]); let request = Request::new(UpdateFlightPlanRequest { id: "AT-4321".into(), flight_plan: new_flight_plan.clone().as_api(), }); let response = service.update_flight_plan(request).await.unwrap(); if let Payload::Error(_) = response.into_inner().payload.unwrap() { panic!("unexpected payload"); } let command = command_bus.get_mut().try_recv().unwrap(); match command { Command::UpdateFlightPlan(airplane_id, flight_plan) => { assert_eq!("AT-4321", airplane_id.get()); assert_eq!(new_flight_plan, flight_plan); } _ => panic!("unexpected command"), } } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/event/sender.rs
game/src/event/sender.rs
use bevy::prelude::*; use tokio::sync::broadcast::Sender; use crate::event::{Event, EventReceiver}; #[derive(Clone, Debug, Resource)] pub struct EventSender(Sender<Event>); impl EventSender { pub fn new(sender: Sender<Event>) -> Self { Self(sender) } pub fn get(&self) -> &Sender<Event> { &self.0 } pub fn subscribe(&self) -> EventReceiver { EventReceiver::new(self.0.subscribe()) } } #[cfg(test)] mod tests { use super::*; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<EventSender>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<EventSender>(); } #[test] fn trait_unpin() { fn assert_unpin<T: Unpin>() {} assert_unpin::<EventSender>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/event/mod.rs
game/src/event/mod.rs
use auto_traffic_control::v1::stream_response::Event as ApiEvent; use auto_traffic_control::v1::{ Airplane, AirplaneCollided, AirplaneDetected, AirplaneLanded, AirplaneMoved, FlightPlanUpdated, GameStarted, GameStopped, LandingAborted, }; use crate::api::AsApi; use crate::components::{AirplaneId, FlightPlan, Location, Tag}; use crate::map::Map; use crate::resources::Score; pub use self::bus::EventBus; pub use self::receiver::EventReceiver; pub use self::sender::EventSender; mod bus; mod receiver; mod sender; #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub enum Event { AirplaneCollided(AirplaneId, AirplaneId), AirplaneDetected(AirplaneId, Location, FlightPlan, Tag), AirplaneLanded(AirplaneId), AirplaneMoved(AirplaneId, Location), FlightPlanUpdated(AirplaneId, FlightPlan), LandingAborted(AirplaneId), GameStarted(Map), GameStopped(Score), } impl AsApi for Event { type ApiType = auto_traffic_control::v1::stream_response::Event; fn as_api(&self) -> Self::ApiType { match self { Event::AirplaneCollided(airplane_id1, airplane_id2) => { ApiEvent::AirplaneCollided(AirplaneCollided { id1: airplane_id1.as_api(), id2: airplane_id2.as_api(), }) } Event::AirplaneDetected(id, location, flight_plan, tag) => { ApiEvent::AirplaneDetected(AirplaneDetected { airplane: Some(Airplane { id: id.as_api(), point: Some(location.as_api()), flight_plan: flight_plan.as_api(), tag: tag.as_api().into(), }), }) } Event::AirplaneLanded(id) => { ApiEvent::AirplaneLanded(AirplaneLanded { id: id.as_api() }) } Event::AirplaneMoved(id, location) => ApiEvent::AirplaneMoved(AirplaneMoved { id: id.as_api(), point: Some(location.as_api()), }), Event::FlightPlanUpdated(id, flight_plan) => { ApiEvent::FlightPlanUpdated(FlightPlanUpdated { id: id.as_api(), flight_plan: flight_plan.as_api(), }) } Event::LandingAborted(id) => { ApiEvent::LandingAborted(LandingAborted { id: id.as_api() }) } Event::GameStarted(map) => ApiEvent::GameStarted(GameStarted { map: Some(map.as_api()), }), Event::GameStopped(score) => ApiEvent::GameStopped(GameStopped { score: score.get() }), } } } #[cfg(test)] mod tests { use super::Event; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<Event>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Event>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/event/bus.rs
game/src/event/bus.rs
use bevy::prelude::*; use crate::event::EventSender; #[derive(Clone, Debug)] pub struct EventBus { sender: EventSender, } impl EventBus { pub fn sender(&self) -> &EventSender { &self.sender } } impl FromWorld for EventBus { fn from_world(world: &mut World) -> Self { let sender = world.resource::<EventSender>(); Self { sender: sender.clone(), } } } #[cfg(test)] mod tests { use super::EventBus; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<EventBus>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<EventBus>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/event/receiver.rs
game/src/event/receiver.rs
use bevy::prelude::*; use tokio::sync::broadcast::Receiver; use crate::event::Event; #[derive(Debug, Resource)] pub struct EventReceiver(Receiver<Event>); impl EventReceiver { pub fn new(receiver: Receiver<Event>) -> Self { Self(receiver) } pub fn get_mut(&mut self) -> &mut Receiver<Event> { &mut self.0 } } impl From<EventReceiver> for Receiver<Event> { fn from(value: EventReceiver) -> Self { value.0 } } #[cfg(test)] mod tests { use super::*; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<EventReceiver>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<EventReceiver>(); } #[test] fn trait_unpin() { fn assert_unpin<T: Unpin>() {} assert_unpin::<EventReceiver>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/follow_flight_plan.rs
game/src/systems/follow_flight_plan.rs
use bevy::prelude::*; use geo::algorithm::euclidean_distance::EuclideanDistance; use geo::point; use crate::components::{AirplaneId, FlightPlan, Location, Speed, TravelledRoute}; use crate::event::{Event, EventBus}; use crate::map::Direction; pub fn follow_flight_plan( time: Res<Time>, mut query: Query<( &AirplaneId, &mut FlightPlan, &Speed, &mut Transform, &mut TravelledRoute, )>, event_bus: Local<EventBus>, ) { for (airplane_id, mut flight_plan, speed, mut transform, mut travelled_route) in query.iter_mut() { let distance = speed.get() * time.delta().as_secs_f32(); let did_update_flight_plan = fly( &mut transform.translation, &mut flight_plan, &mut travelled_route, distance, ); event_bus .sender() .get() .send(Event::AirplaneMoved( airplane_id.clone(), Location::from(&transform), )) .expect("failed to send event"); // TODO: Handle error if did_update_flight_plan && !flight_plan.get().is_empty() { event_bus .sender() .get() .send(Event::FlightPlanUpdated( airplane_id.clone(), flight_plan.clone(), )) .expect("failed to send event"); // TODO: Handle error } } } fn fly( current_position: &mut Vec3, flight_plan: &mut FlightPlan, travelled_route: &mut TravelledRoute, travelled_distance: f32, ) -> bool { if let Some(next_tile) = flight_plan.get().iter().last() { let current_point = point!(x: current_position.x, y: current_position.y); let next_point = next_tile.as_point(); let distance_between_points = current_point.euclidean_distance(&next_point); if travelled_distance >= distance_between_points { *current_position = next_tile.as_vec3(current_position.z); let node = flight_plan.get_mut().pop().unwrap(); travelled_route.get_mut().push(node); fly( current_position, flight_plan, travelled_route, travelled_distance - distance_between_points, ); return true; } else { let direction = Direction::between(&next_point, &current_point); *current_position += direction.to_vec3().normalize() * travelled_distance; } } false } #[cfg(test)] mod tests { use bevy::prelude::*; use crate::components::{FlightPlan, TravelledRoute}; use crate::map::Node; use crate::TILE_SIZE; use super::fly; #[test] fn fly_and_reach_next_node() { let mut current_position = Node::unrestricted(0, 0).as_vec3(0.0); let mut flight_plan = FlightPlan::new(vec![Node::unrestricted(1, 0)]); let mut travelled_route = TravelledRoute::new(vec![Node::unrestricted(0, 0)]); fly( &mut current_position, &mut flight_plan, &mut travelled_route, TILE_SIZE as f32, ); assert_eq!(current_position, Vec3::new(TILE_SIZE as f32, 0.0, 0.0)); assert_eq!(0, flight_plan.get().len()); assert_eq!(2, travelled_route.get().len()); } #[test] fn fly_towards_next_node() { let mut current_position = Node::unrestricted(0, 0).as_vec3(0.0); let mut flight_plan = FlightPlan::new(vec![Node::unrestricted(1, 0)]); let mut travelled_route = TravelledRoute::new(vec![Node::unrestricted(0, 0)]); let movement_speed = (TILE_SIZE / 2) as f32; fly( &mut current_position, &mut flight_plan, &mut travelled_route, movement_speed, ); assert_eq!(current_position, Vec3::new(movement_speed, 0.0, 0.0)); assert_eq!(1, travelled_route.get().len()); } #[test] fn fly_past_node() { let mut current_position = Node::unrestricted(0, 0).as_vec3(0.0); let mut flight_plan = FlightPlan::new(vec![Node::unrestricted(2, 0), Node::unrestricted(1, 0)]); let mut travelled_route = TravelledRoute::new(vec![Node::unrestricted(0, 0)]); let movement_speed = (TILE_SIZE + (TILE_SIZE / 2)) as f32; fly( &mut current_position, &mut flight_plan, &mut travelled_route, movement_speed, ); assert_eq!(current_position, Vec3::new(movement_speed, 0.0, 0.0)); assert_eq!(1, flight_plan.get().len()); assert_eq!(2, travelled_route.get().len()); } #[test] fn fly_past_node_and_change_direction() { let mut current_position = Node::unrestricted(0, 0).as_vec3(0.0); let mut flight_plan = FlightPlan::new(vec![Node::unrestricted(1, 1), Node::unrestricted(1, 0)]); let mut travelled_route = TravelledRoute::new(vec![Node::unrestricted(0, 0)]); let movement_speed = (TILE_SIZE + (TILE_SIZE / 2)) as f32; fly( &mut current_position, &mut flight_plan, &mut travelled_route, movement_speed, ); assert_eq!(current_position, Vec3::new(32.0, 16.0, 0.0)); assert_eq!(1, flight_plan.get().len()); assert_eq!(2, travelled_route.get().len()); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/land_airplane.rs
game/src/systems/land_airplane.rs
use bevy::prelude::*; use crate::components::{FlightPlan, Landing}; use crate::map::Map; pub fn land_airplane( mut commands: Commands, map: Res<Map>, query: Query<(Entity, &FlightPlan), Without<Landing>>, ) { for (entity, flight_plan) in query.iter() { if flight_plan.get().len() != 1 { continue; } let final_node = flight_plan.next().unwrap(); for airport in map.airports() { if final_node == airport.node() { commands.entity(entity).insert(Landing); } } } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/setup_landscape.rs
game/src/systems/setup_landscape.rs
use bevy::prelude::*; use rand::{thread_rng, Rng}; use crate::rendering::RenderLayer; use crate::{SCREEN_HEIGHT, SCREEN_WIDTH, TILE_SIZE}; pub fn setup_landscape( mut commands: Commands, asset_server: Res<AssetServer>, mut texture_atlases: ResMut<Assets<TextureAtlas>>, ) { let mut rng = thread_rng(); let landscape_handle = asset_server.load("sprites/landscape.png"); let landscape_atlas = TextureAtlas::from_grid(landscape_handle, Vec2::new(32.0, 32.0), 1, 1, None, None); let landscape_atlas_handle = texture_atlases.add(landscape_atlas); let decorations_handle = asset_server.load("sprites/decorations.png"); let decorations_atlas = TextureAtlas::from_grid( decorations_handle, Vec2::new(128.0, 128.0), 4, 2, None, None, ); let decorations_atlas_handle = texture_atlases.add(decorations_atlas); let horizontal_tiles = SCREEN_WIDTH as i32 / TILE_SIZE + 1; let vertical_tiles = SCREEN_HEIGHT as i32 / TILE_SIZE + 1; for y in -vertical_tiles..=vertical_tiles { for x in -horizontal_tiles..=horizontal_tiles { let x = (x * TILE_SIZE) as f32; let y = (y * TILE_SIZE) as f32; commands.spawn(SpriteSheetBundle { texture_atlas: landscape_atlas_handle.clone(), transform: Transform { translation: Vec3::new(x, y, RenderLayer::Landscape.z()), ..Default::default() }, sprite: TextureAtlasSprite::new(0), ..Default::default() }); // 25% chance of a decoration let sprite = rng.gen_range(0..32); if sprite >= 8 { continue; } commands.spawn(SpriteSheetBundle { texture_atlas: decorations_atlas_handle.clone(), transform: Transform { translation: Vec3::new(x - 16.0, y - 16.0, RenderLayer::Decoration.z()), ..Default::default() }, sprite: TextureAtlasSprite { index: sprite, custom_size: Some(Vec2::new(32.0, 32.0)), ..Default::default() }, ..Default::default() }); } } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/generate_flight_plan.rs
game/src/systems/generate_flight_plan.rs
use bevy::prelude::*; use rand::prelude::*; use crate::components::{AirplaneId, FlightPlan, Landing, TravelledRoute}; use crate::event::{Event, EventBus}; use crate::map::{Map, Node, MAP_HEIGHT_RANGE, MAP_WIDTH_RANGE}; const FLIGHT_PLAN_LENGTH: usize = 4; pub fn generate_flight_plan( map: Res<Map>, mut query: Query<(&AirplaneId, &mut FlightPlan, &TravelledRoute), Without<Landing>>, event_bus: Local<EventBus>, ) { for (airplane_id, mut flight_plan, travelled_route) in query.iter_mut() { if !flight_plan.get().is_empty() { continue; } let new_flight_plan = generate_random_plan(travelled_route, &map); *flight_plan = new_flight_plan.clone(); event_bus .sender() .get() .send(Event::FlightPlanUpdated( airplane_id.clone(), new_flight_plan, )) .expect("failed to send event"); // TODO: Handle error } } fn generate_random_plan(travelled_route: &TravelledRoute, map: &Res<Map>) -> FlightPlan { let mut flight_plan = Vec::new(); let mut reversed_route = travelled_route.get().iter().rev(); let mut current_node = *reversed_route .next() .expect("travelled route must include the starting location"); let mut previous_node = reversed_route.next().cloned(); let mut next_node; for _ in 0..FLIGHT_PLAN_LENGTH { next_node = pick_next_tile(&current_node, &previous_node, map); flight_plan.push(next_node); previous_node = Some(current_node); current_node = next_node; } FlightPlan::new(flight_plan.iter().rev().cloned().collect()) } fn pick_next_tile(current_tile: &Node, previous_tile: &Option<Node>, map: &Map) -> Node { let airports: Vec<&Node> = map .airports() .iter() .map(|airport| airport.node()) .collect(); let potential_tiles: Vec<Node> = current_tile .neighbors() .into_iter() .filter(|node| &Some(*node) != previous_tile) .filter(|node| !airports.contains(&node)) .filter(|node| !node.is_restricted()) .filter(|tile| { // Shouldn't be too close to the edge of the map tile.longitude().abs() != *MAP_WIDTH_RANGE.end() && tile.latitude().abs() != *MAP_HEIGHT_RANGE.end() }) .collect(); // Pick random neighbor of the current tile let mut rng = thread_rng(); *potential_tiles .choose(&mut rng) .expect("failed to choose random tile") }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/detect_collisions.rs
game/src/systems/detect_collisions.rs
use bevy::prelude::*; use bevy::sprite::collide_aabb::collide; use crate::components::{AirplaneId, Collider, AIRPLANE_SIZE}; use crate::event::{Event, EventBus}; use crate::AppState; pub struct Size { airplane: Vec2, } impl Default for Size { fn default() -> Self { Self { airplane: Vec2::new(AIRPLANE_SIZE, AIRPLANE_SIZE), } } } pub fn detect_collision( mut app_state: ResMut<State<AppState>>, query: Query<(Entity, &AirplaneId, &Collider, &Transform)>, event_bus: Local<EventBus>, size: Local<Size>, ) { 'outer: for (entity1, airplane_id1, _, transform1) in query.iter() { for (entity2, airplane_id2, _, transform2) in query.iter() { if entity1 == entity2 { continue; } if collide( transform1.translation, size.airplane, transform2.translation, size.airplane, ) .is_some() { event_bus .sender() .get() .send(Event::AirplaneCollided( airplane_id1.clone(), airplane_id2.clone(), )) .expect("failed to send event"); // TODO: Handle error app_state.set(AppState::GameOver).unwrap(); break 'outer; } } } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/rotate_airplane.rs
game/src/systems/rotate_airplane.rs
use bevy::prelude::*; use crate::components::{FlightPlan, TravelledRoute}; use crate::map::Direction; pub fn rotate_airplane(mut query: Query<(&mut FlightPlan, &mut Transform, &mut TravelledRoute)>) { for (flight_plan, mut transform, travelled_route) in query.iter_mut() { let last_point = travelled_route .get() .last() .expect("travelled route must not be empty") .as_point(); let next_point = match flight_plan.next() { Some(node) => node.as_point(), None => continue, }; let direction = Direction::between(&next_point, &last_point); transform.rotation = Quat::from_rotation_z(direction.to_degree().to_radians()); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/despawn_airplane.rs
game/src/systems/despawn_airplane.rs
use bevy::prelude::*; use crate::components::{AirplaneId, FlightPlan, Landing, Tag}; use crate::event::{Event, EventBus}; use crate::map::{Airport, Map, Node}; use crate::rendering::RenderLayer; use crate::resources::Score; pub fn despawn_airplane( mut commands: Commands, map: Res<Map>, mut score: ResMut<Score>, mut query: Query<(Entity, &AirplaneId, &mut FlightPlan, &Tag, &Transform), With<Landing>>, event_bus: Local<EventBus>, ) { for (entity, airplane_id, mut flight_plan, tag, transform) in query.iter_mut() { for airport in map.airports() { let airport_location = airport.node().as_vec3(RenderLayer::Airplane.z()); let airport_tag = airport.tag(); let airplane_location = transform.translation; if airplane_location != airport_location { continue; } if tag == &airport_tag { commands.entity(entity).despawn_recursive(); score.increment(); event_bus .sender() .get() .send(Event::AirplaneLanded(airplane_id.clone())) .expect("failed to send event"); // TODO: Handle error } else { let go_around = go_around_procedure(airport); *flight_plan = FlightPlan::new(vec![go_around]); commands.entity(entity).remove::<Landing>(); event_bus .sender() .get() .send(Event::LandingAborted(airplane_id.clone())) .expect("failed to send event"); // TODO: Handle error event_bus .sender() .get() .send(Event::FlightPlanUpdated( airplane_id.clone(), flight_plan.clone(), )) .expect("failed to send event"); // TODO: Handle error } break; } } } fn go_around_procedure(airport: &Airport) -> Node { let runway_direction = airport.runway().to_vec3(); let next_hop_in_direction = runway_direction * Vec3::splat(-2.0); Node::unrestricted( next_hop_in_direction.x as i32, next_hop_in_direction.y as i32, ) }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/setup_cameras.rs
game/src/systems/setup_cameras.rs
use bevy::prelude::*; pub fn setup_cameras(mut commands: Commands) { commands.spawn(Camera2dBundle::default()); }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/mod.rs
game/src/systems/mod.rs
pub use self::change_app_state::*; pub use self::despawn_airplane::*; pub use self::detect_collisions::*; pub use self::follow_flight_plan::*; pub use self::generate_flight_plan::*; pub use self::land_airplane::*; pub use self::rotate_airplane::*; pub use self::setup_airport::*; pub use self::setup_cameras::*; pub use self::setup_grid::*; pub use self::setup_landscape::*; pub use self::spawn_airplane::*; pub use self::update_flight_plan::*; mod change_app_state; mod despawn_airplane; mod detect_collisions; mod follow_flight_plan; mod generate_flight_plan; mod land_airplane; mod rotate_airplane; mod setup_airport; mod setup_cameras; mod setup_grid; mod setup_landscape; mod spawn_airplane; mod update_flight_plan;
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/change_app_state.rs
game/src/systems/change_app_state.rs
use bevy::prelude::*; use crate::command::CommandBus; use crate::{AppState, Command}; pub fn change_app_state( mut app_state: ResMut<State<AppState>>, mut command_bus: Local<CommandBus>, ) { let mut queued_transition = false; while let Ok(command) = command_bus.receiver().get_mut().try_recv() { match command { Command::StartGame => { app_state.set(AppState::Game).unwrap(); queued_transition = true; break; } _ => continue, } } if queued_transition { // Drain remaining commands to prevent lagging while command_bus.receiver().get_mut().try_recv().is_ok() {} } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/update_flight_plan.rs
game/src/systems/update_flight_plan.rs
use bevy::prelude::*; use crate::command::{Command, CommandBus}; use crate::components::{AirplaneId, FlightPlan}; use crate::event::{Event, EventBus}; use crate::map::Map; pub fn update_flight_plan( map: Res<Map>, mut query: Query<(&AirplaneId, &mut FlightPlan)>, mut command_bus: Local<CommandBus>, event_bus: Local<EventBus>, ) { while let Ok(command) = command_bus.receiver().get_mut().try_recv() { let (airplane_id, new_flight_plan) = match command { Command::UpdateFlightPlan(airplane_id, flight_plan) => (airplane_id, flight_plan), _ => continue, }; for (id, mut current_flight_plan) in query.iter_mut() { if *id == airplane_id { if new_flight_plan .validate(&current_flight_plan, map.routing_grid()) .is_ok() { *current_flight_plan = new_flight_plan.clone(); event_bus .sender() .get() .send(Event::FlightPlanUpdated( airplane_id.clone(), new_flight_plan, )) .expect("failed to send event"); // TODO: Handle error break; } else { // TODO: Handle error } } } } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/spawn_airplane.rs
game/src/systems/spawn_airplane.rs
use bevy::prelude::*; use rand::{thread_rng, Rng}; use crate::components::{ Airplane, AirplaneIdGenerator, Collider, FlightPlan, Location, Speed, Tag, TravelledRoute, }; use crate::event::{Event, EventBus}; use crate::map::{Direction, Node, MAP_HEIGHT_RANGE, MAP_WIDTH_RANGE}; use crate::rendering::RenderLayer; // Planes are spawned this many nodes outside the map area const SPAWN_OFFSET: i32 = 3; #[derive(Clone, Debug, Default, Resource)] pub struct SpawnTimer(Timer); impl SpawnTimer { pub fn new(timer: Timer) -> Self { Self(timer) } } pub fn spawn_airplane( mut commands: Commands, time: Res<Time>, mut timer: ResMut<SpawnTimer>, asset_server: Res<AssetServer>, mut texture_atlases: ResMut<Assets<TextureAtlas>>, mut airplane_id_generator: Local<AirplaneIdGenerator>, event_bus: Local<EventBus>, ) { let mut rng = thread_rng(); let texture_handle = asset_server.load("sprites/airplanes.png"); let texture_atlas = TextureAtlas::from_grid(texture_handle, Vec2::new(128.0, 128.0), 2, 1, None, None); let texture_atlas_handle = texture_atlases.add(texture_atlas); if timer.0.tick(time.delta()).just_finished() { let (spawn, first_node) = random_spawn(); let spawn_point = spawn.as_point(); let airplane_id = airplane_id_generator.generate(); let travelled_route = TravelledRoute::new(vec![spawn]); let flight_plan = FlightPlan::new(vec![first_node]); let direction = Direction::between(&first_node.as_point(), &spawn_point); let tag = if rng.gen_bool(0.5) { Tag::Blue } else { Tag::Red }; let color_offset = match tag { Tag::Blue => 0, Tag::Red => 1, }; commands .spawn(SpriteSheetBundle { texture_atlas: texture_atlas_handle, transform: Transform { translation: Vec3::new( spawn_point.x(), spawn_point.y(), RenderLayer::Airplane.z(), ), rotation: Quat::from_rotation_z(direction.to_degree().to_radians()), ..Default::default() }, sprite: TextureAtlasSprite { index: color_offset, custom_size: Some(Vec2::new(32.0, 32.0)), ..Default::default() }, ..Default::default() }) .insert(Airplane) .insert(airplane_id.clone()) .insert(Collider) .insert(flight_plan.clone()) .insert(Speed::new(32.0)) .insert(tag) .insert(travelled_route); event_bus .sender() .get() .send(Event::AirplaneDetected( airplane_id, Location::from(&spawn), flight_plan, tag, )) .expect("failed to send event"); // TODO: Handle error } } fn random_spawn() -> (Node, Node) { let mut rng = thread_rng(); let (first_node, spawn) = match rng.gen_range(0u32..4u32) { 0 => { let x = rng.gen_range(MAP_WIDTH_RANGE); ( Node::unrestricted(x, *MAP_HEIGHT_RANGE.end()), Node::unrestricted(x, *MAP_HEIGHT_RANGE.end() + SPAWN_OFFSET), ) } 1 => { let y = rng.gen_range(MAP_HEIGHT_RANGE); ( Node::unrestricted(*MAP_WIDTH_RANGE.end(), y), Node::unrestricted(*MAP_WIDTH_RANGE.end() + SPAWN_OFFSET, y), ) } 2 => { let x = rng.gen_range(MAP_WIDTH_RANGE); ( Node::unrestricted(x, *MAP_HEIGHT_RANGE.start()), Node::unrestricted(x, *MAP_HEIGHT_RANGE.start() - SPAWN_OFFSET), ) } _ => { let y = rng.gen_range(MAP_HEIGHT_RANGE); ( Node::unrestricted(*MAP_WIDTH_RANGE.start(), y), Node::unrestricted(*MAP_WIDTH_RANGE.start() - SPAWN_OFFSET, y), ) } }; (spawn, first_node) }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/setup_grid.rs
game/src/systems/setup_grid.rs
use bevy::prelude::*; use crate::map::Map; use crate::rendering::RenderLayer; pub fn setup_grid(map: Res<Map>, mut commands: Commands) { for node in map .routing_grid() .iter() .filter(|node| !node.is_restricted()) { let point = node.as_point(); commands.spawn(SpriteBundle { transform: Transform { translation: Vec3::new(point.x(), point.y(), RenderLayer::RoutingGrid.z()), scale: Vec3::new(2.0, 2.0, 0.0), ..Default::default() }, sprite: Sprite { color: Color::WHITE, ..Default::default() }, ..Default::default() }); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/systems/setup_airport.rs
game/src/systems/setup_airport.rs
use bevy::prelude::*; use crate::components::Tag; use crate::map::{Direction, Map}; use crate::rendering::RenderLayer; use crate::TILE_SIZE; pub fn setup_airport( mut commands: Commands, map: Res<Map>, asset_server: Res<AssetServer>, mut texture_atlases: ResMut<Assets<TextureAtlas>>, ) { let texture_handle = asset_server.load("sprites/airports.png"); let texture_atlas = TextureAtlas::from_grid(texture_handle, Vec2::new(128.0, 128.0), 8, 2, None, None); let texture_atlas_handle = texture_atlases.add(texture_atlas); for airport in map.airports() { let airport_vec3 = airport.node().as_vec3(RenderLayer::Airport.z()); let runway_vec3 = airport_vec3 + airport.runway().to_vec3() * Vec3::splat(TILE_SIZE as f32); let color_offset = match airport.tag() { Tag::Blue => 0, Tag::Red => 8, }; let airport_offset = match airport.runway() { Direction::North => 0, Direction::East => 2, Direction::South => 4, Direction::West => 6, _ => panic!("diagonal airports are not supported"), }; let runway_offset = airport_offset + 1; commands.spawn(SpriteSheetBundle { texture_atlas: texture_atlas_handle.clone(), transform: Transform { translation: airport_vec3, ..Default::default() }, sprite: TextureAtlasSprite { index: color_offset + airport_offset, custom_size: Some(Vec2::new(32.0, 32.0)), ..Default::default() }, ..Default::default() }); commands.spawn(SpriteSheetBundle { texture_atlas: texture_atlas_handle.clone(), transform: Transform { translation: runway_vec3, ..Default::default() }, sprite: TextureAtlasSprite { index: color_offset + runway_offset, custom_size: Some(Vec2::new(32.0, 32.0)), ..Default::default() }, ..Default::default() }); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/map/node.rs
game/src/map/node.rs
use std::cmp::{max, min}; use std::fmt::{Display, Formatter}; use bevy::prelude::*; use geo::{point, Point}; use auto_traffic_control::v1::Node as ApiNode; use crate::api::AsApi; use crate::map::{MAP_HEIGHT, MAP_HEIGHT_RANGE, MAP_WIDTH, MAP_WIDTH_RANGE}; use crate::TILE_SIZE; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)] pub struct Node { longitude: i32, latitude: i32, restricted: bool, } impl Node { pub fn restricted(longitude: i32, latitude: i32) -> Self { Self { longitude, latitude, restricted: true, } } pub fn unrestricted(longitude: i32, latitude: i32) -> Self { Self { longitude, latitude, restricted: false, } } pub fn longitude(&self) -> i32 { self.longitude } pub fn latitude(&self) -> i32 { self.latitude } pub fn is_restricted(&self) -> bool { self.restricted } // TODO: Move to map so that `restricted` can be set from the routing grid pub fn neighbors(&self) -> Vec<Node> { let width_range = max(*MAP_WIDTH_RANGE.start(), self.longitude - 1) ..=min(*MAP_WIDTH_RANGE.end(), self.longitude + 1); let height_range = max(*MAP_HEIGHT_RANGE.start(), self.latitude - 1) ..=min(*MAP_HEIGHT_RANGE.end(), self.latitude + 1); let mut neighbors = Vec::new(); for y in height_range { // TODO: Refactor to avoid clone for x in width_range.clone() { if x == self.longitude && y == self.latitude { continue; } // TODO: Get restriction from routing grid neighbors.push(Node::unrestricted(x, y)); } } neighbors } pub fn is_neighbor(&self, potential_neighbor: &Node) -> bool { let delta_x = potential_neighbor.longitude() - self.longitude(); let delta_y = potential_neighbor.latitude() - self.latitude(); delta_x.abs() <= 1 && delta_y.abs() <= 1 } pub fn as_index(&self) -> usize { let x = self.longitude + MAP_WIDTH as i32 / 2; let y = self.latitude + MAP_HEIGHT as i32 / 2; let index = (y * MAP_WIDTH as i32) + x; index as usize } pub fn as_point(&self) -> Point<f32> { let x = (self.longitude * TILE_SIZE) as f32; let y = (self.latitude * TILE_SIZE) as f32; point!(x: x, y: y) } pub fn as_vec3(&self, z: f32) -> Vec3 { Vec3::new( (self.longitude * TILE_SIZE) as f32, (self.latitude * TILE_SIZE) as f32, z, ) } pub fn to_location(self) -> (i32, i32) { (self.longitude * TILE_SIZE, self.latitude * TILE_SIZE) } } impl Display for Node { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "Node {{ x: {}, y: {} }}", self.longitude, self.latitude) } } impl From<&Point<i32>> for Node { fn from(point: &Point<i32>) -> Self { let x = point.x() / TILE_SIZE; let y = point.y() / TILE_SIZE; Self { longitude: x, latitude: y, restricted: false, // TODO: Get restriction from routing grid } } } impl AsApi for Node { type ApiType = ApiNode; fn as_api(&self) -> Self::ApiType { ApiNode { longitude: self.longitude(), latitude: self.latitude(), restricted: self.restricted, } } } #[cfg(test)] mod tests { use geo::point; use crate::map::{MAP_HEIGHT, MAP_HEIGHT_RANGE, MAP_WIDTH, MAP_WIDTH_RANGE}; use super::{Node, TILE_SIZE}; #[test] fn neighbors_at_center() { let node = Node::unrestricted(0, 0); let neighbors = node.neighbors(); assert_eq!( vec![ Node::unrestricted(-1, -1), Node::unrestricted(0, -1), Node::unrestricted(1, -1), Node::unrestricted(-1, 0), Node::unrestricted(1, 0), Node::unrestricted(-1, 1), Node::unrestricted(0, 1), Node::unrestricted(1, 1), ], neighbors ); } #[test] fn neighbors_at_edge() { let edge = *MAP_WIDTH_RANGE.start(); let node = Node::unrestricted(edge, 0); let neighbors = node.neighbors(); assert_eq!( vec![ Node::unrestricted(edge, -1), Node::unrestricted(edge + 1, -1), Node::unrestricted(edge + 1, 0), Node::unrestricted(edge, 1), Node::unrestricted(edge + 1, 1), ], neighbors ); } #[test] fn neighbors_at_corner() { let x = *MAP_WIDTH_RANGE.start(); let y = *MAP_HEIGHT_RANGE.start(); let node = Node::unrestricted(x, y); let neighbors = node.neighbors(); assert_eq!( vec![ Node::unrestricted(x + 1, y), Node::unrestricted(x, y + 1), Node::unrestricted(x + 1, y + 1), ], neighbors ); } #[test] fn is_neighbor_with_neighbor() { let node = Node::unrestricted(0, 0); let neighbor = Node::unrestricted(1, 1); assert!(neighbor.is_neighbor(&node)); } #[test] fn is_neighbor_with_distant_node() { let node = Node::unrestricted(0, 0); let neighbor = Node::unrestricted(2, 0); assert!(!neighbor.is_neighbor(&node)); } #[test] fn as_index_at_bottom_left() { let node = Node::unrestricted(*MAP_WIDTH_RANGE.start(), *MAP_HEIGHT_RANGE.start()); assert_eq!(0, node.as_index()); } #[test] fn as_index_at_top_right() { let node = Node::unrestricted(*MAP_WIDTH_RANGE.end(), *MAP_HEIGHT_RANGE.end()); assert_eq!((MAP_WIDTH * MAP_HEIGHT) - 1, node.as_index()); } #[test] fn trait_display() { let node = Node::unrestricted(1, 2); assert_eq!("Node { x: 1, y: 2 }", &node.to_string()); } #[test] fn trait_from_0_point() { let point = point!(x: 0, y: 0); let node = Node::from(&point); assert_eq!(0, node.longitude); assert_eq!(0, node.latitude); } #[test] fn trait_from_point_smaller_than_node_size() { let point = point!(x: TILE_SIZE / 2, y: TILE_SIZE / 2); let node = Node::from(&point); assert_eq!(0, node.longitude); assert_eq!(0, node.latitude); } #[test] fn trait_from_point_greater_than_node_size() { let point = point!(x: TILE_SIZE * 2, y: TILE_SIZE * 3); let node = Node::from(&point); assert_eq!(2, node.longitude); assert_eq!(3, node.latitude); } #[test] fn trait_from_negative_point() { let point = point!(x: TILE_SIZE * -2, y: TILE_SIZE * -3); let node = Node::from(&point); assert_eq!(-2, node.longitude); assert_eq!(-3, node.latitude); } #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<Node>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Node>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/map/mod.rs
game/src/map/mod.rs
use std::ops::RangeInclusive; use bevy::prelude::Resource; use auto_traffic_control::v1::Map as ApiMap; use crate::api::AsApi; use crate::components::Tag; use crate::{SCREEN_HEIGHT, SCREEN_WIDTH, TILE_SIZE}; pub use self::airport::*; pub use self::direction::*; pub use self::node::Node; mod airport; mod direction; mod node; // TODO: Refactor constants below to ensure width and range always line up /// The number of tiles that are left empty around the border of the window const BORDER_SIZE: usize = 1; /// The height of the map in tiles pub const MAP_HEIGHT: usize = (SCREEN_HEIGHT as i32 / TILE_SIZE) as usize - (BORDER_SIZE * 2) - 1; pub const MAP_HEIGHT_RANGE: RangeInclusive<i32> = -(MAP_HEIGHT as i32 / 2)..=(MAP_HEIGHT as i32 / 2); /// The width of the map in tiles pub const MAP_WIDTH: usize = ((SCREEN_WIDTH as i32 + TILE_SIZE) / TILE_SIZE) as usize - (BORDER_SIZE * 2) - 1; pub const MAP_WIDTH_RANGE: RangeInclusive<i32> = -(MAP_WIDTH as i32 / 2)..=(MAP_WIDTH as i32 / 2); #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Resource)] pub struct Map { airports: Vec<Airport>, routing_grid: Vec<Node>, } impl Map { pub fn new() -> Self { Self::default() } pub fn airports(&self) -> &[Airport] { &self.airports } pub fn routing_grid(&self) -> &Vec<Node> { &self.routing_grid } } impl Default for Map { fn default() -> Self { let airports = vec![ Airport::new(Node::unrestricted(-2, -2), Direction::West, Tag::Red), Airport::new(Node::unrestricted(1, 4), Direction::South, Tag::Blue), ]; let routing_grid = generate_routing_grid(&airports); Self { airports, routing_grid, } } } impl AsApi for Map { type ApiType = ApiMap; fn as_api(&self) -> Self::ApiType { ApiMap { airports: self .airports .iter() .map(|airport| airport.as_api()) .collect(), routing_grid: self.routing_grid.iter().map(|node| node.as_api()).collect(), width: MAP_WIDTH as u32, height: MAP_HEIGHT as u32, } } } fn generate_routing_grid(airports: &[Airport]) -> Vec<Node> { let mut nodes = Vec::with_capacity(MAP_WIDTH * MAP_HEIGHT); for y in MAP_HEIGHT_RANGE { for x in MAP_WIDTH_RANGE { nodes.push(Node::unrestricted(x, y)); } } for airport in airports { let airport_node = airport.node(); for neighbor in airport_node.neighbors() { let direction_to_airport = Direction::between(&neighbor.as_point(), &airport_node.as_point()); if direction_to_airport != airport.runway() { *nodes.get_mut(neighbor.as_index()).unwrap() = Node::restricted(neighbor.longitude(), neighbor.latitude()); } } } nodes } #[cfg(test)] mod tests { use crate::map::{Node, MAP_HEIGHT, MAP_WIDTH}; use super::Map; #[test] fn generate_routing_grid_removes_neighbors() { let map = Map::default(); let airport = map.airports().get(0).unwrap().node(); let neighbors = vec![ Node::restricted(airport.longitude(), airport.latitude() + 1), Node::restricted(airport.longitude() + 1, airport.latitude() + 1), Node::restricted(airport.longitude() + 1, airport.latitude()), Node::restricted(airport.longitude() + 1, airport.latitude() - 1), Node::restricted(airport.longitude(), airport.latitude() - 1), Node::restricted(airport.longitude() - 1, airport.latitude() - 1), // Runway to the west Node::unrestricted(airport.longitude() - 1, airport.latitude()), Node::restricted(airport.longitude() - 1, airport.latitude() + 1), ]; neighbors .iter() .for_each(|node| assert!(map.routing_grid().contains(node))); assert_eq!(MAP_WIDTH * MAP_HEIGHT, map.routing_grid().len()); } #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<Map>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Map>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/map/airport.rs
game/src/map/airport.rs
use auto_traffic_control::v1::Airport as ApiAirport; use crate::api::AsApi; use crate::components::Tag; use crate::map::{Direction, Node}; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub struct Airport { node: Node, runway: Direction, tag: Tag, } impl Airport { pub fn new(node: Node, runway: Direction, tag: Tag) -> Self { Self { node, runway, tag } } pub fn node(&self) -> &Node { &self.node } pub fn runway(&self) -> Direction { self.runway } #[allow(dead_code)] // TODO: Remove when tags are introduced to flight plans pub fn tag(&self) -> Tag { self.tag } } impl AsApi for Airport { type ApiType = ApiAirport; fn as_api(&self) -> Self::ApiType { ApiAirport { node: Some(self.node.as_api()), tag: self.tag.as_api().into(), } } } #[cfg(test)] mod tests { use super::Airport; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<Airport>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Airport>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/map/direction.rs
game/src/map/direction.rs
use std::fmt::Debug; use bevy::prelude::Vec3; use geo::Point; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub enum Direction { North, NorthEast, East, SouthEast, South, SouthWest, West, NorthWest, } impl Direction { pub fn between(a: &Point<f32>, b: &Point<f32>) -> Self { let x = a.x() - b.x(); let y = a.y() - b.y(); if x == 0.0 { if y <= 0.0 { return Direction::South; } if y > 0.0 { return Direction::North; } } if x < 0.0 { if y == 0.0 { return Direction::West; } if y < 0.0 { return Direction::SouthWest; } if y > 0.0 { return Direction::NorthWest; } } if x > 0.0 { if y == 0.0 { return Direction::East; } if y < 0.0 { return Direction::SouthEast; } if y > 0.0 { return Direction::NorthEast; } } panic!("failed to determine direction"); } pub fn to_degree(self) -> f32 { match self { Direction::North => 90.0, Direction::NorthEast => 45.0, Direction::East => 0.0, Direction::SouthEast => 315.0, Direction::South => 270.0, Direction::SouthWest => 225.0, Direction::West => 180.0, Direction::NorthWest => 135.0, } } pub fn to_vec3(self) -> Vec3 { match self { Direction::North => Vec3::new(0.0, 1.0, 0.0), Direction::NorthEast => Vec3::new(1.0, 1.0, 0.0), Direction::East => Vec3::new(1.0, 0.0, 0.0), Direction::SouthEast => Vec3::new(1.0, -1.0, 0.0), Direction::South => Vec3::new(0.0, -1.0, 0.0), Direction::SouthWest => Vec3::new(-1.0, -1.0, 0.0), Direction::West => Vec3::new(-1.0, 0.0, 0.0), Direction::NorthWest => Vec3::new(-1.0, 1.0, 0.0), } } } #[cfg(test)] mod tests { use super::Direction; #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<Direction>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Direction>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/resources/mod.rs
game/src/resources/mod.rs
pub use self::score::Score; mod score;
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/game/src/resources/score.rs
game/src/resources/score.rs
use bevy::prelude::*; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Resource)] pub struct Score(u32); impl Score { pub fn new() -> Self { Self::default() } pub fn get(&self) -> u32 { self.0 } pub fn increment(&mut self) { self.0 += 1; } } #[cfg(test)] mod tests { use super::Score; #[test] fn get() { let score = Score::new(); assert_eq!(0, score.get()); } #[test] fn increment() { let mut score = Score::new(); score.increment(); assert_eq!(1, score.get()); } #[test] fn trait_send() { fn assert_send<T: Send>() {} assert_send::<Score>(); } #[test] fn trait_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Score>(); } }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/sdk/rust/build.rs
sdk/rust/build.rs
use std::path::PathBuf; use glob::glob; fn main() -> Result<(), Box<dyn std::error::Error>> { println!("cargo:rerun-if-changed=api"); let proto_path = PathBuf::from("api"); let protocol_buffers: Vec<PathBuf> = glob("api/**/*.proto") .unwrap() .map(|path| path.unwrap()) .collect(); let build_server = std::env::var("CARGO_FEATURE_SERVER").is_ok(); tonic_build::configure() .build_server(build_server) .compile(&protocol_buffers, &[proto_path.to_str().unwrap()])?; Ok(()) }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
jdno/auto-traffic-control
https://github.com/jdno/auto-traffic-control/blob/b5972dfbfedf8419727adc116bf77951c8cc5202/sdk/rust/src/lib.rs
sdk/rust/src/lib.rs
// tonic does not derive `Eq` for the gRPC message types, which causes a warning from Clippy. The // current suggestion is to explicitly allow the lint in the module that imports the protos. // Read more: https://github.com/hyperium/tonic/issues/1056 #![allow(clippy::derive_partial_eq_without_eq)] pub mod v1 { tonic::include_proto!("atc.v1"); }
rust
Apache-2.0
b5972dfbfedf8419727adc116bf77951c8cc5202
2026-01-04T20:20:35.289412Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch09/linz/src/parser.rs
ch09/linz/src/parser.rs
//! # 線形型言語のパーサ //! //! λ計算に線形型システムを適用した独自の線形型言語のパーサ。 //! 独自言語の構文は以下を参照。 //! //! ## 構文 //! //! ```text //! <VAR> := 1文字以上のアルファベットから成り立つ変数 //! //! <E> := <LET> | <IF> | <SPLIT> | <FREE> | <APP> | <VAR> | <QVAL> //! //! <LET> := let <VAR> : <T> = <E>; <E> //! <IF> := if <E> { <E> } else { <E> } //! <SPLIT> := split <E> as <VAR>, <VAR> { <E> } //! <FREE> := free <E>; <E> //! <APP> := ( <E> <E> ) //! //! <Q> := lin | un //! //! 値 //! <QVAL> := <Q> <VAL> //! <VAL> := <B> | <PAIR> | <FN> //! <B> := true | false //! <PAIR> := < <E> , <E> > //! <FN> := fn <VAR> : <T> { <E> } //! //! 型 //! <T> := <Q> <P> //! <P> := bool | //! ( <T> * <T> ) //! ( <T> -> <T> ) //! ``` use nom::{ branch::alt, bytes::complete::tag, character::complete::{alpha1, char, multispace0, multispace1}, error::VerboseError, sequence::delimited, IResult, }; use std::fmt; /// 抽象構文木 /// /// ```text /// <E> := <LET> | <IF> | <SPLIT> | <FREE> | <APP> | <VAR> | <QVAL> /// ``` #[derive(Debug)] pub enum Expr { Let(LetExpr), // let式 If(IfExpr), // if式 Split(SplitExpr), // split式 Free(FreeExpr), // free文 App(AppExpr), // 関数適用 Var(String), // 変数 QVal(QValExpr), // 値 } /// 関数適用 /// /// ```text /// <APP> := ( <E> <E> ) /// /// (expr1 expr2) /// ``` #[derive(Debug)] pub struct AppExpr { pub expr1: Box<Expr>, pub expr2: Box<Expr>, } /// if式 /// /// ```text /// <IF> := if <E> { <E> } else { <E> } /// /// if cond_expr { /// then_expr /// } else { /// else_expr /// } /// ``` #[derive(Debug)] pub struct IfExpr { pub cond_expr: Box<Expr>, pub then_expr: Box<Expr>, pub else_expr: Box<Expr>, } /// split式 /// /// ```text /// <SPLIT> := split <E> as <VAR>, <VAR> { <E> } /// /// split expr as left, right { /// body /// } /// ``` #[derive(Debug)] pub struct SplitExpr { pub expr: Box<Expr>, pub left: String, pub right: String, pub body: Box<Expr>, } /// let式 /// /// ```text /// <LET> := let <VAR> : <T> = <E> { <E> } /// /// let var : ty = expr1 { expr2 } /// ``` #[derive(Debug)] pub struct LetExpr { pub var: String, pub ty: TypeExpr, pub expr1: Box<Expr>, pub expr2: Box<Expr>, } /// 値。真偽値、関数、ペア値などになる /// /// ```text /// <VAL> := <B> | <PAIR> | <FN> /// <B> := true | false /// <PAIR> := < <E> , <E> > /// <FN> := fn <VAR> : <T> { <E> } /// ``` #[derive(Debug)] pub enum ValExpr { Bool(bool), // 真偽値リテラル Pair(Box<Expr>, Box<Expr>), // ペア Fun(FnExpr), // 関数(λ抽象) } /// 修飾子 /// /// ```text /// <Q> := lin | un /// ``` #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum Qual { Lin, // 線形型 Un, // 制約のない一般的な型 } /// 修飾子付き値 /// /// ``` /// <QV> := <Q> <VAL> /// ``` #[derive(Debug)] pub struct QValExpr { pub qual: Qual, pub val: ValExpr, } /// 関数 /// /// ```text /// <FN> := fn <VAR> : <T> { <E> } /// /// fn var : ty { expr } /// ``` #[derive(Debug)] pub struct FnExpr { pub var: String, pub ty: TypeExpr, pub expr: Box<Expr>, } /// free文 /// /// ```text /// <FREE> := free <E>; <E> /// /// free var; expr /// ``` #[derive(Debug)] pub struct FreeExpr { pub var: String, pub expr: Box<Expr>, } /// 修飾子付き型 /// /// ```text /// <QV> := <Q> <VAL> /// ``` #[derive(Debug, Eq, PartialEq, Clone)] pub struct TypeExpr { pub qual: Qual, pub prim: PrimType, } impl fmt::Display for TypeExpr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.qual == Qual::Lin { write!(f, "lin {}", self.prim) } else { write!(f, "un {}", self.prim) } } } /// プリミティブ型 /// /// ```text /// <P> := bool | /// ( <T> * <T> ) /// ( <T> -> <T> ) /// ``` #[derive(Debug, Eq, PartialEq, Clone)] pub enum PrimType { Bool, // 真偽値型 Pair(Box<TypeExpr>, Box<TypeExpr>), // ペア型 Arrow(Box<TypeExpr>, Box<TypeExpr>), // 関数型 } impl fmt::Display for PrimType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { PrimType::Bool => write!(f, "bool"), PrimType::Pair(t1, t2) => write!(f, "({t1} * {t2})"), PrimType::Arrow(t1, t2) => write!(f, "({t1} -> {t2})"), } } } pub fn parse_expr(i: &str) -> IResult<&str, Expr, VerboseError<&str>> { let (i, _) = multispace0(i)?; let (i, val) = alt((alpha1, tag("(")))(i)?; match val { "let" => parse_let(i), "if" => parse_if(i), "split" => parse_split(i), "free" => parse_free(i), "lin" => parse_qval(Qual::Lin, i), "un" => parse_qval(Qual::Un, i), "(" => parse_app(i), _ => Ok((i, Expr::Var(val.to_string()))), } } /// 関数適用をパース。 fn parse_app(i: &str) -> IResult<&str, Expr, VerboseError<&str>> { let (i, _) = multispace0(i)?; let (i, e1) = parse_expr(i)?; // 適用する関数 let (i, _) = multispace1(i)?; let (i, e2) = parse_expr(i)?; // 引数 let (i, _) = multispace0(i)?; let (i, _) = char(')')(i)?; Ok(( i, Expr::App(AppExpr { expr1: Box::new(e1), expr2: Box::new(e2), }), )) } /// free文をパース。 fn parse_free(i: &str) -> IResult<&str, Expr, VerboseError<&str>> { let (i, _) = multispace1(i)?; let (i, var) = alpha1(i)?; // 解放する変数 let (i, _) = multispace0(i)?; let (i, _) = char(';')(i)?; let (i, e) = parse_expr(i)?; // 続けて実行する式 Ok(( i, Expr::Free(FreeExpr { var: var.to_string(), expr: Box::new(e), }), )) } /// split式をパース。 fn parse_split(i: &str) -> IResult<&str, Expr, VerboseError<&str>> { let (i, _) = multispace1(i)?; let (i, e1) = parse_expr(i)?; // 分解するペア let (i, _) = multispace1(i)?; let (i, _) = tag("as")(i)?; let (i, _) = multispace1(i)?; let (i, v1) = parse_var(i)?; // 一つめの変数 let (i, _) = multispace0(i)?; let (i, _) = char(',')(i)?; let (i, _) = multispace0(i)?; let (i, v2) = parse_var(i)?; // 二つめの変数 let (i, _) = multispace0(i)?; // { <E> }というように、波括弧で囲まれた式をパース let (i, e2) = delimited( char('{'), delimited(multispace0, parse_expr, multispace0), char('}'), )(i)?; Ok(( i, Expr::Split(SplitExpr { expr: Box::new(e1), left: v1, right: v2, body: Box::new(e2), }), )) } /// if式をパース。 fn parse_if(i: &str) -> IResult<&str, Expr, VerboseError<&str>> { let (i, _) = multispace1(i)?; let (i, e1) = parse_expr(i)?; // 条件 let (i, _) = multispace0(i)?; // 条件が真の時に実行する式 let (i, e2) = delimited( char('{'), delimited(multispace0, parse_expr, multispace0), char('}'), )(i)?; let (i, _) = multispace0(i)?; let (i, _) = tag("else")(i)?; let (i, _) = multispace0(i)?; // 条件が偽の時に実行する式 let (i, e3) = delimited( char('{'), delimited(multispace0, parse_expr, multispace0), char('}'), )(i)?; Ok(( i, Expr::If(IfExpr { cond_expr: Box::new(e1), then_expr: Box::new(e2), else_expr: Box::new(e3), }), )) } /// let式をパース。 fn parse_let(i: &str) -> IResult<&str, Expr, VerboseError<&str>> { let (i, _) = multispace1(i)?; let (i, var) = parse_var(i)?; // 束縛する変数 let (i, _) = multispace0(i)?; let (i, _) = char(':')(i)?; let (i, _) = multispace0(i)?; let (i, ty) = parse_type(i)?; // 変数の型 let (i, _) = multispace0(i)?; let (i, _) = char('=')(i)?; let (i, _) = multispace0(i)?; let (i, e1) = parse_expr(i)?; // 変数の値 let (i, _) = multispace0(i)?; let (i, _) = char(';')(i)?; let (i, e2) = parse_expr(i)?; // 実行する式 Ok(( i, Expr::Let(LetExpr { var, ty, expr1: Box::new(e1), expr2: Box::new(e2), }), )) } /// ペアをパース。 fn parse_pair(i: &str) -> IResult<&str, ValExpr, VerboseError<&str>> { let (i, _) = multispace0(i)?; let (i, v1) = parse_expr(i)?; // 一つめの値 let (i, _) = multispace0(i)?; let (i, _) = char(',')(i)?; let (i, _) = multispace0(i)?; let (i, v2) = parse_expr(i)?; // 二つめの値 let (i, _) = multispace0(i)?; let (i, _) = char('>')(i)?; // 閉じ括弧 Ok((i, ValExpr::Pair(Box::new(v1), Box::new(v2)))) } /// linとun修飾子をパース。 fn parse_qual(i: &str) -> IResult<&str, Qual, VerboseError<&str>> { let (i, val) = alt((tag("lin"), tag("un")))(i)?; if val == "lin" { Ok((i, Qual::Lin)) } else { Ok((i, Qual::Un)) } } /// 関数をパース。 fn parse_fn(i: &str) -> IResult<&str, ValExpr, VerboseError<&str>> { let (i, _) = multispace1(i)?; let (i, var) = parse_var(i)?; // 引数 let (i, _) = multispace0(i)?; let (i, _) = char(':')(i)?; let (i, _) = multispace0(i)?; let (i, ty) = parse_type(i)?; // 引数の型 let (i, _) = multispace0(i)?; // { <E> }というように、波括弧で囲まれた式をパース let (i, expr) = delimited( char('{'), delimited(multispace0, parse_expr, multispace0), char('}'), )(i)?; Ok(( i, ValExpr::Fun(FnExpr { var, ty, expr: Box::new(expr), }), )) } /// 真偽値、関数、ペアの値をパース。 fn parse_val(i: &str) -> IResult<&str, ValExpr, VerboseError<&str>> { let (i, val) = alt((tag("fn"), tag("true"), tag("false"), tag("<")))(i)?; match val { "fn" => parse_fn(i), "true" => Ok((i, ValExpr::Bool(true))), "false" => Ok((i, ValExpr::Bool(false))), "<" => parse_pair(i), _ => unreachable!(), } } /// 修飾子付き値をパース。 fn parse_qval(q: Qual, i: &str) -> IResult<&str, Expr, VerboseError<&str>> { let (i, _) = multispace1(i)?; let (i, v) = parse_val(i)?; Ok((i, Expr::QVal(QValExpr { qual: q, val: v }))) } /// 変数をパース。変数は1文字以上のアルファベットから成り立つ。 fn parse_var(i: &str) -> IResult<&str, String, VerboseError<&str>> { let (i, v) = alpha1(i)?; Ok((i, v.to_string())) } /// 真偽値、関数、ペア型をパース。 fn parse_type(i: &str) -> IResult<&str, TypeExpr, VerboseError<&str>> { let (i, q) = parse_qual(i)?; // 修飾子 let (i, _) = multispace1(i)?; let (i, val) = alt((tag("bool"), tag("(")))(i)?; if val == "bool" { // bool型 Ok(( i, TypeExpr { qual: q, prim: PrimType::Bool, }, )) } else { // 関数型かペア型 let (i, _) = multispace0(i)?; let (i, t1) = parse_type(i)?; // 一つめの型 let (i, _) = multispace0(i)?; // ->か*をパース // ->の場合は関数型で、場合はペア型 let (i, op) = alt((tag("*"), tag("->")))(i)?; let (i, _) = multispace0(i)?; let (i, t2) = parse_type(i)?; // 二つめの型 let (i, _) = multispace0(i)?; let (i, _) = char(')')(i)?; Ok(( i, TypeExpr { qual: q, prim: if op == "*" { PrimType::Pair(Box::new(t1), Box::new(t2)) } else { PrimType::Arrow(Box::new(t1), Box::new(t2)) }, }, )) } }
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch09/linz/src/helper.rs
ch09/linz/src/helper.rs
pub trait SafeAdd: Sized { fn safe_add(&self, n: &Self) -> Option<Self>; } impl SafeAdd for usize { fn safe_add(&self, n: &Self) -> Option<Self> { self.checked_add(*n) } } pub fn safe_add<T, F, E>(dst: &mut T, src: &T, f: F) -> Result<(), E> where T: SafeAdd, F: Fn() -> E, { if let Some(n) = dst.safe_add(src) { *dst = n; Ok(()) } else { Err(f()) } }
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch09/linz/src/typing.rs
ch09/linz/src/typing.rs
use crate::{helper::safe_add, parser}; use std::{borrow::Cow, cmp::Ordering, collections::BTreeMap, mem}; type VarToType = BTreeMap<String, Option<parser::TypeExpr>>; /// 型環境 #[derive(Debug, Clone, Eq, PartialEq)] pub struct TypeEnv { env_lin: TypeEnvStack, // lin用 env_un: TypeEnvStack, // un用 } impl TypeEnv { pub fn new() -> TypeEnv { TypeEnv { env_lin: TypeEnvStack::new(), env_un: TypeEnvStack::new(), } } /// 型環境をpush fn push(&mut self, depth: usize) { self.env_lin.push(depth); self.env_un.push(depth); } /// 型環境をpop fn pop(&mut self, depth: usize) -> (Option<VarToType>, Option<VarToType>) { let t1 = self.env_lin.pop(depth); let t2 = self.env_un.pop(depth); (t1, t2) } /// 型環境へ変数と型をpush fn insert(&mut self, key: String, value: parser::TypeExpr) { if value.qual == parser::Qual::Lin { self.env_lin.insert(key, value); } else { self.env_un.insert(key, value); } } /// linとunの型環境からget_mutし、depthが大きい方を返す fn get_mut(&mut self, key: &str) -> Option<&mut Option<parser::TypeExpr>> { match (self.env_lin.get_mut(key), self.env_un.get_mut(key)) { (Some((d1, t1)), Some((d2, t2))) => match d1.cmp(&d2) { Ordering::Less => Some(t2), Ordering::Greater => Some(t1), Ordering::Equal => panic!("invalid type environment"), }, (Some((_, t1)), None) => Some(t1), (None, Some((_, t2))) => Some(t2), _ => None, } } } /// 型環境のスタック #[derive(Debug, Clone, Eq, PartialEq, Default)] struct TypeEnvStack { vars: BTreeMap<usize, VarToType>, } impl TypeEnvStack { fn new() -> TypeEnvStack { TypeEnvStack { vars: BTreeMap::new(), } } // 型環境をpush fn push(&mut self, depth: usize) { self.vars.insert(depth, BTreeMap::new()); } // 型環境をpop fn pop(&mut self, depth: usize) -> Option<VarToType> { self.vars.remove(&depth) } // スタックの最も上にある型環境に変数名と型を追加 fn insert(&mut self, key: String, value: parser::TypeExpr) { if let Some(last) = self.vars.iter_mut().next_back() { last.1.insert(key, Some(value)); } } // スタックを上からたどっていき、はじめに見つかる変数の型を取得 fn get_mut(&mut self, key: &str) -> Option<(usize, &mut Option<parser::TypeExpr>)> { for (depth, elm) in self.vars.iter_mut().rev() { if let Some(e) = elm.get_mut(key) { return Some((*depth, e)); } } None } } type TResult<'a> = Result<parser::TypeExpr, Cow<'a, str>>; /// 型付け関数 /// 式を受け取り、型を返す pub fn typing<'a>(expr: &parser::Expr, env: &mut TypeEnv, depth: usize) -> TResult<'a> { match expr { parser::Expr::App(e) => typing_app(e, env, depth), parser::Expr::QVal(e) => typing_qval(e, env, depth), parser::Expr::Free(e) => typing_free(e, env, depth), parser::Expr::If(e) => typing_if(e, env, depth), parser::Expr::Split(e) => typing_split(e, env, depth), parser::Expr::Var(e) => typing_var(e, env), parser::Expr::Let(e) => typing_let(e, env, depth), } } /// 関数適用の型付け fn typing_app<'a>(expr: &parser::AppExpr, env: &mut TypeEnv, depth: usize) -> TResult<'a> { // 関数部分 let t1 = typing(&expr.expr1, env, depth)?; let t_arg; let t_ret; match t1.prim { parser::PrimType::Arrow(a, b) => { t_arg = a; // 引数の型 t_ret = b; // 返り値の型 } _ => return Err("関数型でない".into()), } // 引数部分 let t2 = typing(&expr.expr2, env, depth)?; // 引数の型が一致しているかチェック if *t_arg == t2 { Ok(*t_ret) } else { Err("関数適用時における引数の型が異なる".into()) } } /// 修飾子付き値の型付け fn typing_qval<'a>(expr: &parser::QValExpr, env: &mut TypeEnv, depth: usize) -> TResult<'a> { // プリミティブ型を計算 let p = match &expr.val { parser::ValExpr::Bool(_) => parser::PrimType::Bool, parser::ValExpr::Pair(e1, e2) => { // 式e1とe2をtypingにより型付け let t1 = typing(e1, env, depth)?; let t2 = typing(e2, env, depth)?; // expr.qualがUnであり、 // e1か、e2の型にlinが含まれていた場合、型付けエラー if expr.qual == parser::Qual::Un && (t1.qual == parser::Qual::Lin || t2.qual == parser::Qual::Lin) { return Err("un型のペア内でlin型を利用している".into()); } // ペア型を返す parser::PrimType::Pair(Box::new(t1), Box::new(t2)) } parser::ValExpr::Fun(e) => { // 関数の型付け // un型の関数内では、lin型の自由変数をキャプチャできないため // lin用の型環境を置き換え let env_prev = if expr.qual == parser::Qual::Un { Some(mem::take(&mut env.env_lin)) } else { None }; // depthをインクリメントしてpush let mut depth = depth; safe_add(&mut depth, &1, || "変数スコープのネストが深すぎる")?; env.push(depth); env.insert(e.var.clone(), e.ty.clone()); // 関数中の式を型付け let t = typing(&e.expr, env, depth)?; // スタックをpopし、popした型環境の中にlin型が含まれていた場合、型付けエラー let (elin, _) = env.pop(depth); for (k, v) in elin.unwrap().iter() { if v.is_some() { return Err(format!("関数定義内でlin型の変数\"{k}\"を消費していない").into()); } } // lin用の型環境を復元 if let Some(ep) = env_prev { env.env_lin = ep; } // 関数型を返す parser::PrimType::Arrow(Box::new(e.ty.clone()), Box::new(t)) } }; // 修飾子付き型を返す Ok(parser::TypeExpr { qual: expr.qual, prim: p, }) } /// free式の型付け fn typing_free<'a>(expr: &parser::FreeExpr, env: &mut TypeEnv, depth: usize) -> TResult<'a> { if let Some((_, t)) = env.env_lin.get_mut(&expr.var) { if t.is_some() { *t = None; return typing(&expr.expr, env, depth); } } Err(format!( "既にfreeしたか、lin型ではない変数\"{}\"をfreeしている", expr.var ) .into()) } /// if式の型付け fn typing_if<'a>(expr: &parser::IfExpr, env: &mut TypeEnv, depth: usize) -> TResult<'a> { let t1 = typing(&expr.cond_expr, env, depth)?; // 条件の式の型はbool if t1.prim != parser::PrimType::Bool { return Err("ifの条件式がboolでない".into()); } let mut e = env.clone(); let t2 = typing(&expr.then_expr, &mut e, depth)?; let t3 = typing(&expr.else_expr, env, depth)?; // thenとelse部の型は同じで、 // thenとelse部評価後の型環境は同じかをチェック if t2 != t3 || e != *env { return Err("ifのthenとelseの式の型が異なる".into()); } Ok(t2) } /// split式の型付け fn typing_split<'a>(expr: &parser::SplitExpr, env: &mut TypeEnv, depth: usize) -> TResult<'a> { if expr.left == expr.right { return Err("splitの変数名が同じ".into()); } let t1 = typing(&expr.expr, env, depth)?; let mut depth = depth; safe_add(&mut depth, &1, || "変数スコープのネストが深すぎる")?; match t1.prim { parser::PrimType::Pair(p1, p2) => { env.push(depth); // ローカル変数の型を追加 env.insert(expr.left.clone(), *p1); env.insert(expr.right.clone(), *p2); } _ => { return Err("splitの引数がペア型でない".into()); } } let ret = typing(&expr.body, env, depth); // ローカル変数を削除 let (elin, _) = env.pop(depth); // lin型の変数を消費しているかチェック for (k, v) in elin.unwrap().iter() { if v.is_some() { return Err(format!("splitの式内でlin型の変数\"{k}\"を消費していない").into()); } } ret } /// 変数の型付け fn typing_var<'a>(expr: &str, env: &mut TypeEnv) -> TResult<'a> { let ret = env.get_mut(expr); if let Some(it) = ret { // 定義されている if let Some(t) = it { // 消費されていない if t.qual == parser::Qual::Lin { // lin型 let eret = t.clone(); *it = None; // linを消費 return Ok(eret); } else { return Ok(t.clone()); } } } Err(format!( "\"{}\"という変数は定義されていないか、利用済みか、キャプチャできない", expr ) .into()) } /// let式の型付け fn typing_let<'a>(expr: &parser::LetExpr, env: &mut TypeEnv, depth: usize) -> TResult<'a> { // 変数束縛 let t1 = typing(&expr.expr1, env, depth)?; // 束縛変数の型をチェック if t1 != expr.ty { return Err(format!("変数\"{}\"の型が異なる", expr.var).into()); } // 関数内 let mut depth = depth; safe_add(&mut depth, &1, || "変数スコープのネストが深すぎる")?; env.push(depth); env.insert(expr.var.clone(), t1); // 変数の型をinsert let t2 = typing(&expr.expr2, env, depth)?; // lin型の変数を消費しているかチェック let (elin, _) = env.pop(depth); for (k, v) in elin.unwrap().iter() { if v.is_some() { return Err(format!("let式内でlin型の変数\"{k}\"を消費していない").into()); } } Ok(t2) }
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch09/linz/src/main.rs
ch09/linz/src/main.rs
mod helper; mod parser; mod typing; use nom::error::convert_error; use std::{env, error::Error, fs}; fn main() -> Result<(), Box<dyn Error>> { // コマンドライン引数の検査 let args: Vec<String> = env::args().collect(); if args.len() < 2 { eprintln!("以下のようにファイル名を指定して実行してください\ncargo run codes/ex1.lin"); return Err("引数が不足".into()); } // ファイル読み込み let content = fs::read_to_string(&args[1])?; let ast = parser::parse_expr(&content); // パース println!("AST:\n{:#?}\n", ast); match ast { Ok((_, expr)) => { let mut ctx = typing::TypeEnv::new(); println!("式:\n{content}"); // 型付け let a = typing::typing(&expr, &mut ctx, 0)?; println!("の型は\n{a}\nです。"); } Err(nom::Err::Error(e)) => { let msg = convert_error(content.as_str(), e); eprintln!("パースエラー:\n{msg}"); return Err(msg.into()); } _ => (), } Ok(()) }
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch09/parser/src/main.rs
ch09/parser/src/main.rs
//! # 逆ポーランド記法計算機 //! //! パーサコンビネータのnomの説明のコード。 //! //! 以下のようなBNFをパースし、実行する。 //! //! ```text //! <EXPR> := <NUM> | <ADD> <EXPR> <EXPR | <MUL> <EXPR> <EXPR> //! ``` use nom::{ branch::alt, character::complete::{char, one_of}, error::ErrorKind, multi::{many0, many1}, IResult, }; use rustyline::Editor; #[derive(Debug)] enum Expr { Num(u64), // 数値 Add(Box<Expr>, Box<Expr>), // 加算 Mul(Box<Expr>, Box<Expr>), // 乗算 } fn main() { let mut rl = Editor::<()>::new().unwrap(); loop { // 1行読み込んでパースし成功すれば評価 if let Ok(readline) = rl.readline(">> ") { if let Some(e) = parse(&readline) { println!("result: {}", eval(&e)); } } else { break; } } } fn parse(c: &str) -> Option<Expr> { match parse_expr(c) { Ok((_, e)) => { println!("AST: {:?}", e); Some(e) } Err(e) => { println!("{e}"); None } } } fn parse_expr(c: &str) -> IResult<&str, Expr> { // 0個以上のホワイトスペースをスキップ let (c, _) = many0(char(' '))(c)?; // parse_numかparse_opをパース let result = alt((parse_num, parse_op))(c)?; Ok(result) } fn parse_num(c: &str) -> IResult<&str, Expr> { // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9のいずれかが、1個以上 // 正規表現で[0..9]+ let (c1, v) = many1(one_of("0123456789"))(c)?; let var: String = v.into_iter().collect(); // Vec<char>をStringに変換 // Stringをu64に変換 if let Ok(n) = var.parse::<u64>() { Ok((c1, Expr::Num(n))) // Numを返す } else { let err = nom::error::Error::new(c, ErrorKind::Fail); Err(nom::Err::Failure(err)) } } fn parse_op(c: &str) -> IResult<&str, Expr> { // +か*のどちらか let (c, op) = one_of("+*")(c)?; let (c, e1) = parse_expr(c)?; // 一つめの式をパース let (c, e2) = parse_expr(c)?; // 二つめの式をパース if op == '+' { Ok((c, Expr::Add(Box::new(e1), Box::new(e2)))) // Addを返す } else { Ok((c, Expr::Mul(Box::new(e1), Box::new(e2)))) // Mulを返す } } fn eval(e: &Expr) -> u64 { match e { Expr::Num(n) => *n, Expr::Add(e1, e2) => eval(e1) + eval(e2), Expr::Mul(e1, e2) => eval(e1) * eval(e2), } }
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch07/zrsh/src/shell.rs
ch07/zrsh/src/shell.rs
use crate::helper::DynError; use nix::{ libc, sys::{ signal::{killpg, signal, SigHandler, Signal}, wait::{waitpid, WaitPidFlag, WaitStatus}, }, unistd::{self, dup2, execvp, fork, pipe, setpgid, tcgetpgrp, tcsetpgrp, ForkResult, Pid}, }; use rustyline::{error::ReadlineError, Editor}; use signal_hook::{consts::*, iterator::Signals}; use std::{ collections::{BTreeMap, HashMap, HashSet}, ffi::CString, mem::replace, path::PathBuf, process::exit, sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender}, thread, }; /// ドロップ時にクロージャfを呼び出す型 struct CleanUp<F> where F: Fn(), { f: F, } impl<F> Drop for CleanUp<F> where F: Fn(), { fn drop(&mut self) { (self.f)() } } /// workerスレッドが受信するメッセージ enum WorkerMsg { Signal(i32), // シグナルを受信 Cmd(String), // コマンド入力 } /// mainスレッドが受信するメッセージ enum ShellMsg { Continue(i32), // シェルの読み込みを再開。i32は最後の終了コード Quit(i32), // シェルを終了。i32はシェルの終了コード } #[derive(Debug)] pub struct Shell { logfile: String, // ログファイル } impl Shell { pub fn new(logfile: &str) -> Self { Shell { logfile: logfile.to_string(), } } /// mainスレッド pub fn run(&self) -> Result<(), DynError> { // SIGTTOUを無視に設定しないと、SIGTSTPが配送される unsafe { signal(Signal::SIGTTOU, SigHandler::SigIgn).unwrap() }; let mut rl = Editor::<()>::new()?; if let Err(e) = rl.load_history(&self.logfile) { eprintln!("ZeroSh: ヒストリファイルの読み込みに失敗: {e}"); } // チャネルを生成し、signal_handlerとworkerスレッドを生成 let (worker_tx, worker_rx) = channel(); let (shell_tx, shell_rx) = sync_channel(0); spawn_sig_handler(worker_tx.clone())?; Worker::new().spawn(worker_rx, shell_tx); let exit_val; // 終了コード let mut prev = 0; // 直前の終了コード loop { // 1行読み込んで、その行をworkerに送信 let face = if prev == 0 { '\u{1F642}' } else { '\u{1F480}' }; match rl.readline(&format!("ZeroSh {face} %> ")) { Ok(line) => { let line_trimed = line.trim(); // 前後の空白文字を削除 if line_trimed.is_empty() { continue; // 空のコマンドの場合は再読み込み } else { rl.add_history_entry(line_trimed); // ヒストリファイルに追加 } worker_tx.send(WorkerMsg::Cmd(line)).unwrap(); // workerに送信 match shell_rx.recv().unwrap() { ShellMsg::Continue(n) => prev = n, // 読み込み再開 ShellMsg::Quit(n) => { // シェルを終了 exit_val = n; break; } } } Err(ReadlineError::Interrupted) => eprintln!("ZeroSh: 終了はCtrl+D"), Err(ReadlineError::Eof) => { worker_tx.send(WorkerMsg::Cmd("exit".to_string())).unwrap(); match shell_rx.recv().unwrap() { ShellMsg::Quit(n) => { // シェルを終了 exit_val = n; break; } _ => panic!("exitに失敗"), } } Err(e) => { eprintln!("ZeroSh: 読み込みエラー\n{e}"); exit_val = 1; break; } } } if let Err(e) = rl.save_history(&self.logfile) { eprintln!("ZeroSh: ヒストリファイルの書き込みに失敗: {e}"); } exit(exit_val); } } /// signal_handlerスレッド fn spawn_sig_handler(tx: Sender<WorkerMsg>) -> Result<(), DynError> { let mut signals = Signals::new(&[SIGINT, SIGTSTP, SIGCHLD])?; thread::spawn(move || { for sig in signals.forever() { // シグナルを受信しworkerスレッドに送信 tx.send(WorkerMsg::Signal(sig)).unwrap(); } }); Ok(()) } #[derive(Debug, PartialEq, Eq, Clone)] enum ProcState { Run, // 実行中 Stop, // 停止中 } #[derive(Debug, Clone)] struct ProcInfo { state: ProcState, // 実行状態 pgid: Pid, // プロセスグループID } #[derive(Debug)] struct Worker { exit_val: i32, // 終了コード fg: Option<Pid>, // フォアグラウンドのプロセスグループID // ジョブIDから(プロセスグループID, 実行コマンド)へのマップ jobs: BTreeMap<usize, (Pid, String)>, // プロセスグループIDから(ジョブID, プロセスID)へのマップ pgid_to_pids: HashMap<Pid, (usize, HashSet<Pid>)>, pid_to_info: HashMap<Pid, ProcInfo>, // プロセスIDからプロセスグループIDへのマップ shell_pgid: Pid, // シェルのプロセスグループID } impl Worker { fn new() -> Self { Worker { exit_val: 0, fg: None, // フォアグラウンドはシェル jobs: BTreeMap::new(), pgid_to_pids: HashMap::new(), pid_to_info: HashMap::new(), // シェルのプロセスグループIDを取得 shell_pgid: tcgetpgrp(libc::STDIN_FILENO).unwrap(), } } /// workerスレッドを起動 fn spawn(mut self, worker_rx: Receiver<WorkerMsg>, shell_tx: SyncSender<ShellMsg>) { thread::spawn(move || { for msg in worker_rx.iter() { match msg { WorkerMsg::Cmd(line) => { match parse_cmd(&line) { Ok(cmd) => { if self.built_in_cmd(&cmd, &shell_tx) { // 組み込みコマンドならworker_rxから受信 continue; } if !self.spawn_child(&line, &cmd) { // 子プロセス生成に失敗した場合シェルからの入力を再開 shell_tx.send(ShellMsg::Continue(self.exit_val)).unwrap(); } } Err(e) => { eprintln!("ZeroSh: {e}"); shell_tx.send(ShellMsg::Continue(self.exit_val)).unwrap(); } } } WorkerMsg::Signal(SIGCHLD) => { self.wait_child(&shell_tx); // 子プロセスの状態変化管理 } _ => (), // 無視 } } }); } /// 子プロセスの状態変化を管理 fn wait_child(&mut self, shell_tx: &SyncSender<ShellMsg>) { // WUNTRACED: 子プロセスの停止 // WNOHANG: ブロックしない // WCONTINUED: 実行再開時 let flag = Some(WaitPidFlag::WUNTRACED | WaitPidFlag::WNOHANG | WaitPidFlag::WCONTINUED); loop { match syscall(|| waitpid(Pid::from_raw(-1), flag)) { Ok(WaitStatus::Exited(pid, status)) => { // プロセスが終了 self.exit_val = status; // 終了コードを保存 self.process_term(pid, shell_tx); } Ok(WaitStatus::Signaled(pid, sig, core)) => { // プロセスがシグナルにより終了 eprintln!( "\nZeroSh: 子プロセスがシグナルにより終了{}: pid = {pid}, signal = {sig}", if core { "(コアダンプ)" } else { "" } ); self.exit_val = sig as i32 + 128; // 終了コードを保存 self.process_term(pid, shell_tx); } // プロセスが停止 Ok(WaitStatus::Stopped(pid, _sig)) => self.process_stop(pid, shell_tx), // プロセスが実行再開 Ok(WaitStatus::Continued(pid)) => self.process_continue(pid), Ok(WaitStatus::StillAlive) => return, // waitすべき子プロセスはいない Err(nix::Error::ECHILD) => return, // 子プロセスはいない Err(e) => { eprintln!("\nZeroSh: waitが失敗: {e}"); exit(1); } #[cfg(any(target_os = "linux", target_os = "android"))] Ok(WaitStatus::PtraceEvent(pid, _, _) | WaitStatus::PtraceSyscall(pid)) => { self.process_stop(pid, shell_tx) } } } } /// プロセスの再開処理 fn process_continue(&mut self, pid: Pid) { self.set_pid_state(pid, ProcState::Run); } /// プロセスの停止処理 fn process_stop(&mut self, pid: Pid, shell_tx: &SyncSender<ShellMsg>) { self.set_pid_state(pid, ProcState::Stop); // プロセスを停止中に設定 let pgid = self.pid_to_info.get(&pid).unwrap().pgid; // プロセスグループIDを取得 let job_id = self.pgid_to_pids.get(&pgid).unwrap().0; // ジョブIDを取得 self.manage_job(job_id, pgid, shell_tx); // 必要ならフォアグラウンドプロセスをシェルに設定 } /// プロセスの終了処理 fn process_term(&mut self, pid: Pid, shell_tx: &SyncSender<ShellMsg>) { // プロセスの情報を削除し、必要ならフォアグラウンドプロセスをシェルに設定 if let Some((job_id, pgid)) = self.remove_pid(pid) { self.manage_job(job_id, pgid, shell_tx); } } /// プロセスの実行状態を設定し、以前の状態を返す。 /// pidが存在しないプロセスの場合はNoneを返す。 fn set_pid_state(&mut self, pid: Pid, state: ProcState) -> Option<ProcState> { let info = self.pid_to_info.get_mut(&pid)?; Some(replace(&mut info.state, state)) } /// プロセスの情報を削除し、削除できた場合プロセスの所属する。 /// (ジョブID, プロセスグループID)を返す。 /// 存在しないプロセスの場合はNoneを返す。 fn remove_pid(&mut self, pid: Pid) -> Option<(usize, Pid)> { let pgid = self.pid_to_info.get(&pid)?.pgid; // プロセスグループIDを取得 let it = self.pgid_to_pids.get_mut(&pgid)?; it.1.remove(&pid); // プロセスグループからpidを削除 let job_id = it.0; // ジョブIDを取得 Some((job_id, pgid)) } /// ジョブ情報を削除し、関連するプロセスグループの情報も削除 fn remove_job(&mut self, job_id: usize) { if let Some((pgid, _)) = self.jobs.remove(&job_id) { if let Some((_, pids)) = self.pgid_to_pids.remove(&pgid) { assert!(pids.is_empty()); // ジョブを削除するときはプロセスグループは空のはず } } } /// 空のプロセスグループなら真 fn is_group_empty(&self, pgid: Pid) -> bool { self.pgid_to_pids.get(&pgid).unwrap().1.is_empty() } /// プロセスグループのプロセスすべてが停止中なら真 fn is_group_stop(&self, pgid: Pid) -> Option<bool> { for pid in self.pgid_to_pids.get(&pgid)?.1.iter() { if self.pid_to_info.get(pid).unwrap().state == ProcState::Run { return Some(false); } } Some(true) } /// 新たなジョブIDを取得 fn get_new_job_id(&self) -> Option<usize> { for i in 0..=usize::MAX { if !self.jobs.contains_key(&i) { return Some(i); } } None } /// 新たなジョブ情報を追加 /// /// - job_id: ジョブID /// - pgid: プロセスグループID /// - pids: プロセス fn insert_job(&mut self, job_id: usize, pgid: Pid, pids: HashMap<Pid, ProcInfo>, line: &str) { assert!(!self.jobs.contains_key(&job_id)); self.jobs.insert(job_id, (pgid, line.to_string())); // ジョブ情報を追加 let mut procs = HashSet::new(); // pgid_to_pidsへ追加するプロセス for (pid, info) in pids { procs.insert(pid); assert!(!self.pid_to_info.contains_key(&pid)); self.pid_to_info.insert(pid, info); // プロセスの情報を追加 } assert!(!self.pgid_to_pids.contains_key(&pgid)); self.pgid_to_pids.insert(pgid, (job_id, procs)); // プロセスグループの情報を追加 } /// シェルをフォアグラウンドに設定 fn set_shell_fg(&mut self, shell_tx: &SyncSender<ShellMsg>) { self.fg = None; tcsetpgrp(libc::STDIN_FILENO, self.shell_pgid).unwrap(); shell_tx.send(ShellMsg::Continue(self.exit_val)).unwrap(); } /// ジョブの管理。引数には変化のあったジョブとプロセスグループを指定 /// /// - フォアグラウンドプロセスが空の場合、シェルをフォアグラウンドに設定 /// - フォアグラウンドプロセスがすべて停止中の場合、シェルをフォアグラウンドに設定 fn manage_job(&mut self, job_id: usize, pgid: Pid, shell_tx: &SyncSender<ShellMsg>) { let is_fg = self.fg.map_or(false, |x| pgid == x); // フォアグラウンドのプロセスか? let line = &self.jobs.get(&job_id).unwrap().1; if is_fg { // 状態が変化したプロセスはフォアグラウンド if self.is_group_empty(pgid) { // フォアグラウンドプロセスが空の場合、 // ジョブ情報を削除しシェルをフォアグラウンドに設定 eprintln!("[{job_id}] 終了\t{line}"); self.remove_job(job_id); self.set_shell_fg(shell_tx); } else if self.is_group_stop(pgid).unwrap() { // フォアグラウンドプロセスがすべて停止中の場合、シェルをフォアグラウンドに設定 eprintln!("\n[{job_id}] 停止\t{line}"); self.set_shell_fg(shell_tx); } } else { // プロセスグループが空の場合、ジョブ情報を削除 if self.is_group_empty(pgid) { eprintln!("\n[{job_id}] 終了\t{line}"); self.remove_job(job_id); } } } /// 子プロセスを生成。失敗した場合はシェルからの入力を再開させる必要あり fn spawn_child(&mut self, line: &str, cmd: &[(&str, Vec<&str>)]) -> bool { assert_ne!(cmd.len(), 0); // コマンドが空でないか検査 // ジョブIDを取得 let job_id = if let Some(id) = self.get_new_job_id() { id } else { eprintln!("ZeroSh: 管理可能なジョブの最大値に到達"); return false; }; if cmd.len() > 2 { eprintln!("ZeroSh: 三つ以上のコマンドによるパイプはサポートしていません"); return false; } let mut input = None; // 二つめのプロセスの標準入力 let mut output = None; // 一つめのプロセスの標準出力 if cmd.len() == 2 { // パイプを作成 let p = pipe().unwrap(); input = Some(p.0); output = Some(p.1); } // パイプを閉じる関数を定義 let cleanup_pipe = CleanUp { f: || { if let Some(fd) = input { syscall(|| unistd::close(fd)).unwrap(); } if let Some(fd) = output { syscall(|| unistd::close(fd)).unwrap(); } }, }; let pgid; // 一つめのプロセスを生成 match fork_exec(Pid::from_raw(0), cmd[0].0, &cmd[0].1, None, output, input) { Ok(child) => { pgid = child; } Err(e) => { eprintln!("ZeroSh: プロセス生成エラー: {e}"); return false; } } // プロセス、ジョブの情報を追加 let info = ProcInfo { state: ProcState::Run, pgid, }; let mut pids = HashMap::new(); pids.insert(pgid, info.clone()); // 一つめのプロセスの情報 // 二つめのプロセスを生成 if cmd.len() == 2 { match fork_exec(pgid, cmd[1].0, &cmd[1].1, input, None, output) { Ok(child) => { pids.insert(child, info); } Err(e) => { eprintln!("ZeroSh: プロセス生成エラー: {e}"); return false; } } } std::mem::drop(cleanup_pipe); // パイプをクローズ // ジョブ情報を追加し、子プロセスをフォアグラウンドに self.fg = Some(pgid); self.insert_job(job_id, pgid, pids, line); tcsetpgrp(libc::STDIN_FILENO, pgid).unwrap(); true } /// 組み込みコマンドの場合はtrueを返す fn built_in_cmd(&mut self, cmd: &[(&str, Vec<&str>)], shell_tx: &SyncSender<ShellMsg>) -> bool { if cmd.len() > 1 { return false; // 組み込みコマンドのパイプは非対応なのでエラー } match cmd[0].0 { "exit" => self.run_exit(&cmd[0].1, shell_tx), "jobs" => self.run_jobs(shell_tx), "fg" => self.run_fg(&cmd[0].1, shell_tx), "cd" => self.run_cd(&cmd[0].1, shell_tx), _ => false, } } /// カレントディレクトリを変更。引数がない場合は、ホームディレクトリに移動。第2引数以降は無視 fn run_cd(&mut self, args: &[&str], shell_tx: &SyncSender<ShellMsg>) -> bool { let path = if args.len() == 1 { // 引数が指定されていない場合、ホームディレクトリか/へ移動 dirs::home_dir() .or_else(|| Some(PathBuf::from("/"))) .unwrap() } else { PathBuf::from(args[1]) }; // カレントディレクトリを変更 if let Err(e) = std::env::set_current_dir(&path) { self.exit_val = 1; // 失敗 eprintln!("cdに失敗: {e}"); } else { self.exit_val = 0; // 成功 } shell_tx.send(ShellMsg::Continue(self.exit_val)).unwrap(); true } /// exitコマンドを実行 /// /// 第1引数が指定された場合、それを終了コードとしてシェルを終了。 /// 引数がない場合は、最後に終了したプロセスの終了コードとしてシェルを終了。 fn run_exit(&mut self, args: &[&str], shell_tx: &SyncSender<ShellMsg>) -> bool { // 実行中のジョブがある場合は終了しない if !self.jobs.is_empty() { eprintln!("ジョブが実行中なので終了できません"); self.exit_val = 1; // 失敗 shell_tx.send(ShellMsg::Continue(self.exit_val)).unwrap(); // シェルを再開 return true; } // 終了コードを取得 let exit_val = if let Some(s) = args.get(1) { if let Ok(n) = (*s).parse::<i32>() { n } else { // 終了コードか整数ではない eprintln!("{s}は不正な引数です"); self.exit_val = 1; // 失敗 shell_tx.send(ShellMsg::Continue(self.exit_val)).unwrap(); // シェルを再開 return true; } } else { self.exit_val }; shell_tx.send(ShellMsg::Quit(exit_val)).unwrap(); // シェルを終了 true } /// jobsコマンドを実行 fn run_jobs(&mut self, shell_tx: &SyncSender<ShellMsg>) -> bool { for (job_id, (pgid, cmd)) in &self.jobs { let state = if self.is_group_stop(*pgid).unwrap() { "停止中" } else { "実行中" }; println!("[{job_id}] {state}\t{cmd}") } self.exit_val = 0; // 成功 shell_tx.send(ShellMsg::Continue(self.exit_val)).unwrap(); // シェルを再開 true } /// fgコマンドを実行 fn run_fg(&mut self, args: &[&str], shell_tx: &SyncSender<ShellMsg>) -> bool { self.exit_val = 1; // とりあえず失敗に設定 // 引数をチェック if args.len() < 2 { eprintln!("usage: fg 数字"); shell_tx.send(ShellMsg::Continue(self.exit_val)).unwrap(); // シェルを再開 return true; } // ジョブIDを取得 if let Ok(n) = args[1].parse::<usize>() { if let Some((pgid, cmd)) = self.jobs.get(&n) { eprintln!("[{n}] 再開\t{cmd}"); // フォアグラウンドプロセスに設定 self.fg = Some(*pgid); tcsetpgrp(libc::STDIN_FILENO, *pgid).unwrap(); // ジョブの実行を再開 killpg(*pgid, Signal::SIGCONT).unwrap(); return true; } } // 失敗 eprintln!("{}というジョブは見つかりませんでした", args[1]); shell_tx.send(ShellMsg::Continue(self.exit_val)).unwrap(); // シェルを再開 true } } /// システムコール呼び出しのラッパ。EINTRならリトライ fn syscall<F, T>(f: F) -> Result<T, nix::Error> where F: Fn() -> Result<T, nix::Error>, { loop { match f() { Err(nix::Error::EINTR) => (), // リトライ result => return result, } } } /// プロセスグループIDを指定してfork & exec /// pgidが0の場合は子プロセスのPIDが、プロセスグループIDとなる /// /// - inputがSome(fd)の場合は、標準入力をfdと設定 /// - outputSome(fd)の場合は、標準出力をfdと設定 /// - fd_closeがSome(fd)の場合は、fork後にfdをクローズ fn fork_exec( pgid: Pid, filename: &str, args: &[&str], input: Option<i32>, output: Option<i32>, fd_close: Option<i32>, ) -> Result<Pid, DynError> { let filename = CString::new(filename).unwrap(); let args: Vec<CString> = args.iter().map(|s| CString::new(*s).unwrap()).collect(); match syscall(|| unsafe { fork() })? { ForkResult::Parent { child, .. } => { // 子プロセスのプロセスグループIDをpgidに設定 setpgid(child, pgid).unwrap(); Ok(child) } ForkResult::Child => { // 子プロセスのプロセスグループIDをpgidに設定 setpgid(Pid::from_raw(0), pgid).unwrap(); if let Some(fd) = fd_close { syscall(|| unistd::close(fd)).unwrap(); } // 標準入出力を設定 if let Some(infd) = input { syscall(|| dup2(infd, libc::STDIN_FILENO)).unwrap(); } if let Some(outfd) = output { syscall(|| dup2(outfd, libc::STDOUT_FILENO)).unwrap(); } // signal_hookで利用されるUNIXドメインソケットとpipeをクローズ for i in 3..=6 { let _ = syscall(|| unistd::close(i)); } // 実行ファイルをメモリに読み込み match execvp(&filename, &args) { Err(_) => { unistd::write(libc::STDERR_FILENO, "不明なコマンドを実行\n".as_bytes()).ok(); exit(1); } Ok(_) => unreachable!(), } } } } /// スペースでsplit fn parse_cmd_one(line: &str) -> Result<(&str, Vec<&str>), DynError> { let cmd: Vec<&str> = line.split(' ').collect(); let mut filename = ""; let mut args = Vec::new(); // 引数を生成。ただし、空の文字列filterで取り除く for (n, s) in cmd.iter().filter(|s| !s.is_empty()).enumerate() { if n == 0 { filename = *s; } args.push(*s); } if filename.is_empty() { Err("空のコマンド".into()) } else { Ok((filename, args)) } } /// パイプでsplit fn parse_pipe(line: &str) -> Vec<&str> { let cmds: Vec<&str> = line.split('|').collect(); cmds } type CmdResult<'a> = Result<Vec<(&'a str, Vec<&'a str>)>, DynError>; /// コマンドをパースし、実行ファイルと引数にわける。 /// また、パイプの場合は複数のコマンドにわけてVecに保存。 /// /// # 例1 /// /// 入力"echo abc def"に対して、`Ok(vec![("echo", vec!["echo", "abc", "def"])])` /// を返す。 /// /// # 例2 /// /// 入力"echo abc | less"に対して、`Ok(vec![("echo", vec!["echo", "abc"]), ("less", vec!["less"])])` /// を返す。 fn parse_cmd(line: &str) -> CmdResult { let cmds = parse_pipe(line); if cmds.is_empty() { return Err("空のコマンド".into()); } let mut result = Vec::new(); for cmd in cmds { let (filename, args) = parse_cmd_one(cmd)?; result.push((filename, args)); } Ok(result) }
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch07/zrsh/src/helper.rs
ch07/zrsh/src/helper.rs
pub type DynError = Box<dyn std::error::Error + Send + Sync + 'static>;
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch07/zrsh/src/main.rs
ch07/zrsh/src/main.rs
mod helper; mod shell; use helper::DynError; const HISTORY_FILE: &str = ".zerosh_history"; fn main() -> Result<(), DynError> { let mut logfile = HISTORY_FILE; let mut home = dirs::home_dir(); if let Some(h) = &mut home { h.push(HISTORY_FILE); logfile = h.to_str().unwrap_or(HISTORY_FILE); } let sh = shell::Shell::new(logfile); sh.run()?; Ok(()) }
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch01/mul/src/main.rs
ch01/mul/src/main.rs
// mainという関数を定義 fn main() { let x: i32 = 10; // i32型の変数をxを定義して、10を代入(型指定あり) let y = 20; // 変数yを定義して20を代入(型指定なし) let z = mul(x, y); // 関数呼び出し println!("z = {z}"); // {z}で変数zを表示 } // i32型の引数xとyを受け取り、i32型の値を返す関数mulを定義 fn mul(x: i32, y: i32) -> i32 { // セミコロンが最後にないことに注意 // 関数の最後の値が返り値となる x * y } // この位置には、以下のように式は書けない // let x = 10; // let y = 20; // let z = mul(x, y);
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch05/mod_ex3/src/main.rs
ch05/mod_ex3/src/main.rs
mod a; mod b; fn main() {}
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch05/mod_ex3/src/a/a_2.rs
ch05/mod_ex3/src/a/a_2.rs
struct TypeA2;
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch05/mod_ex3/src/a/a_1.rs
ch05/mod_ex3/src/a/a_1.rs
struct TypeA1;
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch05/mod_ex3/src/a/mod.rs
ch05/mod_ex3/src/a/mod.rs
mod a_1; mod a_2; struct TypeA;
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch05/mod_ex3/src/b/b_1.rs
ch05/mod_ex3/src/b/b_1.rs
struct TypeB1;
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch05/mod_ex3/src/b/b_2.rs
ch05/mod_ex3/src/b/b_2.rs
struct TypeB2;
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false
ytakano/rust_zero
https://github.com/ytakano/rust_zero/blob/843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c/ch05/mod_ex3/src/b/mod.rs
ch05/mod_ex3/src/b/mod.rs
mod b_1; mod b_2; struct TypeB;
rust
MIT
843eb4cf9b2dff3b24defc4ada1f04a58a8efe6c
2026-01-04T20:20:39.285647Z
false