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
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/saved_tracks/saved_tracks_model.rs
src/app/components/saved_tracks/saved_tracks_model.rs
use gio::prelude::*; use gio::SimpleActionGroup; use std::ops::Deref; use std::rc::Rc; use crate::app::components::{labels, PlaylistModel}; use crate::app::models::*; use crate::app::state::SelectionContext; use crate::app::state::{PlaybackAction, SelectionAction, SelectionState}; use crate::app::{ActionDispatcher, AppAction, AppModel, BatchQuery, BrowserAction, SongsSource}; pub struct SavedTracksModel { app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>, } impl SavedTracksModel { pub fn new(app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self { Self { app_model, dispatcher, } } pub fn load_initial(&self) { let loader = self.app_model.get_batch_loader(); let query = BatchQuery { source: SongsSource::SavedTracks, batch: Batch::first_of_size(50), }; self.dispatcher.dispatch_async(Box::pin(async move { loader .query(query, |_s, song_batch| { BrowserAction::SetSavedTracks(Box::new(song_batch)).into() }) .await })); } pub fn load_more(&self) -> Option<()> { let loader = self.app_model.get_batch_loader(); let last_batch = self.song_list_model().last_batch()?.next()?; let query = BatchQuery { source: SongsSource::SavedTracks, batch: last_batch, }; self.dispatcher.dispatch_async(Box::pin(async move { loader .query(query, |_s, song_batch| { BrowserAction::AppendSavedTracks(Box::new(song_batch)).into() }) .await })); Some(()) } } impl PlaylistModel for SavedTracksModel { fn song_list_model(&self) -> SongListModel { self.app_model .get_state() .browser .home_state() .expect("illegal attempt to read home_state") .saved_tracks .clone() } fn is_paused(&self) -> bool { !self.app_model.get_state().playback.is_playing() } fn current_song_id(&self) -> Option<String> { self.app_model.get_state().playback.current_song_id() } fn play_song_at(&self, pos: usize, id: &str) { let source = SongsSource::SavedTracks; let batch = self.song_list_model().song_batch_for(pos); if let Some(batch) = batch { self.dispatcher .dispatch(PlaybackAction::LoadPagedSongs(source, batch).into()); self.dispatcher .dispatch(PlaybackAction::Load(id.to_string()).into()); } } fn autoscroll_to_playing(&self) -> bool { true } fn actions_for(&self, id: &str) -> Option<gio::ActionGroup> { let song = self.song_list_model().get(id)?; let song = song.description(); let group = SimpleActionGroup::new(); for view_artist in song.make_artist_actions(self.dispatcher.box_clone(), None) { group.add_action(&view_artist); } group.add_action(&song.make_album_action(self.dispatcher.box_clone(), None)); group.add_action(&song.make_link_action(None)); Some(group.upcast()) } fn menu_for(&self, id: &str) -> Option<gio::MenuModel> { let song = self.song_list_model().get(id)?; let song = song.description(); let menu = gio::Menu::new(); menu.append(Some(&*labels::VIEW_ALBUM), Some("song.view_album")); for artist in song.artists.iter() { menu.append( Some(&labels::more_from_label(&artist.name)), Some(&format!("song.view_artist_{}", artist.id)), ); } menu.append(Some(&*labels::COPY_LINK), Some("song.copy_link")); Some(menu.upcast()) } fn select_song(&self, id: &str) { let song = self.song_list_model().get(id); if let Some(song) = song { self.dispatcher .dispatch(SelectionAction::Select(vec![song.description().clone()]).into()); } } fn deselect_song(&self, id: &str) { self.dispatcher .dispatch(SelectionAction::Deselect(vec![id.to_string()]).into()); } fn enable_selection(&self) -> bool { self.dispatcher .dispatch(AppAction::EnableSelection(SelectionContext::SavedTracks)); true } fn selection(&self) -> Option<Box<dyn Deref<Target = SelectionState> + '_>> { let selection = self.app_model.map_state(|s| &s.selection); Some(Box::new(selection)) } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/saved_tracks/mod.rs
src/app/components/saved_tracks/mod.rs
#[allow(clippy::module_inception)] mod saved_tracks; pub use saved_tracks::*; mod saved_tracks_model; pub use saved_tracks_model::*;
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/user_menu/user_menu_model.rs
src/app/components/user_menu/user_menu_model.rs
use crate::api::clear_user_cache; use crate::app::credentials::Credentials; use crate::app::state::{LoginAction, PlaybackAction}; use crate::app::{ActionDispatcher, AppModel}; use std::ops::Deref; use std::rc::Rc; pub struct UserMenuModel { app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>, } impl UserMenuModel { pub fn new(app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self { Self { app_model, dispatcher, } } pub fn username(&self) -> Option<impl Deref<Target = String> + '_> { self.app_model .map_state_opt(|s| s.logged_user.user.as_ref()) } pub fn logout(&self) { self.dispatcher.dispatch(PlaybackAction::Stop.into()); self.dispatcher.dispatch_async(Box::pin(async { let _ = Credentials::logout().await; let _ = clear_user_cache().await; Some(LoginAction::Logout.into()) })); } pub fn fetch_user_playlists(&self) { let api = self.app_model.get_spotify(); if let Some(current_user) = self.username() { let current_user = current_user.clone(); self.dispatcher .call_spotify_and_dispatch(move || async move { api.get_saved_playlists(0, 30).await.map(|playlists| { let summaries = playlists .into_iter() .filter(|p| p.owner.id == current_user) .map(|p| p.into()) .collect(); LoginAction::SetUserPlaylists(summaries).into() }) }); } } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/user_menu/user_menu.rs
src/app/components/user_menu/user_menu.rs
use gettextrs::*; use gio::{prelude::ActionMapExt, SimpleAction, SimpleActionGroup}; use gtk::prelude::*; use libadwaita::prelude::AdwDialogExt; use std::rc::Rc; use super::UserMenuModel; use crate::app::components::{EventListener, Settings}; use crate::app::{state::LoginEvent, AppEvent}; pub struct UserMenu { user_button: gtk::MenuButton, model: Rc<UserMenuModel>, } impl UserMenu { pub fn new( user_button: gtk::MenuButton, settings: Settings, about: libadwaita::AboutDialog, parent: gtk::Window, model: UserMenuModel, ) -> Self { let model = Rc::new(model); let action_group = SimpleActionGroup::new(); action_group.add_action(&{ let logout = SimpleAction::new("logout", None); logout.connect_activate(clone!( #[weak] model, move |_, _| { model.logout(); } )); logout }); action_group.add_action(&{ let settings_action = SimpleAction::new("settings", None); settings_action.connect_activate(move |_, _| { settings.show_self(); }); settings_action }); action_group.add_action(&{ let about_action = SimpleAction::new("about", None); about_action.connect_activate(clone!( #[weak] about, #[weak] parent, move |_, _| { about.present(Some(&parent)); } )); about_action }); user_button.insert_action_group("menu", Some(&action_group)); Self { user_button, model } } fn update_menu(&self) { let menu = gio::Menu::new(); // translators: This is a menu entry. menu.append(Some(&gettext("Preferences")), Some("menu.settings")); // translators: This is a menu entry. menu.append(Some(&gettext("About")), Some("menu.about")); // translators: This is a menu entry. menu.append(Some(&gettext("Quit")), Some("app.quit")); if let Some(username) = self.model.username() { let user_menu = gio::Menu::new(); // translators: This is a menu entry. user_menu.append(Some(&gettext("Log out")), Some("menu.logout")); menu.insert_section(0, Some(&username), &user_menu); } self.user_button.set_menu_model(Some(&menu)); } } impl EventListener for UserMenu { fn on_event(&mut self, event: &AppEvent) { match event { AppEvent::LoginEvent(LoginEvent::LoginCompleted) | AppEvent::Started => { self.update_menu(); self.model.fetch_user_playlists(); } _ => {} } } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/user_menu/mod.rs
src/app/components/user_menu/mod.rs
#[allow(clippy::module_inception)] mod user_menu; pub use user_menu::*; mod user_menu_model; pub use user_menu_model::*;
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/scrolling_header/mod.rs
src/app/components/scrolling_header/mod.rs
mod scrolling_header_widget; use gtk::prelude::StaticType; pub use scrolling_header_widget::*; pub fn expose_widgets() { scrolling_header_widget::ScrollingHeaderWidget::static_type(); }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/scrolling_header/scrolling_header_widget.rs
src/app/components/scrolling_header/scrolling_header_widget.rs
use gtk::prelude::*; use gtk::subclass::prelude::*; use gtk::CompositeTemplate; mod imp { use super::*; #[derive(Debug, Default, CompositeTemplate)] #[template(resource = "/dev/diegovsky/Riff/components/scrolling_header.ui")] pub struct ScrollingHeaderWidget { #[template_child] pub scrolled_window: TemplateChild<gtk::ScrolledWindow>, #[template_child] pub revealer: TemplateChild<gtk::Revealer>, } #[glib::object_subclass] impl ObjectSubclass for ScrollingHeaderWidget { const NAME: &'static str = "ScrollingHeaderWidget"; type Type = super::ScrollingHeaderWidget; type ParentType = gtk::Box; type Interfaces = (gtk::Buildable,); fn class_init(klass: &mut Self::Class) { klass.bind_template(); } fn instance_init(obj: &glib::subclass::InitializingObject<Self>) { obj.init_template(); } } impl ObjectImpl for ScrollingHeaderWidget {} impl BuildableImpl for ScrollingHeaderWidget { fn add_child(&self, builder: &gtk::Builder, child: &glib::Object, type_: Option<&str>) { let child_widget = child.downcast_ref::<gtk::Widget>(); match type_ { Some("internal") => self.parent_add_child(builder, child, type_), Some("header") => self.revealer.set_child(child_widget), _ => self.scrolled_window.set_child(child_widget), } } } impl WidgetImpl for ScrollingHeaderWidget {} impl BoxImpl for ScrollingHeaderWidget {} } glib::wrapper! { pub struct ScrollingHeaderWidget(ObjectSubclass<imp::ScrollingHeaderWidget>) @extends gtk::Widget, gtk::Box; } impl ScrollingHeaderWidget { fn set_header_visible(&self, visible: bool) -> bool { let widget = self.imp(); let is_up_to_date = widget.revealer.reveals_child() == visible; if !is_up_to_date { widget.revealer.set_reveal_child(visible); } is_up_to_date } fn is_scrolled_to_top(&self) -> bool { self.imp().scrolled_window.vadjustment().value() <= f64::EPSILON || self.imp().revealer.reveals_child() } pub fn connect_header_visibility<F>(&self, f: F) where F: Fn(bool) + Clone + 'static, { self.set_header_visible(true); f(true); let scroll_controller = gtk::EventControllerScroll::new(gtk::EventControllerScrollFlags::VERTICAL); scroll_controller.connect_scroll(clone!( #[strong] f, #[weak(rename_to = _self)] self, #[upgrade_or] glib::Propagation::Proceed, move |_, _, dy| { let visible = dy < 0f64 && _self.is_scrolled_to_top(); f(visible); if _self.set_header_visible(visible) { glib::Propagation::Proceed } else { glib::Propagation::Stop } } )); let swipe_controller = gtk::GestureSwipe::new(); swipe_controller.set_touch_only(true); swipe_controller.set_propagation_phase(gtk::PropagationPhase::Capture); swipe_controller.connect_swipe(clone!( #[weak(rename_to = _self)] self, move |_, _, dy| { let visible = dy >= 0f64 && _self.is_scrolled_to_top(); f(visible); _self.set_header_visible(visible); } )); self.imp().scrolled_window.add_controller(scroll_controller); self.add_controller(swipe_controller); } pub fn connect_bottom_edge<F>(&self, f: F) where F: Fn() + 'static, { self.imp() .scrolled_window .connect_edge_reached(move |_, pos| { if let gtk::PositionType::Bottom = pos { f() } }); } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/selection/widget.rs
src/app/components/selection/widget.rs
use gio::prelude::ActionMapExt; use gio::{SimpleAction, SimpleActionGroup}; use gtk::prelude::*; use gtk::subclass::prelude::*; use gtk::CompositeTemplate; use crate::app::components::{display_add_css_provider, labels}; use crate::app::models::PlaylistSummary; mod imp { use super::*; #[derive(Debug, Default, CompositeTemplate)] #[template(resource = "/dev/diegovsky/Riff/components/selection_toolbar.ui")] pub struct SelectionToolbarWidget { #[template_child] pub action_bar: TemplateChild<gtk::ActionBar>, #[template_child] pub move_up: TemplateChild<gtk::Button>, #[template_child] pub move_down: TemplateChild<gtk::Button>, #[template_child] pub add: TemplateChild<gtk::MenuButton>, #[template_child] pub remove: TemplateChild<gtk::Button>, #[template_child] pub queue: TemplateChild<gtk::Button>, #[template_child] pub save: TemplateChild<gtk::Button>, } #[glib::object_subclass] impl ObjectSubclass for SelectionToolbarWidget { const NAME: &'static str = "SelectionToolbarWidget"; type Type = super::SelectionToolbarWidget; type ParentType = gtk::Box; fn class_init(klass: &mut Self::Class) { klass.bind_template(); } fn instance_init(obj: &glib::subclass::InitializingObject<Self>) { obj.init_template(); } } impl ObjectImpl for SelectionToolbarWidget { fn constructed(&self) { self.parent_constructed(); display_add_css_provider(resource!("/components/selection_toolbar.css")); } } impl WidgetImpl for SelectionToolbarWidget {} impl BoxImpl for SelectionToolbarWidget {} } glib::wrapper! { pub struct SelectionToolbarWidget(ObjectSubclass<imp::SelectionToolbarWidget>) @extends gtk::Widget, gtk::Box; } #[derive(Debug, Clone, Copy)] pub enum SelectionToolState { Hidden, Visible(bool), } impl SelectionToolState { fn visible(self) -> bool { matches!(self, SelectionToolState::Visible(_)) } fn sensitive(self) -> bool { matches!(self, SelectionToolState::Visible(true)) } } impl SelectionToolbarWidget { pub fn connect_move_down<F>(&self, f: F) where F: Fn() + 'static, { self.imp().move_down.connect_clicked(move |_| f()); } pub fn connect_move_up<F>(&self, f: F) where F: Fn() + 'static, { self.imp().move_up.connect_clicked(move |_| f()); } pub fn connect_queue<F>(&self, f: F) where F: Fn() + 'static, { self.imp().queue.connect_clicked(move |_| f()); } pub fn connect_save<F>(&self, f: F) where F: Fn() + 'static, { self.imp().save.connect_clicked(move |_| f()); } pub fn connect_remove<F>(&self, f: F) where F: Fn() + 'static, { self.imp().remove.connect_clicked(move |_| f()); } pub fn set_move(&self, state: SelectionToolState) { self.imp().move_up.set_sensitive(state.sensitive()); self.imp().move_up.set_visible(state.visible()); self.imp().move_down.set_sensitive(state.sensitive()); self.imp().move_down.set_visible(state.visible()); } pub fn set_queue(&self, state: SelectionToolState) { self.imp().queue.set_sensitive(state.sensitive()); self.imp().queue.set_visible(state.visible()); } pub fn set_add(&self, state: SelectionToolState) { self.imp().add.set_sensitive(state.sensitive()); self.imp().add.set_visible(state.visible()); } pub fn set_remove(&self, state: SelectionToolState) { self.imp().remove.set_sensitive(state.sensitive()); self.imp().remove.set_visible(state.visible()); } pub fn set_save(&self, state: SelectionToolState) { self.imp().save.set_sensitive(state.sensitive()); self.imp().save.set_visible(state.visible()); } pub fn set_visible(&self, visible: bool) { gtk::Widget::set_visible(self.upcast_ref(), visible); self.imp().action_bar.set_revealed(visible); } pub fn connect_playlists<F>(&self, playlists: &[PlaylistSummary], on_playlist_selected: F) where F: Fn(&str) + Clone + 'static, { let menu = gio::Menu::new(); let action_group = SimpleActionGroup::new(); for PlaylistSummary { title, id } in playlists { let action_name = format!("playlist_{id}"); action_group.add_action(&{ let id = id.clone(); let action = SimpleAction::new(&action_name, None); let f = on_playlist_selected.clone(); action.connect_activate(move |_, _| f(&id)); action }); menu.append( Some(&labels::add_to_playlist_label(title)), Some(&format!("add_to.{action_name}")), ); } let popover = gtk::PopoverMenu::from_model(Some(&menu)); self.imp().add.set_popover(Some(&popover)); self.imp() .add .insert_action_group("add_to", Some(&action_group)); } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/selection/mod.rs
src/app/components/selection/mod.rs
mod widget; mod component; pub use component::*; use glib::prelude::*; pub fn expose_widgets() { widget::SelectionToolbarWidget::static_type(); }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/selection/component.rs
src/app/components/selection/component.rs
use gettextrs::gettext; use gtk::prelude::*; use std::ops::Deref; use std::rc::Rc; use crate::app::components::{Component, EventListener}; use crate::app::models::PlaylistSummary; use crate::app::state::{ LoginEvent, SelectionAction, SelectionContext, SelectionEvent, SelectionState, }; use crate::app::{ActionDispatcher, AppAction, AppEvent, AppModel, BrowserAction}; use super::widget::{SelectionToolState, SelectionToolbarWidget}; pub struct SelectionToolbarModel { app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>, } impl SelectionToolbarModel { pub fn new(app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self { Self { app_model, dispatcher, } } pub fn move_up_selection(&self) { self.dispatcher.dispatch(AppAction::MoveUpSelection); } pub fn move_down_selection(&self) { self.dispatcher.dispatch(AppAction::MoveDownSelection); } pub fn queue_selection(&self) { self.dispatcher.dispatch(AppAction::QueueSelection); } fn dequeue_selection(&self) { self.dispatcher.dispatch(AppAction::DequeueSelection); } pub fn remove_selection(&self) { match &self.selection().context { SelectionContext::SavedTracks => self.remove_saved_tracks(), SelectionContext::Queue => self.dequeue_selection(), SelectionContext::EditablePlaylist(id) => self.remove_from_playlist(id), _ => {} } } pub fn save_selection(&self) { let api = self.app_model.get_spotify(); let ids: Vec<String> = self .selection() .peek_selection() .map(|s| &s.id) .cloned() .collect(); self.dispatcher .call_spotify_and_dispatch_many(move || async move { api.save_tracks(ids).await?; Ok(vec![ AppAction::SaveSelection, AppAction::ShowNotification(gettext("Tracks saved!")), ]) }) } fn remove_saved_tracks(&self) { let api = self.app_model.get_spotify(); let ids: Vec<String> = self .selection() .peek_selection() .map(|s| &s.id) .cloned() .collect(); self.dispatcher .call_spotify_and_dispatch_many(move || async move { api.remove_saved_tracks(ids).await?; Ok(vec![AppAction::UnsaveSelection]) }) } fn selection(&self) -> impl Deref<Target = SelectionState> + '_ { self.app_model.map_state(|s| &s.selection) } fn selected_count(&self) -> usize { self.selection().count() } fn user_playlists(&self) -> impl Deref<Target = Vec<PlaylistSummary>> + '_ { self.app_model.map_state(|s| &s.logged_user.playlists) } fn add_to_playlist(&self, id: &str) { let id = id.to_string(); let api = self.app_model.get_spotify(); let uris: Vec<String> = self .selection() .peek_selection() .map(|s| &s.uri) .cloned() .collect(); self.dispatcher .call_spotify_and_dispatch(move || async move { api.add_to_playlist(&id, uris).await?; Ok(SelectionAction::Clear.into()) }) } fn remove_from_playlist(&self, id: &str) { let api = self.app_model.get_spotify(); let id = id.to_string(); let uris: Vec<String> = self .selection() .peek_selection() .map(|s| &s.uri) .cloned() .collect(); self.dispatcher .call_spotify_and_dispatch_many(move || async move { api.remove_from_playlist(&id, uris.clone()).await?; Ok(vec![ BrowserAction::RemoveTracksFromPlaylist(id, uris).into(), SelectionAction::Clear.into(), ]) }) } } pub struct SelectionToolbar { model: Rc<SelectionToolbarModel>, widget: SelectionToolbarWidget, } impl SelectionToolbar { pub fn new(model: SelectionToolbarModel, widget: SelectionToolbarWidget) -> Self { let model = Rc::new(model); widget.connect_move_up(clone!( #[weak] model, move || model.move_up_selection() )); widget.connect_move_down(clone!( #[weak] model, move || model.move_down_selection() )); widget.connect_queue(clone!( #[weak] model, move || model.queue_selection() )); widget.connect_remove(clone!( #[weak] model, move || model.remove_selection() )); widget.connect_save(clone!( #[weak] model, move || model.save_selection() )); Self { model, widget } } fn update_active_tools(&self) { let count = self.model.selected_count(); match self.model.selection().context { SelectionContext::Default => { self.widget.set_move(SelectionToolState::Hidden); self.widget .set_queue(SelectionToolState::Visible(count > 0)); self.widget.set_add(SelectionToolState::Visible(count > 0)); self.widget.set_remove(SelectionToolState::Hidden); self.widget.set_save(SelectionToolState::Visible(count > 0)); } SelectionContext::SavedTracks => { self.widget.set_move(SelectionToolState::Hidden); self.widget .set_queue(SelectionToolState::Visible(count > 0)); self.widget.set_add(SelectionToolState::Visible(count > 0)); self.widget .set_remove(SelectionToolState::Visible(count > 0)); self.widget.set_save(SelectionToolState::Hidden); } SelectionContext::ReadOnlyQueue => { self.widget.set_move(SelectionToolState::Hidden); self.widget.set_queue(SelectionToolState::Hidden); self.widget.set_add(SelectionToolState::Hidden); self.widget.set_remove(SelectionToolState::Hidden); self.widget.set_save(SelectionToolState::Visible(count > 0)); } SelectionContext::Queue => { self.widget .set_move(SelectionToolState::Visible(count == 1)); self.widget.set_queue(SelectionToolState::Hidden); self.widget.set_add(SelectionToolState::Hidden); self.widget .set_remove(SelectionToolState::Visible(count > 0)); self.widget.set_save(SelectionToolState::Visible(count > 0)); } SelectionContext::Playlist => { self.widget.set_move(SelectionToolState::Hidden); self.widget .set_queue(SelectionToolState::Visible(count > 0)); self.widget.set_add(SelectionToolState::Hidden); self.widget.set_remove(SelectionToolState::Hidden); self.widget.set_save(SelectionToolState::Hidden); } SelectionContext::EditablePlaylist(_) => { self.widget.set_move(SelectionToolState::Hidden); self.widget .set_queue(SelectionToolState::Visible(count > 0)); self.widget.set_add(SelectionToolState::Hidden); self.widget .set_remove(SelectionToolState::Visible(count > 0)); self.widget.set_save(SelectionToolState::Hidden); } }; } } impl Component for SelectionToolbar { fn get_root_widget(&self) -> &gtk::Widget { self.widget.upcast_ref() } } impl EventListener for SelectionToolbar { fn on_event(&mut self, event: &AppEvent) { match event { AppEvent::SelectionEvent(SelectionEvent::SelectionModeChanged(active)) => { self.widget.set_visible(*active); self.update_active_tools(); } AppEvent::SelectionEvent(SelectionEvent::SelectionChanged) => { self.update_active_tools(); } AppEvent::LoginEvent(LoginEvent::UserPlaylistsLoaded) => { let model = &self.model; self.widget.connect_playlists( &model.user_playlists(), clone!( #[weak] model, move |s| model.add_to_playlist(s) ), ); } _ => {} } } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/search/search_button.rs
src/app/components/search/search_button.rs
use gtk::prelude::*; use crate::app::components::EventListener; use crate::app::{ActionDispatcher, AppAction}; pub struct SearchBarModel(pub Box<dyn ActionDispatcher>); impl SearchBarModel { pub fn navigate_to_search(&self) { self.0.dispatch(AppAction::ViewSearch()); } } pub struct SearchButton; impl SearchButton { pub fn new(model: SearchBarModel, search_button: gtk::Button) -> Self { search_button.connect_clicked(move |_| { model.navigate_to_search(); }); Self } } impl EventListener for SearchButton {}
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/search/search.rs
src/app/components/search/search.rs
use gtk::prelude::*; use gtk::subclass::prelude::*; use gtk::CompositeTemplate; use std::rc::Rc; use crate::app::components::utils::{wrap_flowbox_item, Debouncer}; use crate::app::components::{AlbumWidget, ArtistWidget, Component, EventListener}; use crate::app::dispatch::Worker; use crate::app::models::{AlbumModel, ArtistModel}; use crate::app::state::{AppEvent, BrowserEvent}; use super::SearchResultsModel; mod imp { use super::*; #[derive(Debug, Default, CompositeTemplate)] #[template(resource = "/dev/diegovsky/Riff/components/search.ui")] pub struct SearchResultsWidget { #[template_child] pub main_header: TemplateChild<libadwaita::HeaderBar>, #[template_child] pub go_back: TemplateChild<gtk::Button>, #[template_child] pub search_entry: TemplateChild<gtk::SearchEntry>, #[template_child] pub status_page: TemplateChild<libadwaita::StatusPage>, #[template_child] pub search_results: TemplateChild<gtk::Widget>, #[template_child] pub albums_results: TemplateChild<gtk::FlowBox>, #[template_child] pub artist_results: TemplateChild<gtk::FlowBox>, } #[glib::object_subclass] impl ObjectSubclass for SearchResultsWidget { const NAME: &'static str = "SearchResultsWidget"; type Type = super::SearchResultsWidget; type ParentType = gtk::Box; fn class_init(klass: &mut Self::Class) { klass.bind_template(); } fn instance_init(obj: &glib::subclass::InitializingObject<Self>) { obj.init_template(); } } impl ObjectImpl for SearchResultsWidget {} impl BoxImpl for SearchResultsWidget {} impl WidgetImpl for SearchResultsWidget { fn grab_focus(&self) -> bool { self.search_entry.grab_focus() } } } glib::wrapper! { pub struct SearchResultsWidget(ObjectSubclass<imp::SearchResultsWidget>) @extends gtk::Widget, gtk::Box; } impl Default for SearchResultsWidget { fn default() -> Self { Self::new() } } impl SearchResultsWidget { pub fn new() -> Self { glib::Object::new() } pub fn connect_go_back<F>(&self, f: F) where F: Fn() + 'static, { self.imp().go_back.connect_clicked(move |_| f()); } pub fn connect_search_updated<F>(&self, f: F) where F: Fn(String) + 'static, { self.imp().search_entry.connect_changed(clone!( #[weak(rename_to = _self)] self, move |s| { let query = s.text(); let query = query.as_str(); _self.imp().status_page.set_visible(query.is_empty()); _self.imp().search_results.set_visible(!query.is_empty()); if !query.is_empty() { f(query.to_string()); } } )); } fn bind_albums_results<F>(&self, worker: Worker, store: &gio::ListStore, on_album_pressed: F) where F: Fn(String) + Clone + 'static, { self.imp() .albums_results .bind_model(Some(store), move |item| { wrap_flowbox_item(item, |album_model| { let f = on_album_pressed.clone(); let album = AlbumWidget::for_model(album_model, worker.clone()); album.connect_album_pressed(clone!( #[weak] album_model, move || { f(album_model.uri()); } )); album }) }); } fn bind_artists_results<F>(&self, worker: Worker, store: &gio::ListStore, on_artist_pressed: F) where F: Fn(String) + Clone + 'static, { self.imp() .artist_results .bind_model(Some(store), move |item| { wrap_flowbox_item(item, |artist_model| { let f = on_artist_pressed.clone(); let artist = ArtistWidget::for_model(artist_model, worker.clone()); artist.connect_artist_pressed(clone!( #[weak] artist_model, move || { f(artist_model.id()); } )); artist }) }); } } pub struct SearchResults { widget: SearchResultsWidget, model: Rc<SearchResultsModel>, album_results_model: gio::ListStore, artist_results_model: gio::ListStore, debouncer: Debouncer, } impl SearchResults { pub fn new(model: SearchResultsModel, worker: Worker) -> Self { let model = Rc::new(model); let widget = SearchResultsWidget::new(); let album_results_model = gio::ListStore::new::<AlbumModel>(); let artist_results_model = gio::ListStore::new::<ArtistModel>(); widget.connect_go_back(clone!( #[weak] model, move || { model.go_back(); } )); widget.connect_search_updated(clone!( #[weak] model, move |q| { model.search(q); } )); widget.bind_albums_results( worker.clone(), &album_results_model, clone!( #[weak] model, move |uri| { model.open_album(uri); } ), ); widget.bind_artists_results( worker, &artist_results_model, clone!( #[weak] model, move |id| { model.open_artist(id); } ), ); Self { widget, model, album_results_model, artist_results_model, debouncer: Debouncer::new(), } } fn update_results(&self) { if let Some(results) = self.model.get_album_results() { self.album_results_model.remove_all(); for album in results.iter() { self.album_results_model.append(&AlbumModel::new( &album.artists_name(), &album.title, album.year(), album.art.as_ref(), &album.id, )); } } if let Some(results) = self.model.get_artist_results() { self.artist_results_model.remove_all(); for artist in results.iter() { self.artist_results_model.append(&ArtistModel::new( &artist.name, &artist.photo, &artist.id, )); } } } fn update_search_query(&self) { self.debouncer.debounce( 600, clone!( #[weak(rename_to = model)] self.model, move || model.fetch_results() ), ); } } impl Component for SearchResults { fn get_root_widget(&self) -> &gtk::Widget { self.widget.as_ref() } } impl EventListener for SearchResults { fn on_event(&mut self, app_event: &AppEvent) { match app_event { AppEvent::BrowserEvent(BrowserEvent::SearchUpdated) => { self.get_root_widget().grab_focus(); self.update_search_query(); } AppEvent::BrowserEvent(BrowserEvent::SearchResultsUpdated) => { self.update_results(); } _ => {} } } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/search/search_model.rs
src/app/components/search/search_model.rs
use std::ops::Deref; use std::rc::Rc; use crate::app::dispatch::ActionDispatcher; use crate::app::models::*; use crate::app::state::{AppAction, AppModel, BrowserAction}; pub struct SearchResultsModel { app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>, } impl SearchResultsModel { pub fn new(app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self { Self { app_model, dispatcher, } } pub fn go_back(&self) { self.dispatcher .dispatch(BrowserAction::NavigationPop.into()); } pub fn search(&self, query: String) { self.dispatcher .dispatch(BrowserAction::Search(query).into()); } fn get_query(&self) -> Option<impl Deref<Target = String> + '_> { self.app_model .map_state_opt(|s| Some(&s.browser.search_state()?.query).filter(|s| !s.is_empty())) } pub fn fetch_results(&self) { let api = self.app_model.get_spotify(); if let Some(query) = self.get_query() { let query = query.to_owned(); self.dispatcher .call_spotify_and_dispatch(move || async move { api.search(&query, 0, 5) .await .map(|results| BrowserAction::SetSearchResults(Box::new(results)).into()) }); } } pub fn get_album_results(&self) -> Option<impl Deref<Target = Vec<AlbumDescription>> + '_> { self.app_model .map_state_opt(|s| Some(&s.browser.search_state()?.album_results)) } pub fn get_artist_results(&self) -> Option<impl Deref<Target = Vec<ArtistSummary>> + '_> { self.app_model .map_state_opt(|s| Some(&s.browser.search_state()?.artist_results)) } pub fn open_album(&self, id: String) { self.dispatcher.dispatch(AppAction::ViewAlbum(id)); } pub fn open_artist(&self, id: String) { self.dispatcher.dispatch(AppAction::ViewArtist(id)); } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/search/mod.rs
src/app/components/search/mod.rs
#[allow(clippy::module_inception)] mod search; pub use search::*; mod search_model; pub use search_model::*; mod search_button; pub use search_button::*;
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playlist/song_actions.rs
src/app/components/playlist/song_actions.rs
use gdk::prelude::*; use gio::SimpleAction; use crate::app::models::SongDescription; use crate::app::state::{AppAction, PlaybackAction}; use crate::app::ActionDispatcher; impl SongDescription { pub fn make_queue_action( &self, dispatcher: Box<dyn ActionDispatcher>, name: Option<&str>, ) -> SimpleAction { let queue = SimpleAction::new(name.unwrap_or("queue"), None); let song = self.clone(); queue.connect_activate(move |_, _| { dispatcher.dispatch(PlaybackAction::Queue(vec![song.clone()]).into()); }); queue } pub fn make_dequeue_action( &self, dispatcher: Box<dyn ActionDispatcher>, name: Option<&str>, ) -> SimpleAction { let dequeue = SimpleAction::new(name.unwrap_or("dequeue"), None); let track_id = self.id.clone(); dequeue.connect_activate(move |_, _| { dispatcher.dispatch(PlaybackAction::Dequeue(track_id.clone()).into()); }); dequeue } pub fn make_link_action(&self, name: Option<&str>) -> SimpleAction { let track_id = self.id.clone(); let copy_link = SimpleAction::new(name.unwrap_or("copy_link"), None); copy_link.connect_activate(move |_, _| { let link = format!("https://open.spotify.com/track/{track_id}"); let clipboard = gdk::Display::default().unwrap().clipboard(); clipboard .set_content(Some(&gdk::ContentProvider::for_value(&link.to_value()))) .expect("Failed to set clipboard content"); }); copy_link } pub fn make_album_action( &self, dispatcher: Box<dyn ActionDispatcher>, name: Option<&str>, ) -> SimpleAction { let album_id = self.album.id.clone(); let view_album = SimpleAction::new(name.unwrap_or("view_album"), None); view_album.connect_activate(move |_, _| { dispatcher.dispatch(AppAction::ViewAlbum(album_id.clone())); }); view_album } pub fn make_artist_actions( &self, dispatcher: Box<dyn ActionDispatcher>, prefix: Option<&str>, ) -> Vec<SimpleAction> { self.artists .iter() .map(|artist| { let id = artist.id.clone(); let view_artist = SimpleAction::new( &format!("{}_{}", prefix.unwrap_or("view_artist"), &id), None, ); let dispatcher = dispatcher.box_clone(); view_artist.connect_activate(move |_, _| { dispatcher.dispatch(AppAction::ViewArtist(id.clone())); }); view_artist }) .collect() } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playlist/playlist.rs
src/app/components/playlist/playlist.rs
use gio::prelude::*; use gtk::prelude::*; use std::ops::Deref; use std::rc::Rc; use crate::app::components::utils::{ancestor, AnimatorDefault}; use crate::app::components::{Component, EventListener, SongWidget}; use crate::app::models::{SongListModel, SongModel, SongState}; use crate::app::state::{PlaybackEvent, SelectionEvent, SelectionState}; use crate::app::{AppEvent, Worker}; pub trait PlaylistModel { fn is_paused(&self) -> bool; fn song_list_model(&self) -> SongListModel; fn current_song_id(&self) -> Option<String>; fn play_song_at(&self, pos: usize, id: &str); fn autoscroll_to_playing(&self) -> bool { true } fn show_song_covers(&self) -> bool { true } fn actions_for(&self, _id: &str) -> Option<gio::ActionGroup> { None } fn menu_for(&self, _id: &str) -> Option<gio::MenuModel> { None } fn select_song(&self, _id: &str) {} fn deselect_song(&self, _id: &str) {} fn enable_selection(&self) -> bool { false } fn selection(&self) -> Option<Box<dyn Deref<Target = SelectionState> + '_>> { None } fn is_selection_enabled(&self) -> bool { self.selection() .map(|s| s.is_selection_enabled()) .unwrap_or(false) } fn song_state(&self, id: &str) -> SongState { let is_playing = self.current_song_id().map(|s| s.eq(id)).unwrap_or(false); let is_selected = self .selection() .map(|s| s.is_song_selected(id)) .unwrap_or(false); SongState { is_selected, is_playing, } } fn toggle_select(&self, id: &str) { if let Some(selection) = self.selection() { if selection.is_song_selected(id) { self.deselect_song(id); } else { self.select_song(id); } } } } pub struct Playlist<Model> { animator: AnimatorDefault, listview: gtk::ListView, model: Rc<Model>, } impl<Model> Playlist<Model> where Model: PlaylistModel + 'static, { pub fn new(listview: gtk::ListView, model: Rc<Model>, worker: Worker) -> Self { let list_model = model.song_list_model(); let selection_model = gtk::NoSelection::new(Some(list_model.clone())); let factory = gtk::SignalListItemFactory::new(); listview.add_css_class("playlist"); listview.set_show_separators(true); listview.set_valign(gtk::Align::Start); listview.set_factory(Some(&factory)); listview.set_single_click_activate(true); listview.set_model(Some(&selection_model)); Self::set_paused(&listview, model.is_paused()); Self::set_selection_active(&listview, model.is_selection_enabled()); factory.connect_setup(|_, item| { let item = item.downcast_ref::<gtk::ListItem>().unwrap(); item.set_child(Some(&SongWidget::new())); }); factory.connect_bind(clone!( #[weak] model, move |_, item| { let item = item.downcast_ref::<gtk::ListItem>().unwrap(); let song_model = item.item().unwrap().downcast::<SongModel>().unwrap(); song_model.set_state(model.song_state(&song_model.get_id())); let widget = item.child().unwrap().downcast::<SongWidget>().unwrap(); widget.bind(&song_model, worker.clone(), model.show_song_covers()); let id = &song_model.get_id(); widget.set_actions(model.actions_for(id).as_ref()); widget.set_menu(model.menu_for(id).as_ref()); } )); factory.connect_unbind(|_, item| { let item = item.downcast_ref::<gtk::ListItem>().unwrap(); let song_model = item.item().unwrap().downcast::<SongModel>().unwrap(); song_model.unbind_all(); }); listview.connect_activate(clone!( #[weak] list_model, #[weak] model, move |_, position| { let song = list_model .index_continuous(position as usize) .expect("attempt to access invalid index"); let song = song.description(); let selection_enabled = model.is_selection_enabled(); if selection_enabled { model.toggle_select(&song.id); } else { model.play_song_at(position as usize, &song.id); } } )); let press_gesture = gtk::GestureLongPress::new(); press_gesture.set_touch_only(false); press_gesture.set_propagation_phase(gtk::PropagationPhase::Capture); press_gesture.connect_pressed(clone!( #[weak] model, move |_, _, _| { model.enable_selection(); } )); listview.add_controller(press_gesture); Self { animator: AnimatorDefault::ease_in_out_animator(), listview, model, } } fn autoscroll_to_playing(&self, index: usize) { let len = self.model.song_list_model().partial_len() as f64; let scrolled_window: Option<gtk::ScrolledWindow> = ancestor(&self.listview); let adj = scrolled_window.map(|w| w.vadjustment()); if let Some(adj) = adj { let v = adj.value(); let v2 = v + 0.9 * adj.page_size(); let pos = (index as f64) * adj.upper() / len; debug!("estimated pos: {}", pos); debug!("current window: {} -- {}", v, v2); if pos < v || pos > v2 { self.animator.animate( 20, clone!( #[weak] adj, #[upgrade_or] false, move |p| { let v = adj.value(); adj.set_value(v + p * (pos - v)); true } ), ); } } } fn update_list(&self) { let autoscroll_to_playing = self.model.autoscroll_to_playing(); let is_selection_enabled = self.model.is_selection_enabled(); self.model.song_list_model().for_each(|i, model_song| { let state = self.model.song_state(&model_song.get_id()); model_song.set_state(state); if state.is_playing && autoscroll_to_playing && !is_selection_enabled { self.autoscroll_to_playing(i); } }); } fn set_selection_active(listview: &gtk::ListView, active: bool) { let class_name = "playlist--selectable"; if active { listview.add_css_class(class_name); } else { listview.remove_css_class(class_name); } } fn set_paused(listview: &gtk::ListView, paused: bool) { let class_name = "playlist--paused"; if paused { listview.add_css_class(class_name); } else { listview.remove_css_class(class_name); } } } impl SongModel { fn set_state( &self, SongState { is_playing, is_selected, }: SongState, ) { self.set_playing(is_playing); self.set_selected(is_selected); } } impl<Model> EventListener for Playlist<Model> where Model: PlaylistModel + 'static, { fn on_event(&mut self, event: &AppEvent) { match event { AppEvent::SelectionEvent(SelectionEvent::SelectionChanged) => { self.update_list(); } AppEvent::PlaybackEvent(PlaybackEvent::TrackChanged(_)) => { self.update_list(); } AppEvent::PlaybackEvent( PlaybackEvent::PlaybackResumed | PlaybackEvent::PlaybackPaused, ) => { Self::set_paused(&self.listview, self.model.is_paused()); } AppEvent::SelectionEvent(SelectionEvent::SelectionModeChanged(_)) => { Self::set_selection_active(&self.listview, self.model.is_selection_enabled()); self.update_list(); } _ => {} } } } impl<Model> Component for Playlist<Model> { fn get_root_widget(&self) -> &gtk::Widget { self.listview.upcast_ref() } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playlist/mod.rs
src/app/components/playlist/mod.rs
#[allow(clippy::module_inception)] mod playlist; pub use playlist::*; mod song; pub use song::*; mod song_actions;
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playlist/song.rs
src/app/components/playlist/song.rs
use crate::app::components::display_add_css_provider; use crate::app::loader::ImageLoader; use crate::app::models::SongModel; use crate::app::Worker; use gio::MenuModel; use glib::subclass::InitializingObject; use gtk::prelude::*; use gtk::subclass::prelude::*; use gtk::CompositeTemplate; mod imp { use super::*; const SONG_CLASS: &str = "song--playing"; #[derive(Debug, Default, CompositeTemplate)] #[template(resource = "/dev/diegovsky/Riff/components/song.ui")] pub struct SongWidget { #[template_child] pub song_index: TemplateChild<gtk::Label>, #[template_child] pub song_icon: TemplateChild<gtk::Spinner>, #[template_child] pub song_checkbox: TemplateChild<gtk::CheckButton>, #[template_child] pub song_title: TemplateChild<gtk::Label>, #[template_child] pub song_artist: TemplateChild<gtk::Label>, #[template_child] pub song_length: TemplateChild<gtk::Label>, #[template_child] pub menu_btn: TemplateChild<gtk::MenuButton>, #[template_child] pub song_cover: TemplateChild<gtk::Image>, } #[glib::object_subclass] impl ObjectSubclass for SongWidget { const NAME: &'static str = "SongWidget"; type Type = super::SongWidget; type ParentType = gtk::Grid; fn class_init(klass: &mut Self::Class) { klass.bind_template(); } fn instance_init(obj: &InitializingObject<Self>) { obj.init_template(); } } lazy_static! { static ref PROPERTIES: [glib::ParamSpec; 2] = [ glib::ParamSpecBoolean::builder("playing").build(), glib::ParamSpecBoolean::builder("selected").build() ]; } impl ObjectImpl for SongWidget { fn properties() -> &'static [glib::ParamSpec] { &*PROPERTIES } fn set_property(&self, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec) { match pspec.name() { "playing" => { let is_playing = value .get() .expect("type conformity checked by `Object::set_property`"); if is_playing { self.obj().add_css_class(SONG_CLASS); } else { self.obj().remove_css_class(SONG_CLASS); } } "selected" => { let is_selected = value .get() .expect("type conformity checked by `Object::set_property`"); self.song_checkbox.set_active(is_selected); } _ => unimplemented!(), } } fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value { match pspec.name() { "playing" => self.obj().has_css_class(SONG_CLASS).to_value(), "selected" => self.song_checkbox.is_active().to_value(), _ => unimplemented!(), } } fn constructed(&self) { self.parent_constructed(); self.song_checkbox.set_sensitive(false); } fn dispose(&self) { while let Some(child) = self.obj().first_child() { child.unparent(); } } } impl WidgetImpl for SongWidget {} impl GridImpl for SongWidget {} } glib::wrapper! { pub struct SongWidget(ObjectSubclass<imp::SongWidget>) @extends gtk::Widget, gtk::Grid; } impl Default for SongWidget { fn default() -> Self { Self::new() } } impl SongWidget { pub fn new() -> Self { display_add_css_provider(resource!("/components/song.css")); glib::Object::new() } pub fn set_actions(&self, actions: Option<&gio::ActionGroup>) { self.insert_action_group("song", actions); } pub fn set_menu(&self, menu: Option<&MenuModel>) { if menu.is_some() { let widget = self.imp(); widget.menu_btn.set_menu_model(menu); widget.menu_btn.add_css_class("song__menu--enabled"); } } fn set_show_cover(&self, show_cover: bool) { let song_class = "song--cover"; if show_cover { self.add_css_class(song_class); } else { self.remove_css_class(song_class); } } fn set_image(&self, pixbuf: &gdk_pixbuf::Pixbuf) { let texture = gdk::Texture::for_pixbuf(pixbuf); self.imp().song_cover.set_paintable(Some(&texture)); } pub fn set_art(&self, model: &SongModel, worker: Worker) { if let Some(url) = model.description().art.clone() { let _self = self.downgrade(); worker.send_local_task(async move { if let Some(_self) = _self.upgrade() { let loader = ImageLoader::new(); let result = loader.load_remote(&url, "jpg", 100, 100).await; if let Some(pixbuf) = result.as_ref() { _self.set_image(pixbuf); } } }); } } pub fn bind(&self, model: &SongModel, worker: Worker, show_cover: bool) { let widget = self.imp(); model.bind_title(&*widget.song_title, "label"); model.bind_artist(&*widget.song_artist, "label"); model.bind_duration(&*widget.song_length, "label"); model.bind_playing(self, "playing"); model.bind_selected(self, "selected"); self.set_show_cover(show_cover); if show_cover { self.set_art(model, worker); } else { model.bind_index(&*widget.song_index, "label"); } } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/now_playing/now_playing_model.rs
src/app/components/now_playing/now_playing_model.rs
use gio::prelude::*; use gio::SimpleActionGroup; use std::ops::Deref; use std::rc::Rc; use crate::app::components::{ labels, DeviceSelectorModel, HeaderBarModel, PlaylistModel, SimpleHeaderBarModel, SimpleHeaderBarModelWrapper, }; use crate::app::models::{SongDescription, SongListModel}; use crate::app::state::Device; use crate::app::state::{ PlaybackAction, PlaybackState, SelectionAction, SelectionContext, SelectionState, }; use crate::app::{ActionDispatcher, AppAction, AppEvent, AppModel}; pub struct NowPlayingModel { app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>, } impl NowPlayingModel { pub fn new(app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self { Self { app_model, dispatcher, } } fn queue(&self) -> impl Deref<Target = PlaybackState> + '_ { self.app_model.map_state(|s| &s.playback) } pub fn load_more(&self) -> Option<()> { let queue = self.queue(); let loader = self.app_model.get_batch_loader(); let query = queue.next_query()?; debug!("next_query = {:?}", &query); self.dispatcher.dispatch_async(Box::pin(async move { loader .query(query, |source, song_batch| { PlaybackAction::LoadPagedSongs(source, song_batch).into() }) .await })); Some(()) } pub fn to_headerbar_model(self: &Rc<Self>) -> Rc<impl HeaderBarModel> { Rc::new(SimpleHeaderBarModelWrapper::new( self.clone(), self.app_model.clone(), self.dispatcher.box_clone(), )) } pub fn device_selector_model(&self) -> DeviceSelectorModel { DeviceSelectorModel::new(self.app_model.clone(), self.dispatcher.box_clone()) } fn current_selection_context(&self) -> SelectionContext { let state = self.app_model.get_state(); match state.playback.current_device() { Device::Local => SelectionContext::Queue, Device::Connect(_) => SelectionContext::ReadOnlyQueue, } } } impl PlaylistModel for NowPlayingModel { fn song_list_model(&self) -> SongListModel { self.queue().songs().clone() } fn is_paused(&self) -> bool { !self.app_model.get_state().playback.is_playing() } fn current_song_id(&self) -> Option<String> { self.queue().current_song_id() } fn play_song_at(&self, _pos: usize, id: &str) { self.dispatcher .dispatch(PlaybackAction::Load(id.to_string()).into()); } fn autoscroll_to_playing(&self) -> bool { false // too buggy for now } fn actions_for(&self, id: &str) -> Option<gio::ActionGroup> { let queue = self.queue(); let song = queue.songs().get(id)?; let song = song.description(); let group = SimpleActionGroup::new(); for view_artist in song.make_artist_actions(self.dispatcher.box_clone(), None) { group.add_action(&view_artist); } group.add_action(&song.make_album_action(self.dispatcher.box_clone(), None)); group.add_action(&song.make_link_action(None)); group.add_action(&song.make_dequeue_action(self.dispatcher.box_clone(), None)); Some(group.upcast()) } fn menu_for(&self, id: &str) -> Option<gio::MenuModel> { let queue = self.queue(); let song = queue.songs().get(id)?; let song = song.description(); let menu = gio::Menu::new(); menu.append(Some(&*labels::VIEW_ALBUM), Some("song.view_album")); for artist in song.artists.iter() { menu.append( Some(&labels::more_from_label(&artist.name)), Some(&format!("song.view_artist_{}", artist.id)), ); } menu.append(Some(&*labels::COPY_LINK), Some("song.copy_link")); menu.append(Some(&*labels::REMOVE_FROM_QUEUE), Some("song.dequeue")); Some(menu.upcast()) } fn select_song(&self, id: &str) { let queue = self.queue(); if let Some(song) = queue.songs().get(id) { let song = song.description().clone(); self.dispatcher .dispatch(SelectionAction::Select(vec![song]).into()); } } fn deselect_song(&self, id: &str) { self.dispatcher .dispatch(SelectionAction::Deselect(vec![id.to_string()]).into()); } fn enable_selection(&self) -> bool { self.dispatcher .dispatch(AppAction::EnableSelection(self.current_selection_context())); true } fn selection(&self) -> Option<Box<dyn Deref<Target = SelectionState> + '_>> { let selection = self.app_model.map_state(|s| &s.selection); Some(Box::new(selection)) } } impl SimpleHeaderBarModel for NowPlayingModel { fn title(&self) -> Option<String> { None } fn title_updated(&self, _: &AppEvent) -> bool { false } fn selection_context(&self) -> Option<SelectionContext> { Some(self.current_selection_context()) } fn select_all(&self) { let songs: Vec<SongDescription> = self.queue().songs().collect(); self.dispatcher .dispatch(SelectionAction::Select(songs).into()); } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/now_playing/mod.rs
src/app/components/now_playing/mod.rs
#[allow(clippy::module_inception)] mod now_playing; pub use now_playing::*; mod now_playing_model; pub use now_playing_model::*;
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/now_playing/now_playing.rs
src/app/components/now_playing/now_playing.rs
use gtk::prelude::*; use gtk::subclass::prelude::*; use gtk::CompositeTemplate; use std::rc::Rc; use super::NowPlayingModel; use crate::app::components::{ Component, DeviceSelector, DeviceSelectorWidget, EventListener, HeaderBarComponent, HeaderBarWidget, Playlist, }; use crate::app::state::PlaybackEvent; use crate::app::{AppEvent, Worker}; mod imp { use super::*; #[derive(Debug, Default, CompositeTemplate)] #[template(resource = "/dev/diegovsky/Riff/components/now_playing.ui")] pub struct NowPlayingWidget { #[template_child] pub song_list: TemplateChild<gtk::ListView>, #[template_child] pub headerbar: TemplateChild<HeaderBarWidget>, #[template_child] pub device_selector: TemplateChild<DeviceSelectorWidget>, #[template_child] pub scrolled_window: TemplateChild<gtk::ScrolledWindow>, } #[glib::object_subclass] impl ObjectSubclass for NowPlayingWidget { const NAME: &'static str = "NowPlayingWidget"; type Type = super::NowPlayingWidget; type ParentType = gtk::Box; fn class_init(klass: &mut Self::Class) { klass.bind_template(); } fn instance_init(obj: &glib::subclass::InitializingObject<Self>) { obj.init_template(); } } impl ObjectImpl for NowPlayingWidget {} impl WidgetImpl for NowPlayingWidget {} impl BoxImpl for NowPlayingWidget {} } glib::wrapper! { pub struct NowPlayingWidget(ObjectSubclass<imp::NowPlayingWidget>) @extends gtk::Widget, gtk::Box; } impl NowPlayingWidget { fn new() -> Self { glib::Object::new() } fn connect_bottom_edge<F>(&self, f: F) where F: Fn() + 'static, { self.imp() .scrolled_window .connect_edge_reached(move |_, pos| { if let gtk::PositionType::Bottom = pos { f() } }); } fn song_list_widget(&self) -> &gtk::ListView { self.imp().song_list.as_ref() } fn headerbar_widget(&self) -> &HeaderBarWidget { self.imp().headerbar.as_ref() } fn device_selector_widget(&self) -> &DeviceSelectorWidget { self.imp().device_selector.as_ref() } } pub struct NowPlaying { widget: NowPlayingWidget, model: Rc<NowPlayingModel>, children: Vec<Box<dyn EventListener>>, } impl NowPlaying { pub fn new(model: Rc<NowPlayingModel>, worker: Worker) -> Self { let widget = NowPlayingWidget::new(); widget.connect_bottom_edge(clone!( #[weak] model, move || { model.load_more(); } )); let playlist = Box::new(Playlist::new( widget.song_list_widget().clone(), model.clone(), worker, )); let headerbar_widget = widget.headerbar_widget(); let headerbar = Box::new(HeaderBarComponent::new( headerbar_widget.clone(), model.to_headerbar_model(), )); let device_selector = Box::new(DeviceSelector::new( widget.device_selector_widget().clone(), model.device_selector_model(), )); Self { widget, model, children: vec![playlist, headerbar, device_selector], } } } impl Component for NowPlaying { fn get_root_widget(&self) -> &gtk::Widget { self.widget.upcast_ref() } fn get_children(&mut self) -> Option<&mut Vec<Box<dyn EventListener>>> { Some(&mut self.children) } } impl EventListener for NowPlaying { fn on_event(&mut self, event: &AppEvent) { if let AppEvent::PlaybackEvent(PlaybackEvent::TrackChanged(_)) = event { self.model.load_more(); } self.broadcast_event(event); } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/user_details/mod.rs
src/app/components/user_details/mod.rs
#[allow(clippy::module_inception)] mod user_details; pub use user_details::*; mod user_details_model; pub use user_details_model::*;
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/user_details/user_details_model.rs
src/app/components/user_details/user_details_model.rs
use std::ops::Deref; use std::rc::Rc; use crate::app::models::*; use crate::app::state::BrowserAction; use crate::app::{ActionDispatcher, AppAction, AppModel, ListStore}; pub struct UserDetailsModel { pub id: String, app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>, } impl UserDetailsModel { pub fn new(id: String, app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self { Self { id, app_model, dispatcher, } } pub fn get_user_name(&self) -> Option<impl Deref<Target = String> + '_> { self.app_model .map_state_opt(|s| s.browser.user_state(&self.id)?.user.as_ref()) } pub fn get_list_store(&self) -> Option<impl Deref<Target = ListStore<AlbumModel>> + '_> { self.app_model .map_state_opt(|s| Some(&s.browser.user_state(&self.id)?.playlists)) } pub fn load_user_details(&self, id: String) { let api = self.app_model.get_spotify(); self.dispatcher .call_spotify_and_dispatch(move || async move { api.get_user(&id) .await .map(|user| BrowserAction::SetUserDetails(Box::new(user)).into()) }); } pub fn open_playlist(&self, id: String) { self.dispatcher.dispatch(AppAction::ViewPlaylist(id)); } pub fn load_more(&self) -> Option<()> { let api = self.app_model.get_spotify(); let state = self.app_model.get_state(); let next_page = &state.browser.user_state(&self.id)?.next_page; let id = next_page.data.clone(); let batch_size = next_page.batch_size; let offset = next_page.next_offset?; self.dispatcher .call_spotify_and_dispatch(move || async move { api.get_user_playlists(&id, offset, batch_size) .await .map(|playlists| BrowserAction::AppendUserPlaylists(id, playlists).into()) }); Some(()) } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/user_details/user_details.rs
src/app/components/user_details/user_details.rs
use gtk::prelude::*; use gtk::subclass::prelude::*; use gtk::CompositeTemplate; use std::rc::Rc; use crate::app::components::utils::wrap_flowbox_item; use crate::app::components::{display_add_css_provider, AlbumWidget, Component, EventListener}; use crate::app::{models::*, ListStore}; use crate::app::{AppEvent, BrowserEvent, Worker}; use super::UserDetailsModel; mod imp { use super::*; #[derive(Debug, Default, CompositeTemplate)] #[template(resource = "/dev/diegovsky/Riff/components/user_details.ui")] pub struct UserDetailsWidget { #[template_child] pub scrolled_window: TemplateChild<gtk::ScrolledWindow>, #[template_child] pub user_name: TemplateChild<gtk::Label>, #[template_child] pub user_playlists: TemplateChild<gtk::FlowBox>, } #[glib::object_subclass] impl ObjectSubclass for UserDetailsWidget { const NAME: &'static str = "UserDetailsWidget"; type Type = super::UserDetailsWidget; type ParentType = gtk::Box; fn class_init(klass: &mut Self::Class) { klass.bind_template(); } fn instance_init(obj: &glib::subclass::InitializingObject<Self>) { obj.init_template(); } } impl ObjectImpl for UserDetailsWidget {} impl WidgetImpl for UserDetailsWidget {} impl BoxImpl for UserDetailsWidget {} } glib::wrapper! { pub struct UserDetailsWidget(ObjectSubclass<imp::UserDetailsWidget>) @extends gtk::Widget, gtk::Box; } impl UserDetailsWidget { fn new() -> Self { display_add_css_provider(resource!("/components/user_details.css")); glib::Object::new() } fn set_user_name(&self, name: &str) { self.add_css_class("user__loaded"); self.imp().user_name.set_text(name); } fn connect_bottom_edge<F>(&self, f: F) where F: Fn() + 'static, { self.imp() .scrolled_window .connect_edge_reached(move |_, pos| { if let gtk::PositionType::Bottom = pos { f() } }); } fn bind_user_playlists<F>(&self, worker: Worker, store: &ListStore<AlbumModel>, on_pressed: F) where F: Fn(String) + Clone + 'static, { self.imp() .user_playlists .bind_model(Some(store.inner()), move |item| { wrap_flowbox_item(item, |item: &AlbumModel| { let f = on_pressed.clone(); let album = AlbumWidget::for_model(item, worker.clone()); album.connect_album_pressed(clone!( #[weak] item, move || { f(item.uri()); } )); album }) }); } } pub struct UserDetails { model: Rc<UserDetailsModel>, widget: UserDetailsWidget, } impl UserDetails { pub fn new(model: UserDetailsModel, worker: Worker) -> Self { model.load_user_details(model.id.clone()); let widget = UserDetailsWidget::new(); let model = Rc::new(model); widget.connect_bottom_edge(clone!( #[weak] model, move || { model.load_more(); } )); if let Some(store) = model.get_list_store() { widget.bind_user_playlists( worker, &store, clone!( #[weak] model, move |uri| { model.open_playlist(uri); } ), ); } Self { model, widget } } fn update_details(&self) { if let Some(name) = self.model.get_user_name() { self.widget.set_user_name(&name); } } } impl Component for UserDetails { fn get_root_widget(&self) -> &gtk::Widget { self.widget.as_ref() } } impl EventListener for UserDetails { fn on_event(&mut self, event: &AppEvent) { match event { AppEvent::BrowserEvent(BrowserEvent::UserDetailsUpdated(id)) if id == &self.model.id => { self.update_details(); } _ => {} } } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/models/mod.rs
src/app/models/mod.rs
// Domain models mod main; pub use main::*; // UI models (GObject) mod songs; pub use songs::*; mod album_model; pub use album_model::*; mod artist_model; pub use artist_model::*; impl From<&AlbumDescription> for AlbumModel { fn from(album: &AlbumDescription) -> Self { AlbumModel::new( &album.artists_name(), &album.title, album.year(), album.art.as_ref(), &album.id, ) } } impl From<AlbumDescription> for AlbumModel { fn from(album: AlbumDescription) -> Self { Self::from(&album) } } impl From<&PlaylistDescription> for AlbumModel { fn from(playlist: &PlaylistDescription) -> Self { AlbumModel::new( &playlist.owner.display_name, &playlist.title, // Playlists do not have their released date since they are expected to be updated anytime. None, playlist.art.as_ref(), &playlist.id, ) } } impl From<PlaylistDescription> for PlaylistSummary { fn from(PlaylistDescription { id, title, .. }: PlaylistDescription) -> Self { Self { id, title } } } impl From<PlaylistDescription> for AlbumModel { fn from(playlist: PlaylistDescription) -> Self { Self::from(&playlist) } } impl From<SongDescription> for SongModel { fn from(song: SongDescription) -> Self { SongModel::new(song) } } impl From<&SongDescription> for SongModel { fn from(song: &SongDescription) -> Self { SongModel::new(song.clone()) } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/models/main.rs
src/app/models/main.rs
use std::{ hash::{Hash, Hasher}, str::FromStr, }; use crate::app::SongsSource; // A batch of whatever #[derive(Clone, Copy, Debug)] pub struct Batch { // What offset does the batch start at pub offset: usize, // How many elements pub batch_size: usize, // Total number of elements if we had all batches pub total: usize, } impl Batch { pub fn first_of_size(batch_size: usize) -> Self { Self { offset: 0, batch_size, total: 0, } } pub fn next(self) -> Option<Self> { let Self { offset, batch_size, total, } = self; Some(Self { offset: offset + batch_size, batch_size, total, }) .filter(|b| b.offset < total) } } // "Something"Ref models usually boil down to an ID/url + a display name #[derive(Clone, Debug)] pub struct UserRef { pub id: String, pub display_name: String, } #[derive(Clone, Debug)] pub struct ArtistRef { pub id: String, pub name: String, } #[derive(Clone, Debug)] pub struct AlbumRef { pub id: String, pub name: String, } #[derive(Clone, Debug)] pub struct SearchResults { pub albums: Vec<AlbumDescription>, pub artists: Vec<ArtistSummary>, } #[derive(Clone, Debug)] pub struct AlbumDescription { pub id: String, pub title: String, pub artists: Vec<ArtistRef>, pub release_date: Option<String>, pub art: Option<String>, pub songs: SongBatch, pub is_liked: bool, } impl AlbumDescription { pub fn artists_name(&self) -> String { self.artists .iter() .map(|a| a.name.to_string()) .collect::<Vec<String>>() .join(", ") } pub fn year(&self) -> Option<u32> { self.release_date .as_ref() .and_then(|date| date.split('-').next()) .and_then(|y| u32::from_str(y).ok()) } } #[derive(Clone, Debug)] pub struct AlbumFullDescription { pub description: AlbumDescription, pub release_details: AlbumReleaseDetails, } #[derive(Clone, Debug)] pub struct AlbumReleaseDetails { pub label: String, pub copyright_text: String, pub total_tracks: usize, } #[derive(Clone, Debug)] pub struct PlaylistDescription { pub id: String, pub title: String, pub art: Option<String>, pub songs: SongBatch, pub owner: UserRef, } #[derive(Clone, Copy, Debug)] pub enum ConnectDeviceKind { Phone, Computer, Speaker, Other, } #[derive(Clone, Debug)] pub struct ConnectDevice { pub id: String, pub label: String, pub kind: ConnectDeviceKind, } #[derive(Clone, Debug)] pub struct PlaylistSummary { pub id: String, pub title: String, } #[derive(Clone, Debug)] pub struct SongDescription { pub id: String, pub track_number: Option<u32>, pub uri: String, pub title: String, pub artists: Vec<ArtistRef>, pub album: AlbumRef, pub duration: u32, pub art: Option<String>, } impl SongDescription { pub fn artists_name(&self) -> String { self.artists .iter() .map(|a| a.name.to_string()) .collect::<Vec<String>>() .join(", ") } } impl Hash for SongDescription { fn hash<H: Hasher>(&self, state: &mut H) { self.id.hash(state); } } #[derive(Copy, Clone, Default)] pub struct SongState { pub is_playing: bool, pub is_selected: bool, } // A batch of SONGS #[derive(Debug, Clone)] pub struct SongBatch { pub songs: Vec<SongDescription>, pub batch: Batch, } impl SongBatch { pub fn empty() -> Self { Self { songs: vec![], batch: Batch::first_of_size(1), } } pub fn resize(self, batch_size: usize) -> Vec<Self> { let SongBatch { mut songs, batch } = self; // Growing a batch is easy... if batch_size > batch.batch_size { let new_batch = Batch { batch_size, ..batch }; vec![Self { songs, batch: new_batch, }] // Shrinking is not! // We have to split the batch in multiple batches } else { let n = songs.len(); let iter_count = n.div_ceil(batch_size); (0..iter_count) .map(|i| { let offset = batch.offset + i * batch_size; let new_batch = Batch { offset, total: batch.total, batch_size, }; let drain_upper = usize::min(batch_size, songs.len()); let new_songs = songs.drain(0..drain_upper).collect(); Self { songs: new_songs, batch: new_batch, } }) .collect() } } } #[derive(Clone, Debug)] pub struct ArtistDescription { pub id: String, pub name: String, pub albums: Vec<AlbumDescription>, pub top_tracks: Vec<SongDescription>, } #[derive(Clone, Debug)] pub struct ArtistSummary { pub id: String, pub name: String, pub photo: Option<String>, } #[derive(Clone, Debug)] pub struct UserDescription { pub id: String, pub name: String, pub playlists: Vec<PlaylistDescription>, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RepeatMode { Song, Playlist, None, } #[derive(Clone, Debug)] pub struct ConnectPlayerState { pub is_playing: bool, #[allow(dead_code)] pub source: Option<SongsSource>, pub current_song_id: Option<String>, pub progress_ms: u32, pub repeat: RepeatMode, pub shuffle: bool, } impl Default for ConnectPlayerState { fn default() -> Self { Self { is_playing: false, source: None, current_song_id: None, progress_ms: 0, repeat: RepeatMode::None, shuffle: false, } } } #[cfg(test)] mod tests { use super::*; fn song(id: &str) -> SongDescription { SongDescription { id: id.to_string(), uri: "".to_string(), title: "Title".to_string(), artists: vec![], album: AlbumRef { id: "".to_string(), name: "".to_string(), }, duration: 1000, art: None, track_number: None, } } #[test] fn resize_batch() { let batch = SongBatch { songs: vec![song("1"), song("2"), song("3"), song("4")], batch: Batch::first_of_size(4), }; let batches = batch.resize(2); assert_eq!(batches.len(), 2); assert_eq!(&batches.get(0).unwrap().songs.get(0).unwrap().id, "1"); assert_eq!(&batches.get(1).unwrap().songs.get(0).unwrap().id, "3"); } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/models/artist_model.rs
src/app/models/artist_model.rs
#![allow(clippy::all)] use gio::prelude::*; use glib::subclass::prelude::*; use glib::Properties; // UI model! glib::wrapper! { pub struct ArtistModel(ObjectSubclass<imp::ArtistModel>); } impl ArtistModel { pub fn new(artist: &str, image: &Option<String>, id: &str) -> ArtistModel { glib::Object::builder() .property("artist", &artist) .property("image", image) .property("id", &id) .build() } } mod imp { use super::*; use std::cell::RefCell; #[derive(Default, Properties)] #[properties(wrapper_type = super::ArtistModel)] pub struct ArtistModel { #[property(get, set)] artist: RefCell<String>, #[property(get, set)] image: RefCell<Option<String>>, #[property(get, set)] id: RefCell<String>, } #[glib::object_subclass] impl ObjectSubclass for ArtistModel { const NAME: &'static str = "ArtistModel"; type Type = super::ArtistModel; type ParentType = glib::Object; } #[glib::derived_properties] impl ObjectImpl for ArtistModel {} }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/models/album_model.rs
src/app/models/album_model.rs
#![allow(clippy::all)] use gio::prelude::*; use glib::subclass::prelude::*; use glib::Properties; // UI model! // Despite the name, it can represent a playlist as well glib::wrapper! { pub struct AlbumModel(ObjectSubclass<imp::AlbumModel>); } impl AlbumModel { pub fn new( artist: &String, album: &String, year: Option<u32>, cover: Option<&String>, uri: &String, ) -> AlbumModel { let year = &year.unwrap_or(0); glib::Object::builder() .property("artist", artist) .property("album", album) .property("year", year) .property("cover", &cover) .property("uri", uri) .build() } } mod imp { use super::*; use std::cell::{Cell, RefCell}; #[derive(Default, Properties)] #[properties(wrapper_type = super::AlbumModel)] pub struct AlbumModel { #[property(get, set)] album: RefCell<String>, #[property(get, set)] artist: RefCell<String>, #[property(get, set)] year: Cell<u32>, #[property(get, set)] cover: RefCell<Option<String>>, #[property(get, set)] uri: RefCell<String>, } #[glib::object_subclass] impl ObjectSubclass for AlbumModel { const NAME: &'static str = "AlbumModel"; type Type = super::AlbumModel; type ParentType = glib::Object; } #[glib::derived_properties] impl ObjectImpl for AlbumModel {} }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/models/songs/support.rs
src/app/models/songs/support.rs
use std::collections::HashMap; use std::convert::{TryFrom, TryInto}; use crate::app::models::*; // A range of numbers [a, b], empty range is allowed as well #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Range { Empty, NotEmpty(u32, u32), } impl Range { // Create a range [a, b] if b >= a, or an empty range otherwise fn of(a: impl TryInto<u32>, b: impl TryInto<u32>) -> Self { match (a.try_into(), b.try_into()) { (Ok(a), Ok(b)) if b >= a => Self::NotEmpty(a, b), _ => Self::Empty, } } fn len(self) -> u32 { match self { Self::Empty => 0, Self::NotEmpty(a, b) => b - a + 1, } } fn union(self, other: Self) -> Self { match (self, other) { (Self::NotEmpty(a0, b0), Self::NotEmpty(a1, b1)) => { let start = u32::min(a0, a1); let end = u32::max(b0, b1); Self::NotEmpty(start, end) } (Self::Empty, r) | (r, Self::Empty) => r, } } fn offset_by(self, offset: i32) -> Self { match self { Self::Empty => Self::Empty, Self::NotEmpty(a, b) => Self::of((a as i32) + offset, (b as i32) + offset), } } // Start index of the range, if not an empty range fn start<Target>(self) -> Option<Target> where Target: TryFrom<u32>, { match self { Self::Empty => None, Self::NotEmpty(a, _) => Some(a.try_into().ok()?), } } } // Represents the range affected by an operation on the list // ListRangeUpdate(position, nb of elements added, nb of elements removed) #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ListRangeUpdate(pub i32, pub i32, pub i32); impl ListRangeUpdate { pub fn inserted(position: impl TryInto<i32>, added: impl TryInto<i32>) -> Self { Self( position.try_into().unwrap_or_default(), 0, added.try_into().unwrap_or_default(), ) } pub fn removed(position: impl TryInto<i32>, removed: impl TryInto<i32>) -> Self { Self( position.try_into().unwrap_or_default(), removed.try_into().unwrap_or_default(), 0, ) } pub fn updated(position: impl TryInto<i32>) -> Self { Self(position.try_into().unwrap_or_default(), 1, 1) } // Merge two range updates pub fn merge(self, other: Self) -> Self { // reorder for simplicity let (left, right) = if self.0 <= other.0 { (self, other) } else { (other, self) }; let Self(p0, r0, a0) = left; let Self(p1, r1, a1) = right; // range [s, e] affected by first update let ra0 = Range::of(p0, p0 + r0 - 1); // ...second update, but only the range affecting existing elements let ra1 = { let s1 = i32::max(p0 + a0, p1); let e1 = i32::max(s1 - 1, p1 + r1 - 1); Range::of(s1, e1) }; // remap to original let ra1 = ra1.offset_by(r0 - a0); // union let rau = ra0.union(ra1); let removed = rau.len() as i32; let position = rau.start().unwrap_or(p0); let added = removed - (r0 - a0) - (r1 - a1); Self(position, removed, added) } } // A list of songs that supports // - batch loading (with non contiguous batches if songs are accessed in random order) // - O(1) time access to a song by its id // - manually adding content (not batched), when managing a queue for instance // - tracking the affected range after a mutation // // Note: the mutated ranges are given in terms of LOADED tracks. The theoretical size of the list is not accounted for. // This is to ease the work of updating the UI: we want to know what loaded/visible elements have moved around. // // Some operations are not very efficient. It might have been smarter to have different structures for our two use cases: // - fixed, batched sources (an album, a playlist) // - editable lists (queue) #[derive(Clone, Debug)] pub struct SongList { total: usize, total_loaded: usize, batch_size: usize, last_batch_key: usize, // Here a batch has an index (key) and a list of associated song ids // Why not a Vec? We could have batch 1, 2, NOT 3, then 4 batches: HashMap<usize, Vec<String>>, indexed_songs: HashMap<String, SongModel>, } impl SongList { pub fn new_sized(batch_size: usize) -> Self { Self { total: 0, total_loaded: 0, batch_size, last_batch_key: 0, batches: Default::default(), indexed_songs: Default::default(), } } pub fn batch_size(&self) -> usize { self.batch_size } pub fn iter(&self) -> impl Iterator<Item = &SongModel> { let indexed_songs = &self.indexed_songs; self.iter_ids_from(0) .filter_map(move |(_, id)| indexed_songs.get(id)) } // How many songs we actually have at the moment pub fn partial_len(&self) -> usize { self.total_loaded } // How many songs are loaded, up to a given batch index fn estimated_len(&self, up_to_batch_index: usize) -> usize { let batches = &self.batches; let batch_size = self.batch_size; let batch_count = (0..up_to_batch_index) .filter(move |i| batches.contains_key(i)) .count(); batch_size * batch_count } // The theoretical len of the playlist, if we had all songs pub fn len(&self) -> usize { self.total } fn iter_ids_from(&self, i: usize) -> impl Iterator<Item = (usize, &'_ String)> { let batch_size = self.batch_size; let index = i / batch_size; self.iter_range(index, self.last_batch_key) .skip(i % batch_size) } // Find the position of a song in the list pub fn find_index(&self, song_id: &str) -> Option<usize> { self.iter_ids_from(0) .find(|(_, id)| &id[..] == song_id) .map(|(pos, _)| pos) } // Iterate over batches (in a given batch range), returning a tuple with the index of a song and its id fn iter_range(&self, a: usize, b: usize) -> impl Iterator<Item = (usize, &'_ String)> { let batch_size = self.batch_size; let batches = &self.batches; (a..=b) .filter_map(move |i| batches.get_key_value(&i)) .flat_map(move |(k, b)| { b.iter() .enumerate() .map(move |(i, id)| (i + *k * batch_size, id)) }) } // Add an id to our batches fn batches_add(batches: &mut HashMap<usize, Vec<String>>, batch_size: usize, id: &str) { let index = batches.len().saturating_sub(1); let count = batches .get(&index) .map(|b| b.len() % batch_size) .unwrap_or(0); // If there's no space in the last batch, we insert a new one if count == 0 { batches.insert(batches.len(), vec![id.to_string()]); } else { batches.get_mut(&index).unwrap().push(id.to_string()); } } pub fn clear(&mut self) -> ListRangeUpdate { let len = self.partial_len(); *self = Self::new_sized(self.batch_size); ListRangeUpdate::removed(0, len) } pub fn remove(&mut self, ids: &[String]) -> ListRangeUpdate { let len = self.total_loaded; let mut batches = HashMap::<usize, Vec<String>>::default(); self.iter_ids_from(0) .filter(|(_, s)| !ids.contains(s)) // Removing is expensive, we have to recreate all batches .for_each(|(_, next)| { Self::batches_add(&mut batches, self.batch_size, next); }); self.last_batch_key = batches.len().saturating_sub(1); self.batches = batches; let removed = ids.len(); self.total = self.total.saturating_sub(removed); self.total_loaded = self.total_loaded.saturating_sub(removed); // Lazy computation of the affected range, basically assume everything has changed ListRangeUpdate(0, len as i32, self.total_loaded as i32) } pub fn append(&mut self, songs: Vec<SongDescription>) -> ListRangeUpdate { let songs_len = songs.len(); // How many loaded/visible songs so far let insertion_start = self.estimated_len(self.last_batch_key + 1); self.total = self.total.saturating_add(songs_len); self.total_loaded = self.total_loaded.saturating_add(songs_len); for song in songs { Self::batches_add(&mut self.batches, self.batch_size, &song.id); self.indexed_songs .insert(song.id.clone(), SongModel::new(song)); } self.last_batch_key = self.batches.len().saturating_sub(1); ListRangeUpdate::inserted(insertion_start, songs_len) } pub fn prepend(&mut self, songs: Vec<SongDescription>) -> ListRangeUpdate { let songs_len = songs.len(); let insertion_start = 0; // Prepending also requires redoing all the batches let mut batches = HashMap::<usize, Vec<String>>::default(); for song in songs { Self::batches_add(&mut batches, self.batch_size, &song.id); self.indexed_songs .insert(song.id.clone(), SongModel::new(song)); } self.iter_ids_from(0).for_each(|(_, next)| { Self::batches_add(&mut batches, self.batch_size, next); }); self.total = self.total.saturating_add(songs_len); self.total_loaded = self.total_loaded.saturating_add(songs_len); self.last_batch_key = batches.len().saturating_sub(1); self.batches = batches; // But it's a bit easier to computer the visibly affected range :) ListRangeUpdate::inserted(insertion_start, songs_len) } // Adding a batch is easy, might only require a resize pub fn add(&mut self, song_batch: SongBatch) -> Option<ListRangeUpdate> { if song_batch.batch.batch_size != self.batch_size { song_batch .resize(self.batch_size) .into_iter() .map(|new_batch| { debug!("adding batch {:?}", &new_batch.batch); self.add_one(new_batch) }) .reduce(|acc, cur| { // If we have added more than one batch we just merge the affected ranges let merged = acc?.merge(cur?); Some(merged).or(acc).or(cur) }) .unwrap_or(None) } else { self.add_one(song_batch) } } fn add_one(&mut self, SongBatch { songs, batch }: SongBatch) -> Option<ListRangeUpdate> { assert_eq!(batch.batch_size, self.batch_size); let index = batch.offset / batch.batch_size; if self.batches.contains_key(&index) { debug!("batch already loaded"); return None; } let insertion_start = self.estimated_len(index); let len = songs.len(); let ids = songs .into_iter() .map(|song| { let song_id = song.id.clone(); self.indexed_songs .insert(song_id.clone(), SongModel::new(song)); song_id }) .collect(); self.batches.insert(index, ids); self.total = batch.total; self.total_loaded += len; self.last_batch_key = usize::max(self.last_batch_key, index); Some(ListRangeUpdate::inserted(insertion_start, len)) } fn index_mut(&mut self, i: usize) -> Option<&mut String> { let batch_size = self.batch_size; let i_batch = i / batch_size; self.batches .get_mut(&i_batch) .and_then(|s| s.get_mut(i % batch_size)) } pub fn swap(&mut self, a: usize, b: usize) -> Option<ListRangeUpdate> { if a == b { return None; } let a_value = self.index_mut(a).map(std::mem::take); let a_value = a_value.as_ref(); let new_a_value = self .index_mut(b) .and_then(|v| Some(std::mem::replace(v, a_value?.clone()))) .or_else(|| a_value.cloned()); let a_mut = self.index_mut(a); if let (Some(a_mut), Some(a_value)) = (a_mut, new_a_value) { *a_mut = a_value; } Some(ListRangeUpdate::updated(a).merge(ListRangeUpdate::updated(b))) } // Get the song at i (if the index is valid AND has been loaded) pub fn index(&self, i: usize) -> Option<&SongModel> { let batch_size = self.batch_size; let batch_id = i / batch_size; let indexed_songs = &self.indexed_songs; self.batches .get(&batch_id) .and_then(|batch| batch.get(i % batch_size)) .and_then(move |id| indexed_songs.get(id)) } // Get the i-th loaded song. VERY different! pub fn index_continuous(&self, i: usize) -> Option<&SongModel> { let batch_size = self.batch_size; let bi = i / batch_size; let batch = (0..=self.last_batch_key) // Skip missing/not loaded batches .filter_map(move |i| self.batches.get(&i)) .nth(bi)?; batch .get(i % batch_size) .and_then(move |id| self.indexed_songs.get(id)) } // Return the batch needed to access the song at index i (if it's not loaded yet) pub fn needed_batch_for(&self, i: usize) -> Option<Batch> { let total = self.total; let batch_size = self.batch_size; let batch_id = i / batch_size; if self.batches.contains_key(&batch_id) { None } else { Some(Batch { batch_size, total, offset: batch_id * batch_size, }) } } // Get the full song batch that contains i pub fn song_batch_for(&self, i: usize) -> Option<SongBatch> { let total = self.total; let batch_size = self.batch_size; let batch_id = i / batch_size; let indexed_songs = &self.indexed_songs; self.batches.get(&batch_id).map(|songs| SongBatch { songs: songs .iter() .filter_map(move |id| Some(indexed_songs.get(id)?.into_description())) .collect(), batch: Batch { batch_size, total, offset: batch_id * batch_size, }, }) } // The last loaded batch pub fn last_batch(&self) -> Option<Batch> { if self.total_loaded == 0 { None } else { Some(Batch { batch_size: self.batch_size, total: self.total, offset: self.last_batch_key * self.batch_size, }) } } pub fn get(&self, id: &str) -> Option<&SongModel> { self.indexed_songs.get(id) } } #[cfg(test)] mod tests { use super::*; const NO_CHANGE: ListRangeUpdate = ListRangeUpdate(0, 0, 0); impl SongList { fn new_from_initial_batch(initial: SongBatch) -> Self { let mut s = Self::new_sized(initial.batch.batch_size); s.add(initial); s } } fn song(id: &str) -> SongDescription { SongDescription { id: id.to_string(), uri: "".to_string(), title: "Title".to_string(), artists: vec![], album: AlbumRef { id: "".to_string(), name: "".to_string(), }, duration: 1000, art: None, track_number: None, } } fn batch(id: usize) -> SongBatch { let offset = id * 2; SongBatch { batch: Batch { offset, batch_size: 2, total: 10, }, songs: vec![ song(&format!("song{offset}")), song(&format!("song{}", offset + 1)), ], } } #[test] fn test_merge_range() { // [0, 1, 2, 3, 4, 5] let change1 = ListRangeUpdate(0, 4, 2); // [x, x, 4, 5] let change2 = ListRangeUpdate(1, 1, 2); // [x, y, y, 4, 5] assert_eq!(change1.merge(change2), ListRangeUpdate(0, 4, 3)); assert_eq!(change2.merge(change1), ListRangeUpdate(0, 4, 3)); // [0, 1, 2, 3, 4, 5, 6] let change1 = ListRangeUpdate(0, 2, 3); // [x, x, x, 2, 3, 4, 5, 6] let change2 = ListRangeUpdate(4, 1, 1); // [x, x, x, 2, y, 4, 5, 6] assert_eq!(change1.merge(change2), ListRangeUpdate(0, 4, 5)); assert_eq!(change2.merge(change1), ListRangeUpdate(0, 4, 5)); // [0, 1, 2, 3, 4, 5, 6] let change1 = ListRangeUpdate(0, 3, 2); // [x, x, 3, 4, 5, 6] let change2 = ListRangeUpdate(4, 1, 1); // [x, x, 3, 4, y, 6] assert_eq!(change1.merge(change2), ListRangeUpdate(0, 6, 5)); assert_eq!(change2.merge(change1), ListRangeUpdate(0, 6, 5)); // [0, 1, 2, 3, 4, 5] let change1 = ListRangeUpdate(0, 4, 2); // [x, x, 4, 5] let change2 = ListRangeUpdate(1, 1, 1); // [x, y, 4, 5] assert_eq!(change1.merge(change2), ListRangeUpdate(0, 4, 2)); assert_eq!(change2.merge(change1), ListRangeUpdate(0, 4, 2)); // [0, 1, 2, 3, 4, 5] let change1 = ListRangeUpdate(0, 4, 2); // [x, x, 4, 5] let change2 = ListRangeUpdate(0, 4, 2); // [y, y] assert_eq!(change1.merge(change2), ListRangeUpdate(0, 6, 2)); assert_eq!(change2.merge(change1), ListRangeUpdate(0, 6, 2)); // [] let change1 = ListRangeUpdate(0, 0, 2); // [x, x] let change2 = ListRangeUpdate(2, 0, 2); // [x, x, y, y] assert_eq!(change1.merge(change2), ListRangeUpdate(0, 0, 4)); assert_eq!(change2.merge(change1), ListRangeUpdate(0, 0, 4)); let change1 = ListRangeUpdate(0, 4, 2); assert_eq!(change1.merge(NO_CHANGE), ListRangeUpdate(0, 4, 2)); assert_eq!(NO_CHANGE.merge(change1), ListRangeUpdate(0, 4, 2)); } #[test] fn test_iter() { let list = SongList::new_from_initial_batch(batch(0)); let mut list_iter = list.iter(); assert_eq!(list_iter.next().unwrap().description().id, "song0"); assert_eq!(list_iter.next().unwrap().description().id, "song1"); assert!(list_iter.next().is_none()); } #[test] fn test_index() { let list = SongList::new_from_initial_batch(batch(0)); let song1 = list.index(1); assert!(song1.is_some()); let song3 = list.index(3); assert!(song3.is_none()); } #[test] fn test_add() { let mut list = SongList::new_from_initial_batch(batch(0)); list.add(batch(1)); let song3 = list.index(3); assert!(song3.is_some()); let list_iter = list.iter(); assert_eq!(list_iter.count(), 4); } #[test] fn test_add_with_range() { let mut list = SongList::new_from_initial_batch(batch(0)); let range = list.add(batch(1)); assert_eq!(range, Some(ListRangeUpdate::inserted(2, 2))); assert_eq!(list.partial_len(), 4); let range = list.add(batch(3)); assert_eq!(range, Some(ListRangeUpdate::inserted(4, 2))); assert_eq!(list.partial_len(), 6); let range = list.add(batch(2)); assert_eq!(range, Some(ListRangeUpdate::inserted(4, 2))); assert_eq!(list.partial_len(), 8); let range = list.add(batch(2)); assert_eq!(range, None); assert_eq!(list.partial_len(), 8); } #[test] fn test_find_non_contiguous() { let mut list = SongList::new_from_initial_batch(batch(0)); list.add(batch(3)); let index = list.find_index("song6"); assert_eq!(index, Some(6)); } #[test] fn test_iter_non_contiguous() { let mut list = SongList::new_from_initial_batch(batch(0)); list.add(batch(2)); assert_eq!(list.partial_len(), 4); let mut list_iter = list.iter(); assert_eq!(list_iter.next().unwrap().description().id, "song0"); assert_eq!(list_iter.next().unwrap().description().id, "song1"); assert_eq!(list_iter.next().unwrap().description().id, "song4"); assert_eq!(list_iter.next().unwrap().description().id, "song5"); assert!(list_iter.next().is_none()); } #[test] fn test_remove() { let mut list = SongList::new_from_initial_batch(batch(0)); list.add(batch(1)); list.remove(&["song0".to_string()]); assert_eq!(list.partial_len(), 3); let mut list_iter = list.iter(); assert_eq!(list_iter.next().unwrap().description().id, "song1"); assert_eq!(list_iter.next().unwrap().description().id, "song2"); assert_eq!(list_iter.next().unwrap().description().id, "song3"); assert!(list_iter.next().is_none()); } #[test] fn test_batch_for() { let mut list = SongList::new_from_initial_batch(batch(0)); list.add(batch(1)); list.add(batch(2)); list.add(batch(3)); assert_eq!(list.partial_len(), 8); let batch = list.song_batch_for(3); assert_eq!(batch.unwrap().batch.offset, 2); } #[test] fn test_append() { let mut list = SongList::new_from_initial_batch(batch(0)); list.append(vec![song("song2")]); list.append(vec![song("song3")]); list.append(vec![song("song4")]); let mut list_iter = list.iter(); assert_eq!(list_iter.next().unwrap().description().id, "song0"); assert_eq!(list_iter.next().unwrap().description().id, "song1"); assert_eq!(list_iter.next().unwrap().description().id, "song2"); assert_eq!(list_iter.next().unwrap().description().id, "song3"); assert_eq!(list_iter.next().unwrap().description().id, "song4"); assert!(list_iter.next().is_none()); } #[test] fn test_swap() { let mut list = SongList::new_sized(10); list.append(vec![song("song0"), song("song1"), song("song2")]); list.swap(0, 3); // should be a no-op list.swap(2, 3); // should be a no-op list.swap(0, 2); list.swap(0, 1); list.swap(2, 2); // should be no-op list.swap(2, 3); // should be no-op let mut list_iter = list.iter(); assert_eq!(list_iter.next().unwrap().description().id, "song1"); assert_eq!(list_iter.next().unwrap().description().id, "song2"); assert_eq!(list_iter.next().unwrap().description().id, "song0"); assert!(list_iter.next().is_none()); } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/models/songs/song_list_model.rs
src/app/models/songs/song_list_model.rs
use gio::prelude::*; use gio::ListModel; use glib::Properties; use gtk::subclass::prelude::*; use std::cell::{Cell, Ref, RefCell, RefMut}; use super::support::*; use crate::app::models::*; // A struct to perform multiple mutations on a SongListModel // Eventually commit() must be called to send an update signal with merged affected ranges #[must_use] pub struct SongListModelPending<'a> { change: Option<ListRangeUpdate>, song_list_model: &'a mut SongListModel, } impl<'a> SongListModelPending<'a> { fn new(change: Option<ListRangeUpdate>, song_list_model: &'a mut SongListModel) -> Self { Self { change, song_list_model, } } pub fn and<Op>(self, op: Op) -> Self where Op: FnOnce(&mut SongListModel) -> SongListModelPending<'_> + 'static, { let Self { change, song_list_model, } = self; let new_change = op(song_list_model).change; let merged_change = if let (Some(change), Some(new_change)) = (change, new_change) { Some(change.merge(new_change)) } else { change.or(new_change) }; Self { change: merged_change, song_list_model, } } pub fn commit(self) -> bool { let Self { change, song_list_model, } = self; song_list_model.notify_changes(change); change.is_some() } } // A GObject wrapper around the SongList glib::wrapper! { pub struct SongListModel(ObjectSubclass<imp::SongListModel>) @implements gio::ListModel; } impl SongListModel { pub fn new(batch_size: u32) -> Self { glib::Object::builder() .property("batch-size", batch_size) .build() } fn inner_mut(&mut self) -> RefMut<SongList> { self.imp().get_mut() } fn inner(&self) -> Ref<SongList> { self.imp().get() } fn notify_changes(&self, changes: impl IntoIterator<Item = ListRangeUpdate> + 'static) { // Eh, not great but that works if cfg!(not(test)) { glib::source::idle_add_local_once(clone!( #[weak(rename_to = s)] self, move || { for ListRangeUpdate(a, b, c) in changes.into_iter() { debug!("pos {}, removed {}, added {}", a, b, c); s.items_changed(a as u32, b as u32, c as u32); } } )); } } pub fn for_each<F>(&self, f: F) where F: Fn(usize, &SongModel), { for (i, song) in self.inner().iter().enumerate() { f(i, song); } } pub fn collect(&self) -> Vec<SongDescription> { self.inner().iter().map(|s| s.into_description()).collect() } pub fn map_collect<T>(&self, map: impl Fn(SongDescription) -> T) -> Vec<T> { self.inner() .iter() .map(|s| map(s.into_description())) .collect() } pub fn add(&mut self, song_batch: SongBatch) -> SongListModelPending { let range = self.inner_mut().add(song_batch); SongListModelPending::new(range, self) } pub fn get(&self, id: &str) -> Option<SongModel> { self.inner().get(id).cloned() } pub fn index(&self, i: usize) -> Option<SongModel> { self.inner().index(i).cloned() } pub fn index_continuous(&self, i: usize) -> Option<SongModel> { self.inner().index_continuous(i).cloned() } pub fn song_batch_for(&self, i: usize) -> Option<SongBatch> { self.inner().song_batch_for(i) } pub fn last_batch(&self) -> Option<Batch> { self.inner().last_batch() } pub fn needed_batch_for(&self, i: usize) -> Option<Batch> { self.inner().needed_batch_for(i) } pub fn partial_len(&self) -> usize { self.inner().partial_len() } pub fn len(&self) -> usize { self.inner().len() } pub fn append(&mut self, songs: Vec<SongDescription>) -> SongListModelPending { let range = self.inner_mut().append(songs); SongListModelPending::new(Some(range), self) } pub fn prepend(&mut self, songs: Vec<SongDescription>) -> SongListModelPending { let range = self.inner_mut().prepend(songs); SongListModelPending::new(Some(range), self) } pub fn find_index(&self, song_id: &str) -> Option<usize> { self.inner().find_index(song_id) } pub fn remove(&mut self, ids: &[String]) -> SongListModelPending { let change = self.inner_mut().remove(ids); SongListModelPending::new(Some(change), self) } pub fn move_down(&mut self, a: usize) -> SongListModelPending { let swap = self.inner_mut().swap(a + 1, a); SongListModelPending::new(swap, self) } pub fn move_up(&mut self, a: usize) -> SongListModelPending { let swap = self.inner_mut().swap(a - 1, a); SongListModelPending::new(swap, self) } pub fn clear(&mut self) -> SongListModelPending { let removed = self.inner_mut().clear(); SongListModelPending::new(Some(removed), self) } } mod imp { use super::*; #[derive(Default, Properties)] #[properties(wrapper_type = super::SongListModel)] pub struct SongListModel { #[property(get, set = Self::set_batch_size, name = "batch-size")] batch_size: Cell<u32>, song_list: RefCell<Option<SongList>>, } impl SongListModel { fn set_batch_size(&self, batch_size: u32) { self.batch_size.set(batch_size); self.song_list .replace(Some(SongList::new_sized(batch_size as usize))); } } #[glib::object_subclass] impl ObjectSubclass for SongListModel { const NAME: &'static str = "SongList"; type Type = super::SongListModel; type ParentType = glib::Object; type Interfaces = (ListModel,); } #[glib::derived_properties] impl ObjectImpl for SongListModel {} impl ListModelImpl for SongListModel { fn item_type(&self) -> glib::Type { SongModel::static_type() } fn n_items(&self) -> u32 { self.get().partial_len() as u32 } fn item(&self, position: u32) -> Option<glib::Object> { self.get() .index_continuous(position as usize) .map(|m| m.clone().upcast()) } } impl SongListModel { pub fn get_mut(&self) -> RefMut<SongList> { RefMut::map(self.song_list.borrow_mut(), |s| { s.as_mut().expect("set at construction") }) } pub fn get(&self) -> Ref<SongList> { Ref::map(self.song_list.borrow(), |s| { s.as_ref().expect("set at construction") }) } } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/models/songs/mod.rs
src/app/models/songs/mod.rs
// The underlying data structure for a list of songs mod support; // A GObject wrapper around that list mod song_list_model; pub use song_list_model::*; mod song_model; pub use song_model::*;
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/models/songs/song_model.rs
src/app/models/songs/song_model.rs
#![allow(clippy::all)] use gio::prelude::*; use glib::{subclass::prelude::*, SignalHandlerId}; use std::{cell::Ref, ops::Deref}; use crate::app::components::utils::format_duration; use crate::app::models::*; // UI model for a song glib::wrapper! { pub struct SongModel(ObjectSubclass<imp::SongModel>); } impl SongModel { pub fn new(song: SongDescription) -> Self { let o: Self = glib::Object::new(); o.imp().song.replace(Some(song)); o } pub fn set_playing(&self, is_playing: bool) { self.set_property("playing", is_playing); } pub fn set_selected(&self, is_selected: bool) { self.set_property("selected", is_selected); } pub fn get_playing(&self) -> bool { self.property("playing") } pub fn get_selected(&self) -> bool { self.property("selected") } pub fn get_id(&self) -> String { self.property("id") } pub fn bind_index(&self, o: &impl ObjectType, property: &str) { self.imp().push_binding( self.bind_property("index", o, property) .flags(glib::BindingFlags::DEFAULT | glib::BindingFlags::SYNC_CREATE) .build(), ); } pub fn bind_artist(&self, o: &impl ObjectType, property: &str) { self.imp().push_binding( self.bind_property("artist", o, property) .flags(glib::BindingFlags::DEFAULT | glib::BindingFlags::SYNC_CREATE) .build(), ); } pub fn bind_title(&self, o: &impl ObjectType, property: &str) { self.imp().push_binding( self.bind_property("title", o, property) .flags(glib::BindingFlags::DEFAULT | glib::BindingFlags::SYNC_CREATE) .build(), ); } pub fn bind_duration(&self, o: &impl ObjectType, property: &str) { self.imp().push_binding( self.bind_property("duration", o, property) .flags(glib::BindingFlags::DEFAULT | glib::BindingFlags::SYNC_CREATE) .build(), ); } pub fn bind_playing(&self, o: &impl ObjectType, property: &str) { self.imp().push_binding( self.bind_property("playing", o, property) .flags(glib::BindingFlags::DEFAULT | glib::BindingFlags::SYNC_CREATE) .build(), ); } pub fn bind_selected(&self, o: &impl ObjectType, property: &str) { self.imp().push_binding( self.bind_property("selected", o, property) .flags(glib::BindingFlags::DEFAULT | glib::BindingFlags::SYNC_CREATE) .build(), ); } pub fn unbind_all(&self) { self.imp().unbind_all(self); } pub fn description(&self) -> impl Deref<Target = SongDescription> + '_ { Ref::map(self.imp().song.borrow(), |s| { s.as_ref().expect("song set at constructor") }) } pub fn into_description(&self) -> SongDescription { self.imp() .song .borrow() .as_ref() .cloned() .expect("song set at constructor") } } mod imp { use super::*; use std::cell::{Cell, RefCell}; // Keep track of signals and bindings targeting this song #[derive(Default)] struct BindingsInner { pub signals: Vec<SignalHandlerId>, pub bindings: Vec<glib::Binding>, } #[derive(Default)] pub struct SongModel { pub song: RefCell<Option<SongDescription>>, pub state: Cell<SongState>, bindings: RefCell<BindingsInner>, } impl SongModel { pub fn push_signal(&self, id: SignalHandlerId) { self.bindings.borrow_mut().signals.push(id); } pub fn push_binding(&self, binding: glib::Binding) { self.bindings.borrow_mut().bindings.push(binding); } pub fn unbind_all<O: ObjectExt>(&self, o: &O) { let mut bindings = self.bindings.borrow_mut(); bindings.signals.drain(..).for_each(|s| o.disconnect(s)); bindings.bindings.drain(..).for_each(|b| b.unbind()); } } #[glib::object_subclass] impl ObjectSubclass for SongModel { const NAME: &'static str = "SongModel"; type Type = super::SongModel; type ParentType = glib::Object; } lazy_static! { static ref PROPERTIES: [glib::ParamSpec; 8] = [ glib::ParamSpecString::builder("id").read_only().build(), glib::ParamSpecUInt::builder("index").read_only().build(), glib::ParamSpecString::builder("title").read_only().build(), glib::ParamSpecString::builder("artist").read_only().build(), glib::ParamSpecString::builder("duration") .read_only() .build(), // URL glib::ParamSpecString::builder("art").read_only().build(), // Can be true when playback is paused; just means this is the current song glib::ParamSpecBoolean::builder("playing") .readwrite() .build(), glib::ParamSpecBoolean::builder("selected") .readwrite() .build(), ]; } impl ObjectImpl for SongModel { fn properties() -> &'static [glib::ParamSpec] { &*PROPERTIES } fn set_property(&self, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec) { match pspec.name() { "playing" => { let is_playing = value .get() .expect("type conformity checked by `Object::set_property`"); let SongState { is_selected, .. } = self.state.get(); self.state.set(SongState { is_playing, is_selected, }); } "selected" => { let is_selected = value .get() .expect("type conformity checked by `Object::set_property`"); let SongState { is_playing, .. } = self.state.get(); self.state.set(SongState { is_playing, is_selected, }); } _ => unimplemented!(), } } fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value { match pspec.name() { "index" => self .song .borrow() .as_ref() .expect("song set at constructor") .track_number .unwrap_or(1) .to_value(), "title" => self .song .borrow() .as_ref() .expect("song set at constructor") .title .to_value(), "artist" => self .song .borrow() .as_ref() .expect("song set at constructor") .artists_name() .to_value(), "id" => self .song .borrow() .as_ref() .expect("song set at constructor") .id .to_value(), "duration" => self .song .borrow() .as_ref() .map(|s| format_duration(s.duration.into())) .expect("song set at constructor") .to_value(), "art" => self .song .borrow() .as_ref() .expect("song set at constructor") .art .to_value(), "playing" => self.state.get().is_playing.to_value(), "selected" => self.state.get().is_selected.to_value(), _ => unimplemented!(), } } } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/api/api_models.rs
src/api/api_models.rs
use form_urlencoded::Serializer; use regex::Regex; use serde::{Deserialize, Serialize}; use std::{ collections::HashSet, convert::{Into, TryFrom, TryInto}, vec::IntoIter, }; use crate::app::{models::*, SongsSource}; #[derive(Serialize)] pub struct PlaylistDetails { pub name: String, } #[derive(Serialize)] pub struct Uris { pub uris: Vec<String>, } #[derive(Serialize)] pub struct PlayOffset { pub position: u32, } #[derive(Serialize)] #[serde(untagged)] pub enum PlayRequest { Contextual { context_uri: String, offset: PlayOffset, }, Uris { uris: Vec<String>, offset: PlayOffset, }, } #[derive(Serialize)] pub struct Ids { pub ids: Vec<String>, } #[derive(Serialize)] pub struct Name<'a> { pub name: &'a str, } pub enum SearchType { Artist, Album, } impl SearchType { fn into_string(self) -> &'static str { match self { Self::Artist => "artist", Self::Album => "album", } } } pub struct SearchQuery { pub query: String, pub types: Vec<SearchType>, pub limit: usize, pub offset: usize, } impl SearchQuery { pub fn into_query_string(self) -> String { let mut types = self .types .into_iter() .fold(String::new(), |acc, t| acc + t.into_string() + ","); types.pop(); let re = Regex::new(r"(\W|\s)+").unwrap(); let query = re.replace_all(&self.query[..], " "); let serialized = Serializer::new(String::new()) .append_pair("q", query.as_ref()) .append_pair("offset", &self.offset.to_string()[..]) .append_pair("limit", &self.limit.to_string()[..]) .append_pair("market", "from_token") .finish(); format!("type={types}&{serialized}") } } #[derive(Deserialize, Debug, Clone)] pub struct Page<T> { items: Option<Vec<T>>, offset: Option<usize>, limit: Option<usize>, total: usize, } impl<T> Page<T> { fn new(items: Vec<T>) -> Self { let l = items.len(); Self { total: l, items: Some(items), offset: Some(0), limit: Some(l), } } fn map<Mapper, U>(self, mapper: Mapper) -> Page<U> where Mapper: Fn(T) -> U, { let Page { items, offset, limit, total, } = self; Page { items: items.map(|item| item.into_iter().map(mapper).collect()), offset, limit, total, } } pub fn limit(&self) -> usize { self.limit .or_else(|| Some(self.items.as_ref()?.len())) .filter(|limit| *limit > 0) .unwrap_or(50) } pub fn total(&self) -> usize { self.total } pub fn offset(&self) -> usize { self.offset.unwrap_or(0) } } impl<T> IntoIterator for Page<T> { type Item = T; type IntoIter = IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.items.unwrap_or_default().into_iter() } } impl<T> Default for Page<T> { fn default() -> Self { Self { items: None, total: 0, offset: Some(0), limit: Some(0), } } } trait WithImages { fn images(&self) -> &[Image]; fn best_image<T: PartialOrd, F: Fn(&Image) -> T>(&self, criterion: F) -> Option<&Image> { let mut ords = self .images() .iter() .map(|image| (criterion(image), image)) .collect::<Vec<(T, &Image)>>(); ords.sort_by(|a, b| (a.0).partial_cmp(&b.0).unwrap()); Some(ords.first()?.1) } fn best_image_for_width(&self, width: i32) -> Option<&Image> { self.best_image(|i| (width - i.width.unwrap_or(0) as i32).abs()) } } #[derive(Deserialize, Debug, Clone)] pub struct Playlist { pub id: String, pub name: String, pub images: Option<Vec<Image>>, pub tracks: Page<PlaylistTrack>, pub owner: PlaylistOwner, } #[derive(Deserialize, Debug, Clone)] pub struct PlaylistOwner { pub id: String, pub display_name: String, } const EMPTY_IMAGE: &'static [Image] = &[Image { url: String::new(), height: Some(640), width: Some(640), }]; impl WithImages for Playlist { fn images(&self) -> &[Image] { match &self.images { Some(x) => &x[..], None => &EMPTY_IMAGE[..], } } } #[derive(Deserialize, Debug, Clone)] pub struct PlaylistTrack { pub is_local: bool, pub track: Option<FailibleTrackItem>, } #[derive(Deserialize, Debug, Clone)] pub struct SavedTrack { pub added_at: String, pub track: TrackItem, } #[derive(Deserialize, Debug, Clone)] pub struct SavedAlbum { pub album: Album, } #[derive(Deserialize, Debug, Clone)] pub struct FullAlbum { #[serde(flatten)] pub album: Album, #[serde(flatten)] pub album_info: AlbumInfo, } #[derive(Deserialize, Debug, Clone)] pub struct Album { pub id: String, pub tracks: Option<Page<AlbumTrackItem>>, pub artists: Vec<Artist>, pub release_date: Option<String>, pub name: String, pub images: Vec<Image>, } #[derive(Deserialize, Debug, Clone)] pub struct AlbumInfo { pub label: String, pub copyrights: Vec<Copyright>, pub total_tracks: u32, } #[derive(Deserialize, Debug, Clone)] pub struct Copyright { pub text: String, #[serde(alias = "type")] pub type_: char, } impl WithImages for Album { fn images(&self) -> &[Image] { &self.images[..] } } #[derive(Deserialize, Debug, Clone)] pub struct Image { pub url: String, pub height: Option<u32>, pub width: Option<u32>, } #[derive(Deserialize, Debug, Clone)] pub struct Artist { pub id: String, pub name: String, pub images: Option<Vec<Image>>, } impl WithImages for Artist { fn images(&self) -> &[Image] { #[allow(clippy::manual_unwrap_or_default)] if let Some(ref images) = self.images { images } else { &[] } } } #[derive(Deserialize, Debug, Clone)] pub struct User { pub id: String, pub display_name: String, } #[derive(Deserialize, Debug, Clone)] pub struct Device { #[serde(alias = "type")] pub type_: String, pub name: String, pub id: String, pub is_active: bool, pub is_restricted: bool, pub volume_percent: u32, } #[derive(Deserialize, Debug, Clone)] pub struct Devices { pub devices: Vec<Device>, } #[derive(Deserialize, Debug, Clone)] pub struct PlayerQueue { pub currently_playing: TrackItem, pub queue: Vec<TrackItem>, } #[derive(Deserialize, Debug, Clone)] pub struct PlayerContext { #[serde(alias = "type")] pub type_: String, pub uri: String, } #[derive(Deserialize, Debug, Clone)] pub struct PlayerState { pub progress_ms: u32, pub is_playing: bool, pub repeat_state: String, pub shuffle_state: bool, pub item: FailibleTrackItem, pub context: Option<PlayerContext>, } impl From<PlayerState> for ConnectPlayerState { fn from( PlayerState { progress_ms, is_playing, repeat_state, shuffle_state, item, context, }: PlayerState, ) -> Self { let repeat = match &repeat_state[..] { "track" => RepeatMode::Song, "context" => RepeatMode::Playlist, _ => RepeatMode::None, }; let source = context.and_then(|PlayerContext { type_, uri }| match type_.as_str() { "album" => { let id = uri.split(':').last().unwrap_or_default(); Some(SongsSource::Album(id.to_string())) } _ => None, }); let shuffle = shuffle_state; let current_song_id = item.get().map(|i| i.track.id); Self { is_playing, progress_ms, repeat, shuffle, source, current_song_id, } } } #[derive(Deserialize, Debug, Clone)] pub struct TopTracks { pub tracks: Vec<TrackItem>, } #[derive(Deserialize, Debug, Clone)] pub struct AlbumTrackItem { pub id: String, pub track_number: Option<usize>, pub uri: String, pub name: String, pub duration_ms: i64, pub artists: Vec<Artist>, } #[derive(Deserialize, Debug, Clone)] pub struct TrackItem { #[serde(flatten)] pub track: AlbumTrackItem, pub album: Album, } #[derive(Deserialize, Debug, Clone)] pub struct BadTrackItem {} #[derive(Deserialize, Debug, Clone)] #[serde(untagged)] pub enum FailibleTrackItem { Ok(Box<TrackItem>), Failing(BadTrackItem), } impl FailibleTrackItem { fn get(self) -> Option<TrackItem> { match self { Self::Ok(track) => Some(*track), Self::Failing(_) => None, } } } #[derive(Deserialize, Debug, Clone)] pub struct RawSearchResults { pub albums: Option<Page<Album>>, pub artists: Option<Page<Artist>>, } impl From<Artist> for ArtistSummary { fn from(artist: Artist) -> Self { let photo = artist.best_image_for_width(200).map(|i| &i.url).cloned(); let Artist { id, name, .. } = artist; Self { id, name, photo } } } impl TryFrom<PlaylistTrack> for TrackItem { type Error = (); fn try_from(PlaylistTrack { is_local, track }: PlaylistTrack) -> Result<Self, Self::Error> { track.ok_or(())?.get().filter(|_| !is_local).ok_or(()) } } impl From<SavedTrack> for TrackItem { fn from(track: SavedTrack) -> Self { track.track } } impl From<PlayerQueue> for Vec<SongDescription> { fn from( PlayerQueue { mut queue, currently_playing, }: PlayerQueue, ) -> Self { let mut ids = HashSet::<String>::new(); queue.insert(0, currently_playing); let queue: Vec<TrackItem> = queue .into_iter() .take_while(|e| { if ids.contains(&e.track.id) { false } else { ids.insert(e.track.id.clone()); true } }) .collect(); Page::new(queue).into() } } impl From<TopTracks> for Vec<SongDescription> { fn from(top_tracks: TopTracks) -> Self { Page::new(top_tracks.tracks).into() } } impl<T> From<Page<T>> for Vec<SongDescription> where T: TryInto<TrackItem>, { fn from(page: Page<T>) -> Self { SongBatch::from(page).songs } } impl From<(Page<AlbumTrackItem>, &Album)> for SongBatch { fn from(page_and_album: (Page<AlbumTrackItem>, &Album)) -> Self { let (page, album) = page_and_album; Self::from(page.map(|track| TrackItem { track, album: album.clone(), })) } } impl<T> From<Page<T>> for SongBatch where T: TryInto<TrackItem>, { fn from(page: Page<T>) -> Self { let batch = Batch { offset: page.offset(), batch_size: page.limit(), total: page.total(), }; let songs = page .into_iter() .filter_map(|t| { let TrackItem { track, album } = t.try_into().ok()?; let AlbumTrackItem { artists, id, uri, name, duration_ms, track_number, } = track; let artists = artists .into_iter() .map(|a| ArtistRef { id: a.id, name: a.name, }) .collect::<Vec<ArtistRef>>(); let art = album.best_image_for_width(200).map(|i| &i.url).cloned(); let Album { id: album_id, name: album_name, .. } = album; let album_ref = AlbumRef { id: album_id, name: album_name, }; Some(SongDescription { id, track_number: track_number.map(|u| u as u32), uri, title: name, artists, album: album_ref, duration: duration_ms as u32, art, }) }) .collect(); SongBatch { songs, batch } } } impl TryFrom<Album> for SongBatch { type Error = (); fn try_from(mut album: Album) -> Result<Self, Self::Error> { let tracks = album.tracks.take().ok_or(())?; Ok((tracks, &album).into()) } } impl From<FullAlbum> for AlbumFullDescription { fn from(full_album: FullAlbum) -> Self { let description = full_album.album.into(); let release_details = full_album.album_info.into(); Self { description, release_details, } } } impl From<Album> for AlbumDescription { fn from(album: Album) -> Self { let artists = album .artists .iter() .map(|a| ArtistRef { id: a.id.clone(), name: a.name.clone(), }) .collect::<Vec<ArtistRef>>(); let songs = album .clone() .try_into() .unwrap_or_else(|_| SongBatch::empty()); let art = album.best_image_for_width(200).map(|i| i.url.clone()); Self { id: album.id, title: album.name, artists, release_date: album.release_date, art, songs, is_liked: false, } } } impl From<AlbumInfo> for AlbumReleaseDetails { fn from( AlbumInfo { label, copyrights, total_tracks, }: AlbumInfo, ) -> Self { let copyright_text = copyrights .iter() .map(|Copyright { type_, text }| format!("[{type_}] {text}")) .collect::<Vec<String>>() .join(",\n "); Self { label, copyright_text, total_tracks: total_tracks as usize, } } } impl From<Playlist> for PlaylistDescription { fn from(playlist: Playlist) -> Self { let art = playlist.best_image_for_width(200).map(|i| i.url.clone()); let Playlist { id, name, tracks, owner, .. } = playlist; let PlaylistOwner { id: owner_id, display_name, } = owner; let song_batch = tracks.into(); PlaylistDescription { id, title: name, art, songs: song_batch, owner: UserRef { id: owner_id, display_name, }, } } } impl From<Device> for ConnectDevice { fn from( Device { id, name, type_, .. }: Device, ) -> Self { let kind = match type_.to_lowercase().as_str() { "smartphone" => ConnectDeviceKind::Phone, "computer" => ConnectDeviceKind::Computer, "speaker" => ConnectDeviceKind::Speaker, _ => ConnectDeviceKind::Other, }; Self { id, label: name, kind, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_playlist_track_null() { let track = r#"{"is_local": false, "track": null}"#; let deserialized: PlaylistTrack = serde_json::from_str(track).unwrap(); let track_item: Option<TrackItem> = deserialized.try_into().ok(); assert!(track_item.is_none()); } #[test] fn test_playlist_track_local() { let track = r#"{"is_local": true, "track": {"name": ""}}"#; let deserialized: PlaylistTrack = serde_json::from_str(track).unwrap(); let track_item: Option<TrackItem> = deserialized.try_into().ok(); assert!(track_item.is_none()); } #[test] fn test_playlist_track_ok() { let track = r#"{"is_local":false,"track":{"album":{"artists":[{"external_urls":{"spotify":""},"href":"","id":"","name":"","type":"artist","uri":""}],"id":"","images":[{"height":64,"url":"","width":64}],"name":""},"artists":[{"id":"","name":""}],"duration_ms":1,"id":"","name":"","uri":""}}"#; let deserialized: PlaylistTrack = serde_json::from_str(track).unwrap(); let track_item: Option<TrackItem> = deserialized.try_into().ok(); assert!(track_item.is_some()); } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/api/client.rs
src/api/client.rs
use form_urlencoded::Serializer; use isahc::config::Configurable; use isahc::http::{method::Method, request::Builder, StatusCode, Uri}; use isahc::{AsyncReadResponseExt, HttpClient, Request}; use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS}; use serde::{de::Deserialize, Serialize}; use serde_json::from_str; use std::convert::Into; use std::marker::PhantomData; use std::str::FromStr; use std::sync::Arc; use thiserror::Error; use crate::player::TokenStore; pub use super::api_models::*; use super::cache::CacheError; const SPOTIFY_HOST: &str = "api.spotify.com"; // https://url.spec.whatwg.org/#path-percent-encode-set const PATH_ENCODE_SET: &AsciiSet = &CONTROLS .add(b' ') .add(b'"') .add(b'#') .add(b'<') .add(b'>') .add(b'?') .add(b'`') .add(b'{') .add(b'}'); fn make_query_params<'a>() -> Serializer<'a, String> { Serializer::new(String::new()) } pub(crate) struct SpotifyRequest<'a, Body, Response> { client: &'a SpotifyClient, request: Builder, body: Body, _type: PhantomData<Response>, } impl<'a, B, R> SpotifyRequest<'a, B, R> where B: Into<isahc::AsyncBody>, { fn method(mut self, method: Method) -> Self { self.request = self.request.method(method); self } fn uri(mut self, path: String, query: Option<&str>) -> Self { let path_and_query = match query { None => path, Some(query) => format!("{path}?{query}"), }; let uri = Uri::builder() .scheme("https") .authority(SPOTIFY_HOST) .path_and_query(&path_and_query[..]) .build() .unwrap(); self.request = self.request.uri(uri); self } fn authenticated(mut self) -> Result<Self, SpotifyApiError> { let token = self.client.token_store.get_cached_blocking(); let token = token.as_ref().ok_or(SpotifyApiError::NoToken)?; self.request = self .request .header("Authorization", format!("Bearer {}", token.access_token)); Ok(self) } pub(crate) fn etag(mut self, etag: Option<String>) -> Self { if let Some(etag) = etag { self.request = self.request.header("If-None-Match", etag); } self } pub(crate) fn json_body<NewBody>(self, body: NewBody) -> SpotifyRequest<'a, Vec<u8>, R> where NewBody: Serialize, { let Self { client, request, _type, .. } = self; SpotifyRequest { client, request: request.header("Content-Type", "application/json"), body: serde_json::to_vec(&body).unwrap(), _type, } } pub(crate) async fn send(self) -> Result<SpotifyResponse<R>, SpotifyApiError> { let Self { client, request, body, .. } = self.authenticated()?; client.send_req(request.body(body).unwrap()).await } pub(crate) async fn send_no_response(self) -> Result<(), SpotifyApiError> { let Self { client, request, body, .. } = self.authenticated()?; client .send_req_no_response(request.body(body).unwrap()) .await } } pub(crate) enum SpotifyResponseKind<T> { Ok(String, PhantomData<T>), NotModified, } pub(crate) struct SpotifyResponse<T> { pub kind: SpotifyResponseKind<T>, pub max_age: u64, pub etag: Option<String>, } impl<'a, T> SpotifyResponse<T> where T: Deserialize<'a>, { pub(crate) fn deserialize(&'a self) -> Option<T> { if let SpotifyResponseKind::Ok(ref content, _) = self.kind { from_str(content) .map_err(|e| error!("Deserialization failed: {}", e)) .ok() } else { None } } } #[derive(Error, Debug)] pub enum SpotifyApiError { #[error("Invalid token")] InvalidToken, #[error("No token")] NoToken, #[error("No content from request")] NoContent, #[error("Request rate exceeded")] TooManyRequests, #[error("Request failed ({0}): {1}")] BadStatus(u16, String), #[error(transparent)] ClientError(#[from] isahc::Error), #[error(transparent)] IoError(#[from] std::io::Error), #[error(transparent)] CacheError(#[from] CacheError), #[error(transparent)] ParseError(#[from] serde_json::Error), #[error(transparent)] ConversionError(#[from] std::string::FromUtf8Error), } pub(crate) struct SpotifyClient { token_store: Arc<TokenStore>, client: HttpClient, } impl SpotifyClient { pub(crate) fn new(token_store: Arc<TokenStore>) -> Self { let mut builder = HttpClient::builder(); if cfg!(debug_assertions) { builder = builder.ssl_options(isahc::config::SslOption::DANGER_ACCEPT_INVALID_CERTS); } let client = builder.build().unwrap(); Self { token_store, client, } } pub(crate) fn request<T>(&self) -> SpotifyRequest<'_, (), T> { SpotifyRequest { client: self, request: Builder::new(), body: (), _type: PhantomData, } } pub(crate) fn has_token(&self) -> bool { self.token_store.get_cached_blocking().is_some() } fn parse_cache_control(cache_control: &str) -> Option<u64> { cache_control .split(',') .find(|s| s.trim().starts_with("max-age=")) .and_then(|s| s.split('=').nth(1)) .and_then(|s| u64::from_str(s).ok()) } async fn send_req<B, T>( &self, request: Request<B>, ) -> Result<SpotifyResponse<T>, SpotifyApiError> where B: Into<isahc::AsyncBody>, { let mut result = self.client.send_async(request).await?; let etag = result .headers() .get("etag") .and_then(|header| header.to_str().ok()) .map(|s| s.to_owned()); let cache_control = result .headers() .get("cache-control") .and_then(|header| header.to_str().ok()) .and_then(Self::parse_cache_control); match result.status() { StatusCode::NO_CONTENT => Err(SpotifyApiError::NoContent), s if s.is_success() => Ok(SpotifyResponse { kind: SpotifyResponseKind::Ok(result.text().await?, PhantomData), max_age: cache_control.unwrap_or(10), etag, }), StatusCode::UNAUTHORIZED => Err(SpotifyApiError::InvalidToken), StatusCode::TOO_MANY_REQUESTS => Err(SpotifyApiError::TooManyRequests), StatusCode::NOT_MODIFIED => Ok(SpotifyResponse { kind: SpotifyResponseKind::NotModified, max_age: cache_control.unwrap_or(10), etag, }), s => Err(SpotifyApiError::BadStatus( s.as_u16(), result .text() .await .unwrap_or_else(|_| "(no details available)".to_string()), )), } } async fn send_req_no_response<B>(&self, request: Request<B>) -> Result<(), SpotifyApiError> where B: Into<isahc::AsyncBody>, { let mut result = self.client.send_async(request).await?; match result.status() { StatusCode::UNAUTHORIZED => Err(SpotifyApiError::InvalidToken), StatusCode::TOO_MANY_REQUESTS => Err(SpotifyApiError::TooManyRequests), StatusCode::NOT_MODIFIED => Ok(()), s if s.is_success() => Ok(()), s => Err(SpotifyApiError::BadStatus( s.as_u16(), result .text() .await .unwrap_or_else(|_| "(no details available)".to_string()), )), } } } impl SpotifyClient { pub(crate) fn get_artist(&self, id: &str) -> SpotifyRequest<'_, (), Artist> { self.request() .method(Method::GET) .uri(format!("/v1/artists/{id}"), None) } pub(crate) fn get_artist_albums( &self, id: &str, offset: usize, limit: usize, ) -> SpotifyRequest<'_, (), Page<Album>> { let query = make_query_params() .append_pair("include_groups", "album,single") .append_pair("country", "from_token") .append_pair("offset", &offset.to_string()[..]) .append_pair("limit", &limit.to_string()[..]) .finish(); self.request() .method(Method::GET) .uri(format!("/v1/artists/{id}/albums"), Some(&query)) } pub(crate) fn get_artist_top_tracks(&self, id: &str) -> SpotifyRequest<'_, (), TopTracks> { let query = make_query_params() .append_pair("market", "from_token") .finish(); self.request() .method(Method::GET) .uri(format!("/v1/artists/{id}/top-tracks"), Some(&query)) } pub(crate) fn is_album_saved(&self, id: &str) -> SpotifyRequest<'_, (), Vec<bool>> { let query = make_query_params().append_pair("ids", id).finish(); self.request() .method(Method::GET) .uri("/v1/me/albums/contains".to_string(), Some(&query)) } pub(crate) fn save_album(&self, id: &str) -> SpotifyRequest<'_, (), ()> { let query = make_query_params().append_pair("ids", id).finish(); self.request() .method(Method::PUT) .uri("/v1/me/albums".to_string(), Some(&query)) } pub(crate) fn save_tracks(&self, ids: Vec<String>) -> SpotifyRequest<'_, Vec<u8>, ()> { self.request() .method(Method::PUT) .uri("/v1/me/tracks".to_string(), None) .json_body(Ids { ids }) } pub(crate) fn remove_saved_album(&self, id: &str) -> SpotifyRequest<'_, (), ()> { let query = make_query_params().append_pair("ids", id).finish(); self.request() .method(Method::DELETE) .uri("/v1/me/albums".to_string(), Some(&query)) } pub(crate) fn remove_saved_tracks(&self, ids: Vec<String>) -> SpotifyRequest<'_, Vec<u8>, ()> { self.request() .method(Method::DELETE) .uri("/v1/me/tracks".to_string(), None) .json_body(Ids { ids }) } pub(crate) fn get_album(&self, id: &str) -> SpotifyRequest<'_, (), FullAlbum> { self.request() .method(Method::GET) .uri(format!("/v1/albums/{id}"), None) } pub(crate) fn get_album_tracks( &self, id: &str, offset: usize, limit: usize, ) -> SpotifyRequest<'_, (), Page<AlbumTrackItem>> { let query = make_query_params() .append_pair("offset", &offset.to_string()[..]) .append_pair("limit", &limit.to_string()[..]) .finish(); self.request() .method(Method::GET) .uri(format!("/v1/albums/{id}/tracks"), Some(&query)) } pub(crate) fn get_playlist(&self, id: &str) -> SpotifyRequest<'_, (), Playlist> { let query = make_query_params() .append_pair("market", "from_token") // why still grab the tracks field? // the model still expects the appearance of a tracks field .append_pair("fields", "id,name,images,owner,tracks(total)") .finish(); self.request() .method(Method::GET) .uri(format!("/v1/playlists/{id}"), Some(&query)) } pub(crate) fn get_playlist_tracks( &self, id: &str, offset: usize, limit: usize, ) -> SpotifyRequest<'_, (), Page<PlaylistTrack>> { let query = make_query_params() .append_pair("market", "from_token") .append_pair("offset", &offset.to_string()[..]) .append_pair("limit", &limit.to_string()[..]) .finish(); self.request() .method(Method::GET) .uri(format!("/v1/playlists/{id}/tracks"), Some(&query)) } pub(crate) fn add_to_playlist( &self, playlist: &str, uris: Vec<String>, ) -> SpotifyRequest<'_, Vec<u8>, ()> { self.request() .method(Method::POST) .uri(format!("/v1/playlists/{playlist}/tracks"), None) .json_body(Uris { uris }) } pub(crate) fn create_new_playlist( &self, name: &str, user_id: &str, ) -> SpotifyRequest<'_, Vec<u8>, Playlist> { self.request() .method(Method::POST) .uri(format!("/v1/users/{user_id}/playlists"), None) .json_body(Name { name }) } pub(crate) fn remove_from_playlist( &self, playlist: &str, uris: Vec<String>, ) -> SpotifyRequest<'_, Vec<u8>, ()> { self.request() .method(Method::DELETE) .uri(format!("/v1/playlists/{playlist}/tracks"), None) .json_body(Uris { uris }) } pub(crate) fn update_playlist_details( &self, playlist: &str, name: String, ) -> SpotifyRequest<'_, Vec<u8>, ()> { self.request() .method(Method::PUT) .uri(format!("/v1/playlists/{playlist}"), None) .json_body(PlaylistDetails { name }) } pub(crate) fn get_saved_albums( &self, offset: usize, limit: usize, ) -> SpotifyRequest<'_, (), Page<SavedAlbum>> { let query = make_query_params() .append_pair("offset", &offset.to_string()[..]) .append_pair("limit", &limit.to_string()[..]) .finish(); self.request() .method(Method::GET) .uri("/v1/me/albums".to_string(), Some(&query)) } pub(crate) fn get_saved_tracks( &self, offset: usize, limit: usize, ) -> SpotifyRequest<'_, (), Page<SavedTrack>> { let query = make_query_params() .append_pair("offset", &offset.to_string()[..]) .append_pair("limit", &limit.to_string()[..]) .finish(); self.request() .method(Method::GET) .uri("/v1/me/tracks".to_string(), Some(&query)) } pub(crate) fn get_saved_playlists( &self, offset: usize, limit: usize, ) -> SpotifyRequest<'_, (), Page<Playlist>> { let query = make_query_params() .append_pair("offset", &offset.to_string()[..]) .append_pair("limit", &limit.to_string()[..]) .finish(); self.request() .method(Method::GET) .uri("/v1/me/playlists".to_string(), Some(&query)) } pub(crate) fn search( &self, query: String, offset: usize, limit: usize, ) -> SpotifyRequest<'_, (), RawSearchResults> { let query = SearchQuery { query, types: vec![SearchType::Album, SearchType::Artist], limit, offset, }; self.request() .method(Method::GET) .uri("/v1/search".to_string(), Some(&query.into_query_string())) } pub(crate) fn get_user(&self, id: &str) -> SpotifyRequest<'_, (), User> { let id = utf8_percent_encode(id, PATH_ENCODE_SET); self.request() .method(Method::GET) .uri(format!("/v1/users/{id}"), None) } pub(crate) fn get_user_playlists( &self, id: &str, offset: usize, limit: usize, ) -> SpotifyRequest<'_, (), Page<Playlist>> { let id = utf8_percent_encode(id, PATH_ENCODE_SET); let query = make_query_params() .append_pair("offset", &offset.to_string()[..]) .append_pair("limit", &limit.to_string()[..]) .finish(); self.request() .method(Method::GET) .uri(format!("/v1/users/{id}/playlists"), Some(&query)) } pub(crate) fn get_player_devices(&self) -> SpotifyRequest<'_, (), Devices> { self.request() .method(Method::GET) .uri("/v1/me/player/devices".to_string(), None) } pub(crate) fn get_player_queue(&self) -> SpotifyRequest<'_, (), PlayerQueue> { self.request() .method(Method::GET) .uri("/v1/me/player/queue".to_string(), None) } pub(crate) fn player_state(&self) -> SpotifyRequest<'_, (), PlayerState> { self.request() .method(Method::GET) .uri("/v1/me/player".to_string(), None) } pub(crate) fn player_resume(&self, device_id: &str) -> SpotifyRequest<'_, (), ()> { let query = make_query_params() .append_pair("device_id", device_id) .finish(); self.request() .method(Method::PUT) .uri("/v1/me/player/play".to_string(), Some(&query)) } pub(crate) fn player_set_playing( &self, device_id: &str, request: PlayRequest, ) -> SpotifyRequest<'_, Vec<u8>, ()> { let query = make_query_params() .append_pair("device_id", device_id) .finish(); self.request() .method(Method::PUT) .uri("/v1/me/player/play".to_string(), Some(&query)) .json_body(request) } pub(crate) fn player_pause(&self, device_id: &str) -> SpotifyRequest<'_, (), ()> { let query = make_query_params() .append_pair("device_id", device_id) .finish(); self.request() .method(Method::PUT) .uri("/v1/me/player/pause".to_string(), Some(&query)) } pub(crate) fn player_next(&self, device_id: &str) -> SpotifyRequest<'_, (), ()> { let query = make_query_params() .append_pair("device_id", device_id) .finish(); self.request() .method(Method::PUT) .uri("/v1/me/player/next".to_string(), Some(&query)) } pub(crate) fn player_seek(&self, device_id: &str, pos: usize) -> SpotifyRequest<'_, (), ()> { let query = make_query_params() .append_pair("device_id", device_id) .append_pair("position_ms", &pos.to_string()[..]) .finish(); self.request() .method(Method::PUT) .uri("/v1/me/player/seek".to_string(), Some(&query)) } pub(crate) fn player_repeat(&self, device_id: &str, state: &str) -> SpotifyRequest<'_, (), ()> { let query = make_query_params() .append_pair("device_id", device_id) .append_pair("state", state) .finish(); self.request() .method(Method::PUT) .uri("/v1/me/player/repeat".to_string(), Some(&query)) } pub(crate) fn player_shuffle( &self, device_id: &str, shuffle: bool, ) -> SpotifyRequest<'_, (), ()> { let query = make_query_params() .append_pair("device_id", device_id) .append_pair("state", if shuffle { "true" } else { "false" }) .finish(); self.request() .method(Method::PUT) .uri("/v1/me/player/shuffle".to_string(), Some(&query)) } pub(crate) fn player_volume(&self, device_id: &str, volume: u8) -> SpotifyRequest<'_, (), ()> { let query = make_query_params() .append_pair("device_id", device_id) .append_pair("volume_percent", &volume.to_string()) .finish(); self.request() .method(Method::PUT) .uri("/v1/me/player/volume".to_string(), Some(&query)) } } #[cfg(test)] pub mod tests { use super::*; #[test] fn test_username_encoding() { let username = "anna.lafuente❤"; let client = SpotifyClient::new(Arc::new(TokenStore::new())); let req = client.get_user(username); assert_eq!( req.request .uri_ref() .and_then(|u| u.path_and_query()) .unwrap() .as_str(), "/v1/users/anna.lafuente%E2%9D%A4" ); } #[test] fn test_search_query() { let query = SearchQuery { query: "test".to_string(), types: vec![SearchType::Album, SearchType::Artist], limit: 5, offset: 0, }; assert_eq!( query.into_query_string(), "type=album,artist&q=test&offset=0&limit=5&market=from_token" ); } #[test] fn test_search_query_spaces_and_stuff() { let query = SearchQuery { query: "test??? wow".to_string(), types: vec![SearchType::Album], limit: 5, offset: 0, }; assert_eq!( query.into_query_string(), "type=album&q=test+wow&offset=0&limit=5&market=from_token" ); } #[test] fn test_search_query_encoding() { let query = SearchQuery { query: "кириллица".to_string(), types: vec![SearchType::Album], limit: 5, offset: 0, }; assert_eq!(query.into_query_string(), "type=album&q=%D0%BA%D0%B8%D1%80%D0%B8%D0%BB%D0%BB%D0%B8%D1%86%D0%B0&offset=0&limit=5&market=from_token"); } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/api/mod.rs
src/api/mod.rs
mod api_models; mod cached_client; mod client; pub mod cache; pub use cached_client::{CachedSpotifyClient, SpotifyApiClient, SpotifyResult}; pub use client::SpotifyApiError; pub async fn clear_user_cache() -> Option<()> { cache::CacheManager::for_dir("riff/net")? .clear_cache_pattern(&cached_client::USER_CACHE) .await .ok() }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/api/cache.rs
src/api/cache.rs
use core::mem::size_of; use futures::join; use regex::Regex; use std::path::{PathBuf,Path}; use std::convert::From; use std::future::Future; use std::time::{Duration, SystemTime}; use tokio::{fs, io}; use thiserror::Error; const EXPIRY_FILE_EXT: &str = ".expiry"; #[derive(Error, Debug)] pub enum CacheError { #[error("No content available")] NoContent, #[error("File could not be saved to cache: {0}")] WriteError(std::io::Error), #[error("File could not be read from cache: {0}")] ReadError(std::io::Error), #[error("File could not be removed from cache: {0}")] RemoveError(std::io::Error), #[error(transparent)] ConversionError(#[from] std::string::FromUtf8Error), } pub type ETag = String; pub enum CacheFile { Fresh(Vec<u8>), Expired(Vec<u8>, Option<ETag>), None, } #[derive(PartialEq, Clone, Copy, Debug)] pub enum CachePolicy { Default, // query remote cache when stale IgnoreExpiry, // always use cached value Revalidate, // always query remote cache IgnoreCached, // ignore cache alltogether } #[derive(PartialEq, Clone, Debug)] pub enum CacheExpiry { Never, AtUnixTimestamp(Duration, Option<ETag>), } impl CacheExpiry { pub fn expire_in_seconds(seconds: u64, etag: Option<ETag>) -> Self { let timestamp = SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap(); Self::AtUnixTimestamp(timestamp + Duration::new(seconds, 0), etag) } fn is_expired(&self) -> bool { match self { Self::Never => false, Self::AtUnixTimestamp(ref duration, _) => { let now = &SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap(); now > duration } } } fn etag(&self) -> Option<&String> { match self { Self::Never => None, Self::AtUnixTimestamp(_, ref etag) => etag.as_ref(), } } } #[derive(Clone)] pub struct CacheManager { root: PathBuf, } impl CacheManager { pub fn for_dir(dir: &str) -> Option<Self> { let root: PathBuf = glib::user_cache_dir().into(); let root = root.join(dir); let mask = 0o744; glib::mkdir_with_parents(&root, mask); Some(Self { root }) } fn cache_path(&self, resource: &str) -> PathBuf { self.root.join(resource) } fn cache_meta_path(&self, resource: &str) -> PathBuf { let full = resource.to_string() + EXPIRY_FILE_EXT; self.root.join(full) } } impl CacheManager { async fn read_expiry_file(&self, resource: &str) -> Result<CacheExpiry, CacheError> { let expiry_file = self.cache_meta_path(resource); match fs::read(&expiry_file).await { Err(e) => match e.kind() { io::ErrorKind::NotFound => Ok(CacheExpiry::Never), _ => Err(CacheError::ReadError(e)), }, Ok(buffer) => { const OFFSET: usize = size_of::<u64>(); let mut duration: [u8; OFFSET] = Default::default(); duration.copy_from_slice(&buffer[..OFFSET]); let duration = Duration::from_secs(u64::from_be_bytes(duration)); let etag = String::from_utf8(buffer[OFFSET..].to_vec()).ok(); Ok(CacheExpiry::AtUnixTimestamp(duration, etag)) } } } pub async fn read_cache_file( &self, resource: &str, policy: CachePolicy, ) -> Result<CacheFile, CacheError> { if matches!(policy, CachePolicy::IgnoreCached) { return Ok(CacheFile::None); } let path = self.cache_path(resource); let (file, expiry) = join!(fs::read(&path), self.read_expiry_file(resource)); match (file, policy) { (Ok(buf), CachePolicy::IgnoreExpiry) => Ok(CacheFile::Fresh(buf)), (Ok(buf), CachePolicy::Revalidate) => { let expiry = expiry.unwrap_or(CacheExpiry::Never); let etag = expiry.etag().cloned(); Ok(CacheFile::Expired(buf, etag)) } (Ok(buf), CachePolicy::Default) => { let expiry = expiry?; let etag = expiry.etag().cloned(); Ok(if expiry.is_expired() { CacheFile::Expired(buf, etag) } else { CacheFile::Fresh(buf) }) } (_, CachePolicy::IgnoreCached) => Ok(CacheFile::None), (Err(e), _) => match e.kind() { io::ErrorKind::NotFound => Ok(CacheFile::None), _ => Err(CacheError::ReadError(e)), }, } } } impl CacheManager { async fn set_expiry_for_path( &self, path: &PathBuf, expiry: CacheExpiry, ) -> Result<(), CacheError> { if let CacheExpiry::AtUnixTimestamp(duration, etag) = expiry { let mut content = duration.as_secs().to_be_bytes().to_vec(); if let Some(etag) = etag { content.append(&mut etag.into_bytes()); } fs::write(path, content) .await .map_err(CacheError::WriteError)?; } Ok(()) } pub async fn clear_cache_pattern(&self, regex: &Regex) -> Result<(), CacheError> { let mut entries = fs::read_dir(&self.root) .await .map_err(CacheError::ReadError)?; while let Ok(Some(entry)) = entries.next_entry().await { let matches = entry .file_name() .to_str() .map(|s| regex.is_match(s)) .unwrap_or(false); if matches { info!("Removing {}...", entry.file_name().to_str().unwrap_or("")); fs::remove_file(entry.path()) .await .map_err(CacheError::RemoveError)?; if let Some(expiry_file_path) = entry .path() .to_str() .map(|path| path.to_string() + EXPIRY_FILE_EXT) { let _ = fs::remove_file(Path::new(&expiry_file_path)).await; } } } Ok(()) } pub async fn set_expired_pattern(&self, regex: &Regex) -> Result<(), CacheError> { let mut entries = fs::read_dir(&self.root) .await .map_err(CacheError::ReadError)?; while let Ok(Some(entry)) = entries.next_entry().await { let matches = entry .file_name() .to_str() .and_then(|s| s.strip_suffix(EXPIRY_FILE_EXT)) .map(|s| regex.is_match(s)) .unwrap_or(false); if matches { self.set_expiry_for_path(&entry.path(), CacheExpiry::expire_in_seconds(0, None)) .await?; } } Ok(()) } pub async fn write_cache_file( &self, resource: &str, content: &[u8], expiry: CacheExpiry, ) -> Result<(), CacheError> { let file = self.cache_path(resource); let meta = self.cache_meta_path(resource); let (r1, r2) = join!( fs::write(&file, content), self.set_expiry_for_path(&meta, expiry) ); r1.map_err(CacheError::WriteError)?; r2?; Ok(()) } pub async fn get_or_write<O, F, E>( &self, resource: &str, policy: CachePolicy, fetch: F, ) -> Result<Vec<u8>, E> where O: Future<Output = Result<FetchResult, E>>, F: FnOnce(Option<ETag>) -> O, E: From<CacheError>, { let file = self.read_cache_file(resource, policy).await?; match file { CacheFile::Fresh(buf) => Ok(buf), CacheFile::Expired(buf, etag) => match fetch(etag).await? { FetchResult::NotModified(expiry) => { let meta = self.cache_meta_path(resource); self.set_expiry_for_path(&meta, expiry).await?; Ok(buf) } FetchResult::Modified(fresh, expiry) => { self.write_cache_file(resource, &fresh, expiry).await?; Ok(fresh) } }, CacheFile::None => match fetch(None).await? { FetchResult::NotModified(_) => Err(E::from(CacheError::NoContent)), FetchResult::Modified(fresh, expiry) => { self.write_cache_file(resource, &fresh, expiry).await?; Ok(fresh) } }, } } } pub enum FetchResult { NotModified(CacheExpiry), Modified(Vec<u8>, CacheExpiry), }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/api/cached_client.rs
src/api/cached_client.rs
use futures::future::BoxFuture; use futures::{join, FutureExt}; use regex::Regex; use serde::de::DeserializeOwned; use serde_json::from_slice; use std::convert::Into; use std::future::Future; use std::sync::Arc; use super::cache::{CacheExpiry, CacheManager, CachePolicy, FetchResult}; use super::client::*; use crate::app::models::*; use crate::player::TokenStore; pub type SpotifyResult<T> = Result<T, SpotifyApiError>; pub trait SpotifyApiClient { fn get_artist(&self, id: &str) -> BoxFuture<SpotifyResult<ArtistDescription>>; fn get_album(&self, id: &str) -> BoxFuture<SpotifyResult<AlbumFullDescription>>; fn get_album_tracks( &self, id: &str, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<SongBatch>>; fn get_playlist(&self, id: &str) -> BoxFuture<SpotifyResult<PlaylistDescription>>; fn get_playlist_tracks( &self, id: &str, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<SongBatch>>; fn get_saved_albums( &self, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<Vec<AlbumDescription>>>; fn get_saved_tracks(&self, offset: usize, limit: usize) -> BoxFuture<SpotifyResult<SongBatch>>; fn save_album(&self, id: &str) -> BoxFuture<SpotifyResult<AlbumDescription>>; fn save_tracks(&self, ids: Vec<String>) -> BoxFuture<SpotifyResult<()>>; fn remove_saved_album(&self, id: &str) -> BoxFuture<SpotifyResult<()>>; fn remove_saved_tracks(&self, ids: Vec<String>) -> BoxFuture<SpotifyResult<()>>; fn get_saved_playlists( &self, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<Vec<PlaylistDescription>>>; fn add_to_playlist(&self, id: &str, uris: Vec<String>) -> BoxFuture<SpotifyResult<()>>; fn create_new_playlist( &self, name: &str, user_id: &str, ) -> BoxFuture<SpotifyResult<PlaylistDescription>>; fn remove_from_playlist(&self, id: &str, uris: Vec<String>) -> BoxFuture<SpotifyResult<()>>; fn update_playlist_details(&self, id: &str, name: String) -> BoxFuture<SpotifyResult<()>>; fn search( &self, query: &str, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<SearchResults>>; fn get_artist_albums( &self, id: &str, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<Vec<AlbumDescription>>>; fn get_user(&self, id: &str) -> BoxFuture<SpotifyResult<UserDescription>>; fn get_user_playlists( &self, id: &str, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<Vec<PlaylistDescription>>>; fn list_available_devices(&self) -> BoxFuture<SpotifyResult<Vec<ConnectDevice>>>; fn get_player_queue(&self) -> BoxFuture<SpotifyResult<Vec<SongDescription>>>; fn player_pause(&self, device_id: String) -> BoxFuture<SpotifyResult<()>>; fn player_resume(&self, device_id: String) -> BoxFuture<SpotifyResult<()>>; #[allow(dead_code)] fn player_next(&self, device_id: String) -> BoxFuture<SpotifyResult<()>>; fn player_seek(&self, device_id: String, pos: usize) -> BoxFuture<SpotifyResult<()>>; fn player_repeat(&self, device_id: String, mode: RepeatMode) -> BoxFuture<SpotifyResult<()>>; fn player_shuffle(&self, device_id: String, shuffle: bool) -> BoxFuture<SpotifyResult<()>>; fn player_volume(&self, device_id: String, volume: u8) -> BoxFuture<SpotifyResult<()>>; fn player_play_in_context( &self, device_id: String, context: String, offset: usize, ) -> BoxFuture<SpotifyResult<()>>; fn player_play_no_context( &self, device_id: String, uris: Vec<String>, offset: usize, ) -> BoxFuture<SpotifyResult<()>>; fn player_state(&self) -> BoxFuture<SpotifyResult<ConnectPlayerState>>; } enum RiffCacheKey<'a> { SavedAlbums(usize, usize), SavedTracks(usize, usize), SavedPlaylists(usize, usize), Album(&'a str), AlbumLiked(&'a str), AlbumTracks(&'a str, usize, usize), Playlist(&'a str), PlaylistTracks(&'a str, usize, usize), ArtistAlbums(&'a str, usize, usize), Artist(&'a str), ArtistTopTracks(&'a str), User(&'a str), UserPlaylists(&'a str, usize, usize), } impl RiffCacheKey<'_> { fn into_raw(self) -> String { match self { Self::SavedAlbums(offset, limit) => format!("me_albums_{offset}_{limit}.json"), Self::SavedTracks(offset, limit) => format!("me_tracks_{offset}_{limit}.json"), Self::SavedPlaylists(offset, limit) => format!("me_playlists_{offset}_{limit}.json"), Self::Album(id) => format!("album_{id}.json"), Self::AlbumTracks(id, offset, limit) => { format!("album_item_{id}_{offset}_{limit}.json") } Self::AlbumLiked(id) => format!("album_liked_{id}.json"), Self::Playlist(id) => format!("playlist_{id}.json"), Self::PlaylistTracks(id, offset, limit) => { format!("playlist_item_{id}_{offset}_{limit}.json") } Self::ArtistAlbums(id, offset, limit) => { format!("artist_albums_{id}_{offset}_{limit}.json") } Self::Artist(id) => format!("artist_{id}.json"), Self::ArtistTopTracks(id) => format!("artist_top_tracks_{id}.json"), Self::User(id) => format!("user_{id}.json"), Self::UserPlaylists(id, offset, limit) => { format!("user_playlists_{id}_{offset}_{limit}.json") } } } } lazy_static! { pub static ref ME_TRACKS_CACHE: Regex = Regex::new(r"^me_tracks_\w+_\w+\.json$").unwrap(); pub static ref ME_ALBUMS_CACHE: Regex = Regex::new(r"^me_albums_\w+_\w+\.json$").unwrap(); pub static ref USER_CACHE: Regex = Regex::new(r"^me_(albums|playlists|tracks)_\w+_\w+\.json$").unwrap(); } fn playlist_cache_key(id: &str) -> Regex { Regex::new(&format!(r"^playlist(_{id}|item_{id}_\w+_\w+)\.json$")).unwrap() } pub struct CachedSpotifyClient { client: SpotifyClient, cache: CacheManager, } impl CachedSpotifyClient { pub fn new(token_store: Arc<TokenStore>) -> CachedSpotifyClient { CachedSpotifyClient { client: SpotifyClient::new(token_store), cache: CacheManager::for_dir("riff/net").unwrap(), } } fn default_cache_policy(&self) -> CachePolicy { if self.client.has_token() { CachePolicy::Default } else { debug!("Forcing cache"); CachePolicy::IgnoreExpiry } } async fn wrap_write<T, O, F>(write: &F, etag: Option<String>) -> SpotifyResult<FetchResult> where O: Future<Output = SpotifyResult<SpotifyResponse<T>>>, F: Fn(Option<String>) -> O, { write(etag) .map(|r| { let SpotifyResponse { kind, max_age, etag, } = r?; let expiry = CacheExpiry::expire_in_seconds(max_age, etag); SpotifyResult::Ok(match kind { SpotifyResponseKind::Ok(content, _) => { debug!("Did not hit cache"); FetchResult::Modified(content.into_bytes(), expiry) } SpotifyResponseKind::NotModified => FetchResult::NotModified(expiry), }) }) .await } async fn cache_get_or_write<T, O, F>( &self, key: RiffCacheKey<'_>, cache_policy: Option<CachePolicy>, write: F, ) -> SpotifyResult<T> where O: Future<Output = SpotifyResult<SpotifyResponse<T>>>, F: Fn(Option<String>) -> O, T: DeserializeOwned, { let write = &write; let cache_key = key.into_raw(); let raw = self .cache .get_or_write( &cache_key, cache_policy.unwrap_or_else(|| self.default_cache_policy()), |etag| Self::wrap_write(write, etag), ) .await?; let result = from_slice::<T>(&raw); match result { Ok(t) => Ok(t), // parsing failed: cache is likely invalid, request again, ignoring cache Err(e) => { dbg!(&cache_key, e); let new_raw = self .cache .get_or_write(&cache_key, CachePolicy::IgnoreCached, |etag| { Self::wrap_write(write, etag) }) .await?; Ok(from_slice::<T>(&new_raw)?) } } } } impl SpotifyApiClient for CachedSpotifyClient { fn get_saved_albums( &self, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<Vec<AlbumDescription>>> { Box::pin(async move { let page = self .cache_get_or_write(RiffCacheKey::SavedAlbums(offset, limit), None, |etag| { self.client .get_saved_albums(offset, limit) .etag(etag) .send() }) .await?; let albums = page .into_iter() .map(|saved| saved.album.into()) .collect::<Vec<AlbumDescription>>(); Ok(albums) }) } fn get_saved_tracks(&self, offset: usize, limit: usize) -> BoxFuture<SpotifyResult<SongBatch>> { Box::pin(async move { let page = self .cache_get_or_write(RiffCacheKey::SavedTracks(offset, limit), None, |etag| { self.client .get_saved_tracks(offset, limit) .etag(etag) .send() }) .await?; Ok(page.into()) }) } fn get_saved_playlists( &self, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<Vec<PlaylistDescription>>> { Box::pin(async move { let page = self .cache_get_or_write(RiffCacheKey::SavedPlaylists(offset, limit), None, |etag| { self.client .get_saved_playlists(offset, limit) .etag(etag) .send() }) .await?; let albums = page .into_iter() .map(|playlist| playlist.into()) .collect::<Vec<PlaylistDescription>>(); Ok(albums) }) } fn add_to_playlist(&self, id: &str, uris: Vec<String>) -> BoxFuture<SpotifyResult<()>> { let id = id.to_owned(); Box::pin(async move { self.cache .set_expired_pattern(&playlist_cache_key(&id)) .await .unwrap_or(()); self.client .add_to_playlist(&id, uris) .send_no_response() .await?; Ok(()) }) } fn create_new_playlist( &self, name: &str, user_id: &str, ) -> BoxFuture<SpotifyResult<PlaylistDescription>> { let name = name.to_owned(); let user_id = user_id.to_owned(); Box::pin(async move { let playlist = self .client .create_new_playlist(&name, &user_id) .send() .await? .deserialize() .unwrap(); Ok(playlist.into()) }) } fn remove_from_playlist(&self, id: &str, uris: Vec<String>) -> BoxFuture<SpotifyResult<()>> { let id = id.to_owned(); Box::pin(async move { self.cache .set_expired_pattern(&playlist_cache_key(&id)) .await .unwrap_or(()); self.client .remove_from_playlist(&id, uris) .send_no_response() .await?; Ok(()) }) } fn update_playlist_details(&self, id: &str, name: String) -> BoxFuture<SpotifyResult<()>> { let id = id.to_owned(); Box::pin(async move { self.cache .set_expired_pattern(&playlist_cache_key(&id)) .await .unwrap_or(()); self.client .update_playlist_details(&id, name) .send_no_response() .await?; Ok(()) }) } fn get_album(&self, id: &str) -> BoxFuture<SpotifyResult<AlbumFullDescription>> { let id = id.to_owned(); Box::pin(async move { let album = self.cache_get_or_write(RiffCacheKey::Album(&id), None, |etag| { self.client.get_album(&id).etag(etag).send() }); let liked = self.cache_get_or_write( RiffCacheKey::AlbumLiked(&id), Some(if self.client.has_token() { CachePolicy::Revalidate } else { CachePolicy::IgnoreExpiry }), |etag| self.client.is_album_saved(&id).etag(etag).send(), ); let (album, liked) = join!(album, liked); let mut album: AlbumFullDescription = album?.into(); album.description.is_liked = liked?[0]; Ok(album) }) } fn save_album(&self, id: &str) -> BoxFuture<SpotifyResult<AlbumDescription>> { let id = id.to_owned(); Box::pin(async move { let _ = self.cache.set_expired_pattern(&ME_ALBUMS_CACHE).await; self.client.save_album(&id).send_no_response().await?; self.get_album(&id[..]).await.map(|a| a.description) }) } fn save_tracks(&self, ids: Vec<String>) -> BoxFuture<SpotifyResult<()>> { Box::pin(async move { let _ = self.cache.set_expired_pattern(&ME_TRACKS_CACHE).await; self.client.save_tracks(ids).send_no_response().await?; Ok(()) }) } fn remove_saved_album(&self, id: &str) -> BoxFuture<SpotifyResult<()>> { let id = id.to_owned(); Box::pin(async move { let _ = self.cache.set_expired_pattern(&ME_ALBUMS_CACHE).await; self.client.remove_saved_album(&id).send_no_response().await }) } fn remove_saved_tracks(&self, ids: Vec<String>) -> BoxFuture<SpotifyResult<()>> { Box::pin(async move { let _ = self.cache.set_expired_pattern(&ME_TRACKS_CACHE).await; self.client .remove_saved_tracks(ids) .send_no_response() .await }) } fn get_album_tracks( &self, id: &str, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<SongBatch>> { let id = id.to_owned(); Box::pin(async move { let album = self.cache_get_or_write( RiffCacheKey::Album(&id), Some(CachePolicy::IgnoreExpiry), |etag| self.client.get_album(&id).etag(etag).send(), ); let songs = self.cache_get_or_write( RiffCacheKey::AlbumTracks(&id, offset, limit), None, |etag| { self.client .get_album_tracks(&id, offset, limit) .etag(etag) .send() }, ); let (album, songs) = join!(album, songs); Ok((songs?, &album?.album).into()) }) } fn get_playlist(&self, id: &str) -> BoxFuture<SpotifyResult<PlaylistDescription>> { let id = id.to_owned(); Box::pin(async move { let playlist = self .cache_get_or_write(RiffCacheKey::Playlist(&id), None, |etag| { self.client.get_playlist(&id).etag(etag).send() }) .await?; Ok(playlist.into()) }) } fn get_playlist_tracks( &self, id: &str, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<SongBatch>> { let id = id.to_owned(); Box::pin(async move { let songs = self .cache_get_or_write( RiffCacheKey::PlaylistTracks(&id, offset, limit), None, |etag| { self.client .get_playlist_tracks(&id, offset, limit) .etag(etag) .send() }, ) .await?; Ok(songs.into()) }) } fn get_artist_albums( &self, id: &str, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<Vec<AlbumDescription>>> { let id = id.to_owned(); Box::pin(async move { let albums = self .cache_get_or_write( RiffCacheKey::ArtistAlbums(&id, offset, limit), None, |etag| { self.client .get_artist_albums(&id, offset, limit) .etag(etag) .send() }, ) .await?; let albums = albums .into_iter() .map(|a| a.into()) .collect::<Vec<AlbumDescription>>(); Ok(albums) }) } fn get_artist(&self, id: &str) -> BoxFuture<SpotifyResult<ArtistDescription>> { let id = id.to_owned(); Box::pin(async move { let artist = self.cache_get_or_write(RiffCacheKey::Artist(&id), None, |etag| { self.client.get_artist(&id).etag(etag).send() }); let albums = self.get_artist_albums(&id, 0, 20); let top_tracks = self.cache_get_or_write(RiffCacheKey::ArtistTopTracks(&id), None, |etag| { self.client.get_artist_top_tracks(&id).etag(etag).send() }); let (artist, albums, top_tracks) = join!(artist, albums, top_tracks); let artist = artist?; let result = ArtistDescription { id: artist.id, name: artist.name, albums: albums?, top_tracks: top_tracks?.into(), }; Ok(result) }) } fn search( &self, query: &str, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<SearchResults>> { let query = query.to_owned(); Box::pin(async move { let results = self .client .search(query, offset, limit) .send() .await? .deserialize() .ok_or(SpotifyApiError::NoContent)?; let albums = results .albums .unwrap_or_default() .into_iter() .map(|saved| saved.into()) .collect::<Vec<AlbumDescription>>(); let artists = results .artists .unwrap_or_default() .into_iter() .map(|saved| saved.into()) .collect::<Vec<ArtistSummary>>(); Ok(SearchResults { albums, artists }) }) } fn get_user_playlists( &self, id: &str, offset: usize, limit: usize, ) -> BoxFuture<SpotifyResult<Vec<PlaylistDescription>>> { let id = id.to_owned(); Box::pin(async move { let playlists = self .cache_get_or_write( RiffCacheKey::UserPlaylists(&id, offset, limit), None, |etag| { self.client .get_user_playlists(&id, offset, limit) .etag(etag) .send() }, ) .await?; let playlists = playlists .into_iter() .map(|a| a.into()) .collect::<Vec<PlaylistDescription>>(); Ok(playlists) }) } fn get_user(&self, id: &str) -> BoxFuture<SpotifyResult<UserDescription>> { let id = id.to_owned(); Box::pin(async move { let user = self.cache_get_or_write(RiffCacheKey::User(&id), None, |etag| { self.client.get_user(&id).etag(etag).send() }); let playlists = self.get_user_playlists(&id, 0, 30); let (user, playlists) = join!(user, playlists); let user = user?; let result = UserDescription { id: user.id, name: user.display_name, playlists: playlists?, }; Ok(result) }) } fn list_available_devices(&self) -> BoxFuture<SpotifyResult<Vec<ConnectDevice>>> { Box::pin(async move { let devices = self .client .get_player_devices() .send() .await? .deserialize() .ok_or(SpotifyApiError::NoContent)?; Ok(devices .devices .into_iter() .filter(|d| { debug!("found device: {:?}", d); !d.is_restricted }) .map(ConnectDevice::from) .collect()) }) } fn get_player_queue(&self) -> BoxFuture<SpotifyResult<Vec<SongDescription>>> { Box::pin(async move { let queue = self .client .get_player_queue() .send() .await? .deserialize() .ok_or(SpotifyApiError::NoContent)?; Ok(queue.into()) }) } fn player_pause(&self, device_id: String) -> BoxFuture<SpotifyResult<()>> { Box::pin(self.client.player_pause(&device_id).send_no_response()) } fn player_resume(&self, device_id: String) -> BoxFuture<SpotifyResult<()>> { Box::pin(self.client.player_resume(&device_id).send_no_response()) } fn player_play_in_context( &self, device_id: String, context_uri: String, offset: usize, ) -> BoxFuture<SpotifyResult<()>> { Box::pin( self.client .player_set_playing( &device_id, PlayRequest::Contextual { context_uri, offset: PlayOffset { position: offset as u32, }, }, ) .send_no_response(), ) } fn player_play_no_context( &self, device_id: String, uris: Vec<String>, offset: usize, ) -> BoxFuture<SpotifyResult<()>> { Box::pin( self.client .player_set_playing( &device_id, PlayRequest::Uris { uris, offset: PlayOffset { position: offset as u32, }, }, ) .send_no_response(), ) } fn player_next(&self, device_id: String) -> BoxFuture<SpotifyResult<()>> { Box::pin(self.client.player_next(&device_id).send_no_response()) } fn player_seek(&self, device_id: String, pos: usize) -> BoxFuture<SpotifyResult<()>> { Box::pin(self.client.player_seek(&device_id, pos).send_no_response()) } fn player_state(&self) -> BoxFuture<SpotifyResult<ConnectPlayerState>> { Box::pin(async move { let result = self .client .player_state() .send() .await? .deserialize() .ok_or(SpotifyApiError::NoContent)?; Ok(result.into()) }) } fn player_repeat(&self, device_id: String, mode: RepeatMode) -> BoxFuture<SpotifyResult<()>> { Box::pin( self.client .player_repeat( &device_id, match mode { RepeatMode::Song => "track", RepeatMode::Playlist => "context", RepeatMode::None => "off", }, ) .send_no_response(), ) } fn player_shuffle(&self, device_id: String, shuffle: bool) -> BoxFuture<SpotifyResult<()>> { Box::pin( self.client .player_shuffle(&device_id, shuffle) .send_no_response(), ) } fn player_volume(&self, device_id: String, volume: u8) -> BoxFuture<SpotifyResult<()>> { Box::pin( self.client .player_volume(&device_id, volume) .send_no_response(), ) } } #[cfg(test)] pub mod tests { use crate::api::api_models::*; #[test] fn test_search_query() { let query = SearchQuery { query: "test".to_string(), types: vec![SearchType::Album, SearchType::Artist], limit: 5, offset: 0, }; assert_eq!( query.into_query_string(), "type=album,artist&q=test&offset=0&limit=5&market=from_token" ); } #[test] fn test_search_query_spaces_and_stuff() { let query = SearchQuery { query: "test??? wow".to_string(), types: vec![SearchType::Album], limit: 5, offset: 0, }; assert_eq!( query.into_query_string(), "type=album&q=test+wow&offset=0&limit=5&market=from_token" ); } #[test] fn test_search_query_encoding() { let query = SearchQuery { query: "кириллица".to_string(), types: vec![SearchType::Album], limit: 5, offset: 0, }; assert_eq!(query.into_query_string(), "type=album&q=%D0%BA%D0%B8%D1%80%D0%B8%D0%BB%D0%BB%D0%B8%D1%86%D0%B0&offset=0&limit=5&market=from_token"); } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/player/player.rs
src/player/player.rs
use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender}; use futures::stream::StreamExt; use librespot::core::authentication::Credentials; use librespot::core::cache::Cache; use librespot::core::config::SessionConfig; use librespot::core::session::Session; use librespot::playback::mixer::softmixer::SoftMixer; use librespot::playback::mixer::{Mixer, MixerConfig}; use librespot::playback::audio_backend; use librespot::playback::config::{AudioFormat, Bitrate, PlayerConfig, VolumeCtrl}; use librespot::playback::player::{Player, PlayerEvent, PlayerEventChannel}; use url::Url; use super::oauth2::{AuthcodeChallenge, RiffOauthClient}; use super::{Command, TokenStore}; use crate::app::credentials; use crate::player::oauth2::OAuthError; use crate::settings::RiffSettings; use std::env; use std::error::Error; use std::fmt; use std::rc::Rc; use std::sync::Arc; #[derive(Debug)] pub enum SpotifyError { LoginFailed, LoggedOut, PlayerNotReady, TechnicalError, } impl Error for SpotifyError {} impl fmt::Display for SpotifyError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::LoginFailed => write!(f, "Login failed!"), Self::LoggedOut => write!(f, "You are logged out!"), Self::PlayerNotReady => write!(f, "Player is not responding."), Self::TechnicalError => { write!(f, "A technical error occured. Check your connectivity.") } } } } pub trait SpotifyPlayerDelegate { fn end_of_track_reached(&self); fn login_challenge_started(&self, url: Url); fn token_login_successful(&self, username: String); fn refresh_successful(&self); fn report_error(&self, error: SpotifyError); fn notify_playback_state(&self, position: u32); fn preload_next_track(&self); } #[derive(Debug, Clone, PartialEq, Eq)] pub enum AudioBackend { GStreamer(String), PulseAudio, Alsa(String), } #[derive(Debug, Clone, PartialEq, Eq)] pub struct SpotifyPlayerSettings { pub bitrate: Bitrate, pub backend: AudioBackend, pub gapless: bool, pub ap_port: Option<u16>, } impl Default for SpotifyPlayerSettings { fn default() -> Self { Self { bitrate: Bitrate::Bitrate160, gapless: true, backend: AudioBackend::PulseAudio, ap_port: None, } } } pub struct SpotifyPlayer { settings: SpotifyPlayerSettings, player: Option<Arc<Player>>, mixer: Option<Box<dyn Mixer>>, session: Option<Session>, // Auth related stuff oauth_client: Arc<RiffOauthClient>, auth_challenge: Option<AuthcodeChallenge>, command_sender: UnboundedSender<Command>, // Receives feedback from commands or various events in the player delegate: Rc<dyn SpotifyPlayerDelegate>, } impl SpotifyPlayer { pub fn new( settings: SpotifyPlayerSettings, delegate: Rc<dyn SpotifyPlayerDelegate>, token_store: Arc<TokenStore>, command_sender: UnboundedSender<Command>, ) -> Self { Self { settings, mixer: None, player: None, session: None, oauth_client: Arc::new(RiffOauthClient::new(token_store)), auth_challenge: None, command_sender, delegate, } } async fn handle_and_notify(&mut self, action: Command) { match self.handle(action).await { Ok(_) => {} Err(e) => self.delegate.report_error(e), } } fn get_player(&self) -> Result<&Arc<Player>, SpotifyError> { self.player.as_ref().ok_or(SpotifyError::PlayerNotReady) } fn get_player_mut(&mut self) -> Result<&mut Arc<Player>, SpotifyError> { self.player.as_mut().ok_or(SpotifyError::PlayerNotReady) } async fn handle(&mut self, action: Command) -> Result<(), SpotifyError> { match action { Command::PlayerSetVolume(volume) => { if let Some(mixer) = self.mixer.as_mut() { mixer.set_volume((VolumeCtrl::MAX_VOLUME as f64 * volume) as u16); } Ok(()) } Command::PlayerResume => { self.get_player()?.play(); Ok(()) } Command::PlayerPause => { self.get_player()?.pause(); Ok(()) } Command::PlayerStop => { self.get_player()?.stop(); Ok(()) } Command::PlayerSeek(position) => { self.get_player()?.seek(position); Ok(()) } Command::PlayerLoad { track, resume } => { self.get_player_mut()?.load(track, resume, 0); Ok(()) } Command::PlayerPreload(track) => { self.get_player_mut()?.preload(track); Ok(()) } Command::RefreshToken => { let session = self.session.as_ref().ok_or(SpotifyError::PlayerNotReady)?; let token = self .oauth_client .get_valid_token() .await .map_err(|_| SpotifyError::LoginFailed)?; let credentials = Credentials::with_access_token(token.access_token.clone()); session .connect(credentials, true) .await .map_err(|_| SpotifyError::LoginFailed)?; self.delegate.refresh_successful(); Ok(()) } Command::Logout => { self.session .take() .ok_or(SpotifyError::PlayerNotReady)? .shutdown(); let _ = self.player.take(); Ok(()) } Command::Restore => { let credentials = self.oauth_client .get_valid_token() .await .map_err(|e| match e { OAuthError::LoggedOut => SpotifyError::LoggedOut, _ => SpotifyError::LoginFailed, })?; info!("Restoring session"); self.initial_login(credentials).await } Command::InitLogin => { let auth_url = match self.auth_challenge.as_ref() { Some(challenge) => challenge.auth_url.clone(), None => { let cmd = self.command_sender.clone(); let challenge = self .oauth_client .spawn_authcode_listener(move || { cmd.unbounded_send(Command::CompleteLogin).unwrap(); }) .await .map_err(|_| SpotifyError::LoginFailed)?; let auth_url = challenge.auth_url.clone(); self.auth_challenge = Some(challenge); auth_url } }; self.delegate.login_challenge_started(auth_url); Ok(()) } Command::CompleteLogin => { let Some(challenge) = self.auth_challenge.take() else { return Err(SpotifyError::LoginFailed); }; let credentials = self .oauth_client .exchange_authcode(challenge) .await .map_err(|_| SpotifyError::LoginFailed)?; info!("Login with OAuth2"); self.initial_login(credentials).await } Command::ReloadSettings => { let settings = RiffSettings::new_from_gsettings().unwrap_or_default(); self.settings = settings.player_settings; let session = self.session.take().ok_or(SpotifyError::PlayerNotReady)?; let new_player = self.create_player(session); tokio::task::spawn_local(player_setup_delegate( new_player.get_player_event_channel(), Rc::clone(&self.delegate), )); self.player.replace(new_player); Ok(()) } } } async fn initial_login( &mut self, credentials: credentials::Credentials, ) -> Result<(), SpotifyError> { let creds = Credentials::with_access_token(&credentials.access_token); let new_session = create_session(&creds, self.settings.ap_port).await?; let username = new_session.username(); let oauth_client = Arc::clone(&self.oauth_client); let session = new_session.clone(); tokio::task::spawn_local(async move { loop { if let Ok(token) = oauth_client.refresh_token_at_expiry().await { _ = session .connect(Credentials::with_access_token(token.access_token), true) .await; } } }); let new_player = self.create_player(new_session.clone()); tokio::task::spawn_local(player_setup_delegate( new_player.get_player_event_channel(), Rc::clone(&self.delegate), )); self.player.replace(new_player); self.session.replace(new_session); self.delegate.token_login_successful(username); Ok(()) } fn create_player(&mut self, session: Session) -> Arc<Player> { let backend = self.settings.backend.clone(); let player_config = PlayerConfig { gapless: self.settings.gapless, bitrate: self.settings.bitrate, ..Default::default() }; info!("bitrate: {:?}", &player_config.bitrate); let soft_volume = self .mixer .get_or_insert_with(|| { let mix = Box::new(SoftMixer::open(MixerConfig { // This value feels reasonable to me. Feel free to change it volume_ctrl: VolumeCtrl::Log(VolumeCtrl::DEFAULT_DB_RANGE / 2.0), ..Default::default() }).expect("Failed to create soft mixer")); // TODO: Should read volume from somewhere instead of hard coding. // Sets volume to 100% mix.set_volume(VolumeCtrl::MAX_VOLUME); mix }) .get_soft_volume(); Player::new(player_config, session, soft_volume, move || match backend { AudioBackend::GStreamer(pipeline) => { let backend = audio_backend::find(Some("gstreamer".to_string())).unwrap(); backend(Some(pipeline), AudioFormat::default()) } AudioBackend::PulseAudio => { info!("using pulseaudio"); env::set_var("PULSE_PROP_application.name", "Riff"); let backend = audio_backend::find(Some("pulseaudio".to_string())).unwrap(); backend(None, AudioFormat::default()) } AudioBackend::Alsa(device) => { info!("using alsa ({})", &device); let backend = audio_backend::find(Some("alsa".to_string())).unwrap(); backend(Some(device), AudioFormat::default()) } }) } pub async fn start(self, receiver: UnboundedReceiver<Command>) -> Result<(), ()> { receiver .fold(self, |mut player, action| async { player.handle_and_notify(action).await; player }) .await; Ok(()) } } const KNOWN_AP_PORTS: [Option<u16>; 4] = [None, Some(80), Some(443), Some(4070)]; async fn create_session_with_port( credentials: &Credentials, ap_port: Option<u16>, ) -> Result<Session, SpotifyError> { let session_config = SessionConfig { ap_port, ..Default::default() }; let root = glib::user_cache_dir().join("riff").join("librespot"); let cache = Cache::new( Some(root.join("credentials")), Some(root.join("volume")), Some(root.join("audio")), None, ) .map_err(|e| dbg!(e)) .ok(); let session = Session::new(session_config, cache); match session.connect(credentials.clone(), true).await { Ok(_) => Ok(session), Err(err) => { warn!("Login failure: {}", err); Err(SpotifyError::LoginFailed) } } } async fn create_session( credentials: &Credentials, ap_port: Option<u16>, ) -> Result<Session, SpotifyError> { match ap_port { Some(_) => create_session_with_port(credentials, ap_port).await, None => { let mut ports_to_try = KNOWN_AP_PORTS.iter(); loop { if let Some(next_port) = ports_to_try.next() { let res = create_session_with_port(credentials, *next_port).await; match res { Err(SpotifyError::TechnicalError) => continue, _ => break res, } } else { break Err(SpotifyError::TechnicalError); } } } } } async fn player_setup_delegate( mut channel: PlayerEventChannel, delegate: Rc<dyn SpotifyPlayerDelegate>, ) { while let Some(event) = channel.recv().await { match event { PlayerEvent::EndOfTrack { .. } => { delegate.end_of_track_reached(); } PlayerEvent::Playing { position_ms, .. } => { delegate.notify_playback_state(position_ms); } PlayerEvent::TimeToPreloadNextTrack { .. } => { debug!("Requesting next track to be preloaded..."); delegate.preload_next_track(); } _ => {} } } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/player/token_store.rs
src/player/token_store.rs
use tokio::sync::RwLock; use crate::app::credentials::Credentials; pub struct TokenStore { storage: RwLock<Option<Credentials>>, } impl TokenStore { pub fn new() -> Self { Self { storage: RwLock::new(None), } } pub fn get_cached_blocking(&self) -> Option<Credentials> { self.storage.blocking_read().clone() } pub async fn get_cached(&self) -> Option<Credentials> { self.storage.read().await.clone() } pub async fn get(&self) -> Option<Credentials> { let local = self.storage.read().await.clone(); if local.is_some() { return local; } match Credentials::retrieve().await { Ok(token) => { self.storage.write().await.replace(token.clone()); Some(token) } Err(e) => { error!("Couldnt get token from secrets service: {e}"); None } } } pub async fn set(&self, creds: Credentials) { debug!("Saving token to store..."); if let Err(e) = creds.save().await { warn!("Couldnt save token to secrets service: {e}"); } self.storage.write().await.replace(creds); } pub async fn clear(&self) { if let Err(e) = Credentials::logout().await { warn!("Couldnt save token to secrets service: {e}"); } self.storage.write().await.take(); } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/player/mod.rs
src/player/mod.rs
use futures::channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender}; use librespot::core::SpotifyUri; use std::cell::RefCell; use std::rc::Rc; use std::sync::Arc; use tokio::task; use url::Url; use crate::app::state::{LoginAction, PlaybackAction}; use crate::app::AppAction; #[allow(clippy::module_inception)] mod player; pub use player::*; mod oauth2; mod token_store; pub use token_store::*; #[derive(Debug, Clone)] pub enum Command { Restore, InitLogin, CompleteLogin, RefreshToken, Logout, PlayerLoad { track: SpotifyUri, resume: bool }, PlayerResume, PlayerPause, PlayerStop, PlayerSeek(u32), PlayerSetVolume(f64), PlayerPreload(SpotifyUri), ReloadSettings, } struct AppPlayerDelegate { sender: RefCell<UnboundedSender<AppAction>>, } impl AppPlayerDelegate { fn new(sender: UnboundedSender<AppAction>) -> Self { let sender = RefCell::new(sender); Self { sender } } } impl SpotifyPlayerDelegate for AppPlayerDelegate { fn end_of_track_reached(&self) { self.sender .borrow_mut() .unbounded_send(PlaybackAction::Next.into()) .unwrap(); } fn token_login_successful(&self, username: String) { self.sender .borrow_mut() .unbounded_send(LoginAction::SetLoginSuccess(username).into()) .unwrap(); } fn refresh_successful(&self) { self.sender .borrow_mut() .unbounded_send(LoginAction::TokenRefreshed.into()) .unwrap(); } fn report_error(&self, error: SpotifyError) { self.sender .borrow_mut() .unbounded_send(match error { SpotifyError::LoginFailed => LoginAction::SetLoginFailure.into(), SpotifyError::LoggedOut => LoginAction::Logout.into(), _ => AppAction::ShowNotification(format!("{error}")), }) .unwrap(); } fn notify_playback_state(&self, position: u32) { self.sender .borrow_mut() .unbounded_send(PlaybackAction::SyncSeek(position).into()) .unwrap(); } fn preload_next_track(&self) { self.sender .borrow_mut() .unbounded_send(PlaybackAction::Preload.into()) .unwrap(); } fn login_challenge_started(&self, url: Url) { self.sender .borrow_mut() .unbounded_send(LoginAction::OpenLoginUrl(url).into()) .unwrap(); } } #[tokio::main] async fn player_main( player_settings: SpotifyPlayerSettings, appaction_sender: UnboundedSender<AppAction>, token_store: Arc<TokenStore>, sender: UnboundedSender<Command>, receiver: UnboundedReceiver<Command>, ) { task::LocalSet::new() .run_until(async move { task::spawn_local(async move { let delegate = Rc::new(AppPlayerDelegate::new(appaction_sender.clone())); let player = SpotifyPlayer::new(player_settings, delegate, token_store, sender); player.start(receiver).await.unwrap(); }) .await .unwrap(); }) .await; } pub fn start_player_service( player_settings: SpotifyPlayerSettings, appaction_sender: UnboundedSender<AppAction>, token_store: Arc<TokenStore>, ) -> UnboundedSender<Command> { let (sender, receiver) = unbounded::<Command>(); let sender_clone = sender.clone(); std::thread::spawn(move || { player_main( player_settings, appaction_sender, token_store, sender_clone, receiver, ) }); sender }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/player/oauth2.rs
src/player/oauth2.rs
//! Provides a Spotify access token using the OAuth authorization code flow //! with PKCE. //! //! Assuming sufficient scopes, the returned access token may be used with Spotify's //! Web API, and/or to establish a new Session with [`librespot_core`]. //! //! The authorization code flow is an interactive process which requires a web browser //! to complete. The resulting code must then be provided back from the browser to this //! library for exchange into an access token. Providing the code can be automatic via //! a spawned http server (mimicking Spotify's client), or manually via stdin. The latter //! is appropriate for headless systems. use crate::app::credentials::Credentials; use log::{error, info, trace}; use oauth2::reqwest::async_http_client; use oauth2::{ basic::BasicClient, AuthUrl, AuthorizationCode, ClientId, CsrfToken, PkceCodeChallenge, RedirectUrl, Scope, TokenResponse, TokenUrl, }; use oauth2::{PkceCodeVerifier, RefreshToken, RequestTokenError}; use std::collections::HashMap; use std::io; use std::net::SocketAddr; use std::sync::Arc; use std::time::{Duration, SystemTime}; use thiserror::Error; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tokio::task::JoinHandle; use url::Url; use super::TokenStore; pub const CLIENT_ID: &str = "782ae96ea60f4cdf986a766049607005"; pub const REDIRECT_URI: &str = "http://127.0.0.1:8898/login"; pub const SCOPES: &str = "user-read-private,\ playlist-read-private,\ playlist-read-collaborative,\ user-library-read,\ user-library-modify,\ user-top-read,\ user-read-recently-played,\ user-read-playback-state,\ playlist-modify-public,\ playlist-modify-private,\ user-modify-playback-state,\ streaming,\ playlist-modify-public"; pub struct RiffOauthClient { client: BasicClient, token_store: Arc<TokenStore>, } pub struct AuthcodeChallenge { pkce_verifier: PkceCodeVerifier, pub auth_url: Url, listener: JoinHandle<Result<AuthorizationCode, OAuthError>>, } impl RiffOauthClient { pub fn new(token_store: Arc<TokenStore>) -> Self { let auth_url = AuthUrl::new("https://accounts.spotify.com/authorize".to_string()) .expect("Malformed URL"); let token_url = TokenUrl::new("https://accounts.spotify.com/api/token".to_string()) .expect("Malformed URL"); let redirect_url = RedirectUrl::new(REDIRECT_URI.to_string()).expect("Malformed URL"); let client = BasicClient::new( ClientId::new(CLIENT_ID.to_string()), None, auth_url, Some(token_url), ) .set_redirect_uri(redirect_url); Self { client, token_store, } } pub async fn spawn_authcode_listener( &self, notify_complete: impl FnOnce() + 'static, ) -> Result<AuthcodeChallenge, OAuthError> { let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256(); // Generate the full authorization URL. // Some of these scopes are unavailable for custom client IDs. Which? let request_scopes: Vec<oauth2::Scope> = SCOPES.split(",").map(|s| Scope::new(s.into())).collect(); let (auth_url, csrf_token) = self .client .authorize_url(CsrfToken::new_random) .add_scopes(request_scopes) .set_pkce_challenge(pkce_challenge) .url(); Ok(AuthcodeChallenge { pkce_verifier, auth_url, listener: tokio::task::spawn_local(async move { let result = wait_for_authcode(csrf_token).await; notify_complete(); result }), }) } /// Obtain a Spotify access token using the authorization code with PKCE OAuth flow. /// The redirect_uri must match what is registered to the client ID. pub async fn exchange_authcode( &self, challenge: AuthcodeChallenge, ) -> Result<Credentials, OAuthError> { let code = challenge .listener .await .map_err(|_| OAuthError::AuthCodeListenerTerminated)??; let token = self .client .exchange_code(code) .set_pkce_verifier(challenge.pkce_verifier) .request_async(async_http_client) .await .map_err(|e| match e { RequestTokenError::ServerResponse(res) => { error!( "An error occured while exchange a code: {}", res.to_string() ); OAuthError::ExchangeCode { e: res.to_string() } } e => OAuthError::ExchangeCode { e: e.to_string() }, })?; trace!("Obtained new access token: {token:?}"); let refresh_token = token .refresh_token() .ok_or(OAuthError::NoRefreshToken)? .secret() .to_string(); let token = Credentials { access_token: token.access_token().secret().to_string(), refresh_token, token_expiry_time: Some( SystemTime::now() + token .expires_in() .unwrap_or_else(|| Duration::from_secs(3600)), ), }; self.token_store.set(token.clone()).await; Ok(token) } pub async fn get_valid_token(&self) -> Result<Credentials, OAuthError> { let token = self.token_store.get().await.ok_or(OAuthError::LoggedOut)?; if token.token_expired() { self.refresh_token(token).await } else { Ok(token) } } pub async fn refresh_token(&self, old_token: Credentials) -> Result<Credentials, OAuthError> { let Ok(token) = self .client .exchange_refresh_token(&RefreshToken::new(old_token.refresh_token)) .request_async(async_http_client) .await .inspect_err(|e| { if let RequestTokenError::ServerResponse(res) = e { error!( "An error occured while refreshing the token: {}", res.to_string() ); } }) else { self.token_store.clear().await; return Err(OAuthError::NoRefreshToken); }; let refresh_token = token .refresh_token() .ok_or(OAuthError::NoRefreshToken)? .secret() .to_string(); let new_token = Credentials { access_token: token.access_token().secret().to_string(), refresh_token, token_expiry_time: Some( SystemTime::now() + token .expires_in() .unwrap_or_else(|| Duration::from_secs(3600)), ), }; self.token_store.set(new_token.clone()).await; Ok(new_token) } pub async fn refresh_token_at_expiry(&self) -> Result<Credentials, OAuthError> { let Some(old_token) = self.token_store.get_cached().await.take() else { return Err(OAuthError::NoRefreshToken); }; let duration = old_token .token_expiry_time .and_then(|d| d.duration_since(SystemTime::now()).ok()) .unwrap_or(Duration::from_secs(120)); info!( "Refreshing token in approx {}min", duration.as_secs().div_euclid(60) ); tokio::time::sleep(duration.saturating_sub(Duration::from_secs(10))).await; info!("Refreshing token..."); self.refresh_token(old_token).await } } #[derive(Debug, Error)] pub enum OAuthError { #[error("Auth code param not found in URI")] AuthCodeNotFound, #[error("CSRF token param not found in URI")] CsrfTokenNotFound, #[error("Failed to bind server to {addr} ({e})")] AuthCodeListenerBind { addr: SocketAddr, e: io::Error }, #[error("Listener terminated without accepting a connection")] AuthCodeListenerTerminated, #[error("Failed to parse redirect URI from HTTP request")] AuthCodeListenerParse, #[error("Failed to write HTTP response")] AuthCodeListenerWrite, #[error("Failed to exchange code for access token ({e})")] ExchangeCode { e: String }, #[error("Spotify did not provide a refresh token")] NoRefreshToken, #[error("No saved token")] LoggedOut, #[error("Mismatched state during auth code exchange")] InvalidState, } /// Spawn HTTP server at provided socket address to accept OAuth callback and return auth code. async fn wait_for_authcode(expected_state: CsrfToken) -> Result<AuthorizationCode, OAuthError> { let addr = get_socket_address(REDIRECT_URI).expect("Invalid redirect uri"); let listener = tokio::net::TcpListener::bind(addr) .await .map_err(|e| OAuthError::AuthCodeListenerBind { addr, e })?; let (mut stream, _) = listener .accept() .await .map_err(|_| OAuthError::AuthCodeListenerTerminated)?; let mut request_line = String::new(); let mut reader = BufReader::new(&mut stream); reader .read_line(&mut request_line) .await .map_err(|_| OAuthError::AuthCodeListenerParse)?; let (state, code) = parse_query(&request_line)?; if *expected_state.secret() != *state.secret() { return Err(OAuthError::InvalidState); } let message = include_str!("./login.html"); let response = format!( "HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}", message.len(), message ); stream .write_all(response.as_bytes()) .await .map_err(|_| OAuthError::AuthCodeListenerWrite)?; Ok(code) } fn parse_query(request_line: &str) -> Result<(CsrfToken, AuthorizationCode), OAuthError> { let query = request_line .split_whitespace() .nth(1) .ok_or(OAuthError::AuthCodeListenerParse)? .split("?") .nth(1) .ok_or(OAuthError::AuthCodeListenerParse)?; let mut query_params: HashMap<String, String> = url::form_urlencoded::parse(query.as_bytes()) .into_owned() .collect(); let csrf_token = query_params .remove("state") .map(CsrfToken::new) .ok_or(OAuthError::CsrfTokenNotFound)?; let code = query_params .remove("code") .map(AuthorizationCode::new) .ok_or(OAuthError::AuthCodeNotFound)?; Ok((csrf_token, code)) } // If the specified `redirect_uri` is HTTP, loopback, and contains a port, // then the corresponding socket address is returned. fn get_socket_address(redirect_uri: &str) -> Option<SocketAddr> { let url = match Url::parse(redirect_uri) { Ok(u) if u.scheme() == "http" && u.port().is_some() => u, _ => return None, }; let socket_addr = match url.socket_addrs(|| None) { Ok(mut addrs) => addrs.pop(), _ => None, }; if let Some(s) = socket_addr { if s.ip().is_loopback() { return socket_addr; } } None } #[cfg(test)] mod test { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use super::*; #[test] fn get_socket_address_none() { // No port assert_eq!(get_socket_address("http://127.0.0.1/foo"), None); assert_eq!(get_socket_address("http://127.0.0.1:/foo"), None); assert_eq!(get_socket_address("http://[::1]/foo"), None); // Not localhost assert_eq!(get_socket_address("http://56.0.0.1:1234/foo"), None); assert_eq!( get_socket_address("http://[3ffe:2a00:100:7031::1]:1234/foo"), None ); // Not http assert_eq!(get_socket_address("https://127.0.0.1/foo"), None); } #[test] fn get_socket_address_localhost() { let localhost_v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1234); let localhost_v6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8888); assert_eq!( get_socket_address("http://127.0.0.1:1234/foo"), Some(localhost_v4) ); assert_eq!( get_socket_address("http://[0:0:0:0:0:0:0:1]:8888/foo"), Some(localhost_v6) ); assert_eq!( get_socket_address("http://[::1]:8888/foo"), Some(localhost_v6) ); } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/connect/player.rs
src/connect/player.rs
use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::sync::{Arc, RwLock}; use futures::channel::mpsc::UnboundedSender; use gettextrs::gettext; use crate::api::{SpotifyApiClient, SpotifyApiError, SpotifyResult}; use crate::app::models::{ConnectPlayerState, RepeatMode, SongDescription}; use crate::app::state::{Device, PlaybackAction}; use crate::app::{AppAction, SongsSource}; #[derive(Debug)] pub enum ConnectCommand { SetDevice(String), PlayerLoadInContext { source: SongsSource, offset: usize, song: String, }, PlayerLoad { songs: Vec<String>, offset: usize, }, PlayerResume, PlayerPause, PlayerStop, PlayerSeek(usize), PlayerRepeat(RepeatMode), PlayerShuffle(bool), PlayerSetVolume(u8), } pub struct ConnectPlayer { api: Arc<dyn SpotifyApiClient + Send + Sync>, action_sender: UnboundedSender<AppAction>, device_id: RwLock<Option<String>>, last_queue: RwLock<u64>, last_state: RwLock<ConnectPlayerState>, } impl ConnectPlayer { pub fn new( api: Arc<dyn SpotifyApiClient + Send + Sync>, action_sender: UnboundedSender<AppAction>, ) -> Self { Self { api: api.clone(), action_sender, device_id: Default::default(), last_queue: Default::default(), last_state: Default::default(), } } fn send_actions(&self, actions: impl IntoIterator<Item = AppAction>) { for action in actions.into_iter() { self.action_sender.unbounded_send(action).unwrap(); } } fn device_lost(&self) { let _ = self.device_id.write().unwrap().take(); self.send_actions([ AppAction::ShowNotification(gettext("Connection to device lost!")), PlaybackAction::SwitchDevice(Device::Local).into(), PlaybackAction::SetAvailableDevices(vec![]).into(), ]); } async fn get_queue_if_changed(&self) -> Option<Vec<SongDescription>> { let last_queue = *self.last_queue.read().ok().as_deref().unwrap_or(&0u64); let songs = self.api.get_player_queue().await.ok(); songs.filter(|songs| { let hash = { let mut hasher = DefaultHasher::new(); songs.hash(&mut hasher); hasher.finish() }; if let Some(last_queue) = self.last_queue.try_write().ok().as_deref_mut() { *last_queue = hash; } hash != last_queue }) } async fn apply_remote_state(&self, state: &ConnectPlayerState) { if let Some(songs) = self.get_queue_if_changed().await { self.send_actions([PlaybackAction::LoadSongs(songs).into()]); } let play_pause = if state.is_playing { PlaybackAction::Load(state.current_song_id.clone().unwrap()) } else { PlaybackAction::Pause }; self.send_actions([ play_pause.into(), PlaybackAction::SetRepeatMode(state.repeat).into(), PlaybackAction::SetShuffled(state.shuffle).into(), PlaybackAction::SyncSeek(state.progress_ms).into(), ]); } pub fn has_device(&self) -> bool { self.device_id .read() .map(|it| it.is_some()) .unwrap_or(false) } pub async fn sync_state(&self) { debug!("polling connect device..."); let player_state = self.api.player_state().await; let Ok(state) = player_state else { self.device_lost(); return; }; self.apply_remote_state(&state).await; if let Ok(mut last_state) = self.last_state.write() { *last_state = state; } } async fn handle_player_load_in_context( &self, device_id: String, current_state: &ConnectPlayerState, command: ConnectCommand, ) -> SpotifyResult<()> { let ConnectCommand::PlayerLoadInContext { source, offset, song, } = command else { panic!("Illegal call"); }; let is_diff_song = current_state .current_song_id .as_ref() .map(|it| it != &song) .unwrap_or(true); let is_paused = !current_state.is_playing; if is_diff_song { let context = source.spotify_uri().unwrap(); self.api .player_play_in_context(device_id, context, offset) .await } else if is_paused { self.api.player_resume(device_id).await } else { Ok(()) } } async fn handle_player_load( &self, device_id: String, current_state: &ConnectPlayerState, command: ConnectCommand, ) -> SpotifyResult<()> { let ConnectCommand::PlayerLoad { songs, offset } = command else { panic!("Illegal call"); }; let is_diff_song = current_state .current_song_id .as_ref() .map(|it| it != &songs[offset]) .unwrap_or(true); let is_paused = !current_state.is_playing; if is_diff_song { self.api .player_play_no_context( device_id, songs .into_iter() .map(|s| format!("spotify:track:{}", s)) .collect(), offset, ) .await } else if is_paused { self.api.player_resume(device_id).await } else { Ok(()) } } async fn handle_other_command( &self, device_id: String, command: ConnectCommand, ) -> SpotifyResult<()> { let state = self.last_state.read(); let Ok(state) = state.as_deref() else { return Ok(()); }; match command { ConnectCommand::PlayerLoadInContext { .. } => { self.handle_player_load_in_context(device_id, state, command) .await } ConnectCommand::PlayerLoad { .. } => { self.handle_player_load(device_id, state, command).await } ConnectCommand::PlayerResume if !state.is_playing => { self.api.player_resume(device_id).await } ConnectCommand::PlayerPause if state.is_playing => { self.api.player_pause(device_id).await } ConnectCommand::PlayerSeek(offset) => self.api.player_seek(device_id, offset).await, ConnectCommand::PlayerRepeat(mode) => self.api.player_repeat(device_id, mode).await, ConnectCommand::PlayerShuffle(shuffle) => { self.api.player_shuffle(device_id, shuffle).await } ConnectCommand::PlayerSetVolume(volume) => { self.api.player_volume(device_id, volume).await } _ => Ok(()), } } pub async fn handle_command(&self, command: ConnectCommand) -> Option<()> { let device_lost = match command { ConnectCommand::SetDevice(new_device_id) => { self.device_id.write().ok()?.replace(new_device_id); self.sync_state().await; false } ConnectCommand::PlayerStop => { let device_id = self.device_id.write().ok()?.take(); if let Some(old_id) = device_id { let _ = self.api.player_pause(old_id).await; } false } _ => { let device_id = self.device_id.read().ok()?.clone(); if let Some(device_id) = device_id { let result = self.handle_other_command(device_id, command).await; matches!(result, Err(SpotifyApiError::BadStatus(404, _))) } else { true } } }; if device_lost { self.device_lost(); } Some(()) } }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
Diegovsky/riff
https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/connect/mod.rs
src/connect/mod.rs
use std::sync::Arc; use std::time::Duration; use futures::channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender}; use futures::StreamExt; use tokio::{task, time}; use crate::api::SpotifyApiClient; use crate::app::AppAction; mod player; pub use player::ConnectCommand; #[tokio::main] async fn connect_server( api: Arc<dyn SpotifyApiClient + Send + Sync>, action_sender: UnboundedSender<AppAction>, receiver: UnboundedReceiver<ConnectCommand>, ) { let player = Arc::new(player::ConnectPlayer::new(api, action_sender)); let player_clone = Arc::clone(&player); task::spawn(async move { let mut interval = time::interval(Duration::from_secs(5)); loop { interval.tick().await; if player_clone.has_device() { player_clone.sync_state().await; } } }); receiver .for_each(|command| async { player.handle_command(command).await.unwrap() }) .await; } pub fn start_connect_server( api: Arc<dyn SpotifyApiClient + Send + Sync>, action_sender: UnboundedSender<AppAction>, ) -> UnboundedSender<ConnectCommand> { let (sender, receiver) = unbounded(); std::thread::spawn(move || connect_server(api, action_sender, receiver)); sender }
rust
MIT
28e5c58658aaee9095b3ed7b6f92bfefeca4baa1
2026-01-04T20:22:28.974811Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/lib.rs
src/lib.rs
extern crate vec_map; pub mod classfile; pub mod classpath; pub mod instruction; pub mod rtda; pub mod shell; pub mod util;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/util/modified_utf8.rs
src/util/modified_utf8.rs
//! From [rust-jvm](https://github.com/maxmcc/rust-jvm/) //! Modified UTF-8 string slices. //! //! See [§4.4.7](https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.7). use std::char; /// Errors which can occur when attempting to interpret a sequence of `u8` as a modified UTF-8 /// string. #[derive(Debug)] pub struct ModifiedUtf8Error { valid_up_to: usize, } /// Converts a slice of bytes in modified UTF-8 encoding to a string slice. pub fn from_modified_utf8(bytes: &[u8]) -> Result<String, ModifiedUtf8Error> { // Refer to §4.4.7 for more information about the modified UTF-8 encoding. let mut result = String::new(); let mut offset = 0; let len = bytes.len(); while offset < len { let old_offset = offset; macro_rules! err { () => { return Err(ModifiedUtf8Error { valid_up_to: old_offset, }); }; } macro_rules! next { () => {{ offset += 1; if offset >= len { err!(); } bytes[offset] }}; } let x = bytes[offset]; if x < 0b0111_1111 { // pattern: 0xxxxxx result.push(x as char); } else if x < 0b1101_1111 { // pattern: 110xxxxx let y = next!(); if y < 0b1011_111 { // pattern: 10xxxxxx let c = ((x & 0x1f) << 6) + (y & 0x3f); result.push(c as char); } else { err!() } } else if x < 0b1110_1111 { // pattern: 1110xxxx let y = next!(); if y < 0b1011_1111 { // pattern: 10xxxxxx let z = next!(); if z < 0b1011_1111 { // pattern: 10xxxxxx let q: u32 = (((x & 0xf) as u32) << 12) + (((y & 0x3f) as u32) << 6) + ((z & 0x3f) as u32); let c = unsafe { char::from_u32_unchecked(q) }; result.push(c); } else { err!() } } else { err!() } } else if x == 0b1110_1101 { // pattern: 11101101 let v = next!(); if v < 0b1010_1111 { // pattern: 10101111 let w = next!(); if w < 0b1011_1111 { // pattern: 10xxxxxx let xx = next!(); if xx == 0b1110_1101 { // pattern: 11101101 let y = next!(); if y < 0b1011_1111 { // pattern: 1011xxxx let z = next!(); if z < 0b1011_1111 { // pattern: 10xxxxxx let q: u32 = 0x10000u32 + (((v & 0x0f) as u32) << 16) + (((w & 0x3f) as u32) << 10) + (((y & 0x0f) as u32) << 6) + ((z & 0x3f) as u32); let c = unsafe { char::from_u32_unchecked(q) }; result.push(c); } else { err!() } } else { err!() } } else { err!() } } else { err!() } } else { err!() } } else { err!() } offset += 1; } Ok(result) }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/util/code_reader.rs
src/util/code_reader.rs
extern crate byteorder; use self::byteorder::{BigEndian, ByteOrder}; use std; use std::rc::Rc; pub struct CodeReader { code: Rc<Vec<u8>>, pub pc: usize, } impl CodeReader { pub fn new(code: Rc<Vec<u8>>) -> CodeReader { CodeReader { code, pc: 0 } } pub fn set_pc(self, pc: usize) -> CodeReader { let CodeReader { pc: _, code } = self; CodeReader { code, pc } } pub fn read_u8(self) -> (u8, CodeReader) { let CodeReader { pc, code } = self; let val = code[pc]; let pc = pc + 1; let code_reader = CodeReader { pc, code }; (val, code_reader) } pub fn read_i8(self) -> (i8, CodeReader) { let CodeReader { pc, code } = self; let v = code[pc]; let val = unsafe { std::mem::transmute::<u8, i8>(v) }; let pc = pc + 1; let code_reader = CodeReader { pc, code }; (val, code_reader) } pub fn read_u16(self) -> (u16, CodeReader) { let CodeReader { pc, code } = self; let val = { let seq = &code[pc..(pc + 2)]; BigEndian::read_u16(&seq) }; let pc = pc + 2; let code_reader = CodeReader { pc, code }; (val, code_reader) } pub fn read_i16(self) -> (i16, CodeReader) { let CodeReader { pc, code } = self; let val = { let seq = &code[pc..(pc + 2)]; BigEndian::read_i16(&seq) }; let pc = pc + 2; let code_reader = CodeReader { pc, code }; (val, code_reader) } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/util/mod.rs
src/util/mod.rs
pub mod code_reader; pub mod converter; pub mod modified_utf8;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/util/converter.rs
src/util/converter.rs
use std; pub fn i32_to_f32(val: i32) -> f32 { unsafe { std::mem::transmute::<i32, f32>(val) } } pub fn f32_to_i32(val: f32) -> i32 { unsafe { std::mem::transmute::<f32, i32>(val) } } pub fn i64_to_i32seq(val: i64) -> [i32; 2] { unsafe { std::mem::transmute::<i64, [i32; 2]>(val) } } pub fn f64_to_i32seq(val: f64) -> [i32; 2] { unsafe { std::mem::transmute::<f64, [i32; 2]>(val) } } pub fn i32seq_to_i64(val: [i32; 2]) -> i64 { unsafe { std::mem::transmute::<[i32; 2], i64>(val) } } pub fn i32seq_to_f64(val: [i32; 2]) -> f64 { unsafe { std::mem::transmute::<[i32; 2], f64>(val) } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/instruction.rs
src/instruction/instruction.rs
use instruction::comparison::dcmp::*; use instruction::comparison::fcmp::*; use instruction::comparison::if_icmp::*; use instruction::comparison::ifcond::*; use instruction::comparison::lcmp::*; use instruction::constant::ldc::*; use instruction::constant::nop::NOP; use instruction::constant::xconst::*; use instruction::constant::xipush::*; use instruction::control::goto::*; use instruction::load::iload::*; use instruction::math::add::*; use instruction::math::and::*; use instruction::math::inc::*; use instruction::math::mul::*; use instruction::math::neg::*; use instruction::store::istore::*; use rtda::thread::Thread; use util::code_reader::CodeReader; pub struct ExecuteResult { pub thread: Thread, pub offset: isize, } pub fn execute(pc: usize, thread: Thread) -> (ExecuteResult, CodeReader) { let (frame, thread) = thread.pop_frame(); let code = frame.method.clone().code.clone(); let code_reader = CodeReader::new(code).set_pc(pc); let (opcode, after_opcode) = code_reader.read_u8(); let instruction = match opcode { 0x00 => NOP, 0x02 => ICONST_M1, 0x03 => ICONST_0, 0x04 => ICONST_1, 0x05 => ICONST_2, 0x06 => ICONST_3, 0x07 => ICONST_4, 0x08 => ICONST_5, 0x09 => LCONST_0, 0x0A => LCONST_1, 0x0B => FCONST_0, 0x0C => FCONST_1, 0x0D => FCONST_2, 0x0E => DCONST_0, 0x0F => DCONST_1, 0x10 => BIPUSH, 0x12 => LDC, 0x14 => LDC2_W, 0x1B => ILOAD_1, 0x1C => ILOAD_2, 0x3C => ISTORE_1, 0x3D => ISTORE_2, 0x60 => IADD, 0x68 => IMUL, 0x69 => LMUL, 0x6A => FMUL, 0x6B => DMUL, 0x74 => INEG, 0x75 => LNEG, 0x76 => FNEG, 0x77 => DNEG, 0x7E => IAND, 0x7F => LAND, 0x84 => IINC, 0x94 => LCMP, 0x95 => FCMPL, 0x96 => FCMPG, 0x97 => DCMPL, 0x98 => DCMPG, 0x99 => IFEQ, 0x9A => IFNE, 0x9B => IFLT, 0x9C => IFGE, 0x9D => IFGT, 0x9E => IFLE, 0x9F => IF_ICMPEQ, 0xA0 => IF_ICMPNE, 0xA1 => IF_ICMPLT, 0xA2 => IF_ICMPGE, 0xA3 => IF_ICMPGT, 0xA4 => IF_ICMPLE, 0xA7 => GOTO, _ => { println!("{:?}", frame); panic!("Unsupported opcode : {:X}", opcode) } }; let thread = thread.push_frame(frame); instruction(after_opcode, thread) }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/mod.rs
src/instruction/mod.rs
mod comparison; mod constant; mod control; pub mod instruction; mod load; mod math; mod store;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/constant/ldc.rs
src/instruction/constant/ldc.rs
use classfile::constant_info::ConstantInfo; use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] pub fn LDC(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("LDC"); let (index, code_reader) = code_reader.read_u8(); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let class_copy = class.clone(); let constant_info = class_copy.constant_pool.get(index as usize); let operand_stack = match constant_info { ConstantInfo::Integer(val) => operand_stack.push_int(*val), ConstantInfo::Float(val) => operand_stack.push_float(*val), _ => panic!("TODO: LDC"), }; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn LDC2_W(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("LDC2_W"); let (index, code_reader) = code_reader.read_u16(); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let class_copy = class.clone(); let constant_info = class_copy.constant_pool.get(index as usize); let operand_stack = match constant_info { ConstantInfo::Long(val) => operand_stack.push_long(*val), ConstantInfo::Double(val) => operand_stack.push_double(*val), _ => panic!("java.lang.ClassFormatError"), }; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/constant/mod.rs
src/instruction/constant/mod.rs
pub mod ldc; pub mod nop; pub mod xconst; pub mod xipush;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/constant/xconst.rs
src/instruction/constant/xconst.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] pub fn DCONST_0(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("DCONST_0"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_double(0f64); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn DCONST_1(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("DCONST_1"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_double(1f64); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn FCONST_0(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("FCONST_0"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_float(0f32); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn FCONST_1(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("FCONST_1"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_float(1f32); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn FCONST_2(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("FCONST_2"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_float(2f32); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn ICONST_M1(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("ICONST_M1"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(-1); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn ICONST_0(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("ICONST_0"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(0); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn ICONST_1(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("ICONST_1"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(1); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn ICONST_2(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("ICONST_2"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(2); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn ICONST_3(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("ICONST_3"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(3); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn ICONST_4(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("ICONST_4"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(4); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn ICONST_5(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("ICONST_5"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(5); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn LCONST_0(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("LCONST_0"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_long(0i64); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn LCONST_1(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("LCONST_1"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_long(1i64); let local_vars = local_vars; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[cfg(test)] mod tests { use classfile::constant_pool::ConstantPool; use classfile::member_info::MemberInfo; use instruction::constant::xconst::*; use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::heap::class::Class; use rtda::heap::method::Method; use rtda::thread::Thread; use rtda::vars::Vars; use std::rc::Rc; use util::code_reader::CodeReader; use vec_map::VecMap; #[test] #[allow(non_snake_case)] fn test_DCONST_0() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = DCONST_0(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_double(); assert_eq!(val, 0f64); } #[test] #[allow(non_snake_case)] fn test_DCONST_1() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = DCONST_1(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_double(); assert_eq!(val, 1f64); } #[test] #[allow(non_snake_case)] fn test_FCONST_0() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = FCONST_0(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_float(); assert_eq!(val, 0f32); } #[test] #[allow(non_snake_case)] fn test_FCONST_1() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = FCONST_1(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_float(); assert_eq!(val, 1f32); } #[test] #[allow(non_snake_case)] fn test_FCONST_2() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = FCONST_2(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_float(); assert_eq!(val, 2f32); } #[test] #[allow(non_snake_case)] fn test_ICONST_M1() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = ICONST_M1(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, -1); } #[test] #[allow(non_snake_case)] fn test_ICONST_0() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = ICONST_0(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 0); } #[test] #[allow(non_snake_case)] fn test_ICONST_1() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = ICONST_1(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 1); } #[test] #[allow(non_snake_case)] fn test_ICONST_2() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = ICONST_2(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 2); } #[test] #[allow(non_snake_case)] fn test_ICONST_3() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = ICONST_3(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 3); } #[test] #[allow(non_snake_case)] fn test_ICONST_4() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = ICONST_4(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 4); } #[test] #[allow(non_snake_case)] fn test_ICONST_5() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = ICONST_5(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 5); } #[test] #[allow(non_snake_case)] fn test_LCONST_0() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = LCONST_0(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_long(); assert_eq!(val, 0i64); } #[test] #[allow(non_snake_case)] fn test_LCONST_1() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = LCONST_1(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_long(); assert_eq!(val, 1i64); } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/constant/xipush.rs
src/instruction/constant/xipush.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] pub fn BIPUSH(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("BIPUSH"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (val, code_reader) = code_reader.read_i8(); let i = val; let operand_stack = operand_stack.push_int(i as i32); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/constant/nop.rs
src/instruction/constant/nop.rs
use instruction::instruction::ExecuteResult; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] pub fn NOP(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/comparison/dcmp.rs
src/instruction/comparison/dcmp.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] fn _dcmp(frame: Frame, flag: bool) -> (f64, f64, Frame) { let Frame { operand_stack, local_vars, method, class, } = frame; let (val2, operand_stack) = operand_stack.pop_double(); let (val1, operand_stack) = operand_stack.pop_double(); let operand_stack = if val1 > val2 { operand_stack.push_int(1) } else if val1 < val2 { operand_stack.push_int(-1) } else if val1 == val2 { operand_stack.push_int(0) } else if flag { operand_stack.push_int(1) } else { operand_stack.push_int(-1) }; let frame = Frame { class, operand_stack, local_vars, method, }; (val1, val2, frame) } #[allow(non_snake_case)] pub fn DCMPG(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("DCMPG"); let (frame, thread) = thread.pop_frame(); let (_, _, frame) = _dcmp(frame, true); let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn DCMPL(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("DCMPG"); let (frame, thread) = thread.pop_frame(); let (_, _, frame) = _dcmp(frame, false); let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[cfg(test)] mod tests { use classfile::constant_pool::ConstantPool; use classfile::member_info::MemberInfo; use instruction::comparison::dcmp::*; use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::heap::class::Class; use rtda::heap::method::Method; use rtda::operand_stack::OperandStack; use rtda::thread::Thread; use rtda::vars::Vars; use std::rc::Rc; use util::code_reader::CodeReader; use vec_map::VecMap; #[test] #[allow(non_snake_case)] fn test_DCMPL() { let frame = create_frame(1.48, 1.49); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = DCMPL(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, -1); } #[test] #[allow(non_snake_case)] fn test_DCMPG() { let frame = create_frame(1.49, 1.48); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = DCMPG(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 1); } #[test] #[allow(non_snake_case)] fn test_DCMPG_equal() { let frame = create_frame(1.49, 1.49); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = DCMPG(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 0); } fn create_frame(op1: f64, op2: f64) -> Frame { let operand_stack = OperandStack::new(10); let operand_stack = operand_stack.push_double(op1); let operand_stack = operand_stack.push_double(op2); let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); Frame { class, local_vars: Vars::new(10), operand_stack: operand_stack, method, } } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/comparison/fcmp.rs
src/instruction/comparison/fcmp.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] fn _fcmp(frame: Frame, flag: bool) -> (f32, f32, Frame) { let Frame { operand_stack, local_vars, method, class, } = frame; let (val2, operand_stack) = operand_stack.pop_float(); let (val1, operand_stack) = operand_stack.pop_float(); let operand_stack = if val1 < val2 { operand_stack.push_int(-1) } else if val1 > val2 { operand_stack.push_int(1) } else if val1 == val2 { operand_stack.push_int(0) } else if flag { operand_stack.push_int(1) } else { operand_stack.push_int(-1) }; let frame = Frame { class, operand_stack, local_vars, method, }; (val1, val2, frame) } #[allow(non_snake_case)] pub fn FCMPG(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("FCMPG"); let (frame, thread) = thread.pop_frame(); let (_, _, frame) = _fcmp(frame, true); let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn FCMPL(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("FCMPL"); let (frame, thread) = thread.pop_frame(); let (_, _, frame) = _fcmp(frame, false); let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[cfg(test)] mod tests { use classfile::constant_pool::ConstantPool; use classfile::member_info::MemberInfo; use instruction::comparison::fcmp::*; use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::heap::class::Class; use rtda::heap::method::Method; use rtda::operand_stack::OperandStack; use rtda::thread::Thread; use rtda::vars::Vars; use std::rc::Rc; use util::code_reader::CodeReader; use vec_map::VecMap; #[test] #[allow(non_snake_case)] fn test_FCMPL() { let frame = create_frame(0.03, 0.042); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = FCMPL(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, -1); } #[test] #[allow(non_snake_case)] fn test_FCMPG() { let frame = create_frame(1.21, 1.1); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = FCMPG(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 1); } #[test] #[allow(non_snake_case)] fn test_FCMPG_equal() { let frame = create_frame(2.345, 2.345); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = FCMPG(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 0); } fn create_frame(op1: f32, op2: f32) -> Frame { let operand_stack = OperandStack::new(10); let operand_stack = operand_stack.push_float(op1); let operand_stack = operand_stack.push_float(op2); let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); Frame { class, local_vars: Vars::new(10), operand_stack: operand_stack, method, } } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/comparison/lcmp.rs
src/instruction/comparison/lcmp.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] pub fn LCMP(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (val2, operand_stack) = operand_stack.pop_long(); let (val1, operand_stack) = operand_stack.pop_long(); let operand_stack = if val1 < val2 { operand_stack.push_int(-1) } else if val1 > val2 { operand_stack.push_int(1) } else { operand_stack.push_int(0) }; let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[cfg(test)] mod tests { use classfile::constant_pool::ConstantPool; use classfile::member_info::MemberInfo; use instruction::comparison::lcmp::*; use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::heap::class::Class; use rtda::heap::method::Method; use rtda::operand_stack::OperandStack; use rtda::thread::Thread; use rtda::vars::Vars; use std::rc::Rc; use util::code_reader::CodeReader; use vec_map::VecMap; #[test] #[allow(non_snake_case)] fn test_LCMP_gt() { let frame = create_frame(9223372036854775807i64, 9223372036854775806i64); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = LCMP(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 1); } #[test] #[allow(non_snake_case)] fn test_LCMP_lt() { let frame = create_frame(-9223372036854775806i64, 9223372036854775807i64); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = LCMP(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, -1); } #[test] #[allow(non_snake_case)] fn test_LCMP_eq() { let frame = create_frame(-9223372036854775806i64, -9223372036854775806i64); let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = LCMP(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 0); } fn create_frame(op1: i64, op2: i64) -> Frame { let operand_stack = OperandStack::new(10); let operand_stack = operand_stack.push_long(op1); let operand_stack = operand_stack.push_long(op2); let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); Frame { class, local_vars: Vars::new(10), operand_stack, method, } } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/comparison/ifcond.rs
src/instruction/comparison/ifcond.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; fn _ifcond(frame: Frame) -> (i32, Frame) { let Frame { operand_stack, local_vars, method, class, } = frame; let (val, operand_stack) = operand_stack.pop_int(); let frame = Frame { class, operand_stack, local_vars, method, }; (val, frame) } #[allow(non_snake_case)] pub fn IFEQ(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IFEQ"); let (offset, code_reader) = code_reader.read_i16(); let (frame, thread) = thread.pop_frame(); let (val, frame) = _ifcond(frame); let offset = if val == 0 { offset as isize } else { 0 }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn IFNE(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IFNE"); let (offset, code_reader) = code_reader.read_i16(); let (frame, thread) = thread.pop_frame(); let (val, frame) = _ifcond(frame); let offset = if val != 0 { offset as isize } else { 0 }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn IFLT(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IFLT"); let (offset, code_reader) = code_reader.read_i16(); let (frame, thread) = thread.pop_frame(); let (val, frame) = _ifcond(frame); let offset = if val < 0 { offset as isize } else { 0 }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn IFGE(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IFGE"); let (offset, code_reader) = code_reader.read_i16(); let (frame, thread) = thread.pop_frame(); let (val, frame) = _ifcond(frame); let offset = if val >= 0 { offset as isize } else { 0 }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn IFGT(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IFGT"); let (offset, code_reader) = code_reader.read_i16(); let (frame, thread) = thread.pop_frame(); let (val, frame) = _ifcond(frame); let offset = if val > 0 { offset as isize } else { 0 }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn IFLE(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IFLE"); let (offset, code_reader) = code_reader.read_i16(); let (frame, thread) = thread.pop_frame(); let (val, frame) = _ifcond(frame); let offset = if val <= 0 { offset as isize } else { 0 }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset }; (execute_result, code_reader) } #[cfg(test)] mod tests { use classfile::constant_pool::ConstantPool; use classfile::member_info::MemberInfo; use instruction::comparison::ifcond::*; use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::heap::class::Class; use rtda::heap::method::Method; use rtda::thread::Thread; use rtda::vars::Vars; use std::rc::Rc; use util::code_reader::CodeReader; use vec_map::VecMap; #[test] #[allow(non_snake_case)] fn test_IFEQ_success() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(0); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IFEQ(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 257); } #[allow(non_snake_case)] fn test_IFEQ_fail() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(0); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IFEQ(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 0); } #[test] #[allow(non_snake_case)] fn test_IFNE_success() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(1); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IFNE(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 257); } #[allow(non_snake_case)] fn test_IFNE_fail() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(0); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IFNE(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 0); } #[test] #[allow(non_snake_case)] fn test_IFLT_success() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(-1); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IFLT(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 257); } #[allow(non_snake_case)] fn test_IFLT_fail() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(0); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IFLT(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 0); } #[test] #[allow(non_snake_case)] fn test_IFGE_success() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(0); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IFGE(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 257); } #[allow(non_snake_case)] fn test_IFGE_fail() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(-1); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IFGE(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 0); } #[test] #[allow(non_snake_case)] fn test_IFGT_success() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(1); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IFGT(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 257); } #[allow(non_snake_case)] fn test_IFGT_fail() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(0); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IFGT(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 0); } #[test] #[allow(non_snake_case)] fn test_IFLE_success() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(0); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IFLE(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 257); } #[allow(non_snake_case)] fn test_IFLE_fail() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(1); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IFLE(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 0); } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/comparison/mod.rs
src/instruction/comparison/mod.rs
pub mod dcmp; pub mod fcmp; pub mod if_icmp; pub mod ifcond; pub mod lcmp;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/comparison/if_icmp.rs
src/instruction/comparison/if_icmp.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] fn _icmpPop(frame: Frame) -> (i32, i32, Frame) { let Frame { operand_stack, local_vars, method, class, } = frame; let (val2, operand_stack) = operand_stack.pop_int(); let (val1, operand_stack) = operand_stack.pop_int(); let frame = Frame { class, operand_stack, local_vars, method, }; (val1, val2, frame) } #[allow(non_snake_case)] pub fn IF_ICMPGT(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IF_ICMPGT"); let (offset, code_reader) = code_reader.read_i16(); let (frame, thread) = thread.pop_frame(); let (val1, val2, frame) = _icmpPop(frame); let offset = if val1 > val2 { offset as isize } else { 0 }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn IF_ICMPGE(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IF_ICMPGE"); let (offset, code_reader) = code_reader.read_i16(); let (frame, thread) = thread.pop_frame(); let (val1, val2, frame) = _icmpPop(frame); let offset = if val1 >= val2 { offset as isize } else { 0 }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn IF_ICMPEQ(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IF_ICMPEQ"); let (offset, code_reader) = code_reader.read_i16(); let (frame, thread) = thread.pop_frame(); let (val1, val2, frame) = _icmpPop(frame); let offset = if val1 == val2 { offset as isize } else { 0 }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn IF_ICMPNE(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IF_ICMPNE"); let (offset, code_reader) = code_reader.read_i16(); let (frame, thread) = thread.pop_frame(); let (val1, val2, frame) = _icmpPop(frame); let offset = if val1 != val2 { offset as isize } else { 0 }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn IF_ICMPLT(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IF_ICMPLT"); let (offset, code_reader) = code_reader.read_i16(); let (frame, thread) = thread.pop_frame(); let (val1, val2, frame) = _icmpPop(frame); let offset = if val1 < val2 { offset as isize } else { 0 }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn IF_ICMPLE(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IF_ICMPLE"); let (offset, code_reader) = code_reader.read_i16(); let (frame, thread) = thread.pop_frame(); let (val1, val2, frame) = _icmpPop(frame); let offset = if val1 <= val2 { offset as isize } else { 0 }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset }; (execute_result, code_reader) } #[cfg(test)] mod tests { use classfile::constant_pool::ConstantPool; use classfile::member_info::MemberInfo; use instruction::comparison::if_icmp::*; use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::heap::class::Class; use rtda::heap::method::Method; use rtda::thread::Thread; use rtda::vars::Vars; use std::rc::Rc; use util::code_reader::CodeReader; use vec_map::VecMap; #[test] #[allow(non_snake_case)] fn test_IF_ICMPGT_success() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(1); let operand_stack = operand_stack.push_int(0); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IF_ICMPGT(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 257); } #[test] #[allow(non_snake_case)] fn test_IF_ICMPGT_fail() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(1); let operand_stack = operand_stack.push_int(2); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IF_ICMPGT(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 0); } #[test] #[allow(non_snake_case)] fn test_IF_ICMPGE_success() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(1); let operand_stack = operand_stack.push_int(1); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IF_ICMPGE(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 257); } #[test] #[allow(non_snake_case)] fn test_IF_ICMPGE_fail() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(0); let operand_stack = operand_stack.push_int(2); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IF_ICMPGE(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 0); } #[test] #[allow(non_snake_case)] fn test_IF_ICMPEQ_success() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(-1); let operand_stack = operand_stack.push_int(-1); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IF_ICMPEQ(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 257); } #[test] #[allow(non_snake_case)] fn test_IF_ICMPEQ_fail() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(0); let operand_stack = operand_stack.push_int(1); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IF_ICMPEQ(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 0); } #[test] #[allow(non_snake_case)] fn test_IF_ICMPNE_success() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(0); let operand_stack = operand_stack.push_int(1); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IF_ICMPNE(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 257); } #[test] #[allow(non_snake_case)] fn test_IF_ICMPNE_fail() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(-1); let operand_stack = operand_stack.push_int(-1); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IF_ICMPNE(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 0); } #[test] #[allow(non_snake_case)] fn test_IF_ICMPLT_success() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(1); let operand_stack = operand_stack.push_int(2); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IF_ICMPLT(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 257); } #[test] #[allow(non_snake_case)] fn test_IF_ICMPLT_fail() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(0); let operand_stack = operand_stack.push_int(0); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IF_ICMPLT(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 0); } #[test] #[allow(non_snake_case)] fn test_IF_ICMPLE_success() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(0); let operand_stack = operand_stack.push_int(0); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IF_ICMPLE(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 257); } #[test] #[allow(non_snake_case)] fn test_IF_ICMPLE_fail() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(2); let operand_stack = operand_stack.push_int(1); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread: _, offset }, _) = IF_ICMPLE(CodeReader::new(Rc::new(vec![1, 1])), thread); assert_eq!(offset, 0); } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/store/istore.rs
src/instruction/store/istore.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; fn _istore(frame: Frame, index: usize) -> Frame { let Frame { operand_stack, local_vars, method, class, } = frame; let (val, operand_stack) = operand_stack.pop_int(); let local_vars = local_vars.set_int(index, val); Frame { class, operand_stack, local_vars, method, } } #[allow(non_snake_case)] pub fn ISTORE_1(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("ISTORE_1"); let (frame, thread) = thread.pop_frame(); let frame = _istore(frame, 1); let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn ISTORE_2(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("ISTORE_2"); let (frame, thread) = thread.pop_frame(); let frame = _istore(frame, 2); let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/store/mod.rs
src/instruction/store/mod.rs
pub mod istore;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/math/mod.rs
src/instruction/math/mod.rs
pub mod add; pub mod and; pub mod inc; pub mod mul; pub mod neg;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/math/inc.rs
src/instruction/math/inc.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] pub fn IINC(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IINC"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (index, code_reader) = code_reader.read_u8(); let (val_1, code_reader) = code_reader.read_u8(); let index = index as usize; let val_1 = val_1 as i32; let val_2 = local_vars.get_int(index); let val = val_1 + val_2; let local_vars = local_vars.set_int(index, val); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/math/neg.rs
src/instruction/math/neg.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] pub fn DNEG(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v, operand_stack) = operand_stack.pop_double(); let operand_stack = operand_stack.push_double(-v); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn FNEG(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v, operand_stack) = operand_stack.pop_float(); let operand_stack = operand_stack.push_float(-v); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn INEG(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v, operand_stack) = operand_stack.pop_int(); let operand_stack = operand_stack.push_int(-v); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn LNEG(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v, operand_stack) = operand_stack.pop_long(); let operand_stack = operand_stack.push_long(-v); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[cfg(test)] mod tests { use classfile::constant_pool::ConstantPool; use classfile::member_info::MemberInfo; use instruction::instruction::ExecuteResult; use instruction::math::neg::*; use rtda::frame::Frame; use rtda::heap::class::Class; use rtda::heap::method::Method; use rtda::thread::Thread; use rtda::vars::Vars; use std::f32; use std::f64; use std::rc::Rc; use util::code_reader::CodeReader; use vec_map::VecMap; #[test] #[allow(non_snake_case)] fn test_DNEG() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_double(2f64); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = DNEG(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_double(); assert_eq!(val, -2f64); } #[test] #[allow(non_snake_case)] fn test_DNEG_zero() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_double(-0f64); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = DNEG(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_double(); assert_eq!(val, 0f64); } #[test] #[allow(non_snake_case)] fn test_DNEG_inf() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_double(f64::INFINITY); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = DNEG(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_double(); assert_eq!(val, f64::NEG_INFINITY); } #[test] #[allow(non_snake_case)] fn test_FNEG() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_float(-100.7678f32); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = FNEG(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_float(); assert_eq!(val, 100.7678f32); } #[test] #[allow(non_snake_case)] fn test_FNEG_max_min() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_float(f32::MAX); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = FNEG(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_float(); assert_eq!(val, f32::MIN); } #[test] #[allow(non_snake_case)] fn test_INEG() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(234556); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = INEG(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, -234556); } #[test] #[allow(non_snake_case)] fn test_LNEG() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_long(-54875845748435i64); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = LNEG(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_long(); assert_eq!(val, 54875845748435i64); } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/math/and.rs
src/instruction/math/and.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] pub fn IAND(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v2, operand_stack) = operand_stack.pop_int(); let (v1, operand_stack) = operand_stack.pop_int(); let result = v1 & v2; let operand_stack = operand_stack.push_int(result); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn LAND(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v2, operand_stack) = operand_stack.pop_long(); let (v1, operand_stack) = operand_stack.pop_long(); let result = v1 & v2; let operand_stack = operand_stack.push_long(result); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[cfg(test)] mod tests { use classfile::constant_pool::ConstantPool; use classfile::member_info::MemberInfo; use instruction::instruction::ExecuteResult; use instruction::math::and::*; use rtda::frame::Frame; use rtda::heap::class::Class; use rtda::heap::method::Method; use rtda::thread::Thread; use rtda::vars::Vars; use std::rc::Rc; use util::code_reader::CodeReader; use vec_map::VecMap; #[test] #[allow(non_snake_case)] fn test_IAND() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(350); let operand_stack = operand_stack.push_int(678); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = IAND(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 6); } #[test] #[allow(non_snake_case)] fn test_LAND() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_long(12345678969); let operand_stack = operand_stack.push_long(2997924580); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = LAND(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_long(); assert_eq!(val, 2458914912); } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/math/add.rs
src/instruction/math/add.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] pub fn IADD(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IADD"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v2, operand_stack) = operand_stack.pop_int(); let (v1, operand_stack) = operand_stack.pop_int(); let result = v1 + v2; let operand_stack = operand_stack.push_int(result); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn DADD(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("DADD"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v2, operand_stack) = operand_stack.pop_double(); let (v1, operand_stack) = operand_stack.pop_double(); let result = v1 + v2; let operand_stack = operand_stack.push_double(result); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn LADD(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("LADD"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v2, operand_stack) = operand_stack.pop_long(); let (v1, operand_stack) = operand_stack.pop_long(); let result = v1 + v2; let operand_stack = operand_stack.push_long(result); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn FADD(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("FADD"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v2, operand_stack) = operand_stack.pop_float(); let (v1, operand_stack) = operand_stack.pop_float(); let result = v1 + v2; let operand_stack = operand_stack.push_float(result); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[cfg(test)] mod tests { use classfile::constant_pool::ConstantPool; use classfile::member_info::MemberInfo; use instruction::instruction::ExecuteResult; use instruction::math::add::*; use rtda::frame::Frame; use rtda::heap::class::Class; use rtda::heap::method::Method; use rtda::thread::Thread; use rtda::vars::Vars; use std::rc::Rc; use util::code_reader::CodeReader; use vec_map::VecMap; #[test] #[allow(non_snake_case)] fn test_IADD() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(2); let operand_stack = operand_stack.push_int(3); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = IADD(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 5); } #[test] #[allow(non_snake_case)] fn test_DADD() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_double(2.71828182845f64); let operand_stack = operand_stack.push_double(3.1415926535897926f64); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = DADD(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_double(); assert_eq!(val, 5.8598744820397926); } #[test] #[allow(non_snake_case)] fn test_FADD() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_float(3.1415926); let operand_stack = operand_stack.push_float(3.1415926); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = FADD(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_float(); assert_eq!(val, 6.2831852); } #[test] #[allow(non_snake_case)] fn test_LADD() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_long(12345678969); let operand_stack = operand_stack.push_long(2997924580); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = DADD(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_long(); assert_eq!(val, 15343603549); } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/math/mul.rs
src/instruction/math/mul.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] pub fn DMUL(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("DMUL"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v2, operand_stack) = operand_stack.pop_double(); let (v1, operand_stack) = operand_stack.pop_double(); let result = v1 * v2; let operand_stack = operand_stack.push_double(result); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn FMUL(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("FMUL"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v2, operand_stack) = operand_stack.pop_float(); let (v1, operand_stack) = operand_stack.pop_float(); let result = v1 * v2; let operand_stack = operand_stack.push_float(result); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn IMUL(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("IMUL"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v2, operand_stack) = operand_stack.pop_int(); let (v1, operand_stack) = operand_stack.pop_int(); let result = v1 * v2; let operand_stack = operand_stack.push_int(result); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn LMUL(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("LMUL"); let (frame, thread) = thread.pop_frame(); let Frame { operand_stack, local_vars, method, class, } = frame; let (v2, operand_stack) = operand_stack.pop_long(); let (v1, operand_stack) = operand_stack.pop_long(); let result = v1 * v2; let operand_stack = operand_stack.push_long(result); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[cfg(test)] mod test { use classfile::constant_pool::ConstantPool; use classfile::member_info::MemberInfo; use instruction::instruction::ExecuteResult; use instruction::math::mul::*; use rtda::frame::Frame; use rtda::heap::class::Class; use rtda::heap::method::Method; use rtda::thread::Thread; use rtda::vars::Vars; use std::rc::Rc; use util::code_reader::CodeReader; use vec_map::VecMap; #[test] #[allow(non_snake_case)] fn test_DMUL() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_double(2.71828182845f64); let operand_stack = operand_stack.push_double(3.1415926535897926f64); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = DMUL(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_double(); assert_eq!(val, 8.53973422264514888498427947f64); } #[test] #[allow(non_snake_case)] fn test_FMUL() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_float(2.71828182845f32); let operand_stack = operand_stack.push_float(3.1415926535897926f32); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = FMUL(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_float(); assert_eq!(val, 8.53973422264514888498427947f32); } #[test] #[allow(non_snake_case)] fn test_IMUL() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_int(2); let operand_stack = operand_stack.push_int(3); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = IMUL(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_int(); assert_eq!(val, 6); } #[test] #[allow(non_snake_case)] fn test_LMUL() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: vec![], })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); let Frame { operand_stack, local_vars, method, class, } = frame; let operand_stack = operand_stack.push_long(1234567890); let operand_stack = operand_stack.push_long(2997924580); let frame = Frame { class, operand_stack, local_vars, method, }; let thread = Thread::new().push_frame(frame); let (ExecuteResult { thread, offset: _ }, _) = LMUL(CodeReader::new(Rc::new(vec![])), thread); let (frame, _) = thread.pop_frame(); let (val, _) = frame.operand_stack.pop_long(); assert_eq!(val, 3701141423109736200); } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/load/mod.rs
src/instruction/load/mod.rs
pub mod iload;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/load/iload.rs
src/instruction/load/iload.rs
use instruction::instruction::ExecuteResult; use rtda::frame::Frame; use rtda::thread::Thread; use util::code_reader::CodeReader; fn _iload(frame: Frame, index: usize) -> Frame { let Frame { operand_stack, local_vars, method, class, } = frame; let val = local_vars.get_int(index); let operand_stack = operand_stack.push_int(val); Frame { class, operand_stack, local_vars, method, } } #[allow(non_snake_case)] pub fn ILOAD_0(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("ILOAD_0"); let (frame, thread) = thread.pop_frame(); let frame = _iload(frame, 0); let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn ILOAD_1(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("ILOAD_1"); let (frame, thread) = thread.pop_frame(); let frame = _iload(frame, 1); let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) } #[allow(non_snake_case)] pub fn ILOAD_2(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("ILOAD_2"); let (frame, thread) = thread.pop_frame(); let frame = _iload(frame, 2); let thread = thread.push_frame(frame); let execute_result = ExecuteResult { thread, offset: 0 }; (execute_result, code_reader) }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/control/goto.rs
src/instruction/control/goto.rs
use instruction::instruction::ExecuteResult; use rtda::thread::Thread; use util::code_reader::CodeReader; #[allow(non_snake_case)] pub fn GOTO(code_reader: CodeReader, thread: Thread) -> (ExecuteResult, CodeReader) { println!("GOTO"); let (offset, code_reader) = code_reader.read_i16(); let offset = offset as isize; let execute_result = ExecuteResult { thread, offset }; (execute_result, code_reader) }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/instruction/control/mod.rs
src/instruction/control/mod.rs
pub mod goto;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/bin/main.rs
src/bin/main.rs
extern crate jvm; use jvm::classpath::classpath::parse; use jvm::instruction::instruction; use jvm::instruction::instruction::ExecuteResult; use jvm::rtda::frame::Frame; use jvm::rtda::heap::class::Class; use jvm::rtda::heap::class_loader::ClassLoader; use jvm::rtda::heap::method::Method; use jvm::rtda::thread::Thread; use jvm::shell::command::Command; use std::rc::Rc; fn main() { let class_name = "src.test_data.FibonacciTest"; let class_name = class_name.replace('.', "/"); let command = Command { class_name, cp_opt: None, jre_opt: None, args: vec![], }; start_jvm(command); } fn start_jvm(command: Command) { let class_path = parse(command.jre_opt, command.cp_opt); let class_loader = ClassLoader::new(class_path); let (main_class, _) = class_loader.load(command.class_name); let main_method = main_class.main_method(); interpret(main_class, main_method) } fn interpret(class: Rc<Class>, method: Rc<Method>) { let thread = Thread::new(); let frame = Frame::new(class, method); let thread = thread.push_frame(frame); execute(thread); } fn execute(thread: Thread) { let mut mut_pc = 0usize; let mut mut_thread = thread; while !mut_thread.is_stack_empty() { let thread = mut_thread; let pc = mut_pc; let (execute_result, after_execute) = instruction::execute(mut_pc, thread); let ExecuteResult { thread, offset } = execute_result; mut_pc = match offset { 0 => after_execute.pc, i => (pc as isize + i) as usize, }; mut_thread = thread; println!("pc: {}", pc); println!("offset: {}", offset); println!("mut_pc: {}", mut_pc); } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/classfile/constant_info.rs
src/classfile/constant_info.rs
#[derive(Debug)] pub enum ConstantInfo { Integer(i32), Float(f32), Long(i64), Double(f64), UTF8(String), String(u16), Class { name_index: u16, }, NameAndType { name_index: u16, descriptor_index: u16, }, FieldRef { class_index: u16, name_and_type_index: u16, }, MethodRef { class_index: u16, name_and_type_index: u16, }, InterfaceMethodRef { class_index: u16, name_and_type_index: u16, }, }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/classfile/class_reader.rs
src/classfile/class_reader.rs
extern crate byteorder; use vec_map::VecMap; use self::byteorder::{BigEndian, ByteOrder}; use classfile::attribute_info::{ AttributeInfo, ExceptionTableEntry, LineNumberTableEntry, LocalVariableTableEntry, }; use classfile::class_file::ClassFile; use classfile::constant_info::ConstantInfo; use classfile::constant_pool::ConstantPool; use classfile::member_info::MemberInfo; use std::rc::Rc; use util::modified_utf8::from_modified_utf8; const CONSTANT_UTF8: u8 = 1; const CONSTANT_INTEGER: u8 = 3; const CONSTANT_FLOAT: u8 = 4; const CONSTANT_LONG: u8 = 5; const CONSTANT_DOUBLE: u8 = 6; const CONSTANT_CLASS: u8 = 7; const CONSTANT_STRING: u8 = 8; const CONSTANT_FIELDREF: u8 = 9; const CONSTANT_METHODREF: u8 = 10; const CONSTANT_INTERFACE_METHODREF: u8 = 11; const CONSTANT_NAME_AND_TYPE: u8 = 12; #[derive(Debug)] pub struct VersionInfo { major_version: u16, minor_version: u16, } pub trait ClassReader { fn read_u8(&self) -> (u8, &[u8]); fn read_u16(&self) -> (u16, &[u8]); fn read_u16s(&self) -> (Vec<u16>, &[u8]); fn read_u32(&self) -> (u32, &[u8]); fn read_i32(&self) -> (i32, &[u8]); fn read_f32(&self) -> (f32, &[u8]); fn read_i64(&self) -> (i64, &[u8]); fn read_f64(&self) -> (f64, &[u8]); fn read_bytes(&self, n: usize) -> (&[u8], &[u8]); fn read_and_check_magic(&self) -> (u32, &[u8]); fn read_and_check_version(&self) -> (VersionInfo, &[u8]); fn read_constant_info(&self) -> (ConstantInfo, &[u8]); fn read_constant_pool(&self) -> (ConstantPool, &[u8]); fn read_access_flags(&self) -> (u16, &[u8]); fn read_this_class(&self) -> (u16, &[u8]); fn read_super_class(&self) -> (u16, &[u8]); fn read_interfaces(&self) -> (Vec<u16>, &[u8]); fn read_member(&self, constant_pool: &ConstantPool) -> (MemberInfo, &[u8]); fn read_members(&self, constant_pool: &ConstantPool) -> (Vec<MemberInfo>, &[u8]); fn read_exception_table(&self) -> (Vec<ExceptionTableEntry>, &[u8]); fn read_line_number_table(&self) -> (Vec<LineNumberTableEntry>, &[u8]); fn read_local_variable_table(&self) -> (Vec<LocalVariableTableEntry>, &[u8]); fn read_attribute(&self, constant_pool: &ConstantPool) -> (AttributeInfo, &[u8]); fn read_attributes(&self, constant_pool: &ConstantPool) -> (Vec<AttributeInfo>, &[u8]); fn parse(&self) -> ClassFile; } impl ClassReader for [u8] { fn read_u8(&self) -> (u8, &[u8]) { let (a, b) = self.split_at(1); (a[0], b) } fn read_u16(&self) -> (u16, &[u8]) { let (a, b) = self.split_at(2); (BigEndian::read_u16(a), b) } fn read_u16s(&self) -> (Vec<u16>, &[u8]) { let (n, after_n) = self.read_u16(); let mut s: Vec<u16> = Vec::with_capacity(n as usize); let mut rest = after_n; for _ in 1..=n { let (value, next_rest) = rest.read_u16(); s.push(value); rest = next_rest; } (s, rest) } fn read_u32(&self) -> (u32, &[u8]) { let (a, b) = self.split_at(4); (BigEndian::read_u32(a), b) } fn read_i32(&self) -> (i32, &[u8]) { let (a, b) = self.split_at(4); (BigEndian::read_i32(a), b) } fn read_f32(&self) -> (f32, &[u8]) { let (a, b) = self.split_at(4); (BigEndian::read_f32(a), b) } fn read_i64(&self) -> (i64, &[u8]) { let (a, b) = self.split_at(8); (BigEndian::read_i64(a), b) } fn read_f64(&self) -> (f64, &[u8]) { let (a, b) = self.split_at(8); (BigEndian::read_f64(a), b) } fn read_bytes(&self, n: usize) -> (&[u8], &[u8]) { self.split_at(n) } fn read_and_check_magic(&self) -> (u32, &[u8]) { let result = self.read_u32(); let (magic, _) = result; assert_eq!(magic, 0xCAFEBABE); result } fn read_and_check_version(&self) -> (VersionInfo, &[u8]) { let (minor_version, after_minor_version) = self.read_u16(); let (major_version, after_major_version) = after_minor_version.read_u16(); assert_eq!(major_version, 52); assert_eq!(minor_version, 0); let version_info = VersionInfo { major_version, minor_version, }; (version_info, after_major_version) } fn read_constant_info(&self) -> (ConstantInfo, &[u8]) { let (tag, after_tag) = self.read_u8(); match tag { CONSTANT_INTEGER => { let (val, rest) = after_tag.read_i32(); (ConstantInfo::Integer(val), rest) } CONSTANT_FLOAT => { let (val, rest) = after_tag.read_f32(); (ConstantInfo::Float(val), rest) } CONSTANT_LONG => { let (val, rest) = after_tag.read_i64(); (ConstantInfo::Long(val), rest) } CONSTANT_DOUBLE => { let (val, rest) = after_tag.read_f64(); (ConstantInfo::Double(val), rest) } CONSTANT_UTF8 => { let (length, after_length) = after_tag.read_u16(); let (bytes, rest) = after_length.read_bytes(length as usize); let string: String = from_modified_utf8(bytes).unwrap(); (ConstantInfo::UTF8(string), rest) } CONSTANT_STRING => { let (val, rest) = after_tag.read_u16(); (ConstantInfo::String(val), rest) } CONSTANT_CLASS => { let (name_index, rest) = after_tag.read_u16(); (ConstantInfo::Class { name_index }, rest) } CONSTANT_NAME_AND_TYPE => { let (name_index, after_name_index) = after_tag.read_u16(); let (descriptor_index, rest) = after_name_index.read_u16(); ( ConstantInfo::NameAndType { name_index, descriptor_index, }, rest, ) } CONSTANT_FIELDREF => { let (class_index, after_class_index) = after_tag.read_u16(); let (name_and_type_index, rest) = after_class_index.read_u16(); ( ConstantInfo::FieldRef { class_index, name_and_type_index, }, rest, ) } CONSTANT_METHODREF => { let (class_index, after_class_index) = after_tag.read_u16(); let (name_and_type_index, rest) = after_class_index.read_u16(); ( ConstantInfo::MethodRef { class_index, name_and_type_index, }, rest, ) } CONSTANT_INTERFACE_METHODREF => { let (class_index, after_class_index) = after_tag.read_u16(); let (name_and_type_index, rest) = after_class_index.read_u16(); ( ConstantInfo::InterfaceMethodRef { class_index, name_and_type_index, }, rest, ) } _ => { panic!("Wrong tag type"); } } } fn read_constant_pool(&self) -> (ConstantPool, &[u8]) { let (count, after_count) = self.read_u16(); let mut constant_pool: ConstantPool = ConstantPool { vec_map: VecMap::with_capacity((count + 1) as usize), }; let mut i: usize = 1; let mut rest: &[u8] = after_count; while i < (count as usize) { let (constant_info, next_rest) = rest.read_constant_info(); rest = next_rest; let add = match constant_info { ConstantInfo::Long(_) | ConstantInfo::Double(_) => 2, _ => 1, }; constant_pool.insert(i, constant_info); i = i + add; } (constant_pool, rest) } fn read_access_flags(&self) -> (u16, &[u8]) { self.read_u16() } fn read_this_class(&self) -> (u16, &[u8]) { self.read_u16() } fn read_super_class(&self) -> (u16, &[u8]) { self.read_u16() } fn read_interfaces(&self) -> (Vec<u16>, &[u8]) { self.read_u16s() } fn read_member(&self, constant_pool: &ConstantPool) -> (MemberInfo, &[u8]) { let (access_flags, after_access_flags) = self.read_u16(); let (name_index, after_name_index) = after_access_flags.read_u16(); let (descriptor_index, after_descriptor_index) = after_name_index.read_u16(); let (attributes, after_attributes) = after_descriptor_index.read_attributes(constant_pool); let name = match constant_pool.get(name_index as usize) { ConstantInfo::UTF8(ref name) => name.to_owned(), _ => panic!("name isn't UTF8"), }; let descriptor = match constant_pool.get(descriptor_index as usize) { ConstantInfo::UTF8(ref descriptor) => descriptor.to_owned(), _ => panic!("descriptor isn't UTF8"), }; let member_info = MemberInfo { access_flags, name_index, descriptor_index, attributes, name, descriptor, }; (member_info, after_attributes) } fn read_members(&self, constant_pool: &ConstantPool) -> (Vec<MemberInfo>, &[u8]) { let (count, after_count) = self.read_u16(); let mut members: Vec<MemberInfo> = Vec::with_capacity(count as usize); let mut rest = after_count; for _ in 1..=count { let (member, after_member) = rest.read_member(constant_pool); members.push(member); rest = after_member; } (members, rest) } fn read_exception_table(&self) -> (Vec<ExceptionTableEntry>, &[u8]) { let (exception_table_length, after_exception_table_length) = self.read_u16(); let mut exception_table: Vec<ExceptionTableEntry> = Vec::with_capacity(exception_table_length as usize); let mut rest = after_exception_table_length; for _ in 1..=exception_table_length { let (start_pc, after_start_pc) = rest.read_u16(); let (end_pc, after_end_pc) = after_start_pc.read_u16(); let (handler_pc, after_handler_pc) = after_end_pc.read_u16(); let (catch_type, after_catch_type) = after_handler_pc.read_u16(); let exception_table_entry = ExceptionTableEntry { start_pc, end_pc, handler_pc, catch_type, }; exception_table.push(exception_table_entry); rest = after_catch_type; } (exception_table, rest) } fn read_line_number_table(&self) -> (Vec<LineNumberTableEntry>, &[u8]) { let (line_number_table_length, after_line_number_table_length) = self.read_u16(); let mut line_number_table: Vec<LineNumberTableEntry> = Vec::with_capacity(line_number_table_length as usize); let mut rest = after_line_number_table_length; for _ in 1..=line_number_table_length { let (start_pc, after_start_pc) = rest.read_u16(); let (line_number, after_line_number) = after_start_pc.read_u16(); let line_number_table_entry = LineNumberTableEntry { start_pc, line_number, }; line_number_table.push(line_number_table_entry); rest = after_line_number; } (line_number_table, rest) } fn read_local_variable_table(&self) -> (Vec<LocalVariableTableEntry>, &[u8]) { let (local_variable_table_length, after_local_variable_table_length) = self.read_u16(); let mut local_variable_table: Vec<LocalVariableTableEntry> = Vec::with_capacity(local_variable_table_length as usize); let mut rest = after_local_variable_table_length; for _ in 1..=local_variable_table_length { let (start_pc, after_start_pc) = rest.read_u16(); let (length, after_length) = after_start_pc.read_u16(); let (name_index, after_name_index) = after_length.read_u16(); let (descriptor_index, after_descriptor_index) = after_name_index.read_u16(); let (index, after_index) = after_descriptor_index.read_u16(); let local_variable_table_entry = LocalVariableTableEntry { start_pc, length, name_index, descriptor_index, index, }; local_variable_table.push(local_variable_table_entry); rest = after_index; } (local_variable_table, rest) } fn read_attribute(&self, constant_pool: &ConstantPool) -> (AttributeInfo, &[u8]) { let (attribute_name_index, after_attribute_name_index) = self.read_u16(); let attribute_name = match constant_pool.get(attribute_name_index as usize) { ConstantInfo::UTF8(attribute_name) => attribute_name, _ => panic!("attribute_name isn't UTF8"), }; let (attribute_length, after_attribute_length) = after_attribute_name_index.read_u32(); match attribute_name.as_str() { "Code" => { let (max_stack, after_max_stack) = after_attribute_length.read_u16(); let (max_locals, after_max_locals) = after_max_stack.read_u16(); let (code_length, after_code_length) = after_max_locals.read_u32(); let (code, after_code) = after_code_length.read_bytes(code_length as usize); let (exception_table, after_exception_table) = after_code.read_exception_table(); let (attributes, after_attributes) = after_exception_table.read_attributes(constant_pool); ( AttributeInfo::Code { max_stack, max_locals, code: Rc::new(code.to_vec()), exception_table, attributes, }, after_attributes, ) } "ConstantValue" => { let (constant_value_index, after_constant_value_index) = after_attribute_length.read_u16(); ( AttributeInfo::ConstantValue { constant_value_index, }, after_constant_value_index, ) } "Deprecated" => (AttributeInfo::Deprecated, after_attribute_length), "Exceptions" => { let (exception_index_table, after_exception_index_table) = after_attribute_length.read_u16s(); ( AttributeInfo::Exceptions { exception_index_table, }, after_exception_index_table, ) } "SourceFile" => { let (sourcefile_index, after_sourcefile_index) = after_attribute_length.read_u16(); ( AttributeInfo::SourceFile { sourcefile_index }, after_sourcefile_index, ) } "Synthetic" => (AttributeInfo::Synthetic {}, after_attribute_length), "LineNumberTable" => { let (line_number_table, after_line_number_table) = after_attribute_length.read_line_number_table(); ( AttributeInfo::LineNumberTable { line_number_table }, after_line_number_table, ) } "LocalVariableTable" => { let (local_variable_table, after_local_variable_table) = after_attribute_length.read_local_variable_table(); ( AttributeInfo::LocalVariableTable { local_variable_table, }, after_local_variable_table, ) } _ => { let (_, after_attribute_info) = after_attribute_length.read_bytes(attribute_length as usize); let attribute_name = attribute_name.to_string(); ( AttributeInfo::Unparsed { attribute_name, attribute_length, }, after_attribute_info, ) } } } fn read_attributes(&self, constant_pool: &ConstantPool) -> (Vec<AttributeInfo>, &[u8]) { let (attributes_count, after_attributes_count) = self.read_u16(); let mut attributes: Vec<AttributeInfo> = Vec::with_capacity(attributes_count as usize); let mut rest = after_attributes_count; for _ in 1..=attributes_count { let (attribute_info, next_rest) = rest.read_attribute(constant_pool); attributes.push(attribute_info); rest = next_rest; } (attributes, rest) } fn parse(&self) -> ClassFile { let (_, after_magic) = self.read_and_check_magic(); let (version_info, after_version_info) = after_magic.read_and_check_version(); let VersionInfo { major_version, minor_version, } = version_info; let (constant_pool, after_constant_pool) = after_version_info.read_constant_pool(); let (access_flags, after_access_flags) = after_constant_pool.read_access_flags(); let (this_class, after_this_class) = after_access_flags.read_this_class(); let (super_class, after_super_class) = after_this_class.read_this_class(); let (interfaces, after_interfaces) = after_super_class.read_interfaces(); let (fields, after_fields) = after_interfaces.read_members(&constant_pool); let (methods, after_methods) = after_fields.read_members(&constant_pool); let (attributes, _) = after_methods.read_attributes(&constant_pool); ClassFile { major_version, minor_version, constant_pool, access_flags, this_class, super_class, interfaces, fields, methods, attributes, } } } #[cfg(test)] mod tests { use classfile::attribute_info::{AttributeInfo, LineNumberTableEntry}; use classfile::class_file::ClassFile; use classfile::class_reader::ClassReader; use classfile::constant_info::ConstantInfo; use classfile::member_info::MemberInfo; use std::fs::File; use std::io::Read; #[test] fn parse() { // todo: assert access_flags let path: &str = "src/test_data/Object.class"; let input = File::open(path).unwrap(); let bytes: Vec<u8> = input.bytes().map(|x| x.unwrap()).collect(); let ClassFile { major_version, minor_version, constant_pool, access_flags, this_class, super_class, interfaces, fields, methods, attributes, } = bytes.parse(); assert_eq!(major_version, 52); assert_eq!(minor_version, 0); assert_eq!(constant_pool.capacity(), 79); match constant_pool.get(1) { ConstantInfo::Class { name_index } => assert_eq!(*name_index, 49u16), _ => panic!(), }; match constant_pool.get(9) { ConstantInfo::MethodRef { class_index, name_and_type_index, } => { assert_eq!(class_index.to_owned(), 1 as u16); assert_eq!(name_and_type_index.to_owned(), 59 as u16); } _ => panic!(), }; match constant_pool.get(13) { ConstantInfo::Integer(value) => assert_eq!(*value, 999999i32), _ => panic!(), }; match constant_pool.get(22) { ConstantInfo::UTF8(value) => assert_eq!(value, "registerNatives"), _ => panic!(), }; match constant_pool.get(50) { ConstantInfo::NameAndType { name_index, descriptor_index, } => { assert_eq!(*name_index, 18u16); assert_eq!(*descriptor_index, 19u16); } _ => panic!(), }; match constant_pool.get(77) { ConstantInfo::UTF8(value) => assert_eq!(value, "(Ljava/lang/String;)V"), _ => panic!(), }; assert_eq!(access_flags, 33); assert_eq!(this_class, 17); assert_eq!(super_class, 0); assert_eq!(interfaces.len(), 0); assert_eq!(fields.len(), 0); assert_eq!(methods.len(), 14); match methods.get(2).unwrap() { MemberInfo { name_index, descriptor_index, attributes, access_flags: _, name: _, descriptor: _, } => { assert_eq!(*name_index, 23u16); assert_eq!(*descriptor_index, 24u16); assert_eq!(attributes.len(), 1usize); } } match methods.get(13).unwrap() { MemberInfo { name_index, descriptor_index, attributes, access_flags: _, name: _, descriptor: _, } => { assert_eq!(*name_index, 46u16); assert_eq!(*descriptor_index, 19u16); assert_eq!(attributes.len(), 1usize); match attributes.get(0).unwrap() { AttributeInfo::Code { max_stack, max_locals, code, exception_table, attributes, } => { assert_eq!(*max_stack, 0u16); assert_eq!(*max_locals, 0u16); assert_eq!(code.len(), 4usize); assert_eq!(exception_table.len(), 0usize); assert_eq!(attributes.len(), 1usize); match attributes.get(0).unwrap() { AttributeInfo::LineNumberTable { line_number_table } => { match line_number_table.get(0).unwrap() { LineNumberTableEntry { start_pc, line_number, } => { assert_eq!(*start_pc, 0u16); assert_eq!(*line_number, 41u16) } } } _ => panic!(), } } _ => panic!(), } } } assert_eq!(attributes.len(), 1); match attributes.get(0).unwrap() { AttributeInfo::SourceFile { sourcefile_index } => { assert_eq!(*sourcefile_index, 48u16); } _ => panic!(), } } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/classfile/member_info.rs
src/classfile/member_info.rs
use classfile::attribute_info::AttributeInfo; #[derive(Debug)] pub struct MemberInfo { pub access_flags: u16, pub name: String, pub name_index: u16, pub descriptor_index: u16, pub descriptor: String, pub attributes: Vec<AttributeInfo>, } impl MemberInfo { pub fn code_attribute(&self) -> Option<&AttributeInfo> { self.attributes.iter().find(|x| match x { AttributeInfo::Code { .. } => true, _ => false, }) } pub fn constant_value_attribute(&self) -> Option<&AttributeInfo> { self.attributes.iter().find(|x| match x { AttributeInfo::ConstantValue { .. } => true, _ => false, }) } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/classfile/mod.rs
src/classfile/mod.rs
extern crate vec_map; pub mod attribute_info; pub mod class_file; pub mod class_reader; pub mod constant_info; pub mod constant_pool; pub mod member_info;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/classfile/attribute_info.rs
src/classfile/attribute_info.rs
use std::rc::Rc; #[derive(Debug)] pub struct ExceptionTableEntry { pub start_pc: u16, pub end_pc: u16, pub handler_pc: u16, pub catch_type: u16, } #[derive(Debug)] pub struct LineNumberTableEntry { pub start_pc: u16, pub line_number: u16, } #[derive(Debug)] pub struct LocalVariableTableEntry { pub start_pc: u16, pub length: u16, pub name_index: u16, pub descriptor_index: u16, pub index: u16, } #[derive(Debug)] pub enum AttributeInfo { Code { max_stack: u16, max_locals: u16, code: Rc<Vec<u8>>, exception_table: Vec<ExceptionTableEntry>, attributes: Vec<AttributeInfo>, }, ConstantValue { constant_value_index: u16, }, Deprecated, Exceptions { exception_index_table: Vec<u16>, }, SourceFile { sourcefile_index: u16, }, Synthetic, Unparsed { attribute_name: String, attribute_length: u32, }, LineNumberTable { line_number_table: Vec<LineNumberTableEntry>, }, LocalVariableTable { local_variable_table: Vec<LocalVariableTableEntry>, }, }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/classfile/class_file.rs
src/classfile/class_file.rs
use classfile::attribute_info::AttributeInfo; use classfile::constant_pool::ConstantPool; use classfile::member_info::MemberInfo; #[derive(Debug)] pub struct ClassFile { pub major_version: u16, pub minor_version: u16, pub constant_pool: ConstantPool, pub access_flags: u16, pub this_class: u16, pub super_class: u16, pub interfaces: Vec<u16>, pub fields: Vec<MemberInfo>, pub methods: Vec<MemberInfo>, pub attributes: Vec<AttributeInfo>, } impl ClassFile { pub fn main_method<'a>(&'a self) -> &'a MemberInfo { self.methods .iter() .find(|x| x.name == "main" && x.descriptor == "([Ljava/lang/String;)V") .expect("Main method not found") } pub fn class_name(&self) -> &str { self.constant_pool.get_class_name(self.this_class as usize) } pub fn super_class_name(&self) -> &str { let super_class = self.super_class as usize; if super_class > 0 { self.constant_pool.get_class_name(super_class) } else { "" } } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/classfile/constant_pool.rs
src/classfile/constant_pool.rs
use classfile::constant_info::ConstantInfo; use vec_map::VecMap; #[derive(Debug)] pub struct ConstantPool { pub vec_map: VecMap<ConstantInfo>, } impl ConstantPool { pub fn insert(&mut self, index: usize, constant_info: ConstantInfo) { self.vec_map.insert(index, constant_info); } pub fn get(&self, index: usize) -> &ConstantInfo { self.vec_map.get(index).expect("Bad constant pool index") } pub fn capacity(&self) -> usize { self.vec_map.capacity() } fn get_utf8(&self, index: usize) -> &str { match self.get(index) { ConstantInfo::UTF8(ref name) => name, _ => panic!("index isn't to UTF8"), } } pub fn get_class_name(&self, index: usize) -> &str { let constant_info = self.get(index); let name_index = match constant_info { ConstantInfo::Class { name_index } => name_index, _ => panic!("index isn't to Class"), }; self.get_utf8(*name_index as usize) } // fn get_class_ref(&self, index: usize) -> &str { // } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/shell/command.rs
src/shell/command.rs
pub struct Command<'a> { pub class_name: String, pub cp_opt: Option<String>, pub jre_opt: Option<String>, pub args: Vec<&'a str>, }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/shell/mod.rs
src/shell/mod.rs
pub mod command;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/classpath/classpath.rs
src/classpath/classpath.rs
extern crate zip; use std::env; use std::fs::read_dir; use std::fs::File; use std::io; use std::io::Error; use std::io::ErrorKind; use std::io::Read; use std::path::Path; use std::path::PathBuf; #[derive(Debug)] enum Entry { Dir { path: PathBuf }, Wildcard { path_vec: Vec<PathBuf> }, Zip { path: PathBuf }, } impl Entry { fn new(path: &str) -> Entry { if path.ends_with("*") { // println!("Entry::new Wildcard {}", path); let len = path.len(); let base_path = &path[..len - 1]; // println!("base_path {:?}", base_path); let path_vec: Vec<PathBuf> = read_dir(base_path) .unwrap() .map(|x| x.unwrap()) .map(|x| x.path()) .filter(|x| { x.extension() .map(|x| x.to_str().unwrap() == "jar") .unwrap_or(false) }) .collect(); // println!("path_vec {:?}", path_vec); Entry::Wildcard { path_vec } } else if path.ends_with(".jar") { // println!("Entry::new Zip {}", path); Entry::Zip { path: Path::new(path).to_owned(), } } else { // println!("Entry::new Dir {}", path); Entry::Dir { path: Path::new(path).to_owned(), } } } fn read_class(&self, class_file_name: &str) -> Result<Vec<u8>, io::Error> { match self { Entry::Dir { path } => { // println!("read class {} using Dir", class_file_name); let filepath = Path::new(path).join(class_file_name); let mut file = File::open(filepath)?; let meta = file.metadata()?; let mut buf = Vec::<u8>::with_capacity(meta.len() as usize); file.read_to_end(&mut buf)?; Ok(buf) } Entry::Wildcard { path_vec } => { // println!("read class {} using Wildcard", class_file_name); path_vec .iter() .map(|x| Entry::new(x.to_str().unwrap())) .map(|x| x.read_class(class_file_name)) .find(|x| x.is_ok()) .unwrap_or(Err(Error::new(ErrorKind::Other, "Class not found"))) } Entry::Zip { path } => { // println!("read class {} using Zip", class_file_name); let file = File::open(path)?; let mut zip = zip::ZipArchive::new(file)?; let mut file = zip.by_name(&class_file_name)?; let mut buf = Vec::<u8>::with_capacity(file.size() as usize); file.read_to_end(&mut buf); Ok(buf) } } } } #[derive(Debug)] pub struct ClassPath { boot: Entry, user: Entry, } impl ClassPath { pub fn read_class(&self, name: &str) -> Result<Vec<u8>, io::Error> { let class_file_name = name.to_owned() + ".class"; self.boot .read_class(&class_file_name) .or_else(|x| self.user.read_class(&class_file_name)) // .or_else(|| self.ext.read_class()) } } fn parse_boot_classpath(jre: &str) -> Entry { let jre_lib_path = Path::new(jre) .join("lib") .join("*") .to_str() .unwrap() .to_owned(); Entry::new(&jre_lib_path) } fn parse_user_classpath(cp_opt: Option<String>) -> Entry { let cp = cp_opt.unwrap_or(".".to_owned()); Entry::new(&cp) } fn exists(path: &str) -> bool { Path::new(path).exists() } fn get_jre(jre_opt: Option<String>) -> String { match jre_opt { Some(ref jre) if exists(jre) => jre.to_string(), _ => { if exists("./jre") { "./jre".to_string() } else { match env::var_os("JAVA_HOME") { Some(java_home) => Path::new(&java_home) .join("jre") .to_str() .unwrap() .to_string(), None => panic!("Can not find JRE folder"), } } } } } pub fn parse(jre_opt: Option<String>, cp_opt: Option<String>) -> ClassPath { let jre = get_jre(jre_opt); let boot = parse_boot_classpath(&jre); let user = parse_user_classpath(cp_opt); ClassPath { user, boot } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/classpath/mod.rs
src/classpath/mod.rs
pub mod classpath;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/vars.rs
src/rtda/vars.rs
extern crate vec_map; use self::vec_map::VecMap; use rtda::slot::Slot; #[derive(Debug)] pub struct Vars { vec_map: VecMap<Slot>, } impl Vars { pub fn new(max_locals: usize) -> Vars { if max_locals > 0 { let vec_map = VecMap::with_capacity(max_locals); Vars { vec_map } } else { panic!("max_locals < 0") } } pub fn set_int(mut self, index: usize, val: i32) -> Vars { self.vec_map.insert(index, Slot::Num(val)); self } pub fn get_int(&self, index: usize) -> i32 { match self.vec_map[index] { Slot::Num(val) => val, _ => panic!("get_int from wrong place"), } } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/slot.rs
src/rtda/slot.rs
#[derive(Debug)] pub enum Slot { Num(i32), }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/mod.rs
src/rtda/mod.rs
pub mod frame; pub mod heap; pub mod operand_stack; mod slot; mod stack; pub mod thread; pub mod vars;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/stack.rs
src/rtda/stack.rs
use rtda::frame::Frame; pub struct Stack { max_size: usize, vec: Vec<Frame>, } impl Stack { pub fn new(max_size: usize) -> Stack { let vec = Vec::with_capacity(max_size); Stack { max_size, vec } } pub fn push(mut self, frame: Frame) -> Stack { if self.vec.len() == self.max_size { panic!("java.lang.StackOverflowError") } else { self.vec.push(frame); self } } pub fn pop(mut self) -> (Frame, Stack) { let frame = self.vec.pop().unwrap(); (frame, self) } pub fn is_empty(&self) -> bool { self.vec.is_empty() } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/frame.rs
src/rtda/frame.rs
use rtda::heap::class::Class; use rtda::heap::method::Method; use rtda::operand_stack::OperandStack; use rtda::vars::Vars; use std::rc::Rc; #[derive(Debug)] pub struct Frame { pub local_vars: Vars, pub operand_stack: OperandStack, pub method: Rc<Method>, pub class: Rc<Class>, } impl Frame { pub fn new(class: Rc<Class>, method: Rc<Method>) -> Frame { let Method { max_stack, max_locals, .. } = *method; let local_vars = Vars::new(max_locals); let operand_stack = OperandStack::new(max_stack); Frame { class, local_vars, operand_stack, method, } } } #[cfg(test)] mod tests { use classfile::constant_pool::ConstantPool; use classfile::member_info::MemberInfo; use rtda::frame::Frame; use rtda::heap::class::Class; use rtda::heap::method::Method; use rtda::operand_stack::OperandStack; use rtda::vars::Vars; use std::rc::Rc; use vec_map::VecMap; #[test] fn frame() { let method = Rc::new(Method::new(MemberInfo { access_flags: 0u16, name: "".to_string(), name_index: 0u16, descriptor_index: 0u16, descriptor: "".to_string(), attributes: Vec::new(), })); let class = Rc::new(Class { access_flags: 0u16, name: "".to_string(), constant_pool: ConstantPool { vec_map: VecMap::new(), }, fields: Vec::new(), methods: Vec::new(), super_class: None, instance_slot_count: 0usize, static_slot_count: 0usize, static_vars: Vars::new(2), }); let frame = Frame::new(class, method); local_vars(frame.local_vars); operand_stack(frame.operand_stack); } fn local_vars(local_vars: Vars) { let local_vars = local_vars.set_int(0, 100); let local_vars = local_vars.set_int(1, -100); assert_eq!(local_vars.get_int(0), 100); assert_eq!(local_vars.get_int(1), -100); } fn operand_stack(operand_stack: OperandStack) { let operand_stack = operand_stack.push_int(100); let operand_stack = operand_stack.push_double(2.71828182845f64); let operand_stack = operand_stack.push_int(-100); let operand_stack = operand_stack.push_long(2997924580); let operand_stack = operand_stack.push_float(3.1415926); let (val, operand_stack) = operand_stack.pop_float(); assert_eq!(val, 3.1415926); let (val, operand_stack) = operand_stack.pop_long(); assert_eq!(val, 2997924580); let (val, operand_stack) = operand_stack.pop_int(); assert_eq!(val, -100); let (val, operand_stack) = operand_stack.pop_double(); assert_eq!(val, 2.71828182845f64); let (val, _) = operand_stack.pop_int(); assert_eq!(val, 100); } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/operand_stack.rs
src/rtda/operand_stack.rs
use rtda::slot::Slot; use util::converter; #[derive(Debug)] pub struct OperandStack { vec: Vec<Slot>, } impl OperandStack { pub fn new(max_stack: usize) -> OperandStack { OperandStack { vec: Vec::with_capacity(max_stack), } } pub fn push_int(mut self, val: i32) -> OperandStack { self.vec.push(Slot::Num(val)); self } pub fn pop_int(mut self) -> (i32, OperandStack) { let val = self.vec.pop().unwrap(); match val { Slot::Num(val) => (val, self), _ => panic!(), } } pub fn push_long(mut self, val: i64) -> OperandStack { let [a, b] = converter::i64_to_i32seq(val); self.vec.push(Slot::Num(a)); self.vec.push(Slot::Num(b)); self } pub fn pop_long(mut self) -> (i64, OperandStack) { let b = match self.vec.pop().unwrap() { Slot::Num(val) => val, _ => panic!(), }; let a = match self.vec.pop().unwrap() { Slot::Num(val) => val, _ => panic!(), }; (converter::i32seq_to_i64([a, b]), self) } pub fn push_double(mut self, val: f64) -> OperandStack { let [a, b] = converter::f64_to_i32seq(val); self.vec.push(Slot::Num(a)); self.vec.push(Slot::Num(b)); self } pub fn pop_double(mut self) -> (f64, OperandStack) { let b = match self.vec.pop().unwrap() { Slot::Num(val) => val, _ => panic!(), }; let a = match self.vec.pop().unwrap() { Slot::Num(val) => val, _ => panic!(), }; (converter::i32seq_to_f64([a, b]), self) } pub fn push_float(mut self, val: f32) -> OperandStack { let val = converter::f32_to_i32(val); self.vec.push(Slot::Num(val)); self } pub fn pop_float(mut self) -> (f32, OperandStack) { let val = self.vec.pop().unwrap(); match val { Slot::Num(val) => (converter::i32_to_f32(val), self), _ => panic!(), } } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/thread.rs
src/rtda/thread.rs
use rtda::frame::Frame; use rtda::stack::Stack; const STACK_SIZE: usize = 1024; pub struct Thread { stack: Stack, } impl Thread { pub fn new() -> Thread { Thread { stack: Stack::new(STACK_SIZE), } } pub fn push_frame(self, frame: Frame) -> Thread { let Thread { stack } = self; Thread { stack: stack.push(frame), } } pub fn pop_frame(self) -> (Frame, Thread) { let Thread { stack } = self; let (frame, stack) = stack.pop(); let thread = Thread { stack }; (frame, thread) } pub fn is_stack_empty(&self) -> bool { self.stack.is_empty() } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/heap/class_loader.rs
src/rtda/heap/class_loader.rs
use classfile::class_file::ClassFile; use classfile::class_reader::ClassReader; use classfile::constant_info::ConstantInfo; use classfile::constant_pool::ConstantPool; use classpath::classpath::ClassPath; use rtda::heap::class::Class; use rtda::heap::field::Field; use rtda::heap::method::Method; use rtda::vars::Vars; use std::collections::HashMap; use std::rc::Rc; pub struct ClassLoader { class_path: ClassPath, class_map: HashMap<String, Rc<Class>>, } struct Acc { constant_pool: ConstantPool, next_instance_field_slot_id: usize, next_static_field_slot_id: usize, static_vars: Vars, } impl ClassLoader { pub fn new(class_path: ClassPath) -> ClassLoader { ClassLoader { class_path, class_map: HashMap::new(), } } pub fn load(self, name: String) -> (Rc<Class>, ClassLoader) { println!("load {}", &name); if self.class_map.contains_key(&name) { let class = Rc::clone(self.class_map.get(&name).unwrap()); (class, self) } else { let data = self.read(&name); let (class, mut class_loader) = ClassLoader::define(self, data); let class_copy = Rc::clone(&class); class_loader.class_map.insert(name, class); (class_copy, class_loader) } } fn read(&self, name: &str) -> Vec<u8> { self.class_path .read_class(name) .expect("java.lang.ClassNotFoundException") } fn define(class_loader: ClassLoader, data: Vec<u8>) -> (Rc<Class>, ClassLoader) { let class_file = data.parse(); let name = class_file.class_name().to_owned(); let super_class_name = class_file.super_class_name().to_owned(); let ClassFile { access_flags, methods, fields, constant_pool, .. } = class_file; let methods: Vec<Rc<Method>> = methods .into_iter() .map(|x| Rc::new(Method::new(x))) .collect(); let (super_class, class_loader) = if name != "java/lang/Object" { let (class, class_loader) = class_loader.load(super_class_name); (Some(class), class_loader) } else { (None, class_loader) }; fn fold_func(acc: Acc, field: &Field) -> Acc { let Acc { next_instance_field_slot_id: instance_field_slot_id, next_static_field_slot_id: static_field_slot_id, static_vars, constant_pool, } = acc; let slot_id_delta: usize = if field.is_long_or_double() { 2 } else { 1 }; let (next_instance_field_slot_id, next_static_field_slot_id, static_vars) = if field.is_static() { let static_vars: Vars = if field.is_final() { let constant_value_index = field.constant_value_index; if constant_value_index.is_some() { let constant_value_index = constant_value_index.unwrap(); match field.class_member.descriptor.as_str() { // todo: Complete Z B C S I J D Ljava/lang/String "F" => { let val = match constant_pool.get(constant_value_index) { ConstantInfo::Integer(val) => *val, _ => panic!("Not Integer"), }; static_vars.set_int(static_field_slot_id, val) } _ => panic!("TODO"), } } else { static_vars } } else { static_vars }; ( instance_field_slot_id, static_field_slot_id + slot_id_delta, static_vars, ) } else { ( instance_field_slot_id + slot_id_delta, static_field_slot_id, static_vars, ) }; Acc { next_instance_field_slot_id, next_static_field_slot_id, static_vars, constant_pool, } } let next_static_field_slot_id: usize = 0; let next_instance_field_slot_id: usize = super_class .clone() .map(|x| x.instance_slot_count) .unwrap_or(0); let static_vars = Vars::new(10); let fields: Vec<Field> = fields.into_iter().map(|x| Field::new(x)).collect(); let Acc { next_instance_field_slot_id: instance_slot_count, next_static_field_slot_id: static_slot_count, static_vars, constant_pool, } = fields.iter().fold( Acc { next_instance_field_slot_id, next_static_field_slot_id, constant_pool, static_vars, }, fold_func, ); let class = Rc::new(Class { access_flags, fields, name, super_class, methods, instance_slot_count, static_slot_count, static_vars, constant_pool, }); (class, class_loader) } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/heap/symbol_ref.rs
src/rtda/heap/symbol_ref.rs
use classfile::constant_pool::ConstantPool; use rtda::heap::class::Class; use std::rc::Rc; use classfile::constant_info::ConstantInfo; pub struct SymbolRef { constant_pool: Rc<ConstantPool>, class_name: String, class: Rc<Class>, } impl SymbolRef { fn new(constant_pool: Rc<ConstantPool>, constant_class_info: ConstantInfo) -> ClassRef { let class_name = } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/heap/field.rs
src/rtda/heap/field.rs
use classfile::attribute_info::AttributeInfo; use classfile::member_info::MemberInfo; use rtda::heap::class_member::ClassMember; #[derive(Debug)] pub struct Field { pub class_member: ClassMember, pub constant_value_index: Option<usize>, } impl Field { pub fn new(member_info: MemberInfo) -> Field { let class_member = ClassMember::new(&member_info); let constant_value_index = member_info.constant_value_attribute().map(|x| match x { AttributeInfo::ConstantValue { constant_value_index, } => *constant_value_index as usize, _ => panic!("Not ConstantValue"), }); Field { class_member, constant_value_index, } } pub fn is_static(&self) -> bool { self.class_member.is_static() } pub fn is_long_or_double(&self) -> bool { let descriptor = &self.class_member.descriptor; descriptor == "J" || descriptor == "D" } pub fn is_final(&self) -> bool { self.class_member.is_final() } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/heap/object.rs
src/rtda/heap/object.rs
use rtda::heap::class::Class; use rtda::slot::Slot; struct Object { class: Class, fields: Vec<Slot>, }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/heap/class_ref.rs
src/rtda/heap/class_ref.rs
use rtda::heap::symbol_ref::SymbolRef; use std::rc::Rc; use classfile::constant_pool::ConstantPool; use classfile::constant_info::ConstantInfo; struct ClassRef { symbol_ref: SymbolRef, } impl ClassRef { fn new(constant_pool: Rc<ConstantPool>, constant_class_info: ConstantInfo) -> ClassRef { let symbol_ref = SymbolRef{ constant_pool, } } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/heap/class.rs
src/rtda/heap/class.rs
use classfile::constant_pool::ConstantPool; use rtda::heap::field::Field; use rtda::heap::method::Method; use rtda::vars::Vars; use std::rc::Rc; #[derive(Debug)] pub struct Class { pub access_flags: u16, pub name: String, // pub super_class_name: String, // interface_names: Vec<String>, pub constant_pool: ConstantPool, pub fields: Vec<Field>, pub methods: Vec<Rc<Method>>, // loader * ClassLoader pub super_class: Option<Rc<Class>>, // interfaces [] * Class pub instance_slot_count: usize, pub static_slot_count: usize, pub static_vars: Vars, } impl Class { pub fn main_method(&self) -> Rc<Method> { self.get_method("main", "([Ljava/lang/String;)V", true) } fn get_method(&self, name: &str, descriptor: &str, is_static: bool) -> Rc<Method> { println!( "name {} descriptor {} is_static {}", name, descriptor, is_static ); let reference = self.methods .iter() .find(|x| { x.is_static() == is_static && x.name() == name && x.descriptor() == descriptor }) .expect("Method not found"); Rc::clone(reference) } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/heap/mod.rs
src/rtda/heap/mod.rs
mod access_flags; pub mod class; pub mod class_loader; mod class_member; mod field; pub mod method; mod object;
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false
standbyme/jvm-rs
https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/heap/method.rs
src/rtda/heap/method.rs
use classfile::attribute_info::AttributeInfo; use classfile::member_info::MemberInfo; use rtda::heap::class_member::ClassMember; use std::rc::Rc; #[derive(Debug)] pub struct Method { class_member: ClassMember, pub max_locals: usize, pub max_stack: usize, pub code: Rc<Vec<u8>>, } impl Method { pub fn new(member_info: MemberInfo) -> Method { let class_member = ClassMember::new(&member_info); let code_attribute = member_info.code_attribute(); match code_attribute { Some(AttributeInfo::Code { max_stack, max_locals, code, .. }) => Method { class_member, max_stack: *max_stack as usize, max_locals: *max_locals as usize, code: Rc::clone(code), }, None => Method { class_member, max_stack: 0, max_locals: 1, code: Rc::new(Vec::new()), }, _ => panic!(), } } pub fn is_static(&self) -> bool { self.class_member.is_static() } pub fn name(&self) -> &str { &self.class_member.name } pub fn descriptor(&self) -> &str { &self.class_member.descriptor } }
rust
MIT
ebdc07e9049d84688effdccec03a0a5b0aeda0bb
2026-01-04T20:23:41.645579Z
false