├── .gitignore ├── tests ├── artifacts │ ├── creator │ │ ├── 37573 │ │ │ ├── raw │ │ │ └── processed │ │ ├── 2073761 │ │ │ ├── raw │ │ │ └── processed │ │ ├── 5449239 │ │ │ ├── raw │ │ │ └── processed │ │ ├── 8599996 │ │ │ ├── raw │ │ │ └── processed │ │ └── 15557115 │ │ │ ├── raw │ │ │ └── processed │ ├── comment_user │ │ └── 1705254 │ │ │ ├── raw │ │ │ └── processed │ ├── level_comment │ │ ├── 258976 │ │ │ ├── raw │ │ │ └── processed │ │ ├── 259333 │ │ │ ├── raw │ │ │ └── processed │ │ └── 260007 │ │ │ ├── raw │ │ │ └── processed │ ├── searched_user │ │ └── stardust1971 │ │ │ ├── raw │ │ │ └── processed │ ├── profile_comment │ │ └── 1922667 │ │ │ ├── raw │ │ │ └── processed │ ├── song │ │ ├── 444085 │ │ │ ├── raw │ │ │ └── processed │ │ ├── 686782 │ │ │ ├── raw │ │ │ └── processed │ │ ├── 771517 │ │ │ ├── raw │ │ │ └── processed │ │ └── 1204676 │ │ │ ├── raw │ │ │ └── processed │ ├── listed_level │ │ ├── 72540 │ │ │ ├── raw │ │ │ └── processed │ │ ├── 11774780 │ │ │ ├── raw │ │ │ └── processed │ │ ├── 24904605 │ │ │ ├── raw │ │ │ └── processed │ │ ├── 63355989 │ │ │ ├── raw │ │ │ └── processed │ │ └── 97598449 │ │ │ ├── raw │ │ │ └── processed │ └── profile │ │ └── 8451 │ │ ├── raw │ │ └── processed ├── creator.rs ├── profile.rs ├── searched_user.rs ├── song.rs ├── misc.rs ├── level.rs ├── comment.rs ├── framework.rs └── response.rs ├── src ├── model │ ├── comment │ │ ├── mod.rs │ │ ├── profile.rs │ │ └── level.rs │ ├── level │ │ ├── object │ │ │ ├── ids.rs │ │ │ ├── mod.rs │ │ │ ├── speed.rs │ │ │ └── internal.rs │ │ └── metadata.rs │ ├── creator.rs │ ├── mod.rs │ ├── user │ │ ├── searched.rs │ │ ├── mod.rs │ │ └── profile.rs │ └── song.rs ├── serde │ ├── ser │ │ ├── mod.rs │ │ ├── error.rs │ │ ├── indexed.rs │ │ └── request.rs │ ├── de │ │ ├── mod.rs │ │ ├── error.rs │ │ └── indexed.rs │ ├── mod.rs │ └── thunk.rs ├── lib.rs ├── split.rs ├── request │ ├── user.rs │ ├── mod.rs │ └── comment.rs ├── util.rs └── response.rs ├── rustfmt.toml ├── dash-rs-derive ├── Cargo.toml └── src │ ├── lib.rs │ ├── utils.rs │ ├── struct_gen.rs │ └── field.rs ├── LICENSE ├── .github └── workflows │ ├── rust-build.yml │ ├── rustfmt.yml │ └── coverage.yml ├── Cargo.toml ├── README.md ├── benches └── level_processing_benchmark.rs └── examples ├── download_featured_levels.rs └── refresh_test_artifacts.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | .idea 3 | Cargo.lock 4 | *.iml -------------------------------------------------------------------------------- /tests/artifacts/creator/37573/raw: -------------------------------------------------------------------------------- 1 | 37573:superhexagon:0 -------------------------------------------------------------------------------- /tests/artifacts/creator/5449239/raw: -------------------------------------------------------------------------------- 1 | 5449239:Edicts:324721 -------------------------------------------------------------------------------- /tests/artifacts/creator/15557115/raw: -------------------------------------------------------------------------------- 1 | 15557115:iArcanGD:4491402 -------------------------------------------------------------------------------- /tests/artifacts/creator/2073761/raw: -------------------------------------------------------------------------------- 1 | 2073761:stardust1971:8451 -------------------------------------------------------------------------------- /tests/artifacts/creator/8599996/raw: -------------------------------------------------------------------------------- 1 | 8599996:Subwoofer:1275405 -------------------------------------------------------------------------------- /src/model/comment/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod level; 2 | pub mod profile; 3 | -------------------------------------------------------------------------------- /tests/artifacts/comment_user/1705254/raw: -------------------------------------------------------------------------------- 1 | 1~Pauze~9~58~10~18~11~16~14~0~15~2~16~1705254 -------------------------------------------------------------------------------- /tests/artifacts/level_comment/260007/raw: -------------------------------------------------------------------------------- 1 | 2~R3VydS4=~3~2723387~4~63~7~0~10~0~9~5 days~6~260007~11~2~12~75,255,75 -------------------------------------------------------------------------------- /tests/artifacts/creator/37573/processed: -------------------------------------------------------------------------------- 1 | { 2 | "user_id": 37573, 3 | "name": "superhexagon", 4 | "account_id": null 5 | } -------------------------------------------------------------------------------- /tests/artifacts/creator/5449239/processed: -------------------------------------------------------------------------------- 1 | { 2 | "user_id": 5449239, 3 | "name": "Edicts", 4 | "account_id": 324721 5 | } -------------------------------------------------------------------------------- /tests/artifacts/creator/15557115/processed: -------------------------------------------------------------------------------- 1 | { 2 | "user_id": 15557115, 3 | "name": "iArcanGD", 4 | "account_id": 4491402 5 | } -------------------------------------------------------------------------------- /tests/artifacts/creator/2073761/processed: -------------------------------------------------------------------------------- 1 | { 2 | "user_id": 2073761, 3 | "name": "stardust1971", 4 | "account_id": 8451 5 | } -------------------------------------------------------------------------------- /tests/artifacts/creator/8599996/processed: -------------------------------------------------------------------------------- 1 | { 2 | "user_id": 8599996, 3 | "name": "Subwoofer", 4 | "account_id": 1275405 5 | } -------------------------------------------------------------------------------- /tests/artifacts/searched_user/stardust1971/raw: -------------------------------------------------------------------------------- 1 | 1:stardust1971:2:2073761:13:151:17:499:6:0:9:95:10:9:11:10:14:0:15:2:16:8451:3:13791:52:16:8:19:4:483 -------------------------------------------------------------------------------- /tests/artifacts/profile_comment/1922667/raw: -------------------------------------------------------------------------------- 1 | 2~QSB3aW5kb3cgdG8gdGhlIHBhc3QsIGEgZ2xpbXBzZSBvZiB0aGUgZnV0dXJlLCBBbiBPZGUgdG8gVGltZS4=~4~432~9~6 days~6~1922667 -------------------------------------------------------------------------------- /tests/artifacts/level_comment/259333/raw: -------------------------------------------------------------------------------- 1 | 2~TGV0cyBtYWtlIGF1Z3VzdCAxMHRoIFBhdXplJ3MgaW50ZXJuYXRpb25hbCBkYXk=~3~7178197~4~58~7~0~10~0~9~5 days~6~259333~11~1~12~255,255,255 -------------------------------------------------------------------------------- /src/serde/ser/mod.rs: -------------------------------------------------------------------------------- 1 | //! Module containing serde serializers for the various custom data formats RobTop uses. 2 | 3 | pub mod error; 4 | pub mod indexed; 5 | pub mod request; 6 | -------------------------------------------------------------------------------- /tests/artifacts/profile_comment/1922667/processed: -------------------------------------------------------------------------------- 1 | {"content":"A window to the past, a glimpse of the future, An Ode to Time.","likes":432,"comment_id":1922667,"time_since_post":"6 days"} -------------------------------------------------------------------------------- /tests/artifacts/song/771517/raw: -------------------------------------------------------------------------------- 1 | 1~|~771517~|~2~|~Rebirth~|~3~|~948~|~4~|~AeronMusic~|~5~|~8.34~|~6~|~~|~10~|~https%3A%2F%2Faudio.ngfiles.com%2F771000%2F771517_Rebirth.mp3%3Ff1508862699~|~7~|~~|~8~|~1 -------------------------------------------------------------------------------- /tests/artifacts/song/686782/raw: -------------------------------------------------------------------------------- 1 | 1~|~686782~|~2~|~Badland~|~3~|~2787~|~4~|~BoomKitty~|~5~|~11~|~6~|~~|~10~|~http%3A%2F%2Faudio.ngfiles.com%2F686000%2F686782_Badland.mp3~|~7~|~UCwHQ93ecuoQne93sgY-x8Nw~|~8~|~1 -------------------------------------------------------------------------------- /tests/artifacts/comment_user/1705254/processed: -------------------------------------------------------------------------------- 1 | {"name":"Pauze","icon_index":58,"primary_color":{"Known":[80,80,80]},"secondary_color":{"Known":[0,200,255]},"icon_type":"Cube","has_glow":true,"account_id":1705254} -------------------------------------------------------------------------------- /tests/artifacts/listed_level/72540/raw: -------------------------------------------------------------------------------- 1 | 1:72540:2:demon world:5:7:6:37573:8:10:9:20:10:452111:12:9:13:7:14:-2916:17:1:43:4:25::18:10:19:0:42:0:45:0:3:aGFwcHkgbmV3IHllYXIhIQ==:15:3:30:0:31:0:37:0:38:0:39:0:46:1:47:2:35:0 -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | edition = "2018" 2 | fn_params_layout = "Compressed" 3 | match_block_trailing_comma = true 4 | max_width = 140 5 | newline_style = "Unix" 6 | use_field_init_shorthand = true 7 | use_try_shorthand = true 8 | -------------------------------------------------------------------------------- /tests/artifacts/level_comment/258976/raw: -------------------------------------------------------------------------------- 1 | 2~U3BlY2lhbCB0aGFua3MgdG8gSGFkbywgQ2luY2ksIFN5bmFjdGl2ZSwgQ29vbCwgUHJpc20sIFN1Yndvb2ZlciwgYW5kIEhhZG8gZm9yIHBsYXl0ZXN0aW5nLg==~3~7226087~4~104~7~0~10~0~9~5 days~6~258976~11~2~12~75,255,75 -------------------------------------------------------------------------------- /tests/artifacts/song/444085/raw: -------------------------------------------------------------------------------- 1 | 1~|~444085~|~2~|~Dark Angel - F-777~|~3~|~286~|~4~|~F-777~|~5~|~8.96~|~6~|~~|~10~|~http%3A%2F%2Faudio.ngfiles.com%2F444000%2F444085_Dark_Angel___F_777.mp3~|~7~|~UC6MNIegxWVDe6tOjL92QkUw~|~8~|~1 -------------------------------------------------------------------------------- /src/model/level/object/ids.rs: -------------------------------------------------------------------------------- 1 | pub const SLOW_PORTAL: u16 = 200; 2 | pub const NORMAL_PORTAL: u16 = 201; 3 | pub const MEDIUM_PORTAL: u16 = 202; 4 | pub const FAST_PORTAL: u16 = 203; 5 | pub const VERY_FAST_PORTAL: u16 = 1334; 6 | -------------------------------------------------------------------------------- /tests/artifacts/song/1204676/raw: -------------------------------------------------------------------------------- 1 | 1~|~1204676~|~2~|~Hide n Seek Ranch~|~3~|~15747~|~4~|~PuffballsUnited~|~5~|~6.34~|~6~|~~|~10~|~https%3A%2F%2Faudio.ngfiles.com%2F1204000%2F1204676_Hide-n-Seek-Ranch.mp3%3Ff1680307735~|~7~|~~|~8~|~1 -------------------------------------------------------------------------------- /tests/artifacts/level_comment/260007/processed: -------------------------------------------------------------------------------- 1 | {"user":null,"content":"Guru.","user_id":2723387,"likes":63,"comment_id":260007,"is_flagged_spam":false,"time_since_post":"5 days","progress":0,"mod_level":"Elder","special_color":{"Known":[75,255,75]}} -------------------------------------------------------------------------------- /src/serde/de/mod.rs: -------------------------------------------------------------------------------- 1 | //! Module containing serde deserializers for the various custom data formats RobTop uses. 2 | //! 3 | //! All of these deserializers have the goal to use zero-allocations for maximum efficiency 4 | 5 | pub mod error; 6 | pub mod indexed; 7 | -------------------------------------------------------------------------------- /tests/artifacts/profile/8451/raw: -------------------------------------------------------------------------------- 1 | 1:stardust1971:2:2073761:13:151:17:499:10:9:11:10:51:63:3:13791:52:16:46:2621:4:483:8:19:18:0:19:0:50:0:20:stardust19710:21:95:22:48:23:33:24:18:25:11:26:10:28:1:43:2:48:13:53:3:54:1:30:13731:16:8451:31:0:44:stadust1971:45::49:0:29:1 -------------------------------------------------------------------------------- /tests/artifacts/level_comment/259333/processed: -------------------------------------------------------------------------------- 1 | {"user":null,"content":"Lets make august 10th Pauze's international day","user_id":7178197,"likes":58,"comment_id":259333,"is_flagged_spam":false,"time_since_post":"5 days","progress":0,"mod_level":"Normal","special_color":{"Known":[255,255,255]}} -------------------------------------------------------------------------------- /tests/artifacts/listed_level/63355989/raw: -------------------------------------------------------------------------------- 1 | 1:63355989:2:Fantasy:5:3:6:15557115:8:10:9:40:10:23324:12:0:13:21:14:2141:17::43:5:25::18:7:19:24978:42:0:45:37865:3:Q29sbGFiIHdpdGggQnJpbmRpa3osIHRoYW5rIHlvdSBmb3IgdGhpcyBsZXZlbCB1d3UsIEVOSk9ZISEg:15:3:30:63309629:31:0:37:2:38:1:39:7:46:1:47:2:35:771517 -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![forbid(unsafe_code)] 2 | 3 | pub mod model; 4 | pub mod request; 5 | pub mod response; 6 | pub(crate) mod serde; 7 | pub mod util; 8 | 9 | pub use crate::serde::{Dash, DeError, GJFormat, IndexedDeserializer, IndexedSerializer, ProcessError, SerError, Thunk, ThunkProcessor}; 10 | -------------------------------------------------------------------------------- /tests/artifacts/listed_level/97598449/raw: -------------------------------------------------------------------------------- 1 | 1:97598449:2:Loco Motive:5:2:6:8599996:8:10:9:40:10:3011016:12:0:13:22:14:153976:17::43:5:25::18:6:19:25049:42:1:45:18374:3:WWVlICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIEhhdw==:15:5:30:0:31:0:37:0:38:0:39:6:46:1:47:2:35:1204676 -------------------------------------------------------------------------------- /tests/artifacts/song/771517/processed: -------------------------------------------------------------------------------- 1 | { 2 | "song_id": 771517, 3 | "name": "Rebirth", 4 | "index_3": 948, 5 | "artist": "AeronMusic", 6 | "filesize": 8.34, 7 | "index_6": null, 8 | "index_7": null, 9 | "index_8": "1", 10 | "link": "https://audio.ngfiles.com/771000/771517_Rebirth.mp3?f1508862699" 11 | } -------------------------------------------------------------------------------- /tests/artifacts/level_comment/258976/processed: -------------------------------------------------------------------------------- 1 | {"user":null,"content":"Special thanks to Hado, Cinci, Synactive, Cool, Prism, Subwoofer, and Hado for playtesting.","user_id":7226087,"likes":104,"comment_id":258976,"is_flagged_spam":false,"time_since_post":"5 days","progress":0,"mod_level":"Elder","special_color":{"Known":[75,255,75]}} -------------------------------------------------------------------------------- /tests/artifacts/song/686782/processed: -------------------------------------------------------------------------------- 1 | { 2 | "song_id": 686782, 3 | "name": "Badland", 4 | "index_3": 2787, 5 | "artist": "BoomKitty", 6 | "filesize": 11.0, 7 | "index_6": null, 8 | "index_7": "UCwHQ93ecuoQne93sgY-x8Nw", 9 | "index_8": "1", 10 | "link": "http://audio.ngfiles.com/686000/686782_Badland.mp3" 11 | } -------------------------------------------------------------------------------- /tests/artifacts/listed_level/11774780/raw: -------------------------------------------------------------------------------- 1 | 1:11774780:2:Dark Realm:5:2:6:2073761:8:10:9:30:10:108975:12:0:13:20:14:11730:17:1:43:0:25::18:10:19:11994:42:0:45:0:3:TXkgYmVzdCBsZXZlbCB5ZXQuIFZpZGVvIG9uIG15IFlvdVR1YmUuIEhhdmUgZnVuIGluIHRoaXMgZmFzdC1wYWNlZCBERU1PTiA-OikgdjIgRml4ZWQgc29tZSB0aGluZ3M=:15:3:30:0:31:0:37:3:38:1:39:10:46:1:47:2:35:444085 -------------------------------------------------------------------------------- /dash-rs-derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "dash-rs-derive" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [lib] 9 | proc-macro = true 10 | 11 | [dependencies] 12 | proc-macro2 = "1.0.71" 13 | quote = "1.0.33" 14 | syn = "2.0.42" -------------------------------------------------------------------------------- /tests/artifacts/song/444085/processed: -------------------------------------------------------------------------------- 1 | { 2 | "song_id": 444085, 3 | "name": "Dark Angel - F-777", 4 | "index_3": 286, 5 | "artist": "F-777", 6 | "filesize": 8.96, 7 | "index_6": null, 8 | "index_7": "UC6MNIegxWVDe6tOjL92QkUw", 9 | "index_8": "1", 10 | "link": "http://audio.ngfiles.com/444000/444085_Dark_Angel___F_777.mp3" 11 | } -------------------------------------------------------------------------------- /tests/artifacts/song/1204676/processed: -------------------------------------------------------------------------------- 1 | { 2 | "song_id": 1204676, 3 | "name": "Hide n Seek Ranch", 4 | "index_3": 15747, 5 | "artist": "PuffballsUnited", 6 | "filesize": 6.34, 7 | "index_6": null, 8 | "index_7": null, 9 | "index_8": "1", 10 | "link": "https://audio.ngfiles.com/1204000/1204676_Hide-n-Seek-Ranch.mp3?f1680307735" 11 | } -------------------------------------------------------------------------------- /tests/artifacts/listed_level/24904605/raw: -------------------------------------------------------------------------------- 1 | 1:24904605:2:The Badland:5:4:6:5449239:8:10:9:40:10:969711:12:0:13:20:14:81238:17:1:43:5:25::18:10:19:18801:42:0:45:0:3:SGUgbWF5IGhhdmUgYmVlbiBkZWZlYXRlZCwgYnV0IGNhbiB5b3Ugc3RvcCBoaXMgcmV0dXJuPyBEZWRpY2F0ZWQgdG8gTGF6ZXJCbGl0eiBhbmQgTWFuaXguIDEwMGsgT2JqZWN0cyEgRm9yIE5HQyBjb250ZXN0IDszOykvLy8=:15:4:30:22073337:31:0:37:3:38:1:39:10:46:1:47:2:35:686782 -------------------------------------------------------------------------------- /tests/artifacts/searched_user/stardust1971/processed: -------------------------------------------------------------------------------- 1 | { 2 | "name": "stardust1971", 3 | "user_id": 2073761, 4 | "stars": 13791, 5 | "demons": 483, 6 | "index_6": "0", 7 | "creator_points": 19, 8 | "icon_index": 95, 9 | "primary_color": { 10 | "Known": [ 11 | 255, 12 | 0, 13 | 0 14 | ] 15 | }, 16 | "secondary_color": { 17 | "Known": [ 18 | 255, 19 | 125, 20 | 0 21 | ] 22 | }, 23 | "secret_coins": 151, 24 | "icon_type": "Cube", 25 | "has_glow": true, 26 | "account_id": 8451, 27 | "user_coins": 499, 28 | "moons": 16 29 | } -------------------------------------------------------------------------------- /tests/artifacts/listed_level/72540/processed: -------------------------------------------------------------------------------- 1 | { 2 | "level_id": 72540, 3 | "name": "demon world", 4 | "description": "happy new year!!", 5 | "version": 7, 6 | "creator": 37573, 7 | "difficulty": { 8 | "Demon": "Medium" 9 | }, 10 | "downloads": 452111, 11 | "main_song": 9, 12 | "gd_version": 7, 13 | "likes": -2916, 14 | "length": "Long", 15 | "stars": 10, 16 | "featured": 0, 17 | "copy_of": null, 18 | "two_player": false, 19 | "custom_song": null, 20 | "coin_amount": 0, 21 | "coins_verified": false, 22 | "stars_requested": null, 23 | "is_epic": false, 24 | "object_amount": null, 25 | "index_46": "1", 26 | "index_47": "2", 27 | "level_data": null 28 | } -------------------------------------------------------------------------------- /src/model/level/object/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::model::level::object::speed::Speed; 2 | use serde::{Deserialize, Serialize}; 3 | 4 | pub mod ids; 5 | mod internal; 6 | pub mod speed; 7 | 8 | #[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)] 9 | pub struct LevelObject { 10 | pub id: u16, 11 | pub x: f32, 12 | pub y: f32, 13 | pub flipped_x: bool, 14 | pub flipped_y: bool, 15 | pub rotation: f32, 16 | // ... other fields they all have ... 17 | pub metadata: ObjectData, 18 | } 19 | 20 | #[derive(Debug, Clone, PartialEq, Copy, Serialize, Deserialize)] 21 | pub enum ObjectData { 22 | None, 23 | Unknown, 24 | SpeedPortal { checked: bool, speed: Speed }, 25 | } 26 | -------------------------------------------------------------------------------- /tests/artifacts/listed_level/63355989/processed: -------------------------------------------------------------------------------- 1 | { 2 | "level_id": 63355989, 3 | "name": "Fantasy", 4 | "description": "Collab with Brindikz, thank you for this level uwu, ENJOY!! ", 5 | "version": 3, 6 | "creator": 15557115, 7 | "difficulty": "Harder", 8 | "downloads": 23324, 9 | "main_song": null, 10 | "gd_version": 21, 11 | "likes": 2141, 12 | "length": "Long", 13 | "stars": 7, 14 | "featured": 24978, 15 | "copy_of": 63309629, 16 | "two_player": false, 17 | "custom_song": 771517, 18 | "coin_amount": 2, 19 | "coins_verified": true, 20 | "stars_requested": 7, 21 | "is_epic": false, 22 | "object_amount": 37865, 23 | "index_46": "1", 24 | "index_47": "2", 25 | "level_data": null 26 | } -------------------------------------------------------------------------------- /tests/artifacts/listed_level/97598449/processed: -------------------------------------------------------------------------------- 1 | { 2 | "level_id": 97598449, 3 | "name": "Loco Motive", 4 | "description": "Yee Haw", 5 | "version": 2, 6 | "creator": 8599996, 7 | "difficulty": "Harder", 8 | "downloads": 3011016, 9 | "main_song": null, 10 | "gd_version": 22, 11 | "likes": 153976, 12 | "length": "Platformer", 13 | "stars": 6, 14 | "featured": 25049, 15 | "copy_of": null, 16 | "two_player": false, 17 | "custom_song": 1204676, 18 | "coin_amount": 0, 19 | "coins_verified": false, 20 | "stars_requested": 6, 21 | "is_epic": true, 22 | "object_amount": 18374, 23 | "index_46": "1", 24 | "index_47": "2", 25 | "level_data": null 26 | } -------------------------------------------------------------------------------- /tests/creator.rs: -------------------------------------------------------------------------------- 1 | use dash_rs::model::creator::Creator; 2 | use framework::load_test_units; 3 | use std::path::Path; 4 | 5 | mod framework; 6 | 7 | enum CreatorTester {} 8 | 9 | impl framework::Testable for CreatorTester { 10 | type Target<'a> = Creator<'a>; 11 | } 12 | 13 | #[test] 14 | fn test_creator() { 15 | let units = load_test_units::( 16 | Path::new(env!("CARGO_MANIFEST_DIR")) 17 | .join("tests") 18 | .join("artifacts") 19 | .join("creator"), 20 | ); 21 | 22 | for (path, unit) in units { 23 | println!("Testing case {:?}", path); 24 | 25 | unit.test_consistency(); 26 | unit.test_load_save_roundtrip(); 27 | unit.test_save_load_roundtrip(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /tests/profile.rs: -------------------------------------------------------------------------------- 1 | use dash_rs::model::user::profile::Profile; 2 | use framework::load_test_units; 3 | use std::path::Path; 4 | 5 | mod framework; 6 | 7 | enum ProfileTester {} 8 | 9 | impl framework::Testable for ProfileTester { 10 | type Target<'a> = Profile<'a>; 11 | } 12 | 13 | #[test] 14 | fn test_profile() { 15 | let units = load_test_units::( 16 | Path::new(env!("CARGO_MANIFEST_DIR")) 17 | .join("tests") 18 | .join("artifacts") 19 | .join("profile"), 20 | ); 21 | 22 | for (path, unit) in units { 23 | println!("Testing case {:?}", path); 24 | 25 | unit.test_consistency(); 26 | unit.test_load_save_roundtrip(); 27 | unit.test_save_load_roundtrip(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /tests/artifacts/listed_level/11774780/processed: -------------------------------------------------------------------------------- 1 | { 2 | "level_id": 11774780, 3 | "name": "Dark Realm", 4 | "description": "My best level yet. Video on my YouTube. Have fun in this fast-paced DEMON >:) v2 Fixed some things", 5 | "version": 2, 6 | "creator": 2073761, 7 | "difficulty": { 8 | "Demon": "Hard" 9 | }, 10 | "downloads": 108975, 11 | "main_song": null, 12 | "gd_version": 20, 13 | "likes": 11730, 14 | "length": "Long", 15 | "stars": 10, 16 | "featured": 11994, 17 | "copy_of": null, 18 | "two_player": false, 19 | "custom_song": 444085, 20 | "coin_amount": 3, 21 | "coins_verified": true, 22 | "stars_requested": 10, 23 | "is_epic": false, 24 | "object_amount": null, 25 | "index_46": "1", 26 | "index_47": "2", 27 | "level_data": null 28 | } -------------------------------------------------------------------------------- /tests/searched_user.rs: -------------------------------------------------------------------------------- 1 | use dash_rs::model::user::searched::SearchedUser; 2 | use framework::load_test_units; 3 | use std::path::Path; 4 | 5 | mod framework; 6 | 7 | enum SearchedUserTester {} 8 | 9 | impl framework::Testable for SearchedUserTester { 10 | type Target<'a> = SearchedUser<'a>; 11 | } 12 | 13 | #[test] 14 | fn test_searched_user() { 15 | let units = load_test_units::( 16 | Path::new(env!("CARGO_MANIFEST_DIR")) 17 | .join("tests") 18 | .join("artifacts") 19 | .join("searched_user"), 20 | ); 21 | 22 | for (path, unit) in units { 23 | println!("Testing case {:?}", path); 24 | 25 | unit.test_consistency(); 26 | unit.test_load_save_roundtrip(); 27 | unit.test_save_load_roundtrip(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /tests/artifacts/listed_level/24904605/processed: -------------------------------------------------------------------------------- 1 | { 2 | "level_id": 24904605, 3 | "name": "The Badland", 4 | "description": "He may have been defeated, but can you stop his return? Dedicated to LazerBlitz and Manix. 100k Objects! For NGC contest ;3;)///", 5 | "version": 4, 6 | "creator": 5449239, 7 | "difficulty": { 8 | "Demon": "Insane" 9 | }, 10 | "downloads": 969711, 11 | "main_song": null, 12 | "gd_version": 20, 13 | "likes": 81238, 14 | "length": "ExtraLong", 15 | "stars": 10, 16 | "featured": 18801, 17 | "copy_of": 22073337, 18 | "two_player": false, 19 | "custom_song": 686782, 20 | "coin_amount": 3, 21 | "coins_verified": true, 22 | "stars_requested": 10, 23 | "is_epic": false, 24 | "object_amount": null, 25 | "index_46": "1", 26 | "index_47": "2", 27 | "level_data": null 28 | } -------------------------------------------------------------------------------- /tests/song.rs: -------------------------------------------------------------------------------- 1 | use dash_rs::model::song::NewgroundsSong; 2 | use framework::load_test_units; 3 | use std::path::Path; 4 | 5 | mod framework; 6 | 7 | enum NewgroundsSongTester {} 8 | 9 | impl framework::Testable for NewgroundsSongTester { 10 | type Target<'a> = NewgroundsSong<'a>; 11 | 12 | fn canonicalize(target: &mut Self::Target<'_>) { 13 | target.link.process().unwrap(); 14 | } 15 | } 16 | 17 | #[test] 18 | fn test_newgrounds_song() { 19 | let units = load_test_units::(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests").join("artifacts").join("song")); 20 | 21 | for (path, unit) in units { 22 | println!("Testing case {:?}", path); 23 | 24 | unit.test_consistency(); 25 | unit.test_load_save_roundtrip(); 26 | unit.test_save_load_roundtrip(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/serde/ser/error.rs: -------------------------------------------------------------------------------- 1 | use std::{fmt::Display, io}; 2 | 3 | use thiserror::Error; 4 | 5 | /// Errors that can occur during serialization 6 | #[derive(Debug, Error)] 7 | pub enum Error { 8 | /// Some custom error happened during serialization. 9 | #[error("{0}")] 10 | Custom(String), 11 | 12 | /// A given [`Serializer`](serde::Serializer) function was not supported 13 | #[error("unsupported serializer function: {0}")] 14 | Unsupported(&'static str), 15 | 16 | #[error("io error: {0}")] 17 | Io(#[from] io::Error), 18 | 19 | #[error("failed utf8 conversion: {0}")] 20 | Utf8(#[from] std::string::FromUtf8Error), 21 | } 22 | 23 | impl serde::ser::Error for Error { 24 | fn custom(msg: T) -> Self 25 | where 26 | T: Display, 27 | { 28 | Error::Custom(msg.to_string()) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /tests/misc.rs: -------------------------------------------------------------------------------- 1 | use dash_rs::{ 2 | model::{creator::Creator, song::NewgroundsSong}, 3 | GJFormat, 4 | }; 5 | 6 | mod framework; 7 | 8 | const CREO_DUNE_DATA_TOO_MANY_FIELDS: &str = "1~|~771277~|~54~|~should be ignored~|~2~|~Creo - \ 9 | Dune~|~3~|~50531~|~4~|~CreoMusic~|~5~|~8.\ 10 | 03~|~6~|~~|~7~|~UCsCWA3Y3JppL6feQiMRgm6Q~|~8~|~1~|~10~|~https%3A%2F%2Faudio.ngfiles.com%\ 11 | 2F771000%2F771277_Creo---Dune.mp3%3Ff1508708604~|~9~|~should be ignored"; 12 | 13 | const CREATOR_REGISTERED_DATA_TOO_MANY_FIELDS: &str = "4170784:Serponge:119741:34:fda:32:asd:3"; 14 | 15 | #[test] 16 | fn deserialize_too_many_fields() { 17 | // Superfluous fields should just be ignored 18 | NewgroundsSong::from_gj_str(CREO_DUNE_DATA_TOO_MANY_FIELDS).unwrap(); 19 | Creator::from_gj_str(CREATOR_REGISTERED_DATA_TOO_MANY_FIELDS).unwrap(); 20 | } 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 stadust 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /tests/artifacts/profile/8451/processed: -------------------------------------------------------------------------------- 1 | { 2 | "name": "stardust1971", 3 | "user_id": 2073761, 4 | "stars": 13791, 5 | "demons": 483, 6 | "creator_points": 19, 7 | "primary_color": { 8 | "Known": [ 9 | 255, 10 | 0, 11 | 0 12 | ] 13 | }, 14 | "secondary_color": { 15 | "Known": [ 16 | 255, 17 | 125, 18 | 0 19 | ] 20 | }, 21 | "secret_coins": 151, 22 | "account_id": 8451, 23 | "user_coins": 499, 24 | "index_18": "0", 25 | "index_19": "0", 26 | "youtube_url": "stardust19710", 27 | "cube_index": 95, 28 | "ship_index": 48, 29 | "ball_index": 33, 30 | "ufo_index": 18, 31 | "wave_index": 11, 32 | "robot_index": 10, 33 | "has_glow": true, 34 | "index_29": "1", 35 | "global_rank": 13731, 36 | "index_31": "0", 37 | "index_38": null, 38 | "index_39": null, 39 | "index_40": null, 40 | "spider_index": 2, 41 | "twitter_url": "stadust1971", 42 | "twitch_url": null, 43 | "diamonds": 2621, 44 | "death_effect_index": 13, 45 | "mod_level": "None", 46 | "index_50": "0", 47 | "index_51": "63", 48 | "moons": 16, 49 | "swing_index": 3, 50 | "jetpack_index": 1 51 | } -------------------------------------------------------------------------------- /.github/workflows/rust-build.yml: -------------------------------------------------------------------------------- 1 | name: Validate build 2 | 3 | # Checks if code inside pull requests against 'master' compiles and passes all tests 4 | # Taken from: https://github.com/actions-rs/meta/blob/master/recipes/quickstart.md 5 | 6 | on: 7 | push: 8 | branches: master 9 | pull_request: 10 | branches: master 11 | 12 | jobs: 13 | check: 14 | name: Check 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v2 18 | - uses: actions-rs/toolchain@v1 19 | with: 20 | profile: minimal 21 | toolchain: stable 22 | override: true 23 | - uses: actions-rs/cargo@v1 24 | with: 25 | command: check 26 | args: --examples --tests 27 | clippy: 28 | name: Clippy Lints 29 | runs-on: ubuntu-latest 30 | steps: 31 | - uses: actions/checkout@v2 32 | - uses: actions-rs/toolchain@v1 33 | with: 34 | toolchain: nightly 35 | components: clippy 36 | override: true 37 | - uses: actions-rs/clippy-check@v1 38 | with: 39 | token: ${{ secrets.GITHUB_TOKEN }} 40 | args: --all-features 41 | -------------------------------------------------------------------------------- /.github/workflows/rustfmt.yml: -------------------------------------------------------------------------------- 1 | name: Rustfmt 2 | 3 | # Runs `cargo fmt` whenever code is pushed or pr'd into master. 4 | 5 | on: 6 | push: 7 | branches: 8 | - master 9 | pull_request: 10 | branches: 11 | - master 12 | types: 13 | - closed 14 | 15 | jobs: 16 | format: 17 | name: Rustfmt 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - uses: actions/checkout@v2 22 | - uses: actions-rs/toolchain@v1 23 | with: 24 | profile: minimal 25 | toolchain: stable 26 | override: true 27 | components: rustfmt 28 | - run: rustup component add rustfmt 29 | - uses: actions-rs/cargo@v1 30 | with: 31 | command: fmt 32 | args: --all 33 | - name: Commit files # only runs if something actually changed 34 | run: | 35 | if [[ -n "$(git status -s)" ]]; then 36 | git config --local user.email "action@github.com" 37 | git config --local user.name "GitHub Action" 38 | git commit -m "CI: Automatic Rustfmt" -a 39 | fi 40 | - name: Push changes 41 | uses: ad-m/github-push-action@master 42 | with: 43 | github_token: ${{ secrets.GITHUB_TOKEN }} 44 | -------------------------------------------------------------------------------- /src/model/comment/profile.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | serde::{Base64Decoder, Thunk}, 3 | GJFormat, 4 | }; 5 | use dash_rs_derive::Dash; 6 | use serde::{Deserialize, Serialize}; 7 | use std::borrow::Cow; 8 | use variant_partial_eq::VariantPartialEq; 9 | 10 | #[derive(Debug, Serialize, Deserialize, Eq, VariantPartialEq, Clone, Dash)] 11 | pub struct ProfileComment<'a> { 12 | /// The actual content of the [`ProfileComment`] made. 13 | #[serde(borrow)] 14 | #[variant_compare = "crate::util::option_variant_eq"] 15 | #[dash(index = 2)] 16 | pub content: Option>, 17 | 18 | /// The amount of likes this [`ProfileComment`] has received 19 | #[dash(index = 4)] 20 | pub likes: i32, 21 | 22 | /// The unique id of this [`ProfileComment`]. Additionally, there is also no [`LevelComment`](crate::model::comment::level::LevelComment) 23 | /// with this id 24 | #[dash(index = 6)] 25 | pub comment_id: u64, 26 | 27 | /// Robtop's completely braindead way of keeping track of when this [`ProfileComment`] was 28 | /// posted 29 | #[dash(index = 9)] 30 | pub time_since_post: Cow<'a, str>, 31 | } 32 | 33 | impl<'de> GJFormat<'de> for ProfileComment<'de> { 34 | const DELIMITER: &'static str = "~"; 35 | const MAP_LIKE: bool = true; 36 | } 37 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["dash-rs-derive"] 3 | 4 | [package] 5 | name = "dash-rs" 6 | version = "0.1.0" 7 | authors = ["stadust <43299462+stadust@users.noreply.github.com>"] 8 | edition = "2018" 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [dependencies] 13 | serde = {version = "1.0.118", features = ["derive"]} 14 | base64 = "0.21.5" 15 | log = {version = "0.4.8" } 16 | percent-encoding = "2.1.0" 17 | itoa = "1.0.10" 18 | flate2 = {version = "1.0.14", features = ["zlib"], default-features=false} 19 | variant_partial_eq = { git = "https://github.com/stadust/variant-partial-eq" } 20 | thiserror = "1.0.51" 21 | dash-rs-derive = { path = "dash-rs-derive" } 22 | 23 | [dev-dependencies] 24 | # benchmark 25 | env_logger = "0.10.1" 26 | criterion = "0.5.1" 27 | 28 | # Dependencies used by examples 29 | reqwest = "0.11.17" 30 | tokio = {version = "1.28.0", features = ["macros", "rt-multi-thread"]} 31 | serde_json = "1.0.108" 32 | pretty_assertions = "1.4.0" 33 | 34 | [build-dependencies] 35 | serde = {version = "1.0.104", features = ["derive"]} 36 | serde_yaml = "0.9.29" 37 | 38 | [[bench]] 39 | name = "level_processing_benchmark" 40 | harness = false 41 | 42 | [lints.rust] 43 | unexpected_cfgs = { level = "warn", check-cfg = ['cfg(dash_rs_dev_debug)'] } -------------------------------------------------------------------------------- /.github/workflows/coverage.yml: -------------------------------------------------------------------------------- 1 | name: coverage 2 | 3 | # Runs tests with coverage and reports the results 4 | 5 | on: 6 | pull_request: 7 | push: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | coverage: 13 | name: coverage 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - name: Checkout repository 18 | uses: actions/checkout@v3 19 | 20 | - name: Install rust toolchain 21 | uses: actions-rs/toolchain@v1 22 | with: 23 | profile: minimal 24 | toolchain: stable 25 | override: true 26 | components: llvm-tools-preview 27 | 28 | - name: Run tests 29 | uses: actions-rs/cargo@v1 30 | with: 31 | command: test 32 | env: 33 | RUST_BACKTRACE: 1 34 | RUSTFLAGS: -Cinstrument-coverage 35 | 36 | - name: Install grcov 37 | uses: actions-rs/cargo@v1 38 | with: 39 | command: install 40 | args: grcov 41 | 42 | - name: Generate coverage report 43 | run: grcov . -s . --binary-path ./target/debug/ -t lcov --ignore-not-existing -o ./target/debug/coverage.lcov --keep-only "src/*" 44 | 45 | - name: Upload coverage report 46 | uses: codecov/codecov-action@v3 47 | with: 48 | files: ./target/debug/coverage.lcov 49 | -------------------------------------------------------------------------------- /src/split.rs: -------------------------------------------------------------------------------- 1 | //! Module exposing a ['memchr'] based iterator for splitting strings 2 | 3 | use memchr::memmem; 4 | 5 | #[derive(Debug)] 6 | pub struct Split<'de> { 7 | input: &'de str, 8 | delimiter: &'static str, 9 | finder: memmem::FindIter<'de, 'static>, 10 | end_of_last_delimiter: Option, 11 | } 12 | 13 | impl<'de> Split<'de> { 14 | pub fn new(haystack: &'de str, needle: &'static str) -> Self { 15 | Split { 16 | input: haystack, 17 | delimiter: needle, 18 | finder: memmem::find_iter(haystack.as_ref(), needle), 19 | end_of_last_delimiter: Some(0), 20 | } 21 | } 22 | 23 | pub fn position(&self) -> usize { 24 | self.end_of_last_delimiter.unwrap_or(self.input.len()) 25 | } 26 | } 27 | 28 | impl<'de> Iterator for Split<'de> { 29 | type Item = &'de str; 30 | 31 | fn next(&mut self) -> Option { 32 | match self.end_of_last_delimiter { 33 | Some(end_of_last) => match self.finder.next() { 34 | Some(next) => { 35 | self.end_of_last_delimiter = Some(next + self.delimiter.len()); 36 | Some(&self.input[end_of_last..next]) 37 | }, 38 | None => { 39 | self.end_of_last_delimiter = None; 40 | Some(&self.input[end_of_last..]) 41 | }, 42 | }, 43 | None => None, 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/model/creator.rs: -------------------------------------------------------------------------------- 1 | use dash_rs_derive::Dash; 2 | use serde::{Deserialize, Serialize}; 3 | use std::borrow::Cow; 4 | use variant_partial_eq::VariantPartialEq; 5 | 6 | use crate::GJFormat; 7 | 8 | /// Struct modelling a [`Creator`] of a level. 9 | /// 10 | /// ## GD Internals 11 | /// The Geometry Dash servers provide a list of the creators of the 12 | /// levels in a `getGJLevels` response. 13 | /// 14 | /// Creators do not use the map-like representation, meaning the order of fields in the raw data 15 | /// must correspond to the order of fields in this struct. 16 | #[derive(Debug, Deserialize, Serialize, VariantPartialEq, Eq, Clone, Dash)] 17 | pub struct Creator<'a> { 18 | /// The [`Creator`]'s unique user ID 19 | #[dash(index = 1)] 20 | pub user_id: u64, 21 | 22 | /// The [`Creator`]'s name 23 | #[serde(borrow)] 24 | #[dash(index = 2)] 25 | pub name: Cow<'a, str>, 26 | 27 | /// The [`Creator`]'s unique account ID. 28 | /// 29 | /// This field is [`None`] if the creator hasn't registered for an account. 30 | #[dash(index = 3)] 31 | #[dash(with = "crate::util::default_to_none")] 32 | pub account_id: Option, 33 | } 34 | 35 | impl<'de> GJFormat<'de> for Creator<'de> { 36 | const DELIMITER: &'static str = ":"; 37 | const MAP_LIKE: bool = false; 38 | } 39 | 40 | impl<'a> Creator<'a> { 41 | pub fn into_owned(self) -> Creator<'static> { 42 | Creator { 43 | user_id: self.user_id, 44 | name: Cow::Owned(self.name.into_owned()), 45 | account_id: self.account_id, 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/model/level/object/speed.rs: -------------------------------------------------------------------------------- 1 | // TODO: Speed portals and stuff 2 | use serde::{Deserialize, Serialize}; 3 | 4 | /// Enum modelling the different speeds a player can have during gameplay 5 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] 6 | pub enum Speed { 7 | Slow, 8 | #[default] 9 | Normal, 10 | Medium, 11 | Fast, 12 | VeryFast, 13 | Unknown(u8), 14 | } 15 | 16 | /// Converts the speed to the game-internal "pixel / second" value represented by some [`Speed`] 17 | /// variant 18 | impl From for f32 { 19 | fn from(speed: Speed) -> f32 { 20 | match speed { 21 | Speed::Unknown(_) => 0.0, 22 | Speed::Slow => 251.16, 23 | Speed::Normal => 311.58, 24 | Speed::Medium => 387.42, 25 | Speed::Fast => 468.0, 26 | Speed::VeryFast => 576.0, 27 | } 28 | } 29 | } 30 | 31 | impl From for Speed { 32 | fn from(value: u8) -> Self { 33 | match value { 34 | 0 => Speed::Slow, 35 | 1 => Speed::Normal, 36 | 2 => Speed::Medium, 37 | 3 => Speed::Fast, 38 | 4 => Speed::VeryFast, 39 | unknown => Speed::Unknown(unknown), 40 | } 41 | } 42 | } 43 | 44 | impl From for u8 { 45 | fn from(speed: Speed) -> Self { 46 | match speed { 47 | Speed::Slow => 0, 48 | Speed::Normal => 1, 49 | Speed::Medium => 2, 50 | Speed::Fast => 3, 51 | Speed::VeryFast => 4, 52 | Speed::Unknown(unknown) => unknown, 53 | } 54 | } 55 | } 56 | 57 | crate::into_conversion!(Speed, u8); 58 | -------------------------------------------------------------------------------- /src/model/level/metadata.rs: -------------------------------------------------------------------------------- 1 | use crate::{model::level::object::speed::Speed, GJFormat}; 2 | use dash_rs_derive::Dash; 3 | use serde::{Deserialize, Serialize}; 4 | 5 | #[derive(Debug, PartialEq, Clone, Default, Copy, Serialize, Deserialize, Dash)] 6 | pub struct LevelMetadata { 7 | #[dash(index = "kA4")] 8 | #[dash(default = "one")] 9 | pub starting_speed: Speed, 10 | 11 | #[dash(index = "kA13")] 12 | #[dash(default)] 13 | pub song_offset: f64, 14 | 15 | #[dash(index = "kA15")] 16 | #[dash(default)] 17 | pub song_fade_in: bool, 18 | 19 | #[dash(index = "kA16")] 20 | #[dash(default)] 21 | pub song_fade_out: bool, 22 | 23 | #[dash(index = "kA8")] 24 | #[dash(default)] 25 | pub dual_start: bool, 26 | 27 | #[dash(index = "kA10")] 28 | #[dash(default)] 29 | pub two_player_controls: bool, 30 | 31 | #[dash(index = "kA11")] 32 | #[dash(default)] 33 | pub start_gravity_inverted: bool, 34 | // ... other fields in the metadata section ... 35 | } 36 | 37 | impl<'de> GJFormat<'de> for LevelMetadata { 38 | const DELIMITER: &'static str = ","; 39 | const MAP_LIKE: bool = true; 40 | } 41 | 42 | fn one() -> u8 { 43 | 1 44 | } 45 | 46 | // starting_speed(index = kA4), 47 | // song_offset(index = kA13), 48 | // fade_in(index = kA15), 49 | // fade_out(index = kA16), 50 | // song guidelines: kA16 51 | // background texture index: kA6 52 | // ground texture index: kA7 53 | // ground line index: kA17 54 | // font: kA18 55 | // color page (???): kS39 56 | // starting game mode: kA2 57 | // starting size: kA3 58 | // dual_start(index = kA8), 59 | // level/start pos (???): kA9 60 | // two_player_controls(index = kA10), 61 | // start_gravity_inverted(index = kA11, optional), 62 | -------------------------------------------------------------------------------- /src/serde/de/error.rs: -------------------------------------------------------------------------------- 1 | //! Module containing the error type for deserialization errors 2 | 3 | use std::fmt::Display; 4 | 5 | use thiserror::Error; 6 | 7 | /// Errors that can occur during deserialization 8 | #[derive(Debug, Error)] 9 | pub enum Error<'de> { 10 | /// End of input data was reached. 11 | /// 12 | /// This means that more data was expected to finish deserialization, however all input had 13 | /// already been processed 14 | #[error("Unexpected EOF while parsing")] 15 | Eof, 16 | 17 | /// Some custom error happened while deserializing the data at the specified index. 18 | #[error("{value:?} at index {index:?} caused {message}")] 19 | Custom { 20 | /// The error message 21 | message: String, 22 | 23 | /// The index of the data that caused the error 24 | /// 25 | /// Is [`None`] if the error happens at a point where no index was available, such as when 26 | /// parsing the index itself 27 | index: Option<&'de str>, 28 | 29 | /// The value that caused the error 30 | /// 31 | /// Not available if the error is not related to any value (for instance if the format 32 | /// itself was malformed). 33 | value: Option<&'de str>, 34 | }, 35 | 36 | /// A given [`Deserializer`](serde::Deserializer) function was not supported 37 | #[error("unsupported deserializer function: {0}")] 38 | Unsupported(&'static str), 39 | } 40 | 41 | impl serde::de::Error for Error<'_> { 42 | fn custom(msg: T) -> Self 43 | where 44 | T: Display, 45 | { 46 | Error::Custom { 47 | message: msg.to_string(), 48 | index: None, 49 | value: None, 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tests/level.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | 3 | use dash_rs::model::level::Level; 4 | use framework::load_test_units; 5 | 6 | mod framework; 7 | 8 | enum LevelTester {} 9 | 10 | impl framework::Testable for LevelTester { 11 | type Target<'a> = Level<'a, ()>; 12 | 13 | fn canonicalize(level: &mut Self::Target<'_>) { 14 | if let Some(ref mut hunk) = level.description { 15 | hunk.process().unwrap(); 16 | } 17 | } 18 | } 19 | 20 | #[test] 21 | fn test_listed_level() { 22 | let units = load_test_units::( 23 | Path::new(env!("CARGO_MANIFEST_DIR")) 24 | .join("tests") 25 | .join("artifacts") 26 | .join("listed_level"), 27 | ); 28 | 29 | for (path, unit) in units { 30 | println!("Testing case {:?}", path); 31 | 32 | unit.test_consistency(); 33 | unit.test_load_save_roundtrip(); 34 | unit.test_save_load_roundtrip(); 35 | } 36 | } 37 | 38 | enum FullLevelTester {} 39 | 40 | impl framework::Testable for FullLevelTester { 41 | type Target<'a> = Level<'a>; 42 | 43 | fn canonicalize(level: &mut Self::Target<'_>) { 44 | if let Some(ref mut hunk) = level.description { 45 | hunk.process().unwrap(); 46 | } 47 | level.level_data.level_data.process().unwrap(); 48 | level.level_data.password.process().unwrap(); 49 | } 50 | } 51 | 52 | #[test] 53 | fn test_full_level() { 54 | let units = load_test_units::(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests").join("artifacts").join("level")); 55 | 56 | for (path, unit) in units { 57 | println!("Testing case {:?}", path); 58 | 59 | unit.test_consistency(); 60 | // Cannot do round trip testing for onw, as the level data handling in dash-rs is incomplete 61 | // (to put it nicely) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `dash-rs` - Efficient processing of Geometry Dash data 2 | 3 | ![build](https://github.com/stadust/dash-rs/actions/workflows/rust-build.yml/badge.svg) 4 | [![codecov](https://codecov.io/gh/stadust/dash-rs/branch/master/graph/badge.svg?token=2EA56CDN6T)](https://codecov.io/gh/stadust/dash-rs) 5 | 6 | `dash-rs` (spoken 'dashers') is an experimental library related to modelling, and more imporant _processing_ all data formats related to RobTop's 2013 game "Geometry Dash". The long-term goal is to have this crate replace `gdcf_model`, `gdcf_parse` and some parts of `gdrs` in GDCF. 7 | 8 | The project is a collaboration with [mgostIH](https://github.com/mgostIH), on whose idea the initial library design is based on and who continues to provide incredibly helpful insights into optimization, Geometry Dash and Rust. 9 | 10 | ## Using With a Custom GDPS 11 | If you are planning to use this library to interact with a GDPS, you can use: 12 | 13 | ```rust 14 | use dash_rs::request::GD_SERVER_ENDPOINT_BASE_URL; 15 | 16 | GD_SERVER_ENDPOINT_BASE_URL.get_or_init(|| "https://your-custom-gdps-url.com".to_string()); 17 | ``` 18 | 19 | Insert this anywhere before the first call to any `dash-rs` function. 20 | 21 | ## Goals 22 | 23 | The goals for dash-rs are, in order: 24 | 25 | + Zero allocation deserialization for RobTop's HTTP response and local savefile formats, using [serde](https://serde.rs) 26 | + Accurate modelling of all game related data 27 | + Efficient serialization routines for RobTop's HTTP response and local save file formats, using serde. 28 | 29 | The benchmark we're trying to beat is parsing and calculating the length in seconds of the level 'Spacial Rend' in `56ms`, achieved on my Laptop's Intel:tm: Core i7-8850H using `gdcf_parse`. 30 | 31 | ## Disclaimer 32 | 33 | I, in no way, claim to know what I'm doing. 34 | 35 | ## License 36 | 37 | This project is licensed under the terms of the MIT license. 38 | -------------------------------------------------------------------------------- /dash-rs-derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::convert::TryFrom; 2 | 3 | use field::FieldMapping; 4 | use proc_macro::TokenStream; 5 | use proc_macro2::Span; 6 | use quote::ToTokens; 7 | use struct_gen::InternalStruct; 8 | use syn::{parse_macro_input, spanned::Spanned, Data, DataStruct, DeriveInput, Error, Fields, Result}; 9 | 10 | mod field; 11 | mod struct_gen; 12 | mod utils; 13 | 14 | #[proc_macro_derive(Dash, attributes(dash))] 15 | pub fn derive_dash(ts: TokenStream) -> TokenStream { 16 | let input = parse_macro_input!(ts as DeriveInput); 17 | expand_dash_derive(input) 18 | .map(|is| is.to_token_stream()) 19 | .unwrap_or_else(syn::Error::into_compile_error) 20 | .into() 21 | } 22 | 23 | fn expand_dash_derive(input: DeriveInput) -> Result { 24 | let DeriveInput { ident, generics, data, .. } = input; 25 | 26 | let Data::Struct(DataStruct { fields, .. }) = data else { 27 | return Err(Error::new(Span::call_site(), "#[derive(Dash)] only support structs")); 28 | }; 29 | 30 | let Fields::Named(fields_named) = fields else { 31 | return Err(Error::new(fields.span(), "#[derive(Dash) only supports structs with named fields")); 32 | }; 33 | 34 | let primary_lifetime = utils::find_unique_lifetime(&generics)?; 35 | 36 | #[allow(clippy::manual_try_fold)] // 37 | let fields = fields_named 38 | .named 39 | .into_iter() 40 | .map(FieldMapping::try_from) 41 | .fold(Ok(Vec::new()), |acc, res| match (acc, res) { 42 | (Ok(mut ifields), Ok(ifield)) => { 43 | ifields.push(ifield); 44 | Ok(ifields) 45 | }, 46 | (Ok(_), Err(err)) | (Err(err), Ok(_)) => Err(err), 47 | (Err(mut err), Err(err2)) => { 48 | err.combine(err2); 49 | Err(err) 50 | }, 51 | })?; 52 | 53 | Ok(InternalStruct { 54 | name: ident, 55 | fields, 56 | generics, 57 | lifetime: primary_lifetime, 58 | }) 59 | } 60 | -------------------------------------------------------------------------------- /dash-rs-derive/src/utils.rs: -------------------------------------------------------------------------------- 1 | use syn::{spanned::Spanned, Error, Generics, LifetimeParam, Result, Type}; 2 | 3 | /// If the given [`Generics`] contain a unique lifetime, return it. If there are no lifetimes, 4 | /// return a `'static` lifetime. Otherwise, return a spanned error indicating either a lack of 5 | /// lifetimes, or too many lifetimes 6 | pub fn find_unique_lifetime(generics: &Generics) -> Result> { 7 | let mut lifetime_iter = generics.lifetimes(); 8 | let first_lifetime = lifetime_iter.next().cloned(); 9 | 10 | if let Some(lifetime_param) = lifetime_iter.next() { 11 | return Err(Error::new(lifetime_param.span(), "Expected exactly one lifetime, found multiple")); 12 | } 13 | 14 | Ok(first_lifetime) 15 | } 16 | 17 | pub fn type_contains_lifetime(ty: &Type) -> bool { 18 | match ty { 19 | Type::Array(_) => todo!(), 20 | Type::BareFn(_) => todo!(), 21 | Type::Group(_) => todo!(), 22 | Type::ImplTrait(_) => todo!(), 23 | Type::Infer(_) => todo!(), 24 | Type::Macro(_) => todo!(), 25 | Type::Never(_) => todo!(), 26 | Type::Paren(_) => todo!(), 27 | Type::Path(type_path) => { 28 | type_path.path.segments.iter().any(|segment| match &segment.arguments { 29 | syn::PathArguments::None => false, 30 | syn::PathArguments::AngleBracketed(generic_type_parameters) => { 31 | generic_type_parameters.args.iter().any(|generic| match generic { 32 | syn::GenericArgument::Lifetime(_) => true, 33 | syn::GenericArgument::Type(ty) => type_contains_lifetime(ty), 34 | syn::GenericArgument::Const(_) => false, 35 | syn::GenericArgument::AssocType(assoc_ty) => type_contains_lifetime(&assoc_ty.ty), 36 | syn::GenericArgument::AssocConst(_) => false, 37 | syn::GenericArgument::Constraint(_) => todo!(), 38 | _ => todo!(), 39 | }) 40 | }, 41 | syn::PathArguments::Parenthesized(_) => todo!(), 42 | }) || type_path 43 | .qself 44 | .as_ref() 45 | .map(|qself| type_contains_lifetime(&qself.ty)) 46 | .unwrap_or(false) 47 | }, 48 | Type::Ptr(_) => todo!(), 49 | Type::Reference(reference) => reference.lifetime.is_some(), 50 | Type::Slice(_) => todo!(), 51 | Type::TraitObject(_) => todo!(), 52 | Type::Tuple(_) => todo!(), 53 | Type::Verbatim(_) => todo!(), 54 | _ => todo!(), 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /tests/comment.rs: -------------------------------------------------------------------------------- 1 | use dash_rs::model::comment::{ 2 | level::{CommentUser, LevelComment}, 3 | profile::ProfileComment, 4 | }; 5 | use framework::load_test_units; 6 | use std::path::Path; 7 | 8 | mod framework; 9 | 10 | enum LevelCommentTester {} 11 | 12 | impl framework::Testable for LevelCommentTester { 13 | type Target<'a> = LevelComment<'a>; 14 | 15 | fn canonicalize(target: &mut Self::Target<'_>) { 16 | if let Some(ref mut cnt) = target.content { 17 | cnt.process().unwrap(); 18 | } 19 | if let Some(ref mut cnt) = target.special_color { 20 | cnt.process().unwrap(); 21 | } 22 | } 23 | } 24 | 25 | #[test] 26 | fn test_level_comment() { 27 | let units = load_test_units::( 28 | Path::new(env!("CARGO_MANIFEST_DIR")) 29 | .join("tests") 30 | .join("artifacts") 31 | .join("level_comment"), 32 | ); 33 | 34 | for (path, unit) in units { 35 | println!("Testing case {:?}", path); 36 | 37 | unit.test_consistency(); 38 | unit.test_load_save_roundtrip(); 39 | unit.test_save_load_roundtrip(); 40 | } 41 | } 42 | 43 | enum CommentUserTester {} 44 | 45 | impl framework::Testable for CommentUserTester { 46 | type Target<'a> = CommentUser<'a>; 47 | } 48 | 49 | #[test] 50 | fn test_level_comment_user() { 51 | let units = load_test_units::( 52 | Path::new(env!("CARGO_MANIFEST_DIR")) 53 | .join("tests") 54 | .join("artifacts") 55 | .join("comment_user"), 56 | ); 57 | 58 | for (path, unit) in units { 59 | println!("Testing case {:?}", path); 60 | 61 | unit.test_consistency(); 62 | unit.test_load_save_roundtrip(); 63 | unit.test_save_load_roundtrip(); 64 | } 65 | } 66 | 67 | enum ProfileCommentTester {} 68 | 69 | impl framework::Testable for ProfileCommentTester { 70 | type Target<'a> = ProfileComment<'a>; 71 | 72 | fn canonicalize(target: &mut Self::Target<'_>) { 73 | if let Some(ref mut cnt) = target.content { 74 | cnt.process().unwrap(); 75 | } 76 | } 77 | } 78 | 79 | #[test] 80 | fn test_profile_comment() { 81 | let units = load_test_units::( 82 | Path::new(env!("CARGO_MANIFEST_DIR")) 83 | .join("tests") 84 | .join("artifacts") 85 | .join("profile_comment"), 86 | ); 87 | 88 | for (path, unit) in units { 89 | println!("Testing case {:?}", path); 90 | 91 | unit.test_consistency(); 92 | unit.test_load_save_roundtrip(); 93 | unit.test_save_load_roundtrip(); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/model/mod.rs: -------------------------------------------------------------------------------- 1 | //! Module containing all data models Geometry Dash uses 2 | //! 3 | //! For each data model there are two versions: 4 | //! * A `Internal...` version which is the deserialization target. It can be constructed without any 5 | //! allocations at all and references the input it was deserialized from. Furthermore, these are 6 | //! nearly one-to-one mapping from response data into rust structures, meaning they also act as 7 | //! documentation of RobTop's data formats. 8 | //! * A version that's public API and which abstracts over robtop's data format in a sensible way. 9 | //! These still borrow their data from the deserialization source, but can optionally own their 10 | //! contents. All data that would require allocations to be completely processed (such as base64 11 | //! encoded level descriptions) is put in [`Thunk`](crate::Thunk)s and can be 12 | //! processed lazily on-demand. This allows us to deserialize the input and construct these 13 | //! representations with zero allocations. 14 | //! 15 | //! These versions can be converted to and from each other, simply by borrowing. 16 | 17 | use serde::{Deserialize, Serialize}; 18 | use std::fmt::{Display, Formatter}; 19 | 20 | pub mod comment; 21 | pub mod creator; 22 | pub mod level; 23 | pub mod song; 24 | pub mod user; 25 | 26 | /// Enum modelling the version of a Geometry Dash client 27 | #[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Hash, Serialize, Deserialize)] 28 | #[serde(into = "u8", from = "u8")] 29 | pub enum GameVersion { 30 | /// Variant representing an unknown version. This variant is only used for 31 | /// levels that were uploaded before the game started tracking the 32 | /// version. This variant's string 33 | /// representation is `"10"` 34 | Unknown, 35 | 36 | /// Variant representing a the version represented by the given minor/major 37 | /// values in the form `major.minor` 38 | Version { minor: u8, major: u8 }, 39 | } 40 | 41 | impl From for GameVersion { 42 | fn from(version: u8) -> Self { 43 | if version == 10 { 44 | GameVersion::Unknown 45 | } else { 46 | GameVersion::Version { 47 | major: (version / 10), 48 | minor: (version % 10), 49 | } 50 | } 51 | } 52 | } 53 | 54 | impl From for u8 { 55 | fn from(version: GameVersion) -> Self { 56 | match version { 57 | GameVersion::Unknown => 10, 58 | GameVersion::Version { minor, major } => major * 10 + minor, 59 | } 60 | } 61 | } 62 | 63 | impl Display for GameVersion { 64 | fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { 65 | match self { 66 | GameVersion::Unknown => write!(f, "Pre 1.6"), 67 | GameVersion::Version { minor: 7, major: 0 } => write!(f, "1.6"), 68 | GameVersion::Version { minor, major } => write!(f, "{}.{}", major, minor), 69 | } 70 | } 71 | } 72 | 73 | crate::into_conversion!(GameVersion, u8); 74 | -------------------------------------------------------------------------------- /src/model/level/object/internal.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | model::level::object::{ids, speed::Speed, LevelObject, ObjectData}, 3 | Dash, GJFormat, 4 | }; 5 | use serde::{Deserialize, Serialize}; 6 | 7 | #[derive(Debug, Deserialize, Serialize, Clone, Copy, Default)] 8 | pub struct InternalLevelObject { 9 | #[serde(rename = "1")] 10 | id: u16, 11 | 12 | #[serde(rename = "2")] 13 | x: f32, 14 | 15 | #[serde(rename = "3")] 16 | y: f32, 17 | 18 | #[serde(rename = "4", default)] 19 | flipped_x: bool, 20 | 21 | #[serde(rename = "5", default)] 22 | flipped_y: bool, 23 | 24 | #[serde(rename = "6", default)] 25 | rotation: f32, 26 | 27 | // ... other common fields 28 | 29 | // portal related fields 30 | #[serde(rename = "13", default)] 31 | checked: bool, 32 | } 33 | 34 | impl<'de> Dash<'de> for LevelObject { 35 | fn dash_deserialize>(deserializer: D) -> Result { 36 | let internal = InternalLevelObject::deserialize(deserializer)?; 37 | 38 | let metadata = match internal.id { 39 | ids::SLOW_PORTAL => ObjectData::SpeedPortal { 40 | checked: internal.checked, 41 | speed: Speed::Slow, 42 | }, 43 | ids::NORMAL_PORTAL => ObjectData::SpeedPortal { 44 | checked: internal.checked, 45 | speed: Speed::Normal, 46 | }, 47 | ids::FAST_PORTAL => ObjectData::SpeedPortal { 48 | checked: internal.checked, 49 | speed: Speed::Fast, 50 | }, 51 | ids::VERY_FAST_PORTAL => ObjectData::SpeedPortal { 52 | checked: internal.checked, 53 | speed: Speed::VeryFast, 54 | }, 55 | _ => ObjectData::Unknown, 56 | }; 57 | 58 | Ok(LevelObject { 59 | id: internal.id, 60 | x: internal.x, 61 | y: internal.y, 62 | flipped_x: internal.flipped_x, 63 | flipped_y: internal.flipped_y, 64 | rotation: internal.rotation, 65 | metadata, 66 | }) 67 | } 68 | 69 | fn dash_serialize(&self, serializer: S) -> Result { 70 | let mut internal = InternalLevelObject { 71 | id: self.id, 72 | x: self.x, 73 | y: self.y, 74 | flipped_x: self.flipped_x, 75 | flipped_y: self.flipped_y, 76 | rotation: self.rotation, 77 | ..InternalLevelObject::default() 78 | }; 79 | 80 | match self.metadata { 81 | ObjectData::None | ObjectData::Unknown => {}, 82 | ObjectData::SpeedPortal { checked, .. } => { 83 | internal.checked = checked; 84 | }, 85 | }; 86 | 87 | internal.serialize(serializer) 88 | } 89 | } 90 | 91 | impl<'de> GJFormat<'de> for LevelObject { 92 | const DELIMITER: &'static str = ","; 93 | const MAP_LIKE: bool = true; 94 | } 95 | -------------------------------------------------------------------------------- /src/model/user/searched.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | model::user::{Color, IconType}, 3 | GJFormat, 4 | }; 5 | use dash_rs_derive::Dash; 6 | use serde::{Deserialize, Serialize}; 7 | use std::borrow::Cow; 8 | use variant_partial_eq::VariantPartialEq; 9 | 10 | /// Struct modelling the partial user data returned by the `getGJUsers` endpoint. 11 | /// 12 | /// Note that no field `diamonds` exists here. This is consistent with Geometry Dash's behavior, as 13 | /// the GD server exhibit a bug where they do not provide diamonds information, although the client 14 | /// has the UI for it. 15 | #[derive(Debug, Clone, VariantPartialEq, Eq, Serialize, Deserialize, Dash)] 16 | pub struct SearchedUser<'a> { 17 | /// This [`SearchedUser`]'s name 18 | #[dash(index = 1)] 19 | pub name: Cow<'a, str>, 20 | 21 | /// The [`SearchedUser`]'s unique user ID 22 | #[dash(index = 2)] 23 | pub user_id: u64, 24 | 25 | /// This [`SearchedUser`]'s stars 26 | #[dash(index = 3)] 27 | pub stars: u32, 28 | 29 | /// This [`SearchedUser`]'s beaten demons 30 | #[dash(index = 4)] 31 | pub demons: u16, 32 | 33 | // TODO: figure this value out 34 | #[dash(index = 6)] 35 | pub index_6: Option>, 36 | 37 | /// This [`SearchedUser`]'s creator points 38 | #[dash(index = 8)] 39 | pub creator_points: u16, 40 | 41 | /// The index of the icon being displayed. 42 | #[dash(index = 9)] 43 | pub icon_index: u16, 44 | 45 | /// This [`SearchedUser`]'s primary color 46 | /// 47 | /// ## GD Internals: 48 | /// The game internally assigned each color some really 49 | /// obscure ID that doesn't correspond to the index in the game's color selector at all, which 50 | /// makes it pretty useless. dash-rs thus translates all in-game colors into their RGB 51 | /// representation. 52 | #[dash(index = 10)] 53 | pub primary_color: Color, 54 | 55 | /// This [`SearchedUser`]'s secondary color 56 | /// 57 | /// ## GD Internals: 58 | /// Same things as above apply 59 | #[dash(index = 11)] 60 | pub secondary_color: Color, 61 | 62 | /// The amount of secret coins this [`SearchedUser`] has collected. 63 | #[dash(index = 13)] 64 | pub secret_coins: u8, 65 | 66 | /// The type of icon being displayed 67 | #[dash(index = 14)] 68 | pub icon_type: IconType, 69 | 70 | /// Values indicating whether this [`SearchedUser`] has glow activated or not. 71 | #[dash(index = 15)] 72 | #[dash(serialize_with = "crate::util::true_to_two")] 73 | pub has_glow: bool, 74 | 75 | /// The [`SearchedUser`]'s unique account ID 76 | #[dash(index = 16)] 77 | pub account_id: u64, 78 | 79 | /// The amount of user coins this [`SearchedUser`] has collected. 80 | #[dash(index = 17)] 81 | pub user_coins: u16, 82 | 83 | /// The number of moons this [`SearchedUser`] has collected. Currently always zero due to a 84 | /// server bug (similar to how the game always displays 0 diamonds here) 85 | #[dash(index = 52)] 86 | pub moons: u32, 87 | } 88 | 89 | impl<'de> GJFormat<'de> for SearchedUser<'de> { 90 | const DELIMITER: &'static str = ":"; 91 | const MAP_LIKE: bool = true; 92 | } 93 | -------------------------------------------------------------------------------- /benches/level_processing_benchmark.rs: -------------------------------------------------------------------------------- 1 | use base64::{engine::general_purpose::URL_SAFE, Engine}; 2 | use criterion::{criterion_group, criterion_main, Criterion}; 3 | use dash_rs::{ 4 | model::level::{Level, LevelData}, 5 | GJFormat, Thunk, 6 | }; 7 | use flate2::read::GzDecoder; 8 | use std::{fs::read_to_string, io::Read}; 9 | 10 | pub fn ocular_miracle_benchmark(c: &mut Criterion) { 11 | let response = read_to_string("./benches/data/62152040_ocular_miracle_gjdownload_response").unwrap(); 12 | 13 | c.bench_function("parse ocular machine", |b| { 14 | b.iter(|| { 15 | let mut level: Level = Level::from_gj_str(&response).unwrap(); 16 | 17 | level.level_data.level_data.process().unwrap(); 18 | }) 19 | }); 20 | } 21 | 22 | pub fn spacial_rend_benchmark(c: &mut Criterion) { 23 | let response = read_to_string("./benches/data/40292513_special_rend_gjdownload_response").unwrap(); 24 | 25 | c.bench_function("parse spacial rend", |b| { 26 | b.iter(|| { 27 | let mut level: Level = Level::from_gj_str(&response).unwrap(); 28 | 29 | level.level_data.level_data.process().unwrap(); 30 | }) 31 | }); 32 | } 33 | 34 | pub fn decoding_ocular_miracle_benchmark(c: &mut Criterion) { 35 | let response = read_to_string("./benches/data/62152040_ocular_miracle_gjdownload_response").unwrap(); 36 | 37 | c.bench_function("decode ocular miracle", |b| { 38 | b.iter(|| { 39 | let level: Level = Level::from_gj_str(&response).unwrap(); 40 | match level.level_data.level_data { 41 | Thunk::Unprocessed(unprocessed) => { 42 | let decoded = URL_SAFE.decode(&*unprocessed).unwrap(); 43 | let mut decompressed = String::new(); 44 | let mut decoder = GzDecoder::new(&decoded[..]); 45 | 46 | decoder.read_to_string(&mut decompressed).unwrap(); 47 | }, 48 | Thunk::Processed(_) => unreachable!(), 49 | } 50 | }) 51 | }); 52 | } 53 | 54 | pub fn decoding_spacial_rend_benchmark(c: &mut Criterion) { 55 | let response = read_to_string("./benches/data/40292513_special_rend_gjdownload_response").unwrap(); 56 | 57 | c.bench_function("decode spacial rend", |b| { 58 | b.iter(|| { 59 | let level: Level = Level::from_gj_str(&response).unwrap(); 60 | match level.level_data.level_data { 61 | Thunk::Unprocessed(unprocessed) => { 62 | let decoded = URL_SAFE.decode(&*unprocessed).unwrap(); 63 | let mut decompressed = String::new(); 64 | let mut decoder = GzDecoder::new(&decoded[..]); 65 | 66 | decoder.read_to_string(&mut decompressed).unwrap(); 67 | }, 68 | Thunk::Processed(_) => unreachable!(), 69 | } 70 | }) 71 | }); 72 | } 73 | 74 | criterion_group!( 75 | benches, 76 | ocular_miracle_benchmark, 77 | spacial_rend_benchmark, 78 | decoding_spacial_rend_benchmark, 79 | decoding_ocular_miracle_benchmark 80 | ); 81 | criterion_main!(benches); 82 | -------------------------------------------------------------------------------- /examples/download_featured_levels.rs: -------------------------------------------------------------------------------- 1 | //! Retries the first page of featured levels, downloading the ones that can be copied in-game 2 | //! 3 | //! For each level that is free to copy, the server resposne is stored in `data/.lvl`. 4 | //! For each level that requires a password to copy, the server resposne is stored in 5 | //! `data/_.lvl`. 6 | //! 7 | //! WARNING: Robtop has set some aggressive ratelimits on the download level endpoint. Attempting 8 | //! to download too many levels (20 per minute from my testing) in too short a period of time will 9 | //! ratelimit you for one hour (HTTP 429 with retry-after=3600). There is also a further ratelimit 10 | //! that last a full day, hit by downloading approximately 100 levels "too fast" (I am not sure on 11 | //! the details here). Use this script at your own risk. 12 | 13 | use dash_rs::{ 14 | model::level::Password, 15 | request::level::{LevelRequest, LevelRequestType, LevelsRequest}, 16 | response::{parse_download_gj_level_response, parse_get_gj_levels_response}, 17 | }; 18 | use reqwest::{ 19 | header::{HeaderMap, CONTENT_TYPE}, 20 | Client, Response, 21 | }; 22 | use std::{path::Path, time::Duration}; 23 | 24 | #[tokio::main] 25 | async fn main() { 26 | let out_dir = Path::new("data"); 27 | 28 | if !out_dir.exists() { 29 | std::fs::create_dir(out_dir).unwrap(); 30 | } 31 | 32 | let http_client = Client::new(); 33 | 34 | // Note: There is a further ratelimit of 130 levels per ??, exceeding which will ban you for a day. 35 | for page in 1.. { 36 | let request = LevelsRequest::default().request_type(LevelRequestType::Featured).page(page); 37 | 38 | let response = make_request(&http_client, &request.to_url(), request.to_string()).await; 39 | let response_text = response.text().await.unwrap(); 40 | 41 | let levels = parse_get_gj_levels_response(&response_text).unwrap(); 42 | 43 | for level in levels { 44 | println!("Downloading level {} (ID: {})", level.name, level.level_id); 45 | 46 | let download_request = LevelRequest::new(level.level_id); 47 | 48 | let response = make_request(&http_client, &download_request.to_url(), download_request.to_string()).await; 49 | 50 | let response_text = response.text().await.unwrap(); 51 | 52 | let mut level = parse_download_gj_level_response(&response_text).unwrap(); 53 | 54 | match level.level_data.password.process() { 55 | Ok(Password::FreeCopy) => std::fs::write(format!("../data/{}.lvl", level.level_id), &response_text).unwrap(), 56 | Ok(Password::PasswordCopy(pw)) => std::fs::write(format!("../data/{}_{}.lvl", level.level_id, pw), &response_text).unwrap(), 57 | _ => println!("Sadly not copyable, skipping!"), 58 | } 59 | 60 | // RobTop has a rate limit of 20 levels per minute. Exceeding it will results in a `429 TOO MANY 61 | // REQUESTS` response with `retry-after: 3600`, effectively temp-banning you for an hour 62 | std::thread::sleep(Duration::from_secs(60 / 20 + 1)); 63 | } 64 | } 65 | } 66 | 67 | async fn make_request(client: &Client, endpoint: &str, data: String) -> Response { 68 | client.post(endpoint) 69 | .headers(HeaderMap::new()) // boomlings.com rejects any request with a User-Agent header set, so make sure reqwest doesn't "helpfully" add one 70 | .body(data) 71 | .header(CONTENT_TYPE, "application/x-www-form-urlencoded") 72 | .send() 73 | .await 74 | .unwrap() 75 | } 76 | -------------------------------------------------------------------------------- /src/request/user.rs: -------------------------------------------------------------------------------- 1 | //! Module containing request definitions for retrieving users 2 | 3 | use crate::{ 4 | model::creator::Creator, 5 | request::{endpoint_base_url, BaseRequest, GD_22}, 6 | }; 7 | use serde::Serialize; 8 | use std::borrow::Cow; 9 | use std::fmt::Display; 10 | 11 | pub const GET_USER_ENDPOINT: &str = "getGJUserInfo20.php"; 12 | pub const SEARCH_USER_ENDPOINT: &str = "getGJUsers20.php"; 13 | 14 | /// Struct modelled after a request to `getGJUserInfo20.php`. 15 | /// 16 | /// In the geometry Dash API, this endpoint is used to download player profiles from the servers by 17 | /// their account IDs 18 | #[derive(Debug, Default, Clone, Copy, Serialize, Hash)] 19 | pub struct UserRequest<'a> { 20 | /// The base request data 21 | pub base: BaseRequest<'a>, 22 | 23 | /// The **account ID** (_not_ user ID) of the users whose data to retrieve. 24 | /// 25 | /// ## GD Internals: 26 | /// This field is called `targetAccountID` in the boomlings API 27 | #[serde(rename = "targetAccountID")] 28 | pub user: u64, 29 | } 30 | 31 | impl UserRequest<'_> { 32 | pub const fn new(user_id: u64) -> UserRequest<'static> { 33 | UserRequest { 34 | base: GD_22, 35 | user: user_id, 36 | } 37 | } 38 | 39 | pub fn to_url(&self) -> String { 40 | format!("{}{}", endpoint_base_url(), GET_USER_ENDPOINT) 41 | } 42 | } 43 | 44 | impl From for UserRequest<'_> { 45 | fn from(user_id: u64) -> Self { 46 | UserRequest::new(user_id) 47 | } 48 | } 49 | 50 | impl From> for UserRequest<'_> { 51 | fn from(creator: Creator<'_>) -> Self { 52 | UserRequest::from(creator.user_id) 53 | } 54 | } 55 | 56 | impl Display for UserRequest<'_> { 57 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 58 | write!(f, "{}", super::to_string(self)) 59 | } 60 | } 61 | 62 | #[derive(Debug, Clone, Serialize, PartialEq, Eq)] 63 | pub struct UserSearchRequest<'a> { 64 | /// The base request data 65 | pub base: BaseRequest<'a>, 66 | 67 | /// Unknown, probably related to pagination 68 | /// 69 | /// ## GD Internals: 70 | /// This field is called `total` in the boomlings API 71 | pub total: u32, 72 | 73 | /// The page of users to retrieve 74 | /// 75 | /// Since the behavior of the search function was changed to return only the user whose name 76 | /// matches the search string exactly (previous behavior was a prefix search), it is not 77 | /// possible to retrieve more than 1 user via this endpoint anymore, rendering the pagination 78 | /// parameters useless. 79 | /// 80 | /// ## GD Internals: 81 | /// This field is called `page` in the boomlings API 82 | pub page: u32, 83 | 84 | /// The name of the user being searched for 85 | /// 86 | /// ## GD Internals: 87 | /// This field is called `str` in the boomlings API 88 | #[serde(rename = "str")] 89 | pub search_string: Cow<'a, str>, 90 | } 91 | 92 | impl<'a> UserSearchRequest<'a> { 93 | pub fn new(search_string: impl Into>) -> Self { 94 | UserSearchRequest { 95 | base: GD_22, 96 | total: 0, 97 | page: 0, 98 | search_string: search_string.into(), 99 | } 100 | } 101 | 102 | pub fn to_url(&self) -> String { 103 | format!("{}{}", endpoint_base_url(), SEARCH_USER_ENDPOINT) 104 | } 105 | } 106 | 107 | impl<'a> From<&'a str> for UserSearchRequest<'a> { 108 | fn from(search_string: &'a str) -> Self { 109 | UserSearchRequest::new(search_string) 110 | } 111 | } 112 | 113 | impl<'a: 'b, 'b> From<&'b Creator<'a>> for UserSearchRequest<'b> { 114 | fn from(creator: &'b Creator<'a>) -> Self { 115 | UserSearchRequest::from(&*creator.name) 116 | } 117 | } 118 | 119 | impl Display for UserSearchRequest<'_> { 120 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 121 | write!(f, "{}", super::to_string(self)) 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/util.rs: -------------------------------------------------------------------------------- 1 | //! Module containing various utility functions related to processing Geometry Dash data 2 | 3 | use serde::Serializer; 4 | 5 | /// Performs RobTop's XOR en-/decoding routine on `encoded` using `key` 6 | /// 7 | /// Note that although both `encrypted` and `key` are `str`s, the decryption 8 | /// is done directly on the bytes, and the result of each byte-wise XOR 9 | /// operation is casted to `char`, meaning this function only works for 10 | /// ASCII strings. 11 | #[inline] 12 | pub fn cyclic_xor(encoded: &mut [u8], key: &T) 13 | where 14 | T: AsRef<[u8]> + ?Sized, // ?Sized needed here because we want for example to accept &[u8], where T would be [u8] 15 | { 16 | // for_each usually specializes better for iterators 17 | // Also changed into using ^= for simplicity 18 | encoded.iter_mut().zip(key.as_ref().iter().cycle()).for_each(|(d, k)| *d ^= k); 19 | } 20 | 21 | pub fn option_variant_eq(a: &Option, b: &Option) -> bool 22 | where 23 | A: PartialEq, 24 | { 25 | match (a, b) { 26 | (Some(a), Some(b)) => a == b, 27 | (None, None) => true, 28 | _ => false, 29 | } 30 | } 31 | 32 | pub(crate) mod default_to_none { 33 | use serde::{Deserialize, Deserializer, Serialize, Serializer}; 34 | 35 | pub fn serialize(to_serialize: &Option, serializer: S) -> Result 36 | where 37 | S: Serializer, 38 | T: Default + Serialize, 39 | { 40 | match to_serialize { 41 | None => T::default().serialize(serializer), 42 | Some(ref t) => t.serialize(serializer), 43 | } 44 | } 45 | 46 | pub fn deserialize<'de, D, T>(deserializer: D) -> Result, D::Error> 47 | where 48 | D: Deserializer<'de>, 49 | T: Default + Deserialize<'de> + PartialEq, 50 | { 51 | let deserialized = T::deserialize(deserializer)?; 52 | 53 | if deserialized == T::default() { 54 | Ok(None) 55 | } else { 56 | Ok(Some(deserialized)) 57 | } 58 | } 59 | } 60 | 61 | pub(crate) fn false_to_empty_string(b: &bool, serializer: S) -> Result { 62 | match *b { 63 | true => serializer.serialize_str("1"), 64 | false => serializer.serialize_str(""), 65 | } 66 | } 67 | 68 | pub(crate) fn true_to_two(b: &bool, serializer: S) -> Result { 69 | match *b { 70 | true => serializer.serialize_str("2"), 71 | false => serializer.serialize_str("0"), 72 | } 73 | } 74 | 75 | pub(crate) fn true_to_ten(b: &bool, serializer: S) -> Result { 76 | match *b { 77 | true => serializer.serialize_str("10"), 78 | false => serializer.serialize_str("0"), 79 | } 80 | } 81 | 82 | #[macro_export] 83 | macro_rules! into_conversion { 84 | ($for:ty, $proxy_type:ty) => { 85 | impl $crate::serde::InternalProxy for $for { 86 | type DeserializeProxy = $proxy_type; 87 | type SerializeProxy<'a> 88 | = $proxy_type 89 | where 90 | Self: 'a; 91 | 92 | fn to_serialize_proxy(&self) -> $proxy_type { 93 | (*self).into() 94 | } 95 | 96 | fn from_deserialize_proxy(from: $proxy_type) -> $for { 97 | <$for>::from(from) 98 | } 99 | } 100 | }; 101 | } 102 | 103 | #[macro_export] 104 | macro_rules! dash_rs_newtype { 105 | ($name:ident) => { 106 | #[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)] 107 | #[serde(transparent)] 108 | pub struct $name<'a>(pub Cow<'a, str>); 109 | 110 | impl<'a> $crate::serde::InternalProxy for $name<'a> { 111 | type DeserializeProxy = &'a str; 112 | type SerializeProxy<'b> 113 | = &'b str 114 | where 115 | Self: 'b; 116 | 117 | fn to_serialize_proxy(&self) -> &str { 118 | use std::borrow::Borrow; 119 | 120 | self.0.borrow() 121 | } 122 | 123 | fn from_deserialize_proxy(from: &'a str) -> $name<'a> { 124 | $name(Cow::Borrowed(from)) 125 | } 126 | } 127 | }; 128 | } 129 | -------------------------------------------------------------------------------- /tests/framework.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] // not all test modules use all functions 2 | 3 | use std::{ 4 | collections::BTreeMap, 5 | fmt::Debug, 6 | marker::PhantomData, 7 | path::{Path, PathBuf}, 8 | }; 9 | 10 | use dash_rs::{GJFormat, IndexedDeserializer}; 11 | use pretty_assertions::assert_eq; 12 | use serde::Deserialize; 13 | 14 | pub fn load_test_units(unit_dir: impl AsRef) -> BTreeMap> { 15 | let mut map = BTreeMap::new(); 16 | 17 | for dir_entry in std::fs::read_dir(unit_dir).unwrap() { 18 | let dir_entry = dir_entry.unwrap(); 19 | 20 | assert!(dir_entry.metadata().unwrap().is_dir()); 21 | 22 | map.insert(dir_entry.path(), TestUnit::new(dir_entry.path())); 23 | } 24 | 25 | map 26 | } 27 | 28 | pub trait Testable { 29 | type Target<'a>: GJFormat<'a> + Deserialize<'a> + Debug + for<'b> PartialEq>; 30 | 31 | /// Canonicalizes this test target object before comparisons 32 | /// 33 | /// For example, this is where all Thunks should be evaluated 34 | fn canonicalize(_target: &mut Self::Target<'_>) {} 35 | } 36 | 37 | pub struct TestUnit { 38 | raw: PathBuf, 39 | processed: PathBuf, 40 | ghost: PhantomData, 41 | } 42 | 43 | impl TestUnit { 44 | fn new(unit_container: impl AsRef) -> Self { 45 | let raw = unit_container.as_ref().join("raw"); 46 | let processed = unit_container.as_ref().join("processed"); 47 | 48 | assert!(raw.exists()); 49 | assert!(processed.exists()); 50 | 51 | TestUnit { 52 | raw, 53 | processed, 54 | ghost: PhantomData, 55 | } 56 | } 57 | 58 | fn load_raw_data(&self) -> String { 59 | let raw_data = std::fs::read(&self.raw).unwrap(); 60 | String::from_utf8(raw_data).unwrap() 61 | } 62 | } 63 | 64 | impl TestUnit 65 | where 66 | D: Testable, 67 | { 68 | pub fn test_consistency(&self) { 69 | let processed_json = std::fs::read(&self.processed).unwrap(); 70 | let processed_json = std::str::from_utf8(&processed_json).unwrap(); 71 | let processed_artifact: D::Target<'_> = serde_json::from_str(processed_json).unwrap(); 72 | 73 | let raw = self.load_raw_data(); 74 | let mut processed = D::Target::from_gj_str(&raw).unwrap(); 75 | D::canonicalize(&mut processed); 76 | 77 | assert_eq!(processed_artifact, processed); 78 | } 79 | 80 | pub fn test_load_save_roundtrip(&self) { 81 | let raw = self.load_raw_data(); 82 | let mut loaded = D::Target::from_gj_str(&raw).unwrap(); 83 | D::canonicalize(&mut loaded); 84 | 85 | let mut buffer = Vec::new(); 86 | loaded.write_gj(&mut buffer).unwrap(); 87 | let saved = std::str::from_utf8(&buffer).unwrap(); 88 | 89 | assert_indexed_strings_equal::>(&raw, saved) 90 | } 91 | 92 | pub fn test_save_load_roundtrip(&self) { 93 | let processed_json = std::fs::read(&self.processed).unwrap(); 94 | let processed_json = std::str::from_utf8(&processed_json).unwrap(); 95 | let processed: D::Target<'_> = serde_json::from_str(processed_json).unwrap(); 96 | 97 | let mut buffer = Vec::new(); 98 | processed.write_gj(&mut buffer).unwrap(); 99 | let saved = std::str::from_utf8(&buffer).unwrap(); 100 | 101 | let mut restored = D::Target::from_gj_str(saved).unwrap(); 102 | D::canonicalize(&mut restored); 103 | 104 | assert_eq!(processed, restored); 105 | } 106 | } 107 | 108 | fn assert_indexed_strings_equal<'a, D: GJFormat<'a>>(a: &str, b: &str) { 109 | let mut deserializer_a = IndexedDeserializer::new(a, D::DELIMITER, D::MAP_LIKE); 110 | let mut deserializer_b = IndexedDeserializer::new(b, D::DELIMITER, D::MAP_LIKE); 111 | 112 | if D::MAP_LIKE { 113 | let map_a = BTreeMap::<&str, &str>::deserialize(&mut deserializer_a).unwrap(); 114 | let map_b = BTreeMap::<&str, &str>::deserialize(&mut deserializer_b).unwrap(); 115 | 116 | // BTreeMap + pretty_assertions will make sure that this is easily interpretable 117 | assert_eq!(map_a, map_b); 118 | } else { 119 | let vec_a = Vec::<&str>::deserialize(&mut deserializer_a).unwrap(); 120 | let vec_b = Vec::<&str>::deserialize(&mut deserializer_b).unwrap(); 121 | 122 | assert_eq!(vec_a, vec_b); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /dash-rs-derive/src/struct_gen.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::{Ident, Span}; 2 | use quote::{format_ident, quote, ToTokens}; 3 | use syn::{Generics, Lifetime, LifetimeParam}; 4 | 5 | use crate::field::FieldMapping; 6 | 7 | pub struct InternalStruct { 8 | /// Name of the API-version of this struct 9 | pub name: Ident, 10 | pub fields: Vec, 11 | pub generics: Generics, 12 | /// The unique lifetime of the struct for which we are deriving `Dash`, if it exists. 13 | pub lifetime: Option, 14 | } 15 | 16 | impl InternalStruct { 17 | fn serialize_struct_name(&self) -> Ident { 18 | format_ident!("Internal{}Ser", self.name) 19 | } 20 | 21 | fn deserialize_struct_name(&self) -> Ident { 22 | format_ident!("Internal{}De", self.name) 23 | } 24 | 25 | fn ser_struct(&self) -> proc_macro2::TokenStream { 26 | let name = self.serialize_struct_name(); 27 | let static_lifetime = Lifetime::new("'static", Span::call_site()); 28 | let lifetime = match self.lifetime { 29 | Some(ref lifetime) => &lifetime.lifetime, 30 | None => &static_lifetime, 31 | }; 32 | let fields = self.fields.iter().map(|ifield| ifield.ser_field_tokens(lifetime)); 33 | let generics = &self.generics; 34 | 35 | quote! { 36 | #[derive(Serialize)] 37 | struct #name#generics { 38 | #(#fields)* 39 | } 40 | } 41 | } 42 | 43 | fn de_struct(&self) -> proc_macro2::TokenStream { 44 | let name = self.deserialize_struct_name(); 45 | let fields = self.fields.iter().map(|ifield| ifield.de_field_tokens()); 46 | let generics = &self.generics; 47 | 48 | quote! { 49 | #[derive(Deserialize)] 50 | struct #name#generics { 51 | #(#fields)* 52 | } 53 | } 54 | } 55 | 56 | fn serialize_implementation(&self) -> proc_macro2::TokenStream { 57 | // assume a `Serializer` is in scope, named serializer 58 | let serialize_struct = self.serialize_struct_name(); 59 | let initializers = self.fields.iter().map(|ifield| ifield.serialize()); 60 | 61 | quote! { 62 | let internal = #serialize_struct { 63 | #(#initializers)* 64 | }; 65 | internal.serialize(serializer) 66 | } 67 | } 68 | 69 | fn deserialize_implementation(&self) -> proc_macro2::TokenStream { 70 | // assume a `Deserializer` is in scope, named deserializer 71 | let deserialize_struct = self.deserialize_struct_name(); 72 | let api_struct = &self.name; 73 | let initializers = self.fields.iter().map(|ifield| ifield.deserialize()); 74 | 75 | quote! { 76 | let internal = #deserialize_struct::deserialize(deserializer)?; 77 | 78 | Ok(#api_struct { 79 | #(#initializers)* 80 | }) 81 | } 82 | } 83 | } 84 | 85 | impl ToTokens for InternalStruct { 86 | fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { 87 | let ser_struct = self.ser_struct(); 88 | let de_struct = self.de_struct(); 89 | let name = &self.name; 90 | 91 | let artificial_lifetime = Lifetime::new("'__dash", Span::call_site()); 92 | let existing_params = &self.generics.params; 93 | let (generic_arg_list, lifetime) = match self.lifetime { 94 | Some(ref lifetime) => (quote! {<#existing_params>}, &lifetime.lifetime), 95 | None => (quote! {<#artificial_lifetime,#existing_params>}, &artificial_lifetime), 96 | }; 97 | let where_clause = &self.generics.where_clause; 98 | 99 | let deserialize_impl = self.deserialize_implementation(); 100 | let serialize_impl = self.serialize_implementation(); 101 | 102 | tokens.extend(quote! { 103 | const _: () = { 104 | use serde::{Serializer, Deserializer}; 105 | use crate::serde::Dash; 106 | use crate::serde::InternalProxy; 107 | 108 | #ser_struct 109 | #de_struct 110 | 111 | impl#generic_arg_list Dash<#lifetime> for #name<#existing_params> 112 | #where_clause 113 | { 114 | fn dash_deserialize>(deserializer: D) -> Result { 115 | #deserialize_impl 116 | } 117 | 118 | fn dash_serialize(&self, serializer: S) -> Result { 119 | #serialize_impl 120 | } 121 | } 122 | }; 123 | }) 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/request/mod.rs: -------------------------------------------------------------------------------- 1 | //! Module containing all structs modelling requests to the Boomlings APIs. 2 | //! 3 | //! These directly implement (de)serialization into RobTop's data format, unlike models where 4 | //! RobTop's eccentricities are hidden. This is since directly re-using these structs outside of 5 | //! making/proxying requests for the Boomlings servers seems rather useless to me, as they already 6 | //! contain a lot of Boomlings-specific fields. 7 | //! This can also be edited for a specific GDPS, e.g 1.9 GDPS. (hi absowute :3) 8 | 9 | use std::sync::OnceLock; 10 | 11 | use crate::{model::GameVersion, serde::RequestSerializer}; 12 | use serde::{Deserialize, Serialize}; 13 | 14 | macro_rules! const_setter { 15 | ($name: ident, $field: ident, $t: ty) => { 16 | pub const fn $name(mut self, $field: $t) -> Self { 17 | self.$field = $field; 18 | self 19 | } 20 | }; 21 | 22 | ($name: ident, $t: ty) => { 23 | pub const fn $name(mut self, arg0: $t) -> Self { 24 | self.$name = arg0; 25 | self 26 | } 27 | }; 28 | 29 | ($(#[$attr:meta])* $name: ident: $t: ty) => { 30 | $(#[$attr])* 31 | pub const fn $name(mut self, $name: $t) -> Self { 32 | self.$name = $name; 33 | self 34 | } 35 | }; 36 | 37 | ($(#[$attr:meta])* $field:ident[$name: ident]: $t: ty) => { 38 | $(#[$attr])* 39 | pub const fn $name(mut self, $field: $t) -> Self { 40 | self.$field = $field; 41 | self 42 | } 43 | } 44 | } 45 | 46 | pub mod comment; 47 | pub mod level; 48 | pub mod user; 49 | 50 | pub static GD_SERVER_ENDPOINT_BASE_URL: OnceLock = OnceLock::new(); 51 | 52 | pub fn endpoint_base_url() -> &'static str { 53 | GD_SERVER_ENDPOINT_BASE_URL.get_or_init(|| BOOMLINGS_ENDPOINTS_BASE.to_string()) 54 | } 55 | 56 | pub const BOOMLINGS_ENDPOINTS_BASE: &str = "https://www.boomlings.com/database/"; 57 | 58 | /// A `BaseRequest` instance that has all its fields set to the 59 | /// same values a Geometry Dash 2.1 client would use 60 | pub const GD_21: BaseRequest = BaseRequest::new( 61 | GameVersion::Version { major: 2, minor: 1 }, 62 | GameVersion::Version { major: 3, minor: 3 }, 63 | "Wmfd2893gb7", 64 | ); 65 | 66 | /// A `BaseRequest` instance that has all its fields set to the 67 | /// same values a Geometry Dash 2.2 client would use 68 | pub const GD_22: BaseRequest = BaseRequest::new( 69 | GameVersion::Version { major: 2, minor: 2 }, 70 | GameVersion::Version { major: 3, minor: 8 }, 71 | "Wmfd2893gb7", 72 | ); 73 | 74 | /// Base data included in every request made 75 | /// 76 | /// The fields in this struct are only relevant when making a request to the 77 | /// `Boomlings` servers. When using GDCF with a custom Geometry Dash API, they 78 | /// can safely be ignored. 79 | #[derive(Debug, Clone, Hash, Copy, PartialEq, Eq, Serialize, Deserialize)] 80 | pub struct BaseRequest<'a> { 81 | /// The version of the game client we're pretending to be 82 | /// 83 | /// ## GD Internals: 84 | /// This field is called `gameVersion` in the Boomlings API and needs to 85 | /// be converted to a string response. 86 | /// The value of this field doesn't matter, and the request will succeed 87 | /// regardless of what it's been set to. 88 | #[serde(rename = "gameVersion")] 89 | pub game_version: GameVersion, 90 | 91 | /// Internal version of the game client we're pretending to be 92 | /// 93 | /// ## GD Internals: 94 | /// This field is called `binaryVersion` in the Boomlings API and needs to 95 | /// be converted to a string. 96 | /// 97 | /// The value of this field doesn't matter, and the request will succeed 98 | /// regardless of what it's been set to. 99 | #[serde(rename = "binaryVersion")] 100 | pub binary_version: GameVersion, 101 | 102 | /// The current secret string the server uses to identify valid clients. 103 | /// 104 | /// ## GD Internals: 105 | /// Setting this field to an incorrect value will cause the request to fail. 106 | pub secret: &'a str, 107 | } 108 | 109 | impl BaseRequest<'_> { 110 | /// This constructs a new BaseRequest. It also uses the given values. :3 111 | pub const fn new(game_version: GameVersion, binary_version: GameVersion, secret: &'static str) -> BaseRequest<'static> { 112 | BaseRequest { 113 | game_version, 114 | binary_version, 115 | secret, 116 | } 117 | } 118 | } 119 | 120 | impl Default for BaseRequest<'static> { 121 | fn default() -> Self { 122 | GD_22 123 | } 124 | } 125 | 126 | pub(crate) fn to_string(request: S) -> String { 127 | let mut output = Vec::new(); 128 | let mut serializer = RequestSerializer::new(&mut output); 129 | 130 | request.serialize(&mut serializer).unwrap(); 131 | 132 | String::from_utf8(output).unwrap() 133 | } 134 | -------------------------------------------------------------------------------- /src/serde/mod.rs: -------------------------------------------------------------------------------- 1 | mod de; 2 | mod ser; 3 | mod thunk; 4 | 5 | pub use de::{error::Error as DeError, indexed::IndexedDeserializer}; 6 | pub use ser::{error::Error as SerError, indexed::IndexedSerializer, request::RequestSerializer}; 7 | use serde::{Deserializer, Serializer}; 8 | pub use thunk::{Base64Decoder, PercentDecoder, ProcessError, Thunk, ThunkProcessor}; 9 | 10 | use std::{borrow::Cow, io::Write}; 11 | 12 | /// Trait for objects that can be (de)serialized from some Geometry Dash data format (e.g. an 13 | /// indexed description). 14 | /// 15 | /// Internally, all types supporting (de)serialization using a Geometry Dash data format do so on 16 | /// custom, private structs. This is mainly so that details from robtop's data 17 | /// formats don't leak into dash-rs' data representation (as this allows the types in the public API 18 | /// to implemente/derive Serialize/Deserialize in a way differing from the serialization required 19 | /// for Robtop's data formats). Then, this internal representation is converted into the types 20 | /// exposed by `dash-rs`' API using either infallible conversions, or [`Thunk`]ing 21 | /// 22 | /// The lifetime `'de` is the same lifetime that [`serde`](serde.rs) uses on its 23 | /// [`Deserialize`](serde::Deserialize) trait, see also [the serde documentation]. 24 | /// 25 | /// [1]: https://serde.rs/lifetimes.html 26 | pub trait Dash<'de>: Sized { 27 | fn dash_deserialize>(deserializer: D) -> Result; 28 | fn dash_serialize(&self, serializer: S) -> Result; 29 | } 30 | 31 | pub trait GJFormat<'de>: Dash<'de> { 32 | const DELIMITER: &'static str; 33 | const MAP_LIKE: bool; 34 | 35 | fn from_gj_str(input: &'de str) -> Result> { 36 | let mut indexed_deserializer = IndexedDeserializer::new(input, Self::DELIMITER, Self::MAP_LIKE); 37 | 38 | Self::dash_deserialize(&mut indexed_deserializer) 39 | } 40 | 41 | fn write_gj(&self, writer: W) -> Result<(), ser::error::Error> { 42 | let mut indexed_serializer = IndexedSerializer::new(Self::DELIMITER, writer, Self::MAP_LIKE); 43 | 44 | self.dash_serialize(&mut indexed_serializer) 45 | } 46 | } 47 | 48 | /// Trait describing an intermediate step between the raw Geomtry Dash data format, and the APIs 49 | /// exposed by dash-rs 50 | /// 51 | /// Each field in a dash-rs struct that is mapped 1:1 to some index in the Geometry Dash data format 52 | /// is first deserialized to an intermediate proxy type (such as &'de str), before being converted 53 | /// into the type it has in the public API (such as Thunk<'a, PercentDecoder>). This trait handles 54 | /// this conversion and its reciprocal. 55 | pub trait InternalProxy { 56 | /// The type to which an index get deserialized in the internal representation 57 | type DeserializeProxy; 58 | /// The type 59 | type SerializeProxy<'a> 60 | where 61 | Self: 'a; 62 | 63 | fn to_serialize_proxy(&self) -> Self::SerializeProxy<'_>; 64 | fn from_deserialize_proxy(from: Self::DeserializeProxy) -> Self; 65 | } 66 | 67 | macro_rules! identity_conversion { 68 | ($($t: ty),*) => { 69 | $( 70 | impl $crate::serde::InternalProxy for $t { 71 | type DeserializeProxy = $t; 72 | type SerializeProxy<'a> = $t; 73 | 74 | fn to_serialize_proxy(&self) -> Self::SerializeProxy<'_> { 75 | *self 76 | } 77 | 78 | fn from_deserialize_proxy(from: Self::DeserializeProxy) -> Self { 79 | from 80 | } 81 | } 82 | )* 83 | }; 84 | } 85 | 86 | identity_conversion!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64, char, bool); 87 | 88 | impl<'b, T: ToOwned + ?Sized + 'static> InternalProxy for Cow<'b, T> { 89 | type DeserializeProxy = &'b T; 90 | type SerializeProxy<'a> 91 | = &'a T 92 | where 93 | Self: 'a; 94 | 95 | fn to_serialize_proxy(&self) -> Self::SerializeProxy<'_> { 96 | self.as_ref() 97 | } 98 | 99 | fn from_deserialize_proxy(from: Self::DeserializeProxy) -> Self { 100 | Cow::Borrowed(from) 101 | } 102 | } 103 | 104 | impl<'b, T: ThunkProcessor> InternalProxy for Thunk<'b, T> { 105 | type DeserializeProxy = &'b str; 106 | type SerializeProxy<'a> 107 | = Cow<'a, str> 108 | where 109 | Self: 'a; 110 | 111 | fn to_serialize_proxy(&self) -> Self::SerializeProxy<'_> { 112 | self.as_unprocessed().unwrap() 113 | } 114 | 115 | fn from_deserialize_proxy(from: Self::DeserializeProxy) -> Self { 116 | Thunk::Unprocessed(Cow::Borrowed(from)) 117 | } 118 | } 119 | 120 | impl InternalProxy for Option { 121 | type DeserializeProxy = Option; 122 | type SerializeProxy<'a> 123 | = Option> 124 | where 125 | Self: 'a; 126 | 127 | fn to_serialize_proxy(&self) -> Self::SerializeProxy<'_> { 128 | self.as_ref().map(|t| t.to_serialize_proxy()) 129 | } 130 | 131 | fn from_deserialize_proxy(from: Self::DeserializeProxy) -> Self { 132 | from.map(|f| T::from_deserialize_proxy(f)) 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /tests/response.rs: -------------------------------------------------------------------------------- 1 | // This string has been manually edited to ensure that the cases of duplicate and missing 2 | // songs/creators are also covered by the unit test 3 | const GET_GJ_LEVELS_RESPONSE: &str = "1:62953227:2:Noice:5:1:6:14098234:8:10:9:30:10:329795:12:0:13:21:14:16024:17::43:0:25::18:5:19:24981:42:1:45:30320:3:Tm9pY2UgbGV2ZWwsIGhvcGUgeW91IGxpa2UgaXQ=:15:3:30:0:31:0:37:0:38:0:39:5:46:1:47:2:35:778510|1:63362544:2:Happy Day Gd:5:4:6:14098234:8:10:9:30:10:16162:12:0:13:21:14:2772:17::43:0:25::18:4:19:24979:42:0:45:38476:3:NyB5ZWFycyBvZiBqb3lzIGFuZCBzb3Jyb3dzLCB0aGUgYmVzdCBnYW1lIEkga25ldyBhbmQgSSB3aWxsIHN0YXksIGNvbW1lbnQgaG93IG1hbnkgeWVhcnMgeW91IGhhdmUgYmVlbiBhbmQgd2hhdCBtb3RpdmF0ZWQgeW91IHRvIHN0YXk=:15:3:30:0:31:0:37:3:38:1:39:4:46:1:47:2:35:936243|1:63336521:2:Sound Visualization:5:1:6:4123296:8:10:9:50:10:47521:12:0:13:21:14:2951:17::43:6:25::18:8:19:24979:42:1:45:26229:3:dmlzdWFsIGVmZmVjdHM=:15:3:30:0:31:0:37:3:38:1:39:8:46:1:47:2:35:778510|1:63335504:2:Mind Control:5:2:6:10130943:8:10:9:30:10:51434:12:0:13:21:14:4120:17::43:0:25::18:5:19:24979:42:1:45:49951:3:SXQncyBkb25lIHlhYWF5:15:3:30:0:31:0:37:2:38:1:39:5:46:1:47:2:35:763439|1:63333766:2:An Ode to Time:5:8:6:7226087:8:10:9:10:10:10795:12:0:13:21:14:716:17:1:43:3:25::18:10:19:24979:42:0:45:65535:3:QW5kIGl0IGFsbCBjb21lcyBjcmFzaGluZyBkb3duLiAwOC8xMC8yMC4=:15:4:30:0:31:0:37:3:38:1:39:10:46:1:47:2:35:896364|1:63292359:2:AnnoZone:5:2:6:5897998:8:10:9:50:10:7890:12:0:13:21:14:636:17::43:6:25::18:8:19:24979:42:1:45:51592:3:VGhlIEFubm8gU2VyaWVzIGhhcyByZXR1cm5lZCBhZnRlciAyIHllYXJzIHdpdGggYSAzcmQgbGV2ZWwhIERlZGljYXRlZCB0byB0aGUgQnJveXMuIE1vcmUgQW5ubyBTZXJpZXMgbGV2ZWxzIHRvIGNvbWUuLi4_:15:3:30:0:31:0:37:0:38:1:39:7:46:1:47:2:35:638150|1:63260507:2:Trouble:5:3:6:14221993:8:10:9:50:10:4512:12:0:13:21:14:323:17::43:6:25::18:8:19:24979:42:1:45:58854:3:SSBzaG91bGQgb2Yga25vd24geW91IHdlcmUgdHJvdWJsZS4uLi4uLiAgICAgICAgICAgICBoaQ==:15:3:30:0:31:0:37:1:38:1:39:8:46:1:47:2:35:939885|1:63254272:2:AdrenaLines:5:2:6:116033399:8:10:9:40:10:34848:12:0:13:21:14:2419:17::43:5:25::18:6:19:24979:42:0:45:32956:3:ZGVjbyBsdmw_ISBlbmpveSB1d3U=:15:3:30:0:31:0:37:2:38:1:39:6:46:1:47:2:35:887253|1:63232525:2:Metropolis:5:3:6:1647052:8:10:9:10:10:99385:12:0:13:21:14:5506:17:1:43:3:25::18:10:19:24979:42:1:45:65535:3:V2VsY29tZS4uLg==:15:3:30:0:31:0:37:1:38:1:39:10:46:1:47:2:35:674039|1:61865319:2:Utopia:5:4:6:5570844:8:10:9:50:10:148912:12:0:13:21:14:6961:17::43:6:25::18:8:19:24979:42:0:45:13533:3:dXBkYXRlZCwgc2Vjb25kIHBhcnQgZG9lc250IGxvb2sgc28gdWdseSBub3c=:15:3:30:0:31:0:37:3:38:1:39:8:46:1:47:2:35:761926#1647052:DesTicY:95952|4123296:Cdpre:1478680|5570844:Axils:1341135|7226087:Pauze:1705254|8908442:Nikce:2517174|10130943:FaekI:1727914|14098234:AleXins:4322668|14221993:IFuse:5633975|116033399:KumoriGD:11439344#1~|~638150~|~2~|~-ThunderZone v2-~|~3~|~30~|~4~|~Waterflame~|~5~|~8.78~|~6~|~~|~10~|~http%3A%2F%2Faudio.ngfiles.com%2F638000%2F638150_-ThunderZone-v2-.mp3~|~7~|~UCVuv5iaVR55QXIc_BHQLakA~|~8~|~1~:~1~|~674039~|~2~|~Crystal Tokyo~|~3~|~746~|~4~|~Fantomenk~|~5~|~10.54~|~6~|~~|~10~|~http%3A%2F%2Faudio.ngfiles.com%2F674000%2F674039_Crystal-Tokyo.mp3~|~7~|~UCMSBjXolfz29kxnXpBa7LJA~|~8~|~1~:~1~|~761926~|~2~|~mistmurk + 3MBER - Utopia~|~3~|~49123~|~4~|~mistmurk~|~5~|~7.76~|~6~|~~|~10~|~http%3A%2F%2Faudio.ngfiles.com%2F761000%2F761926_mistmurk--3mber---Utopia.mp3~|~7~|~~|~8~|~1~:~1~|~763439~|~2~|~ColBreakz - Mind Control~|~3~|~47795~|~4~|~ColBreakz~|~5~|~10~|~6~|~~|~10~|~http%3A%2F%2Faudio.ngfiles.com%2F763000%2F763439_ColBreakz---Mind-Control.mp3~|~7~|~~|~8~|~1~:~1~|~778510~|~2~|~Hazmat~|~3~|~23384~|~4~|~CricketSaysChill~|~5~|~1.8~|~6~|~~|~10~|~https%3A%2F%2Faudio.ngfiles.com%2F778000%2F778510_Hazmat.mp3%3Ff1512785304~|~7~|~~|~8~|~1~:~1~|~852209~|~2~|~Fried Sushi~|~3~|~28916~|~4~|~lchavasse~|~5~|~5.88~|~6~|~~|~10~|~https%3A%2F%2Faudio.ngfiles.com%2F852000%2F852209_Fried-Sushi.mp3%3Ff1552100587~|~7~|~~|~8~|~1~:~1~|~887253~|~2~|~Adrenaline~|~3~|~51089~|~4~|~PsoGnar~|~5~|~10.35~|~6~|~~|~10~|~https%3A%2F%2Faudio.ngfiles.com%2F887000%2F887253_Adrenaline.mp3%3Ff1570984144~|~7~|~~|~8~|~1~:~1~|~896364~|~2~|~Beethoven - Moonlight Sonata 3rd Movement (meganeko remix)~|~3~|~48917~|~4~|~meganeko~|~5~|~9.45~|~6~|~~|~10~|~https%3A%2F%2Faudio.ngfiles.com%2F896000%2F896364_Beethoven---Moonlight-Sona.mp3%3Ff1575491260~|~7~|~UCP3M2myndqXuAEKKnqm_7SQ~|~8~|~1~:~1~|~936243~|~2~|~Phaera - Ignition~|~3~|~50872~|~4~|~TheArcadium~|~5~|~5.76~|~6~|~~|~10~|~https%3A%2F%2Faudio.ngfiles.com%2F936000%2F936243_Phaera---Ignition.mp3%3Ff1590147327~|~7~|~~|~8~|~1#11389:0:10#f687963dcfd37f857633563ee28b0cfadc727c97"; 4 | 5 | #[test] 6 | fn process_get_gj_levels_response() { 7 | let levels = dash_rs::response::parse_get_gj_levels_response(GET_GJ_LEVELS_RESPONSE).unwrap(); 8 | 9 | for level in levels { 10 | if level.level_id == 63292359 { 11 | assert!(level.creator.is_none()) 12 | } else { 13 | assert!(level.creator.is_some()) 14 | } 15 | if level.level_id == 63260507 { 16 | assert!(level.custom_song.is_none()); 17 | assert!(level.main_song.is_none()) // The custom song was missing from the response, but 18 | // this does _NOT_ mean that the level does not use 19 | // one. Therefore, having a main song set to Some 20 | // here would be wrong. 21 | } else { 22 | assert!(level.custom_song.is_some()) 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/model/comment/level.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | // use std::borrow::Cow; 3 | 4 | use dash_rs_derive::Dash; 5 | use serde::{Deserialize, Serialize}; 6 | use variant_partial_eq::VariantPartialEq; 7 | 8 | use crate::{ 9 | model::user::{Color, IconType, ModLevel}, 10 | serde::{Base64Decoder, Thunk}, 11 | GJFormat, ProcessError, ThunkProcessor, 12 | }; 13 | 14 | #[derive(Debug, Eq, VariantPartialEq, Clone, Deserialize, Serialize, Dash)] 15 | pub struct LevelComment<'a> { 16 | /// Information about the user that made this [`LevelComment`]. Is generally a [`CommentUser`] 17 | /// object 18 | #[dash(no_index)] 19 | pub user: Option>, 20 | 21 | /// The actual content of the [`LevelComment`] made. 22 | #[dash(index = 2)] 23 | #[serde(borrow)] 24 | #[variant_compare = "crate::util::option_variant_eq"] 25 | pub content: Option>, 26 | 27 | /// The unique user id of the player who made this [`LevelComment`] 28 | #[dash(index = 3)] 29 | pub user_id: u64, 30 | 31 | /// The amount of likes this [`LevelComment`] has received 32 | #[dash(index = 4)] 33 | pub likes: i32, 34 | 35 | /// The unique id of this [`LevelComment`]. Additionally, there is also no [`ProfileComment`](crate::model::comment::profile::ProfileComment) 36 | /// with this id 37 | #[dash(index = 6)] 38 | pub comment_id: u64, 39 | 40 | /// Whether this [`LevelComment`] has been flagged as spam (because of having received too many 41 | /// dislikes or for other reasons) 42 | #[dash(index = 7)] 43 | pub is_flagged_spam: bool, 44 | 45 | /// Robtop's completely braindead way of keeping track of when this [`LevelComment`] was posted 46 | #[dash(index = 9)] 47 | pub time_since_post: Cow<'a, str>, 48 | 49 | /// If enabled by the user making this [`LevelComment`], the progress they have done on the 50 | /// level this comment is on. 51 | #[dash(index = 10)] 52 | pub progress: Option, 53 | 54 | /// The level of moderator the player that made this [`LevelComment`] is 55 | #[dash(index = 11)] 56 | pub mod_level: ModLevel, 57 | 58 | /// If this [`LevelComment`]'s text is displayed in a special color (blue for robtop, green for 59 | /// elder mods), the RGB code of that color will be stored here 60 | /// 61 | /// Note that the yellow color of comments made by the creator is not reported here. 62 | #[dash(index = 12)] 63 | #[variant_compare = "crate::util::option_variant_eq"] 64 | pub special_color: Option>, 65 | } 66 | 67 | impl<'de> GJFormat<'de> for LevelComment<'de> { 68 | const DELIMITER: &'static str = "~"; 69 | const MAP_LIKE: bool = true; 70 | } 71 | 72 | impl ThunkProcessor for Color { 73 | type Error = ProcessError; 74 | type Output<'a> = Color; 75 | 76 | fn from_unprocessed(unprocessed: Cow) -> Result, Self::Error> { 77 | let mut split = unprocessed.split(','); 78 | 79 | let r = split.next(); 80 | let g = split.next(); 81 | let b = split.next(); 82 | 83 | if split.next().is_some() { 84 | return Err(ProcessError::IncorrectLength { expected: 3 }); 85 | } 86 | 87 | match (r, g, b) { 88 | (Some(r), Some(g), Some(b)) => Ok(Color::Known(r.parse()?, g.parse()?, b.parse()?)), 89 | _ => Err(ProcessError::IncorrectLength { expected: 3 }), 90 | } 91 | } 92 | 93 | fn as_unprocessed<'b>(processed: &'b Self::Output<'_>) -> Result, Self::Error> { 94 | match processed { 95 | Color::Known(r, g, b) => Ok(Cow::Owned(format!("{},{},{}", r, g, b))), 96 | _ => Err(ProcessError::Unrepresentable), 97 | } 98 | } 99 | 100 | fn downcast_output_lifetime<'b: 'c, 'c, 's>(output: &'s Self::Output<'b>) -> &'s Self::Output<'c> { 101 | output 102 | } 103 | } 104 | 105 | #[derive(Debug, Eq, VariantPartialEq, Clone, Deserialize, Serialize, Dash)] 106 | pub struct CommentUser<'a> { 107 | /// This [`CommentUser`]'s name 108 | #[dash(index = 1)] 109 | pub name: Cow<'a, str>, 110 | 111 | /// The index of the icon being displayed. 112 | #[dash(index = 9)] 113 | pub icon_index: u16, 114 | 115 | /// This [`CommentUser`]'s primary color 116 | /// 117 | /// ## GD Internals: 118 | /// The game internally assigned each color some really 119 | /// obscure ID that doesn't correspond to the index in the game's color selector at all, which 120 | /// makes it pretty useless. dash-rs thus translates all in-game colors into their RGB 121 | /// representation. 122 | #[dash(index = 10)] 123 | pub primary_color: Color, 124 | 125 | /// This [`CommentUser`]'s secondary color 126 | #[dash(index = 11)] 127 | pub secondary_color: Color, 128 | 129 | /// The type of icon being displayed 130 | #[dash(index = 14)] 131 | pub icon_type: IconType, 132 | 133 | /// Values indicating whether this [`CommentUser`] has glow activated or not. 134 | #[dash(index = 15)] 135 | #[dash(serialize_with = "crate::util::true_to_two")] 136 | pub has_glow: bool, 137 | 138 | /// The [`CommentUser`]'s unique account ID 139 | #[dash(index = 16)] 140 | pub account_id: Option, 141 | } 142 | 143 | impl<'de> GJFormat<'de> for CommentUser<'de> { 144 | const DELIMITER: &'static str = "~"; 145 | const MAP_LIKE: bool = true; 146 | } 147 | -------------------------------------------------------------------------------- /src/model/song.rs: -------------------------------------------------------------------------------- 1 | use crate::serde::{GJFormat, PercentDecoder, ProcessError, Thunk}; 2 | use dash_rs_derive::Dash; 3 | use serde::{Deserialize, Serialize}; 4 | use std::{ 5 | borrow::Cow, 6 | fmt::{Display, Formatter}, 7 | }; 8 | use variant_partial_eq::VariantPartialEq; 9 | 10 | /// Struct modelling a [`NewgroundsSong`] 11 | /// 12 | /// ## GD Internals 13 | /// The Geometry Dash servers provide a list of the newgrounds songs of the 14 | /// levels in a `getGJLevels` response. 15 | /// 16 | /// ### Unused indices: 17 | /// The following indices aren't used by the Geometry Dash servers: `9` 18 | #[derive(Debug, VariantPartialEq, Serialize, Deserialize, Clone, Dash)] 19 | pub struct NewgroundsSong<'a> { 20 | /// The newgrounds id of this [`NewgroundsSong`] 21 | #[dash(index = 1)] 22 | pub song_id: u64, 23 | 24 | /// The name of this [`NewgroundsSong`] 25 | #[dash(index = 2)] 26 | pub name: Cow<'a, str>, 27 | 28 | #[dash(index = 3)] 29 | pub index_3: u64, 30 | 31 | /// The artist of this [`NewgroundsSong`] 32 | #[dash(index = 4)] 33 | pub artist: Cow<'a, str>, 34 | 35 | /// The filesize of this [`NewgroundsSong`], in megabytes 36 | #[dash(index = 5)] 37 | pub filesize: f64, 38 | 39 | #[dash(index = 6)] 40 | pub index_6: Option>, 41 | 42 | #[dash(index = 7)] 43 | pub index_7: Option>, 44 | 45 | #[dash(index = 8)] 46 | pub index_8: Cow<'a, str>, 47 | 48 | /// The direct `audio.ngfiles.com` download link for this [`NewgroundsSong`] 49 | #[serde(borrow)] 50 | #[dash(index = 10)] 51 | pub link: Thunk<'a, PercentDecoder>, 52 | } 53 | 54 | impl<'de> GJFormat<'de> for NewgroundsSong<'de> { 55 | const DELIMITER: &'static str = "~|~"; 56 | const MAP_LIKE: bool = true; 57 | } 58 | 59 | impl<'a> NewgroundsSong<'a> { 60 | pub fn into_owned(self) -> Result, ProcessError> { 61 | Ok(NewgroundsSong { 62 | song_id: self.song_id, 63 | name: Cow::Owned(self.name.into_owned()), 64 | index_3: self.index_3, 65 | artist: Cow::Owned(self.artist.into_owned()), 66 | filesize: self.filesize, 67 | index_6: self.index_6.map(|cow| Cow::Owned(cow.into_owned())), 68 | index_7: self.index_7.map(|cow| Cow::Owned(cow.into_owned())), 69 | index_8: Cow::Owned(self.index_8.into_owned()), 70 | link: Thunk::Processed(Cow::Owned(self.link.into_processed()?.into_owned())), 71 | }) 72 | } 73 | } 74 | 75 | /// Struct representing Geometry Dash's main songs. 76 | /// 77 | /// This data is not provided by the API and needs to be manually kept up to 78 | /// date 79 | #[derive(Debug, Eq, PartialEq, Clone, Copy, Serialize, Deserialize)] 80 | #[serde(from = "u8")] 81 | #[serde(into = "u8")] 82 | pub struct MainSong { 83 | /// The ID of this [`MainSong`] 84 | pub main_song_id: u8, 85 | 86 | /// The name of this [`MainSong`] 87 | // even though we (de)serialize using From and Into, we have to mark these as skip so that the 'de lifetime isn't constrained by 88 | // 'static 89 | #[serde(skip)] 90 | pub name: &'static str, 91 | 92 | /// The artist of this [`MainSong`] 93 | #[serde(skip)] 94 | pub artist: &'static str, 95 | } 96 | 97 | impl MainSong { 98 | const fn new(main_song_id: u8, name: &'static str, artist: &'static str) -> MainSong { 99 | MainSong { 100 | main_song_id, 101 | name, 102 | artist, 103 | } 104 | } 105 | } 106 | 107 | /// All current [`MainSong`]s, as of Geometry Dash 2.1 108 | pub const MAIN_SONGS: [MainSong; 22] = [ 109 | MainSong::new(0, "Stereo Madness", "ForeverBound"), 110 | MainSong::new(1, "Back on Track", "DJVI"), 111 | MainSong::new(2, "Polargeist", "Step"), 112 | MainSong::new(3, "Dry Out", "DJVI"), 113 | MainSong::new(4, "Base after Base", "DJVI"), 114 | MainSong::new(5, "Can't Let Go", "DJVI"), 115 | MainSong::new(6, "Jumper", "Waterflame"), 116 | MainSong::new(7, "Time Machine", "Waterflame"), 117 | MainSong::new(8, "Cycles", "DJVI"), 118 | MainSong::new(9, "xStep", "DJVI"), 119 | MainSong::new(10, "Clutterfunk", "Waterflame"), 120 | MainSong::new(11, "Theory of Everything", "DJ-Nate"), 121 | MainSong::new(12, "Electroman ADventures", "Waterflame"), 122 | MainSong::new(13, "Clubstep", "DJ-Nate"), 123 | MainSong::new(14, "Electrodynamix", "DJ-Nate"), 124 | MainSong::new(15, "Hexagon Force", "Waterflame"), 125 | MainSong::new(16, "Blast Processing", "Waterflame"), 126 | MainSong::new(17, "Theory of Everything 2", "DJ-Nate"), 127 | MainSong::new(18, "Geometrical Dominator", "Waterflame"), 128 | MainSong::new(19, "Deadlocked", "F-777"), 129 | MainSong::new(20, "Fingerdash", "MDK"), 130 | MainSong::new(21, "Geomtry Dash", "MDK"), 131 | ]; 132 | 133 | /// Placeholder value for unknown [`MainSong`]s 134 | /// 135 | /// When resolving a ['MainSong'] by its ID, but you pass a wrong ID, or 136 | /// dash-rs hasn't updated to include the new model.song yet, you will receive this object 137 | pub const UNKNOWN: MainSong = MainSong::new( 138 | 0xFF, 139 | "The model.song was added after the release of dash-rs you're using", 140 | "Please either update to the newest version, or bug stadust about adding the new songs", 141 | ); 142 | 143 | impl Display for NewgroundsSong<'_> { 144 | fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { 145 | write!(f, "NewgroundsSong({}, {} by {})", self.song_id, self.name, self.artist) 146 | } 147 | } 148 | 149 | impl From for MainSong { 150 | fn from(song_id: u8) -> Self { 151 | *MAIN_SONGS.get(song_id as usize).unwrap_or(&UNKNOWN) 152 | } 153 | } 154 | 155 | impl From for u8 { 156 | fn from(song: MainSong) -> Self { 157 | song.main_song_id 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/response.rs: -------------------------------------------------------------------------------- 1 | //! Most likely temporary location of helper functions regarding the parsing of complete server 2 | //! responses. 3 | 4 | use thiserror::Error; 5 | 6 | use crate::{ 7 | model::{ 8 | comment::{ 9 | level::{CommentUser, LevelComment}, 10 | profile::ProfileComment, 11 | }, 12 | creator::Creator, 13 | level::{Level, ListedLevel}, 14 | song::NewgroundsSong, 15 | user::{profile::Profile, searched::SearchedUser}, 16 | }, 17 | serde::GJFormat, 18 | DeError, 19 | }; 20 | 21 | // Since NoneError is not stabilized, we cannot do `impl From for ResponseError<'_>`, so 22 | // this is the next best thing 23 | macro_rules! section { 24 | ($iter:expr) => { 25 | match $iter.next() { 26 | Some(section) => section, 27 | None => return Err(ResponseError::UnexpectedFormat), 28 | } 29 | }; 30 | } 31 | 32 | #[derive(Debug, Error)] 33 | pub enum ResponseError<'a> { 34 | /// A deserializer error occured while processing some object contained in the response 35 | #[error("{0}")] 36 | De(DeError<'a>), // cannot use #[from] here due to non-'static lifetime 37 | 38 | /// The response was of the form `"-1"`, which is RobTop's version of `HTTP 404 NOT FOUND` 39 | #[error("not found")] 40 | NotFound, 41 | 42 | /// The response was not worked in the expected way (too few sections, etc.) 43 | #[error("unexpected format")] 44 | UnexpectedFormat, 45 | 46 | #[error("you have been IP banned by Cloudflare")] 47 | IpBanned, 48 | } 49 | 50 | impl<'a> From> for ResponseError<'a> { 51 | fn from(err: DeError<'a>) -> Self { 52 | ResponseError::De(err) 53 | } 54 | } 55 | 56 | pub fn parse_get_gj_levels_response(response: &str) -> Result, ResponseError> { 57 | check_response_errors(response)?; 58 | 59 | let mut sections = response.split('#'); 60 | 61 | let levels = section!(sections); 62 | let creators = section!(sections) 63 | .split('|') 64 | .filter(|s| !s.is_empty()) // It can happen that segments are completely empty. In this case, split returns an iterator that yields `Some("")`, which would cause an error since the empty string is not parsable 65 | .map(Creator::from_gj_str) 66 | .collect::, _>>()?; 67 | let songs = section!(sections) 68 | .split("~:~") 69 | .filter(|s| !s.is_empty()) 70 | .map(NewgroundsSong::from_gj_str) 71 | .collect::, _>>()?; 72 | 73 | levels 74 | .split('|') 75 | .map(|fragment| { 76 | let level: Level<()> = Level::from_gj_str(fragment)?; 77 | // Note: Cloning is cheap because none of the Thunks is evaluated, so we only have references lying 78 | // around. 79 | let creator = creators.iter().find(|creator| creator.user_id == level.creator).cloned(); 80 | let song = level 81 | .custom_song 82 | .and_then(|song_id| songs.iter().find(|song| song.song_id == song_id)) 83 | .cloned(); 84 | 85 | Ok(Level { 86 | level_id: level.level_id, 87 | name: level.name, 88 | description: level.description, 89 | version: level.version, 90 | creator, 91 | difficulty: level.difficulty, 92 | downloads: level.downloads, 93 | main_song: level.main_song, 94 | gd_version: level.gd_version, 95 | likes: level.likes, 96 | length: level.length, 97 | stars: level.stars, 98 | featured: level.featured, 99 | copy_of: level.copy_of, 100 | two_player: level.two_player, 101 | custom_song: song, 102 | coin_amount: level.coin_amount, 103 | coins_verified: level.coins_verified, 104 | stars_requested: level.stars_requested, 105 | is_epic: level.is_epic, 106 | object_amount: level.object_amount, 107 | index_46: level.index_46, 108 | index_47: level.index_47, 109 | level_data: level.level_data, 110 | }) 111 | }) 112 | .collect::>() 113 | } 114 | 115 | pub fn parse_download_gj_level_response(response: &str) -> Result { 116 | check_response_errors(response)?; 117 | 118 | let mut sections = response.split('#'); 119 | 120 | Ok(Level::from_gj_str(section!(sections))?) 121 | } 122 | 123 | pub fn parse_get_gj_user_info_response(response: &str) -> Result { 124 | check_response_errors(response)?; 125 | 126 | Ok(Profile::from_gj_str(response)?) 127 | } 128 | 129 | pub fn parse_get_gj_users_response(response: &str) -> Result { 130 | check_response_errors(response)?; 131 | 132 | let mut sections = response.split('#'); 133 | 134 | // In the past this used to be a paginating endpoint which performed an infix search on the user 135 | // name. Now, it performs a full match, and since account names are unique, this endpoint returns at 136 | // most one object anymore. 137 | Ok(SearchedUser::from_gj_str(section!(sections))?) 138 | } 139 | 140 | pub fn parse_get_gj_comments_response(response: &str) -> Result, ResponseError> { 141 | check_response_errors(response)?; 142 | 143 | let mut sections = response.split('#'); 144 | 145 | // The format here is very weird. We have a '|' separated list of (comment, user) pairs, and said 146 | // pair is separated by a ':' 147 | 148 | section!(sections) 149 | .split('|') 150 | .map(|fragment| { 151 | let mut parts = fragment.split(':'); 152 | 153 | if let (Some(raw_comment), Some(raw_user)) = (parts.next(), parts.next()) { 154 | let mut comment = LevelComment::from_gj_str(raw_comment)?; 155 | 156 | comment.user = if raw_user == "1~~9~~10~~11~~14~~15~~16~" { 157 | None 158 | } else { 159 | Some(CommentUser::from_gj_str(raw_user)?) 160 | }; 161 | 162 | Ok(comment) 163 | } else { 164 | Err(ResponseError::UnexpectedFormat) 165 | } 166 | }) 167 | .collect() 168 | } 169 | 170 | pub fn parse_get_gj_acccount_comments_response(response: &str) -> Result, ResponseError> { 171 | check_response_errors(response)?; 172 | 173 | let mut sections = response.split('#'); 174 | 175 | section!(sections) 176 | .split('|') 177 | .map(|fragment| Ok(ProfileComment::from_gj_str(fragment)?)) 178 | .collect() 179 | } 180 | 181 | fn check_response_errors(response: &str) -> Result<(), ResponseError> { 182 | if response == "-1" { 183 | return Err(ResponseError::NotFound); 184 | } 185 | 186 | if response == "error code: 1005" { 187 | return Err(ResponseError::IpBanned); 188 | } 189 | 190 | Ok(()) 191 | } 192 | -------------------------------------------------------------------------------- /src/request/comment.rs: -------------------------------------------------------------------------------- 1 | //! Module containing request structs for retrieving profile/level comments 2 | 3 | use crate::{ 4 | model::level::Level, 5 | request::{endpoint_base_url, BaseRequest, GD_22}, 6 | }; 7 | use serde::Serialize; 8 | use std::fmt::Display; 9 | 10 | pub const LEVEL_COMMENTS_ENDPOINT: &str = "getGJComments21.php"; 11 | pub const PROFILE_COMMENT_ENDPOINT: &str = "getGJAccountComments20.php"; 12 | 13 | /// The different orderings that can be requested for level comments 14 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] 15 | #[serde(into = "u8")] 16 | pub enum SortMode { 17 | /// Sort the comments by likes, in descending order 18 | /// 19 | /// ## GD Internals: 20 | /// This variant is represented by the numeric value `1` in the boomlings API 21 | Liked, 22 | 23 | /// Sort the comments from newest to oldest 24 | /// 25 | /// ## GD Internals: 26 | /// This variant is represented by the numeric value `0` in the boomlings APII 27 | Recent, 28 | } 29 | 30 | impl From for u8 { 31 | fn from(mode: SortMode) -> Self { 32 | match mode { 33 | SortMode::Liked => 1, 34 | SortMode::Recent => 0, 35 | } 36 | } 37 | } 38 | 39 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Hash)] 40 | pub struct LevelCommentsRequest<'a> { 41 | /// The base request data 42 | pub base: BaseRequest<'a>, 43 | 44 | /// Unknown, probably related to pagination 45 | /// 46 | /// ## GD Internals: 47 | /// This field is called `total` in the boomlings API 48 | pub total: u32, 49 | 50 | /// The page of users to retrieve. The first page is page `0` 51 | /// 52 | /// ## GD Internals: 53 | /// This field is called `page` in the boomlings API 54 | pub page: u32, 55 | 56 | /// What to sort by comments by 57 | /// 58 | /// ## GD Internals: 59 | /// This field is called `mode` in the boomlings API. 60 | #[serde(rename = "mode")] 61 | pub sort_mode: SortMode, 62 | 63 | /// The id of the level to retrieve the comments of 64 | /// 65 | /// ## GD Internals: 66 | /// This field is called `levelID` in the boomlings API 67 | #[serde(rename = "levelID")] 68 | pub level_id: u64, 69 | 70 | /// The amount of comments to retrieve. Note that while in-game this can only be set to 20 or 40 71 | /// (via the "load more comments option), the API accepts any value. So you can set it to 72 | /// something ridiculously high (like u32::MAX_VALUE) and retrieve all comments at once. 73 | /// 74 | /// ## GD Internals: 75 | /// This field is called `count` in the boomlings API 76 | #[serde(rename = "count")] 77 | pub limit: u32, 78 | } 79 | 80 | impl<'a> LevelCommentsRequest<'a> { 81 | const_setter!(total: u32); 82 | 83 | const_setter!(limit: u32); 84 | 85 | const_setter!(page: u32); 86 | 87 | pub fn to_url(&self) -> String { 88 | format!("{}{}", endpoint_base_url(), LEVEL_COMMENTS_ENDPOINT) 89 | } 90 | 91 | pub const fn new(level: u64) -> Self { 92 | Self::with_base(GD_22, level) 93 | } 94 | 95 | pub const fn with_base(base: BaseRequest<'a>, level: u64) -> Self { 96 | LevelCommentsRequest { 97 | level_id: level, 98 | base, 99 | page: 0, 100 | total: 0, 101 | sort_mode: SortMode::Recent, 102 | limit: 20, 103 | } 104 | } 105 | 106 | pub const fn most_liked(mut self) -> Self { 107 | self.sort_mode = SortMode::Liked; 108 | self 109 | } 110 | 111 | pub const fn most_recent(mut self) -> Self { 112 | self.sort_mode = SortMode::Recent; 113 | self 114 | } 115 | } 116 | 117 | impl Display for LevelCommentsRequest<'_> { 118 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 119 | write!(f, "{}", super::to_string(self)) 120 | } 121 | } 122 | 123 | impl From for LevelCommentsRequest<'_> { 124 | fn from(level_id: u64) -> Self { 125 | LevelCommentsRequest::new(level_id) 126 | } 127 | } 128 | 129 | impl From> for LevelCommentsRequest<'_> { 130 | fn from(level: Level<'_, S, U>) -> Self { 131 | LevelCommentsRequest::from(level.level_id) 132 | } 133 | } 134 | 135 | #[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Hash)] 136 | pub struct ProfileCommentsRequest<'a> { 137 | /// The base request data 138 | pub base: BaseRequest<'a>, 139 | 140 | /// Unknown, probably related to pagination 141 | /// 142 | /// ## GD Internals: 143 | /// This field is called `total` in the boomlings API 144 | pub total: u32, 145 | 146 | /// The page of users to retrieve. The first page is page `0` 147 | /// 148 | /// ## GD Internals: 149 | /// This field is called `page` in the boomlings API 150 | pub page: u32, 151 | 152 | /// The account id of the user to retrieve the comments of 153 | /// 154 | /// ## GD Internals: 155 | /// This field is called `accountID` in the boomlings API 156 | #[serde(rename = "accountID")] 157 | pub account_id: u64, 158 | } 159 | 160 | impl<'a> ProfileCommentsRequest<'a> { 161 | const_setter!(total: u32); 162 | 163 | const_setter!(page: u32); 164 | 165 | const_setter!(account_id: u64); 166 | 167 | pub fn to_url(&self) -> String { 168 | format!("{}{}", endpoint_base_url(), PROFILE_COMMENT_ENDPOINT) 169 | } 170 | 171 | pub const fn new(account: u64) -> Self { 172 | Self::with_base(GD_22, account) 173 | } 174 | 175 | pub const fn with_base(base: BaseRequest<'a>, account: u64) -> Self { 176 | ProfileCommentsRequest { 177 | account_id: account, 178 | base, 179 | page: 0, 180 | total: 0, 181 | } 182 | } 183 | } 184 | 185 | impl Display for ProfileCommentsRequest<'_> { 186 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 187 | write!(f, "{}", super::to_string(self)) 188 | } 189 | } 190 | 191 | #[cfg(test)] 192 | mod tests { 193 | use crate::request::comment::{LevelCommentsRequest, ProfileCommentsRequest}; 194 | 195 | #[test] 196 | fn serialize_level_comments() { 197 | if let Err(err) = env_logger::builder().is_test(true).try_init() { 198 | // nothing to make the tests fail over 199 | eprintln!("Error setting up env_logger: {:?}", err) 200 | } 201 | 202 | let request = LevelCommentsRequest::new(1234).most_liked().page(2).limit(15); 203 | 204 | assert_eq!( 205 | super::super::to_string(request), 206 | "gameVersion=22&binaryVersion=38&secret=Wmfd2893gb7&total=0&page=2&mode=1&levelID=1234&count=15" 207 | ); 208 | } 209 | 210 | #[test] 211 | fn serialize_profile_comments() { 212 | if let Err(err) = env_logger::builder().is_test(true).try_init() { 213 | // nothing to make the tests fail over 214 | eprintln!("Error setting up env_logger: {:?}", err) 215 | } 216 | 217 | let request = ProfileCommentsRequest::new(1710032).page(2); 218 | 219 | assert_eq!( 220 | super::super::to_string(request), 221 | "gameVersion=22&binaryVersion=38&secret=Wmfd2893gb7&total=0&page=2&accountID=1710032" 222 | ); 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /src/model/user/mod.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | pub mod profile; 4 | pub mod searched; 5 | 6 | /// Enum representing the different types of moderator a user can be 7 | #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, Serialize, Deserialize)] 8 | pub enum ModLevel { 9 | /// User isn't a moderator 10 | None, 11 | 12 | /// User is a normal moderator 13 | Normal, 14 | 15 | /// User is an elder moderator 16 | Elder, 17 | 18 | /// Unknown or invalid value. This variant will be constructed if robtop ever adds more 19 | /// moderator levels and will hold the internal game value associated with the new moderator 20 | /// level 21 | Unknown(u8), 22 | } 23 | 24 | impl From for u8 { 25 | fn from(level: ModLevel) -> u8 { 26 | match level { 27 | ModLevel::None => 0, 28 | ModLevel::Normal => 1, 29 | ModLevel::Elder => 2, 30 | ModLevel::Unknown(inner) => inner, 31 | } 32 | } 33 | } 34 | 35 | impl From for ModLevel { 36 | fn from(i: u8) -> Self { 37 | match i { 38 | 0 => ModLevel::None, 39 | 1 => ModLevel::Normal, 40 | 2 => ModLevel::Elder, 41 | i => ModLevel::Unknown(i), 42 | } 43 | } 44 | } 45 | 46 | crate::into_conversion!(ModLevel, u8); 47 | 48 | /// The type of icon displayed next a user's comment of next to their search result 49 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] 50 | pub enum IconType { 51 | Cube, 52 | Ship, 53 | Ball, 54 | Ufo, 55 | Wave, 56 | Robot, 57 | Spider, 58 | Unknown(u8), 59 | } 60 | 61 | impl From for IconType { 62 | fn from(i: u8) -> Self { 63 | match i { 64 | 0 => IconType::Cube, 65 | 1 => IconType::Ship, 66 | 2 => IconType::Ball, 67 | 3 => IconType::Ufo, 68 | 4 => IconType::Wave, 69 | 5 => IconType::Robot, 70 | 6 => IconType::Spider, 71 | i => IconType::Unknown(i), 72 | } 73 | } 74 | } 75 | 76 | impl From for u8 { 77 | fn from(mode: IconType) -> u8 { 78 | match mode { 79 | IconType::Cube => 0, 80 | IconType::Ship => 1, 81 | IconType::Ball => 2, 82 | IconType::Ufo => 3, 83 | IconType::Wave => 4, 84 | IconType::Robot => 5, 85 | IconType::Spider => 6, 86 | IconType::Unknown(idx) => idx, 87 | } 88 | } 89 | } 90 | 91 | // Enum representing an in-game icon color 92 | #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, Serialize, Deserialize)] 93 | pub enum Color { 94 | /// A color whose index was known to dash-rs which could be converted to RGB values 95 | Known(u8, u8, u8), 96 | 97 | /// The index of some unknown colors. This variant will be constructed if robtop ever adds more 98 | /// colors and while dash-rs hasn't updated yet 99 | Unknown(u8), 100 | } 101 | 102 | impl From for Color { 103 | fn from(idx: u8) -> Self { 104 | // This match expression is listing the colors in order of the in-game selection menu! 105 | match idx { 106 | 0 => Color::Known(125, 255, 0), 107 | 1 => Color::Known(0, 255, 0), 108 | 2 => Color::Known(0, 255, 125), 109 | 3 => Color::Known(0, 255, 255), 110 | 16 => Color::Known(0, 200, 255), 111 | 4 => Color::Known(0, 125, 255), 112 | 5 => Color::Known(0, 0, 255), 113 | 6 => Color::Known(125, 0, 255), 114 | 13 => Color::Known(185, 0, 255), 115 | 7 => Color::Known(255, 0, 255), 116 | 8 => Color::Known(255, 0, 125), 117 | 9 => Color::Known(255, 0, 0), 118 | 29 => Color::Known(255, 75, 0), 119 | 10 => Color::Known(255, 125, 0), 120 | 14 => Color::Known(255, 185, 0), 121 | 11 => Color::Known(255, 255, 0), 122 | 12 => Color::Known(255, 255, 255), 123 | 17 => Color::Known(175, 175, 175), 124 | 18 => Color::Known(80, 80, 80), 125 | 15 => Color::Known(0, 0, 0), 126 | 27 => Color::Known(125, 125, 0), 127 | 32 => Color::Known(100, 150, 0), 128 | 28 => Color::Known(75, 175, 0), 129 | 38 => Color::Known(0, 150, 0), 130 | 20 => Color::Known(0, 175, 75), 131 | 33 => Color::Known(0, 150, 100), 132 | 21 => Color::Known(0, 125, 125), 133 | 34 => Color::Known(0, 100, 150), 134 | 22 => Color::Known(0, 75, 175), 135 | 39 => Color::Known(0, 0, 150), 136 | 23 => Color::Known(75, 0, 175), 137 | 35 => Color::Known(100, 0, 150), 138 | 24 => Color::Known(125, 0, 125), 139 | 36 => Color::Known(150, 0, 100), 140 | 25 => Color::Known(175, 0, 75), 141 | 37 => Color::Known(150, 0, 0), 142 | 30 => Color::Known(150, 50, 0), 143 | 26 => Color::Known(175, 75, 0), 144 | 31 => Color::Known(150, 100, 0), 145 | 19 => Color::Known(255, 255, 125), 146 | 40 => Color::Known(125, 255, 175), 147 | 41 => Color::Known(125, 125, 255), 148 | idx => Color::Unknown(idx), 149 | } 150 | } 151 | } 152 | 153 | impl From for u8 { 154 | fn from(color: Color) -> Self { 155 | // in this house we are thankful for regular expressions 156 | match color { 157 | Color::Known(125, 255, 0) => 0, 158 | Color::Known(0, 255, 0) => 1, 159 | Color::Known(0, 255, 125) => 2, 160 | Color::Known(0, 255, 255) => 3, 161 | Color::Known(0, 200, 255) => 16, 162 | Color::Known(0, 125, 255) => 4, 163 | Color::Known(0, 0, 255) => 5, 164 | Color::Known(125, 0, 255) => 6, 165 | Color::Known(185, 0, 255) => 13, 166 | Color::Known(255, 0, 255) => 7, 167 | Color::Known(255, 0, 125) => 8, 168 | Color::Known(255, 0, 0) => 9, 169 | Color::Known(255, 75, 0) => 29, 170 | Color::Known(255, 125, 0) => 10, 171 | Color::Known(255, 185, 0) => 14, 172 | Color::Known(255, 255, 0) => 11, 173 | Color::Known(255, 255, 255) => 12, 174 | Color::Known(175, 175, 175) => 17, 175 | Color::Known(80, 80, 80) => 18, 176 | Color::Known(0, 0, 0) => 15, 177 | Color::Known(125, 125, 0) => 27, 178 | Color::Known(100, 150, 0) => 32, 179 | Color::Known(75, 175, 0) => 28, 180 | Color::Known(0, 150, 0) => 38, 181 | Color::Known(0, 175, 75) => 20, 182 | Color::Known(0, 150, 100) => 33, 183 | Color::Known(0, 125, 125) => 21, 184 | Color::Known(0, 100, 150) => 34, 185 | Color::Known(0, 75, 175) => 22, 186 | Color::Known(0, 0, 150) => 39, 187 | Color::Known(75, 0, 175) => 23, 188 | Color::Known(100, 0, 150) => 35, 189 | Color::Known(125, 0, 125) => 24, 190 | Color::Known(150, 0, 100) => 36, 191 | Color::Known(175, 0, 75) => 25, 192 | Color::Known(150, 0, 0) => 37, 193 | Color::Known(150, 50, 0) => 30, 194 | Color::Known(175, 75, 0) => 26, 195 | Color::Known(150, 100, 0) => 31, 196 | Color::Known(255, 255, 125) => 19, 197 | Color::Known(125, 255, 175) => 40, 198 | Color::Known(125, 125, 255) => 41, 199 | Color::Unknown(idx) => idx, 200 | _ => 0, // default color 201 | } 202 | } 203 | } 204 | 205 | crate::into_conversion!(Color, u8); 206 | crate::into_conversion!(IconType, u8); 207 | -------------------------------------------------------------------------------- /examples/refresh_test_artifacts.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fs::OpenOptions, 3 | path::{Path, PathBuf}, 4 | }; 5 | 6 | use dash_rs::{ 7 | model::{creator::Creator, level::Level, song::NewgroundsSong}, 8 | request::{ 9 | level::{CompletionFilter, LevelRequest, LevelsRequest, SearchFilters}, 10 | user::{UserRequest, UserSearchRequest}, 11 | }, 12 | response::{parse_download_gj_level_response, parse_get_gj_user_info_response, parse_get_gj_users_response}, 13 | GJFormat, 14 | }; 15 | use reqwest::{ 16 | header::{HeaderMap, CONTENT_TYPE}, 17 | Client, Response, 18 | }; 19 | use serde::Serialize; 20 | 21 | #[tokio::main] 22 | async fn main() { 23 | // We want debug logging so that it tells us about unmapped indices 24 | env_logger::builder().filter_level(log::LevelFilter::Debug).init(); 25 | 26 | let http_client = Client::new(); 27 | 28 | let artifacts_path = Path::new("tests").join("artifacts"); 29 | let artifacts_backup = Path::new("tests").join("artifacts_backup"); 30 | 31 | std::fs::rename(&artifacts_path, &artifacts_backup).unwrap(); 32 | 33 | // Comment out the ones you dont want to refresh 34 | refresh_full_levels(&artifacts_path, &http_client).await; 35 | refresh_listed_levels(&artifacts_path, &http_client).await; 36 | refresh_profiles(&artifacts_path, &http_client).await; 37 | refresh_searched_users(&artifacts_path, &http_client).await; 38 | 39 | std::fs::remove_dir_all(&artifacts_backup).unwrap(); 40 | } 41 | 42 | async fn refresh_full_levels(artifacts_path: &Path, http_client: &Client) { 43 | println!("Downloading full levels"); 44 | 45 | let levels_path = artifacts_path.join("level"); 46 | let levels_to_download = [ 47 | 897837, // time pressure by aeonair 48 | 11774780, // dark realm by stardust1971 49 | ]; 50 | 51 | for level_id in levels_to_download { 52 | let request = LevelRequest::new(level_id); 53 | let response = make_request(http_client, &request.to_url(), request.to_string()).await; 54 | let response_text = response.text().await.unwrap(); 55 | let level = parse_download_gj_level_response(&response_text).unwrap(); 56 | 57 | let level_artifact_path = levels_path.join(level_id.to_string()); 58 | let _ = std::fs::create_dir_all(&level_artifact_path); 59 | 60 | std::fs::write(level_artifact_path.join("raw"), response_text.split('#').next().unwrap()).unwrap(); 61 | dump_deserialized_artifact(level_artifact_path, &level); 62 | } 63 | } 64 | 65 | async fn refresh_listed_levels(artifacts_path: &Path, http_client: &Client) { 66 | println!("Downloading listed levels"); 67 | 68 | let listed_levels_path = artifacts_path.join("listed_level"); 69 | let creators_path = artifacts_path.join("creator"); 70 | let songs_path = artifacts_path.join("song"); 71 | let levels_to_dowload = vec![ 72 | 72540, // demon world, 1.3 (?) level 73 | 11774780, // dark realm , 1.9 level 74 | 24904605, // The Badland, 2.0 level 75 | 63355989, // fantasy, 2.1 level 76 | 97598449, // Loco Motive, 2.2 platformer level 77 | ]; 78 | 79 | let request = LevelsRequest::default() 80 | .search_filters(SearchFilters::default().completion_filter(CompletionFilter::limit_search(levels_to_dowload))); 81 | 82 | let response = make_request(http_client, &request.to_url(), request.to_string()).await; 83 | let response_text = response.text().await.unwrap(); 84 | 85 | // We'll have to reimplement part of the response parsing here, `parse_get_gj_levels_response` is 86 | // too ergonomic for what we want 87 | let mut section_iter = response_text.split('#'); 88 | let raw_levels = section_iter.next().unwrap(); 89 | let raw_creators = section_iter.next().unwrap(); 90 | let raw_songs = section_iter.next().unwrap(); 91 | 92 | for raw_level in raw_levels.split('|') { 93 | let level = Level::<()>::from_gj_str(raw_level).unwrap(); 94 | 95 | let level_artifact_path = listed_levels_path.join(level.level_id.to_string()); 96 | let _ = std::fs::create_dir_all(&level_artifact_path); 97 | 98 | std::fs::write(level_artifact_path.join("raw"), raw_level).unwrap(); 99 | dump_deserialized_artifact(level_artifact_path, &level); 100 | } 101 | 102 | for raw_creator in raw_creators.split('|') { 103 | let creator = Creator::from_gj_str(raw_creator).unwrap(); 104 | 105 | let creator_artifact_path = creators_path.join(creator.user_id.to_string()); 106 | let _ = std::fs::create_dir_all(&creator_artifact_path); 107 | 108 | std::fs::write(creator_artifact_path.join("raw"), raw_creator).unwrap(); 109 | dump_deserialized_artifact(creator_artifact_path, &creator); 110 | } 111 | 112 | for raw_song in raw_songs.split("~:~") { 113 | let song = NewgroundsSong::from_gj_str(raw_song).unwrap(); 114 | 115 | let song_artifact_path = songs_path.join(song.song_id.to_string()); 116 | let _ = std::fs::create_dir_all(&song_artifact_path); 117 | 118 | std::fs::write(song_artifact_path.join("raw"), raw_song).unwrap(); 119 | dump_deserialized_artifact(song_artifact_path, &song); 120 | } 121 | } 122 | 123 | async fn refresh_profiles(artifacts_path: &Path, http_client: &Client) { 124 | println!("Downloading profiles"); 125 | 126 | let profiles_path = artifacts_path.join("profile"); 127 | let profiles_to_download = [8451 /* stardust1971 */]; 128 | 129 | for account_id in profiles_to_download { 130 | let request = UserRequest::new(account_id); 131 | let response = make_request(http_client, &request.to_url(), request.to_string()).await; 132 | let response_text = response.text().await.unwrap(); 133 | 134 | let profile = parse_get_gj_user_info_response(&response_text).unwrap(); 135 | 136 | let profile_artifact_path = profiles_path.join(account_id.to_string()); 137 | let _ = std::fs::create_dir_all(&profile_artifact_path); 138 | 139 | std::fs::write(profile_artifact_path.join("raw"), &response_text).unwrap(); 140 | dump_deserialized_artifact(profile_artifact_path, &profile); 141 | } 142 | } 143 | 144 | async fn refresh_searched_users(artifacts_path: &Path, http_client: &Client) { 145 | println!("Downloading search-listed users"); 146 | 147 | let searched_users_path = artifacts_path.join("searched_user"); 148 | let users_to_search = ["stardust1971" /* stardust1971 */]; 149 | 150 | for username in users_to_search { 151 | let request = UserSearchRequest::new(username); 152 | let response = make_request(http_client, &request.to_url(), request.to_string()).await; 153 | let response_text = response.text().await.unwrap(); 154 | 155 | let searched_user = parse_get_gj_users_response(&response_text).unwrap(); 156 | 157 | let searched_user_artifact_path = searched_users_path.join(username); 158 | let _ = std::fs::create_dir_all(&searched_user_artifact_path); 159 | 160 | std::fs::write(searched_user_artifact_path.join("raw"), response_text.split('#').next().unwrap()).unwrap(); 161 | dump_deserialized_artifact(searched_user_artifact_path, &searched_user); 162 | } 163 | } 164 | 165 | fn dump_deserialized_artifact(dest: impl AsRef, artifact: &S) { 166 | let mut file = OpenOptions::new() 167 | .create(true) 168 | .truncate(true) 169 | .write(true) 170 | .open(dest.as_ref().join("processed")) 171 | .unwrap(); 172 | serde_json::to_writer_pretty(&mut file, artifact).unwrap(); 173 | } 174 | 175 | async fn make_request(client: &Client, endpoint: &str, data: String) -> Response { 176 | client.post(endpoint) 177 | .headers(HeaderMap::new()) // boomlings.com rejects any request with a User-Agent header set, so make sure reqwest doesn't "helpfully" add one 178 | .body(data) 179 | .header(CONTENT_TYPE, "application/x-www-form-urlencoded") 180 | .send() 181 | .await 182 | .unwrap() 183 | } 184 | -------------------------------------------------------------------------------- /src/model/user/profile.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | model::user::{Color, ModLevel}, 3 | GJFormat, 4 | }; 5 | use dash_rs_derive::Dash; 6 | use serde::{Deserialize, Serialize}; 7 | use std::{ 8 | borrow::Cow, 9 | fmt::{Display, Formatter}, 10 | }; 11 | use variant_partial_eq::VariantPartialEq; 12 | 13 | crate::dash_rs_newtype!(Youtube); 14 | crate::dash_rs_newtype!(Twitch); 15 | crate::dash_rs_newtype!(Twitter); 16 | 17 | impl Display for Youtube<'_> { 18 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 19 | write!(f, "https://www.youtube.com/channel/{}", self.0) 20 | } 21 | } 22 | 23 | impl Display for Twitch<'_> { 24 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 25 | write!(f, "https://www.twitch.tv/{}", self.0) 26 | } 27 | } 28 | 29 | impl Display for Twitter<'_> { 30 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 31 | write!(f, "https://www.twitter.com/{}", self.0) 32 | } 33 | } 34 | 35 | /// Struct representing a Geometry Dash User's profile, as seen after clicking their name in the 36 | /// official client 37 | /// 38 | /// ## GD Internals: 39 | /// The Geometry Dash servers provide user data in a `getGJUserInfo` response 40 | /// 41 | /// ### Unused Indices 42 | /// The following indices aren't used by the Geometry Dash servers: `5`, `6`, `7`, `9`, `12`, `14`, 43 | /// `15`, `27`, `32`, `33`, `34`, `35`, `36`, `37`, `38`, `39`, `40`, `41`, `42`, `47` 44 | #[derive(Debug, Eq, VariantPartialEq, Clone, Serialize, Deserialize, Dash)] 45 | pub struct Profile<'a> { 46 | /// The [`Profile`]'s name 47 | #[dash(index = 1)] 48 | pub name: Cow<'a, str>, 49 | 50 | /// The [`Profile`]'s unique user ID 51 | #[dash(index = 2)] 52 | pub user_id: u64, 53 | 54 | /// The amount of stars this [`Profile`] has collected. 55 | #[dash(index = 3)] 56 | pub stars: u32, 57 | 58 | /// The demons of stars this [`Profile`] has beaten. 59 | #[dash(index = 4)] 60 | pub demons: u16, 61 | 62 | /// The amount of creator points this [`Profile`] was awarded. 63 | #[dash(index = 8)] 64 | pub creator_points: u16, 65 | 66 | /// This [`Profile`]'s primary color 67 | /// 68 | /// ## GD Internals: 69 | /// The game internally assigned each color some really 70 | /// obscure ID that doesn't correspond to the index in the game's color selector at all, which 71 | /// makes it pretty useless. dash-rs thus translates all in-game colors into their RGB 72 | /// representation. 73 | #[dash(index = 10)] 74 | pub primary_color: Color, 75 | 76 | /// This [`Profile`]'s secondary color 77 | /// 78 | /// ## GD Internals: 79 | /// Same things as above apply 80 | #[dash(index = 11)] 81 | pub secondary_color: Color, 82 | 83 | /// The amount of secret coins this [`Profile`] has collected. 84 | #[dash(index = 13)] 85 | pub secret_coins: u8, 86 | 87 | /// The [`Profile`]'s unique account ID 88 | #[dash(index = 16)] 89 | pub account_id: u64, 90 | 91 | /// The amount of user coins this [`Profile`] has collected. 92 | #[dash(index = 17)] 93 | pub user_coins: u16, 94 | 95 | // TODO: figure this value out 96 | #[dash(index = 18)] 97 | pub index_18: Cow<'a, str>, 98 | 99 | // TODO: figure this value out 100 | #[dash(index = 19)] 101 | pub index_19: Cow<'a, str>, 102 | 103 | /// The link to the [`Profile`]'s [YouTube](https://youtube.com) channel, if provided 104 | /// 105 | /// ## GD Internals 106 | /// The value provided is only the `username` section of an `https://www.youtube.com/user/{username}` URL 107 | #[dash(index = 20)] 108 | pub youtube_url: Option>, 109 | 110 | /// The 1-based index of the cube this [`Profile`] currently uses. Indexing of icons starts at 111 | /// the top left corner and then goes left-to-right and top-to-bottom 112 | #[dash(index = 21)] 113 | pub cube_index: u16, 114 | 115 | /// The 1-based index of the ship this [`Profile`] currently uses. Indexing of icons starts at 116 | /// the top left corner and then goes left-to-right and top-to-bottom 117 | #[dash(index = 22)] 118 | pub ship_index: u8, 119 | 120 | /// The 1-based index of the ball this [`Profile`] currently uses. Indexing of icons starts at 121 | /// the top left corner and then goes left-to-right and top-to-bottom 122 | #[dash(index = 23)] 123 | pub ball_index: u8, 124 | 125 | /// The 1-based index of the UFO this [`Profile`] currently uses. Indexing of icons starts at 126 | /// the top left corner and then goes left-to-right and top-to-bottom 127 | #[dash(index = 24)] 128 | pub ufo_index: u8, 129 | 130 | /// The 1-based index of the wave this [`Profile`] currently uses. Indexing of icons starts at 131 | /// the top left corner and then goes left-to-right and top-to-bottom 132 | #[dash(index = 25)] 133 | pub wave_index: u8, 134 | 135 | /// The 1-based index of the robot this [`Profile`] currently uses. Indexing of icons starts at 136 | /// the top left corner and then goes left-to-right and top-to-bottom 137 | #[dash(index = 26)] 138 | pub robot_index: u8, 139 | 140 | /// Values indicating whether this [`Profile`] has glow activated or not. 141 | #[dash(index = 28)] 142 | pub has_glow: bool, 143 | 144 | // TODO: figure this value out 145 | #[dash(index = 29)] 146 | pub index_29: Cow<'a, str>, 147 | 148 | /// This [`Profile`]'s global rank. [`None`] if he is banned or not ranked. 149 | /// 150 | /// ## GD Internals: 151 | /// For unranked/banned users it's `0`. TODO: Why is this an option? 152 | #[dash(index = 30)] 153 | pub global_rank: Option, 154 | 155 | // TODO: figure this value out 156 | #[dash(index = 31)] 157 | pub index_31: Cow<'a, str>, 158 | 159 | // TODO: figure this value out 160 | #[dash(index = 38)] 161 | #[dash(default)] 162 | #[dash(skip_serializing_if = "Option::is_none")] 163 | pub index_38: Option>, 164 | 165 | // TODO: figure this value out 166 | #[dash(index = 39)] 167 | #[dash(default)] 168 | #[dash(skip_serializing_if = "Option::is_none")] 169 | pub index_39: Option>, 170 | 171 | // TODO: figure this value out 172 | #[dash(index = 40)] 173 | #[dash(default)] 174 | #[dash(skip_serializing_if = "Option::is_none")] 175 | pub index_40: Option>, 176 | 177 | /// The 1-based index of the spider this [`Profile`] currently uses. Indexing of icons starts at 178 | /// the top left corner and then goes left-to-right and top-to-bottom 179 | #[dash(index = 43)] 180 | pub spider_index: u8, 181 | 182 | /// The link to the [`Profile`]'s [Twitter](https://twitter.com) account, if provided 183 | /// 184 | /// ## GD Internals 185 | /// The value provided is only the `username` section of an `https://www.twitter.com/{username}` URL 186 | #[dash(index = 44)] 187 | pub twitter_url: Option>, 188 | 189 | /// The link to the [`Profile`]'s [Twitch](https://twitch.tv) channel, if provided 190 | /// 191 | /// ## GD Internals 192 | /// The value provided is only the `username` section of an `https://twitch.tv/{username}` URL 193 | #[dash(index = 45)] 194 | pub twitch_url: Option>, 195 | 196 | /// The amount of diamonds this [`Profile`] has collected. 197 | #[dash(index = 46)] 198 | pub diamonds: u16, 199 | 200 | /// The 1-based index of the death-effect this [`Profile`] currently uses. Indexing of icons 201 | /// starts at the top left corner and then goes left-to-right and top-to-bottom 202 | #[dash(index = 48)] 203 | pub death_effect_index: u8, 204 | 205 | /// The level of moderator this [`Profile`] is 206 | #[dash(index = 49)] 207 | pub mod_level: ModLevel, 208 | 209 | // TODO: figure this value out 210 | #[dash(index = 50)] 211 | pub index_50: Cow<'a, str>, 212 | 213 | #[dash(index = 51)] 214 | pub index_51: Cow<'a, str>, 215 | 216 | /// The number of moons this [`Profile`] has collected 217 | #[dash(index = 52)] 218 | pub moons: u32, 219 | 220 | /// The 1-based index of the swing this [`Profile`] currently uses. Indexing of icons starts at 221 | /// the top left corner and then goes left-to-right and top-to-bottom 222 | #[dash(index = 53)] 223 | pub swing_index: u8, 224 | 225 | /// The 1-based index of the jetpack this [`Profile`] currently uses. Indexing of icons starts 226 | /// at the top left corner and then goes left-to-right and top-to-bottom 227 | #[dash(index = 54)] 228 | pub jetpack_index: u8, 229 | } 230 | 231 | impl<'de> GJFormat<'de> for Profile<'de> { 232 | const DELIMITER: &'static str = ":"; 233 | const MAP_LIKE: bool = true; 234 | } 235 | -------------------------------------------------------------------------------- /dash-rs-derive/src/field.rs: -------------------------------------------------------------------------------- 1 | use std::convert::TryFrom; 2 | 3 | use proc_macro2::{Ident, TokenStream}; 4 | use quote::{format_ident, quote}; 5 | use syn::{ 6 | parse::{discouraged::Speculative, Parse}, 7 | parse_quote, 8 | spanned::Spanned, 9 | Error, Field, Lifetime, LitInt, LitStr, Meta, MetaList, Result, Token, Type, 10 | }; 11 | 12 | use crate::utils; 13 | 14 | #[allow(clippy::large_enum_variant)] // doesn't matter, we're in a proc-macro 15 | pub enum FieldMapping { 16 | /// An internal field that is mapped 1:1 to an API field 17 | OneToOne(OneToOne), 18 | 19 | /// An API field that has no corresponding internal field. 20 | /// 21 | /// These get initialized to [`Default::default`] during deserialization. 22 | NoIndex { field: Ident }, 23 | } 24 | 25 | pub enum LitIndex { 26 | Int(LitInt), 27 | Str(LitStr), 28 | } 29 | 30 | pub struct OneToOne { 31 | /// The index of this field in the internal data format 32 | pub index: LitIndex, 33 | 34 | /// The API field to which this [`InternalField`] is mapped 35 | pub field: Ident, 36 | 37 | /// The type of the API field associated with this internal field 38 | pub api_type: Type, 39 | 40 | /// Attributes to pass through as #[serde(...)] attributes in the internal structures 41 | pub passthrough: Vec, 42 | } 43 | 44 | impl OneToOne { 45 | fn ser_type(&self, lifetime: &Lifetime) -> Type { 46 | let api_type = &self.api_type; 47 | 48 | parse_quote! { 49 | <#api_type as crate::serde::InternalProxy>::SerializeProxy<#lifetime> 50 | } 51 | } 52 | 53 | fn de_type(&self) -> Type { 54 | let api_type = &self.api_type; 55 | parse_quote! { 56 | <#api_type as crate::serde::InternalProxy>::DeserializeProxy 57 | } 58 | } 59 | 60 | fn index(&self) -> String { 61 | match &self.index { 62 | LitIndex::Int(lit_int) => lit_int.base10_digits().to_string(), 63 | LitIndex::Str(lit_str) => lit_str.value(), 64 | } 65 | } 66 | 67 | fn internal_name(&self) -> Ident { 68 | format_ident!("index_{}", self.index()) 69 | } 70 | 71 | fn field_tokens(&self, ty: Type) -> proc_macro2::TokenStream { 72 | let serde_name = self.index(); 73 | let field_name = self.internal_name(); 74 | let passthrough = &self.passthrough; 75 | 76 | if utils::type_contains_lifetime(&ty) { 77 | quote! { 78 | #[serde(rename = #serde_name)] 79 | #[serde(borrow)] 80 | #( 81 | #[serde(#passthrough)] 82 | )* 83 | pub #field_name: #ty, 84 | } 85 | } else { 86 | quote! { 87 | #[serde(rename = #serde_name)] 88 | #( 89 | #[serde(#passthrough)] 90 | )* 91 | pub #field_name: #ty, 92 | } 93 | } 94 | } 95 | 96 | pub fn ser_field_tokens(&self, lifetime: &Lifetime) -> proc_macro2::TokenStream { 97 | self.field_tokens(self.ser_type(lifetime)) 98 | } 99 | 100 | pub fn de_field_tokens(&self) -> proc_macro2::TokenStream { 101 | self.field_tokens(self.de_type()) 102 | } 103 | 104 | pub fn serialize(&self) -> proc_macro2::TokenStream { 105 | let field_name = self.internal_name(); 106 | let field = &self.field; 107 | 108 | quote! { 109 | #field_name: self.#field.to_serialize_proxy(), 110 | } 111 | } 112 | 113 | pub fn deserialize(&self) -> proc_macro2::TokenStream { 114 | let field_name = self.internal_name(); 115 | let field = &self.field; 116 | let api_type = &self.api_type; 117 | 118 | quote! { 119 | #field: <#api_type>::from_deserialize_proxy(internal.#field_name), 120 | } 121 | } 122 | } 123 | 124 | impl FieldMapping { 125 | pub fn ser_field_tokens(&self, lifetime: &Lifetime) -> TokenStream { 126 | match self { 127 | FieldMapping::OneToOne(inner) => inner.ser_field_tokens(lifetime), 128 | FieldMapping::NoIndex { .. } => quote!(), 129 | } 130 | } 131 | 132 | pub fn de_field_tokens(&self) -> TokenStream { 133 | match self { 134 | FieldMapping::OneToOne(inner) => inner.de_field_tokens(), 135 | FieldMapping::NoIndex { .. } => quote!(), 136 | } 137 | } 138 | 139 | pub fn serialize(&self) -> TokenStream { 140 | match self { 141 | FieldMapping::OneToOne(inner) => inner.serialize(), 142 | FieldMapping::NoIndex { .. } => quote!(), 143 | } 144 | } 145 | 146 | pub fn deserialize(&self) -> TokenStream { 147 | match self { 148 | FieldMapping::OneToOne(inner) => inner.deserialize(), 149 | FieldMapping::NoIndex { field } => quote! { 150 | #field: Default::default(), 151 | }, 152 | } 153 | } 154 | } 155 | 156 | #[derive(Default)] 157 | enum FieldMappingBuilder { 158 | #[default] 159 | Initial, 160 | OneToOne { 161 | index: Option, 162 | passthrough: Vec, 163 | }, 164 | NoIndex, 165 | } 166 | 167 | impl FieldMappingBuilder { 168 | fn with_index(&mut self, index: LitIndex) -> bool { 169 | match std::mem::take(self) { 170 | FieldMappingBuilder::Initial => { 171 | *self = FieldMappingBuilder::OneToOne { 172 | index: Some(index), 173 | passthrough: Vec::new(), 174 | } 175 | }, 176 | FieldMappingBuilder::OneToOne { index: None, passthrough } => { 177 | *self = FieldMappingBuilder::OneToOne { 178 | index: Some(index), 179 | passthrough, 180 | } 181 | }, 182 | _ => return false, 183 | } 184 | true 185 | } 186 | 187 | fn no_index(&mut self) -> bool { 188 | match std::mem::take(self) { 189 | FieldMappingBuilder::Initial => *self = FieldMappingBuilder::NoIndex, 190 | _ => return false, 191 | } 192 | true 193 | } 194 | 195 | fn with_passthrough(&mut self, tokens: TokenStream) -> bool { 196 | match std::mem::take(self) { 197 | FieldMappingBuilder::Initial => { 198 | *self = FieldMappingBuilder::OneToOne { 199 | index: None, 200 | passthrough: vec![tokens], 201 | } 202 | }, 203 | FieldMappingBuilder::OneToOne { index, mut passthrough } => { 204 | passthrough.push(tokens); 205 | *self = FieldMappingBuilder::OneToOne { index, passthrough } 206 | }, 207 | FieldMappingBuilder::NoIndex => return false, 208 | } 209 | true 210 | } 211 | } 212 | 213 | impl TryFrom for FieldMapping { 214 | type Error = Error; 215 | 216 | fn try_from(field: Field) -> Result { 217 | let span = field.span(); 218 | let api_type = field.ty; 219 | 220 | let mut builder = FieldMappingBuilder::Initial; 221 | 222 | for attr in field.attrs { 223 | let Meta::List(MetaList { path, tokens, .. }) = attr.meta else { 224 | continue; 225 | }; 226 | 227 | if path.segments.len() != 1 || path.segments[0].ident != "dash" { 228 | continue; 229 | } 230 | 231 | let build_success = match syn::parse2::(tokens)? { 232 | DashAttribute::Index(idx) => builder.with_index(idx), 233 | DashAttribute::PassthroughToSerde(tokens) => builder.with_passthrough(tokens), 234 | DashAttribute::NoIndex => builder.no_index(), 235 | }; 236 | 237 | if !build_success { 238 | return Err(Error::new(span, "unexpected #[dash(...)] attribute")); 239 | } 240 | } 241 | 242 | let field = field.ident.unwrap(); 243 | 244 | match builder { 245 | FieldMappingBuilder::Initial => Err(Error::new_spanned(field, "missing #[dash(...)] attribute")), 246 | FieldMappingBuilder::OneToOne { 247 | index: Some(index), 248 | passthrough, 249 | } => Ok(FieldMapping::OneToOne(OneToOne { 250 | index, 251 | field, 252 | api_type, 253 | passthrough, 254 | })), 255 | FieldMappingBuilder::OneToOne { index: None, .. } => Err(Error::new_spanned(field, "missing #[dash(index = ...)] attribute")), 256 | FieldMappingBuilder::NoIndex => Ok(FieldMapping::NoIndex { field }), 257 | } 258 | } 259 | } 260 | 261 | enum DashAttribute { 262 | Index(LitIndex), 263 | NoIndex, 264 | PassthroughToSerde(TokenStream), 265 | } 266 | 267 | impl Parse for DashAttribute { 268 | fn parse(input: syn::parse::ParseStream) -> Result { 269 | let fork = input.fork(); 270 | 271 | if let Ok(key) = fork.parse::() { 272 | if key == "no_index" { 273 | input.advance_to(&fork); 274 | 275 | return Ok(DashAttribute::NoIndex); 276 | } 277 | if key == "index" { 278 | let _ = fork.parse::()?; 279 | let lookahead = fork.lookahead1(); 280 | 281 | let lit = if lookahead.peek(LitInt) { 282 | LitIndex::Int(fork.parse()?) 283 | } else if lookahead.peek(LitStr) { 284 | LitIndex::Str(fork.parse()?) 285 | } else { 286 | return Err(lookahead.error()); 287 | }; 288 | 289 | input.advance_to(&fork); 290 | 291 | return Ok(DashAttribute::Index(lit)); 292 | } 293 | } 294 | 295 | input.parse().map(DashAttribute::PassthroughToSerde) 296 | } 297 | } 298 | -------------------------------------------------------------------------------- /src/serde/ser/indexed.rs: -------------------------------------------------------------------------------- 1 | use crate::serde::ser::error::Error; 2 | use itoa::{Buffer, Integer}; 3 | use serde::{ 4 | ser::{Error as _, Impossible, SerializeStruct}, 5 | Serialize, Serializer, 6 | }; 7 | use std::{fmt::Display, io::Write}; 8 | 9 | #[allow(missing_debug_implementations)] 10 | pub struct IndexedSerializer { 11 | delimiter: &'static [u8], 12 | writer: W, 13 | map_like: bool, 14 | 15 | /// Value indicating whether this serializer has already serialized something. This is used to 16 | /// check if we need to prepend the delimiter to the next field. 17 | /// 18 | /// Note that this field cannot simply be replaced in favor of a `writer.len() == 0` check. In 19 | /// case of list-like serialization the first field could be `None`, which is serialized to the 20 | /// empty string. In that case, a delimiter needs to be appended, but since the writer would 21 | /// still be empty, no delimiter would be added. 22 | is_start: bool, 23 | } 24 | 25 | impl IndexedSerializer 26 | where 27 | W: Write, 28 | { 29 | pub fn new(delimiter: &'static str, writer: W, map_like: bool) -> Self { 30 | IndexedSerializer { 31 | delimiter: delimiter.as_bytes(), 32 | writer, 33 | map_like, 34 | is_start: true, 35 | } 36 | } 37 | 38 | fn append_integer(&mut self, int: I) -> Result<(), Error> { 39 | if self.is_start { 40 | self.is_start = false; 41 | } else { 42 | self.writer.write_all(self.delimiter)?; 43 | } 44 | 45 | let mut buffer = Buffer::new(); 46 | self.writer.write(buffer.format(int).as_bytes()).map_err(Error::custom)?; 47 | 48 | Ok(()) 49 | } 50 | 51 | fn append_display(&mut self, val: D) -> Result<(), Error> { 52 | if self.is_start { 53 | self.is_start = false; 54 | } else { 55 | self.writer.write_all(self.delimiter)?; 56 | } 57 | 58 | write!(&mut self.writer, "{}", val).map_err(Error::custom)?; 59 | 60 | Ok(()) 61 | } 62 | 63 | fn append(&mut self, s: &str) -> Result<(), Error> { 64 | if self.is_start { 65 | self.is_start = false; 66 | } else { 67 | self.writer.write_all(self.delimiter)?; 68 | } 69 | 70 | self.writer.write_all(s.as_bytes())?; 71 | Ok(()) 72 | } 73 | } 74 | 75 | impl Serializer for &mut IndexedSerializer { 76 | type Error = Error; 77 | type Ok = (); 78 | type SerializeMap = Impossible<(), Error>; 79 | type SerializeSeq = Impossible<(), Error>; 80 | type SerializeStruct = Self; 81 | type SerializeStructVariant = Impossible<(), Error>; 82 | type SerializeTuple = Impossible<(), Error>; 83 | type SerializeTupleStruct = Impossible<(), Error>; 84 | type SerializeTupleVariant = Impossible<(), Error>; 85 | 86 | fn serialize_bool(self, v: bool) -> Result { 87 | self.append(if v { "1" } else { "0" }) 88 | } 89 | 90 | fn serialize_i8(self, v: i8) -> Result { 91 | self.append_integer(v) 92 | } 93 | 94 | fn serialize_i16(self, v: i16) -> Result { 95 | self.append_integer(v) 96 | } 97 | 98 | fn serialize_i32(self, v: i32) -> Result { 99 | self.append_integer(v) 100 | } 101 | 102 | fn serialize_i64(self, v: i64) -> Result { 103 | self.append_integer(v) 104 | } 105 | 106 | fn serialize_u8(self, v: u8) -> Result { 107 | self.append_integer(v) 108 | } 109 | 110 | fn serialize_u16(self, v: u16) -> Result { 111 | self.append_integer(v) 112 | } 113 | 114 | fn serialize_u32(self, v: u32) -> Result { 115 | self.append_integer(v) 116 | } 117 | 118 | fn serialize_u64(self, v: u64) -> Result { 119 | self.append_integer(v) 120 | } 121 | 122 | // Why we do not use dtoa or ryu here: Those libraries append an unneeded 123 | // '.0' suffix for floating point numbers that represent integers. Robtop's 124 | // formatting does not do this, and we'd like to match RobTop formatting 125 | // as closely as possible (if only so that roundtrip tests do not need 126 | // to deal with a myriad of exceptions). 127 | // Therefore, use the standard library, despite it being up to 4x slower 128 | // at printing floats. This is serialization, so performance is less of a 129 | // concern. 130 | fn serialize_f32(self, v: f32) -> Result { 131 | self.append_display(v) 132 | } 133 | 134 | fn serialize_f64(self, v: f64) -> Result { 135 | self.append_display(v) 136 | } 137 | 138 | fn serialize_char(self, v: char) -> Result { 139 | // We don't need allocations for appending a single char 140 | // A buffer of size 4 is always enough to encode a char 141 | let mut char_buffer: [u8; 4] = [0; 4]; 142 | self.append(v.encode_utf8(&mut char_buffer)) 143 | } 144 | 145 | fn serialize_str(self, v: &str) -> Result { 146 | self.append(v) 147 | } 148 | 149 | // Here we serialize bytes by base64 encoding them, so it's always valid in Geometry Dash's format 150 | fn serialize_bytes(self, v: &[u8]) -> Result { 151 | use base64::{engine::general_purpose::URL_SAFE, write::EncoderWriter}; 152 | let mut enc = EncoderWriter::new(&mut self.writer, &URL_SAFE); 153 | enc.write_all(v)?; 154 | enc.finish()?; 155 | Ok(()) 156 | } 157 | 158 | fn serialize_none(self) -> Result { 159 | self.writer.write_all(self.delimiter)?; 160 | Ok(()) 161 | } 162 | 163 | fn serialize_some(self, value: &T) -> Result 164 | where 165 | T: Serialize + ?Sized, 166 | { 167 | value.serialize(self) 168 | } 169 | 170 | fn serialize_unit(self) -> Result { 171 | Err(Error::Unsupported("serialize_unit")) 172 | } 173 | 174 | fn serialize_unit_struct(self, _name: &'static str) -> Result { 175 | Err(Error::Unsupported("serialize_unit_struct")) 176 | } 177 | 178 | fn serialize_unit_variant(self, _name: &'static str, _variant_index: u32, _variant: &'static str) -> Result { 179 | Err(Error::Unsupported("serialize_unit_variant")) 180 | } 181 | 182 | fn serialize_newtype_struct(self, _name: &'static str, _value: &T) -> Result 183 | where 184 | T: Serialize + ?Sized, 185 | { 186 | Err(Error::Unsupported("serialize_newtype_struct")) 187 | } 188 | 189 | fn serialize_newtype_variant( 190 | self, _name: &'static str, _variant_index: u32, _variant: &'static str, _value: &T, 191 | ) -> Result 192 | where 193 | T: Serialize + ?Sized, 194 | { 195 | Err(Error::Unsupported("serialize_newtype_variant")) 196 | } 197 | 198 | fn serialize_seq(self, _len: Option) -> Result { 199 | Err(Error::Unsupported("serialize_seq")) 200 | } 201 | 202 | fn serialize_tuple(self, _len: usize) -> Result { 203 | Err(Error::Unsupported("serialize_tuple")) 204 | } 205 | 206 | fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result { 207 | Err(Error::Unsupported("serialize_tuple_struct")) 208 | } 209 | 210 | fn serialize_tuple_variant( 211 | self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, 212 | ) -> Result { 213 | Err(Error::Unsupported("serialize_tuple_variant")) 214 | } 215 | 216 | fn serialize_map(self, _len: Option) -> Result { 217 | Err(Error::Unsupported("serialize_map")) 218 | } 219 | 220 | fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { 221 | // We don't store the struct name and the amount of fields doesn't matter 222 | Ok(self) 223 | } 224 | 225 | fn serialize_struct_variant( 226 | self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, 227 | ) -> Result { 228 | Err(Error::Unsupported("serialize_struct_variant")) 229 | } 230 | 231 | fn collect_str(self, _value: &T) -> Result 232 | where 233 | T: Display + ?Sized, 234 | { 235 | Err(Error::Unsupported("collect_str")) 236 | } 237 | } 238 | 239 | impl SerializeStruct for &mut IndexedSerializer { 240 | type Ok = (); 241 | type Error = Error; 242 | 243 | fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> 244 | where 245 | T: Serialize + ?Sized, 246 | { 247 | if self.map_like { 248 | self.append(key)?; 249 | } 250 | value.serialize(&mut **self) 251 | } 252 | 253 | fn end(self) -> Result { 254 | Ok(()) 255 | } 256 | } 257 | 258 | #[cfg(test)] 259 | mod tests { 260 | use serde::Serializer; 261 | 262 | use super::IndexedSerializer; 263 | 264 | // Test that documents a robtop quirk: Floats without decimal part are represented as integer 265 | #[test] 266 | fn serialize_float_without_decimal_part_serializes_as_integer() { 267 | let mut buffer = Vec::new(); 268 | let mut serializer = IndexedSerializer::new(":", &mut buffer, false); 269 | serializer.serialize_f64(11.0f64).unwrap(); 270 | assert_eq!("11", std::str::from_utf8(buffer.as_slice()).unwrap()); 271 | } 272 | } 273 | -------------------------------------------------------------------------------- /src/serde/thunk.rs: -------------------------------------------------------------------------------- 1 | use base64::{ 2 | alphabet::URL_SAFE, 3 | engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig}, 4 | DecodeError, DecodeSliceError, Engine, 5 | }; 6 | use percent_encoding::{percent_decode_str, utf8_percent_encode, AsciiSet, CONTROLS}; 7 | use serde::{ser::Error as _, Deserialize, Serialize, Serializer}; 8 | use std::{ 9 | borrow::{Borrow, Cow}, 10 | mem, 11 | num::ParseIntError, 12 | str::Utf8Error, 13 | string::FromUtf8Error, 14 | }; 15 | use thiserror::Error; 16 | 17 | /// Enum modelling the different errors that can occur during processing of a [`Thunk`] 18 | /// 19 | /// ## Why is this a seperate enum 20 | /// One might wonder why this enum exists, and why we don't simply reuse 21 | /// [`Error`](::serde::de::Error). The main reason is that I do not want to include variants 22 | /// in that enum that do not occur during the actual deserialization phase. The second reason has to 23 | /// do with lifetimes: Just using `Error<'a>` for the return type in the [`ThunkProcessor`] functions 24 | /// used by [`Thunk`] is not possible. The reason for that is that processing errors are returned in 25 | /// contexts where data is transformed into owned representations. This means we cannot simply reuse 26 | /// the lifetime the input data is bound to for our errors, as the errors potentially have to 27 | /// outlive the input data (in the worst case they have to be `'static`). Adding a new lifetime to 28 | /// `Thunk` just to use that for the error type is obviously impractical, however it is possible to 29 | /// use `Error<'static>`, which at least doesn't add more downsides. However it still leaves us with 30 | /// an error enum dealing with too much stuff. 31 | #[derive(Debug, Error)] 32 | pub enum ProcessError { 33 | /// Some utf8 encoding error occurred during processing 34 | #[error("{0}")] 35 | Utf8(#[from] Utf8Error), 36 | 37 | /// Some utf8 encoding error occurred while processing after some backing storage was allocated 38 | #[error("{0}")] 39 | FromUtf8(#[from] FromUtf8Error), 40 | 41 | /// Some base64 decoding error occurred during processing 42 | #[error("{0}")] 43 | Base64(#[from] DecodeSliceError), 44 | 45 | /// Some error occurred when parsing a number 46 | #[error("{0}")] 47 | IntParse(#[from] ParseIntError), 48 | 49 | /// Incorrect number of items when parsing a comma separated list (e.g. if an RGB list only has 50 | /// two entries) 51 | #[error("Incorrect number of items in comma separated list. Expected {expected}")] 52 | IncorrectLength { expected: usize }, 53 | 54 | #[error("Received value that cannot be represented in Geometry Dash data format")] 55 | Unrepresentable, 56 | } 57 | 58 | impl From for ProcessError { 59 | fn from(value: DecodeError) -> Self { 60 | ProcessError::Base64(DecodeSliceError::DecodeError(value)) 61 | } 62 | } 63 | 64 | /// Input value whose further deserialization has been delayed 65 | /// 66 | /// This is often used if further processing would require an allocation (for instance when using 67 | /// base64 decoding) or be very long (for instance parsing level data). 68 | /// 69 | /// The required further processing should happen in the [`ThunkProcessor`] implementation, which is 70 | /// invoked by calling [`Thunk::process`]. Think of it as [`Cow`] with extra steps and potential new 71 | /// allocations instead of cloning. 72 | #[derive(Debug, Eq, Clone, Deserialize)] 73 | #[serde(untagged)] 74 | pub enum Thunk<'a, C: ThunkProcessor> { 75 | #[serde(skip)] 76 | Unprocessed(Cow<'a, str>), 77 | Processed(C::Output<'a>), 78 | } 79 | 80 | impl<'a, 'b, P: ThunkProcessor> PartialEq> for Thunk<'a, P> 81 | where 82 | P::Output<'a>: PartialEq>, 83 | { 84 | fn eq(&self, other: &Thunk<'b, P>) -> bool { 85 | match (self, other) { 86 | (Thunk::Processed(o1), Thunk::Processed(o2)) => o1 == o2, 87 | (Thunk::Unprocessed(s1), Thunk::Unprocessed(s2)) => s1 == s2, 88 | _ => false, 89 | } 90 | } 91 | } 92 | 93 | impl<'a, C: ThunkProcessor> Serialize for Thunk<'a, C> 94 | where 95 | for<'b> C::Output<'b>: Serialize, 96 | { 97 | fn serialize(&self, serializer: S) -> Result<::Ok, ::Error> 98 | where 99 | S: Serializer, 100 | { 101 | match self { 102 | Thunk::Unprocessed(unprocessed) => C::from_unprocessed(Cow::Borrowed(unprocessed)) 103 | .map_err(S::Error::custom)? 104 | .serialize(serializer), 105 | Thunk::Processed(processed) => processed.serialize(serializer), 106 | } 107 | } 108 | } 109 | 110 | /// Trait describing how thunks should process their data 111 | /// 112 | /// This trait provides the means to translate from and into RobTop's representation for thunked 113 | /// data, while not being used in the (de)serialization into any other data format. 114 | pub trait ThunkProcessor { 115 | type Error: std::error::Error; 116 | type Output<'a>; 117 | 118 | /// Takes some data from the [`Thunk::Unprocessed`] variant and processes it 119 | /// 120 | /// This function is *not* called automatically during deserialization from a RobTop data 121 | /// format. 122 | fn from_unprocessed(unprocessed: Cow) -> Result, Self::Error>; 123 | 124 | /// Takes some processed thunk value and converts it into RobTop-representation 125 | fn as_unprocessed<'b>(processed: &'b Self::Output<'_>) -> Result, Self::Error>; 126 | 127 | /// The presence of this function essentially forces [`ThunkProcessor::Output`] to be covariant 128 | /// in its lifetime. 129 | /// 130 | /// We need it to be covariant so that functions like [`Thunk::as_unprocessed`] can be implemented. 131 | /// Since the lifetime associated with the output is assumed to be originating from some `&'a str`, 132 | /// and should only describe subslices of said input string, enforcing covariance on this trait should 133 | /// cause no limitations in praxis (e.g. all implementations here should just be able to return `output` 134 | /// identically). 135 | /// 136 | /// We need this function due to a limitation of GATs, where for soundness reasons they have to be assumed 137 | /// to be invariant, yet the language provides no way for a trait to explicitly require different variance. 138 | fn downcast_output_lifetime<'b: 'c, 'c, 's>(output: &'s Self::Output<'b>) -> &'s Self::Output<'c>; 139 | } 140 | 141 | impl<'a, C: ThunkProcessor> Thunk<'a, C> { 142 | /// If this is a [`Thunk::Unprocessed`] variant, calls [`ThunkProcessor::from_unprocessed`] and 143 | /// returns [`Thunk::Processed`]. Simply returns `self` if this is a [`Thunk::Processed`] 144 | /// variant 145 | pub fn process(&mut self) -> Result<&mut C::Output<'a>, C::Error> { 146 | if let Thunk::Unprocessed(raw_data) = self { 147 | *self = Thunk::Processed(C::from_unprocessed(mem::take(raw_data))?) 148 | } 149 | 150 | match self { 151 | Thunk::Processed(p) => Ok(p), 152 | _ => unreachable!(), 153 | } 154 | } 155 | 156 | pub fn as_unprocessed(&self) -> Result, C::Error> { 157 | match self { 158 | Thunk::Unprocessed(unprocessed) => Ok(Cow::Borrowed(unprocessed)), 159 | Thunk::Processed(content) => C::as_unprocessed(content), 160 | } 161 | } 162 | 163 | /// Returns the result of processing this [`Thunk`] 164 | pub fn into_processed(self) -> Result, C::Error> { 165 | match self { 166 | Thunk::Unprocessed(unprocessed) => C::from_unprocessed(unprocessed), 167 | Thunk::Processed(p) => Ok(p), 168 | } 169 | } 170 | 171 | pub fn as_processed<'b>(&'b self) -> Result>, C::Error> 172 | where 173 | C::Output<'b>: Clone, 174 | { 175 | match self { 176 | Thunk::Unprocessed(unprocessed) => C::from_unprocessed(Cow::Borrowed(unprocessed.borrow())).map(Cow::Owned), 177 | Thunk::Processed(processed) => Ok(Cow::Borrowed(C::downcast_output_lifetime(processed))), 178 | } 179 | } 180 | } 181 | 182 | /// Set of characters RobTop encodes when doing percent encoding 183 | /// 184 | /// This is a subset of [`percent_encoding::NON_ALPHANUMERIC`], since that encodes too many 185 | /// characters 186 | pub const ROBTOP_SET: &AsciiSet = &CONTROLS 187 | .add(b' ') // TODO: investigate if this is part of the set. Song links never contain spaces 188 | .add(b':') 189 | .add(b'/') 190 | .add(b'?') 191 | .add(b'~'); 192 | 193 | #[derive(Debug, Eq, PartialEq, Serialize, Deserialize, Clone, Copy)] 194 | pub struct PercentDecoder; 195 | 196 | impl ThunkProcessor for PercentDecoder { 197 | type Error = ProcessError; 198 | type Output<'a> = Cow<'a, str>; 199 | 200 | fn from_unprocessed(unprocessed: Cow) -> Result, Self::Error> { 201 | match unprocessed { 202 | Cow::Borrowed(unprocessed) => percent_decode_str(unprocessed).decode_utf8().map_err(ProcessError::Utf8), 203 | Cow::Owned(unprocessed) => match percent_decode_str(&unprocessed).decode_utf8().map_err(ProcessError::Utf8)? { 204 | Cow::Owned(decoded) => Ok(Cow::Owned(decoded)), 205 | _ => Ok(Cow::Owned(unprocessed)), 206 | }, 207 | } 208 | } 209 | 210 | fn as_unprocessed<'b>(processed: &'b Self::Output<'_>) -> Result, Self::Error> { 211 | Ok(utf8_percent_encode(processed.as_ref(), ROBTOP_SET).into()) 212 | } 213 | 214 | fn downcast_output_lifetime<'b: 'c, 'c, 's>(output: &'s Self::Output<'b>) -> &'s Self::Output<'c> { 215 | output 216 | } 217 | } 218 | 219 | /// Base64 decoder configuration that most closely matches what Geometry Dash is doing. 220 | /// 221 | /// That generally means "be as lenient as possible", aka 222 | /// - Do not care whether padding characters ('=') are present at the end of the base64 encoded string 223 | /// - Do not care if the base64 encoded string is obviously truncated (and try to simply decode as much as you can) 224 | pub const ROBTOP_BASE64_CONFIG: GeneralPurpose = GeneralPurpose::new( 225 | &URL_SAFE, 226 | GeneralPurposeConfig::new() 227 | .with_encode_padding(true) 228 | .with_decode_padding_mode(DecodePaddingMode::Indifferent) 229 | .with_decode_allow_trailing_bits(true), 230 | ); 231 | 232 | #[derive(Debug, Eq, PartialEq, Serialize, Deserialize, Clone, Copy)] 233 | pub struct Base64Decoder; 234 | 235 | impl ThunkProcessor for Base64Decoder { 236 | type Error = ProcessError; 237 | type Output<'a> = Cow<'a, str>; 238 | 239 | fn from_unprocessed(unprocessed: Cow) -> Result, Self::Error> { 240 | let vec = ROBTOP_BASE64_CONFIG.decode(&*unprocessed)?; 241 | let string = String::from_utf8(vec).map_err(ProcessError::FromUtf8)?; 242 | 243 | Ok(Cow::Owned(string)) 244 | } 245 | 246 | fn as_unprocessed<'b>(processed: &'b Self::Output<'_>) -> Result, Self::Error> { 247 | Ok(Cow::Owned(ROBTOP_BASE64_CONFIG.encode(&**processed))) 248 | } 249 | 250 | fn downcast_output_lifetime<'b: 'c, 'c, 's>(output: &'s Self::Output<'b>) -> &'s Self::Output<'c> { 251 | output 252 | } 253 | } 254 | 255 | #[cfg(test)] 256 | pub mod tests { 257 | use std::borrow::Cow; 258 | 259 | use super::{Base64Decoder, ThunkProcessor}; 260 | 261 | #[test] 262 | fn test_base64_decoder_accepts_truncated_inputs() { 263 | let truncated_description = Base64Decoder::from_unprocessed(Cow::Borrowed("Tml2ZWwgZGUgMiBqdWdhZG9yZXMgcXVlIHB1ZWRlcyBjb21wbGV0YXIgc29sbyBvIGNvbiB1biBhbWlnbyAoZXMgbWVub3MgY29tcGxpY2FkbykuIEVsIG5pdmVsIHlhIG5vIHR")).unwrap(); 264 | assert_eq!( 265 | truncated_description, 266 | "Nivel de 2 jugadores que puedes completar solo o con un amigo (es menos complicado). El nivel ya no t" 267 | ); 268 | } 269 | } 270 | -------------------------------------------------------------------------------- /src/serde/de/indexed.rs: -------------------------------------------------------------------------------- 1 | //! Module containing the deserializer for robtop's indexed data format 2 | 3 | use super::error::Error; 4 | use serde::{ 5 | de, 6 | de::{DeserializeSeed, Visitor}, 7 | Deserializer, 8 | }; 9 | use std::str::Split; 10 | 11 | // Special versions of the trace and debug macros used in this module that are statically disabled 12 | // in release mode. We do not want to explicitly pass "release_max_level_off" feature to log because 13 | // we're in a library crate, and since features are additive, that would turn off release mode 14 | // logging in every crate that depends on dash-rs. 15 | macro_rules! dev_trace { 16 | ($($t:tt)*) => { 17 | #[cfg(dash_rs_dev_debug)] 18 | log::trace!($($t)*) 19 | }; 20 | } 21 | 22 | macro_rules! dev_debug { 23 | ($($t:tt)*) => { 24 | #[cfg(dash_rs_dev_debug)] 25 | log::debug!($($t)*) 26 | }; 27 | } 28 | 29 | /// Deserializer for RobTop's indexed data format 30 | /// 31 | /// This format is used in server responses and when storing model.level data. It is based around 32 | /// the idea to concatenate all fields of an object together, using a specific character sequence as 33 | /// a separator. 34 | /// 35 | /// There are two variants of this format: 36 | /// 37 | /// * **Map-like**: Every second field is an key, which is almost always an integer. This key is 38 | /// unique and tells us which field follows. 39 | /// * **List-like**: There are no keys, identification of 40 | /// fields has to occur based on the how many-th field they are. In this case the deserializer 41 | /// generates artificial indices (which just count up by 1 for each field) for error messages. 42 | #[derive(Debug)] 43 | pub struct IndexedDeserializer<'de> { 44 | map_like: bool, 45 | splitter: Split<'de, &'de str>, 46 | input: &'de str, 47 | end_of_current_token: usize, 48 | delimiter: &'de str, 49 | } 50 | 51 | impl<'de> IndexedDeserializer<'de> { 52 | /// Constructs a new `IndexedDeserializer` 53 | /// 54 | /// # Arguments 55 | /// * *source*: The input string to deserialize 56 | /// * *delimiter*: The delimiter separating the individual fields 57 | /// * *map_like*: Whether the input is in map-like format or not (meaning it is in list-like 58 | /// format) 59 | pub fn new(source: &'de str, delimiter: &'static str, map_like: bool) -> Self { 60 | dev_trace!("Deserializing {} with delimiter '{}', maplike {}", source, delimiter, map_like); 61 | 62 | IndexedDeserializer { 63 | splitter: source.split(delimiter), 64 | map_like, 65 | input: source, 66 | end_of_current_token: source.as_ptr() as usize, 67 | delimiter, 68 | } 69 | } 70 | 71 | /// Returns the next token in the input string and consumes it. 72 | /// 73 | /// If the input string has already been fully consumed, returns [`Error::Eof`]. If the 74 | /// non-consumed part of the input starts with the delimiter, returns the empty string. 75 | /// Otherwise returns the sub-slice into the source representing the next token. 76 | fn consume_token(&mut self) -> Option<&'de str> { 77 | let tok = self.splitter.next()?; 78 | self.end_of_current_token = tok.as_ptr() as usize + tok.len(); 79 | 80 | dev_trace!("Splitting off token {}, remaining input: {}", tok, &self.input[self.position()..]); 81 | 82 | Some(tok) 83 | } 84 | 85 | fn position(&self) -> usize { 86 | self.end_of_current_token - self.input.as_ptr() as usize 87 | } 88 | 89 | fn nth_last(&self, nth: usize) -> Option<&'de str> { 90 | self.input[..self.position()].rsplit(self.delimiter).nth(nth - 1) 91 | } 92 | 93 | fn is_next_empty(&self) -> bool { 94 | &self.input[self.position() + self.delimiter.len()..self.position() + 2 * self.delimiter.len()] == self.delimiter 95 | } 96 | 97 | fn is_eof(&self) -> bool { 98 | self.input.len() <= self.position() 99 | } 100 | } 101 | 102 | macro_rules! delegate_to_from_str { 103 | ($deserialize_method:ident, $visitor_method:ident) => { 104 | fn $deserialize_method(self, visitor: V) -> Result<>::Value, Error<'de>> 105 | where 106 | V: Visitor<'de>, 107 | { 108 | let token = self.consume_token(); 109 | 110 | dev_trace!( 111 | "RobtopDeserializer::{} called called on {:?}", 112 | stringify!($deserialize_method), 113 | token 114 | ); 115 | 116 | let token = token.ok_or(Error::Eof)?; 117 | 118 | match token.parse() { 119 | Ok(parsed) => visitor.$visitor_method(parsed), 120 | Err(error) => Err(Error::Custom { 121 | message: error.to_string(), 122 | index: None, 123 | value: Some(token), 124 | }), 125 | } 126 | } 127 | }; 128 | } 129 | 130 | impl<'de> Deserializer<'de> for &mut IndexedDeserializer<'de> { 131 | type Error = Error<'de>; 132 | 133 | delegate_to_from_str!(deserialize_i8, visit_i8); 134 | 135 | delegate_to_from_str!(deserialize_i16, visit_i16); 136 | 137 | delegate_to_from_str!(deserialize_i32, visit_i32); 138 | 139 | delegate_to_from_str!(deserialize_i64, visit_i64); 140 | 141 | delegate_to_from_str!(deserialize_u8, visit_u8); 142 | 143 | delegate_to_from_str!(deserialize_u16, visit_u16); 144 | 145 | delegate_to_from_str!(deserialize_u32, visit_u32); 146 | 147 | delegate_to_from_str!(deserialize_u64, visit_u64); 148 | 149 | delegate_to_from_str!(deserialize_f32, visit_f32); 150 | 151 | delegate_to_from_str!(deserialize_f64, visit_f64); 152 | 153 | fn deserialize_any(self, _visitor: V) -> Result<>::Value, Error<'de>> 154 | where 155 | V: Visitor<'de>, 156 | { 157 | // the data format is by no means self describing 158 | Err(Error::Unsupported("deserialize_any")) 159 | } 160 | 161 | fn deserialize_bool(self, visitor: V) -> Result<>::Value, Error<'de>> 162 | where 163 | V: Visitor<'de>, 164 | { 165 | let token = self.consume_token(); 166 | 167 | dev_trace!("RobtopDeserializer::deserialize_bool called on {:?}", token); 168 | 169 | // Alright so robtop's encoding of boolean is the most inconsistent shit ever. The possible values 170 | // for `false` are "0" or the empty string. The possible values for `true` are 1, 2 or 10. While 171 | // this is no problem for serialization, the deserializer has no way of knowing what kinda of 172 | // boolean is being used and defaults to "0" for `false` and "1" for `true`. If some field deviates 173 | // from that, use a custom `deserialize_with`. Thanks. 174 | 175 | match token { 176 | Some("0") | Some("") | None => visitor.visit_bool(false), 177 | Some("1") | Some("2") | Some("10") => visitor.visit_bool(true), 178 | Some(value) => Err(Error::Custom { 179 | message: "Expected 0, 1, 2, 10 or the empty string".to_owned(), 180 | index: None, 181 | value: Some(value), 182 | }), 183 | } 184 | } 185 | 186 | fn deserialize_char(self, _visitor: V) -> Result<>::Value, Error<'de>> 187 | where 188 | V: Visitor<'de>, 189 | { 190 | Err(Error::Unsupported("deserialize_char")) 191 | } 192 | 193 | fn deserialize_str(self, visitor: V) -> Result<>::Value, Error<'de>> 194 | where 195 | V: Visitor<'de>, 196 | { 197 | let token = self.consume_token(); 198 | 199 | dev_trace!("RobtopDeserializer::deserialize_str called on {:?}", token); 200 | 201 | visitor.visit_borrowed_str(token.ok_or(Error::Eof)?) 202 | } 203 | 204 | fn deserialize_string(self, visitor: V) -> Result<>::Value, Error<'de>> 205 | where 206 | V: Visitor<'de>, 207 | { 208 | let token = self.consume_token(); 209 | 210 | dev_trace!("RobtopDeserializer::deserialize_string called on {:?}", token); 211 | 212 | visitor.visit_borrowed_str(token.ok_or(Error::Eof)?) 213 | } 214 | 215 | fn deserialize_bytes(self, _visitor: V) -> Result<>::Value, Error<'de>> 216 | where 217 | V: Visitor<'de>, 218 | { 219 | Err(Error::Unsupported("deserialize_bytes")) 220 | } 221 | 222 | fn deserialize_byte_buf(self, _visitor: V) -> Result<>::Value, Error<'de>> 223 | where 224 | V: Visitor<'de>, 225 | { 226 | Err(Error::Unsupported("deserialize_byte_buf")) 227 | } 228 | 229 | fn deserialize_option(self, visitor: V) -> Result<>::Value, Error<'de>> 230 | where 231 | V: Visitor<'de>, 232 | { 233 | if self.is_eof() || self.is_next_empty() { 234 | dev_trace!("RobtopDeserializer::deserialize_option called on empty string or EOF"); 235 | 236 | let _ = self.consume_token(); // potentially skip the empty string. Explicitly ignore the return value in case we have Error::Eof 237 | 238 | visitor.visit_none() 239 | } else { 240 | dev_trace!("RobtopDeserializer::deserialize_option called 'Some(_)')"); 241 | 242 | visitor.visit_some(self) 243 | } 244 | } 245 | 246 | fn deserialize_unit(self, _visitor: V) -> Result<>::Value, Error<'de>> 247 | where 248 | V: Visitor<'de>, 249 | { 250 | Err(Error::Unsupported("deserialize_unit")) 251 | } 252 | 253 | fn deserialize_unit_struct(self, _name: &'static str, _visitor: V) -> Result<>::Value, Error<'de>> 254 | where 255 | V: Visitor<'de>, 256 | { 257 | Err(Error::Unsupported("deserialize_unit_struct")) 258 | } 259 | 260 | fn deserialize_newtype_struct(self, _name: &'static str, _visitor: V) -> Result<>::Value, Error<'de>> 261 | where 262 | V: Visitor<'de>, 263 | { 264 | Err(Error::Unsupported("deserialize_newtype_struct")) 265 | } 266 | 267 | fn deserialize_seq(self, visitor: V) -> Result<>::Value, Error<'de>> 268 | where 269 | V: Visitor<'de>, 270 | { 271 | visitor.visit_seq(SeqAccess { 272 | deserializer: self, 273 | index: 0, 274 | }) 275 | } 276 | 277 | fn deserialize_tuple(self, _len: usize, _visitor: V) -> Result<>::Value, Error<'de>> 278 | where 279 | V: Visitor<'de>, 280 | { 281 | Err(Error::Unsupported("deserialize_tuple")) 282 | } 283 | 284 | fn deserialize_tuple_struct(self, _name: &'static str, _len: usize, _visitor: V) -> Result<>::Value, Error<'de>> 285 | where 286 | V: Visitor<'de>, 287 | { 288 | Err(Error::Unsupported("deserialize_tuple_struct")) 289 | } 290 | 291 | fn deserialize_map(self, visitor: V) -> Result<>::Value, Error<'de>> 292 | where 293 | V: Visitor<'de>, 294 | { 295 | visitor.visit_map(MapAccess { deserializer: self }) 296 | } 297 | 298 | fn deserialize_struct( 299 | self, _name: &'static str, _fields: &'static [&'static str], visitor: V, 300 | ) -> Result<>::Value, Error<'de>> 301 | where 302 | V: Visitor<'de>, 303 | { 304 | if self.map_like { 305 | visitor.visit_map(MapAccess { deserializer: self }) 306 | } else { 307 | self.deserialize_seq(visitor) 308 | } 309 | } 310 | 311 | fn deserialize_enum( 312 | self, _name: &'static str, _variants: &'static [&'static str], _visitor: V, 313 | ) -> Result<>::Value, Error<'de>> 314 | where 315 | V: Visitor<'de>, 316 | { 317 | Err(Error::Unsupported("deserialize_enum")) 318 | } 319 | 320 | fn deserialize_identifier(self, visitor: V) -> Result<>::Value, Error<'de>> 321 | where 322 | V: Visitor<'de>, 323 | { 324 | dev_trace!("RobtopDeserializer::deserialize_identifier called"); 325 | 326 | self.deserialize_str(visitor) 327 | } 328 | 329 | fn deserialize_ignored_any(self, visitor: V) -> Result<>::Value, Error<'de>> 330 | where 331 | V: Visitor<'de>, 332 | { 333 | // We are still very much not self describing, however we do need to correctly handle unimplemented 334 | // indices. By the time this is called, they key itself will already have been popped in our 335 | // `MapAccess` implementation. This means we need to skip exactly one item! We'll feed a `None` to 336 | // the visitor. Because idk what we really wanna do here otherwise 337 | let _token = self.consume_token(); 338 | 339 | dev_debug!( 340 | "Ignored token {:?}. Preceding token (potentially an unmapped index) was {:?}", 341 | _token, 342 | self.nth_last(1) 343 | ); 344 | 345 | visitor.visit_none() 346 | } 347 | } 348 | 349 | const INDICES: [&str; 50] = [ 350 | "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", 351 | "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", 352 | "47", "48", "49", "50", 353 | ]; 354 | 355 | struct SeqAccess<'a, 'de> { 356 | deserializer: &'a mut IndexedDeserializer<'de>, 357 | index: usize, 358 | } 359 | 360 | impl<'a, 'de> de::SeqAccess<'de> for SeqAccess<'a, 'de> { 361 | type Error = Error<'de>; 362 | 363 | fn next_element_seed(&mut self, seed: T) -> Result, Error<'de>> 364 | where 365 | T: DeserializeSeed<'de>, 366 | { 367 | self.index += 1; 368 | 369 | dev_trace!("Deserializing list entry at index {}", self.index); 370 | 371 | match seed.deserialize(&mut *self.deserializer) { 372 | Err(Error::Eof) => Ok(None), 373 | Err(Error::Custom { message, value, .. }) => Err(Error::Custom { 374 | message, 375 | value: value.or_else(|| self.deserializer.nth_last(1)), 376 | index: Some(INDICES.get(self.index - 1).unwrap_or(&">=51")), 377 | }), 378 | Err(err) => Err(err), 379 | Ok(item) => Ok(Some(item)), 380 | } 381 | } 382 | } 383 | 384 | struct MapAccess<'a, 'de> { 385 | deserializer: &'a mut IndexedDeserializer<'de>, 386 | } 387 | 388 | impl<'a, 'de> de::MapAccess<'de> for MapAccess<'a, 'de> { 389 | type Error = Error<'de>; 390 | 391 | fn next_key_seed(&mut self, seed: K) -> Result, Error<'de>> 392 | where 393 | K: DeserializeSeed<'de>, 394 | { 395 | dev_trace!("Processing a map key"); 396 | 397 | match seed.deserialize(&mut *self.deserializer) { 398 | Err(Error::Eof) => Ok(None), 399 | Err(Error::Custom { message, .. }) => Err(Error::Custom { 400 | message, 401 | value: None, 402 | index: self.deserializer.nth_last(1), 403 | }), 404 | Err(err) => Err(err), 405 | Ok(item) => Ok(Some(item)), 406 | } 407 | } 408 | 409 | fn next_value_seed(&mut self, seed: V) -> Result> 410 | where 411 | V: DeserializeSeed<'de>, 412 | { 413 | dev_trace!("Processing a map value"); 414 | 415 | match seed.deserialize(&mut *self.deserializer) { 416 | Err(Error::Custom { message, value, .. }) => Err(Error::Custom { 417 | message, 418 | value: value.or_else(|| self.deserializer.nth_last(1)), 419 | index: self.deserializer.nth_last(2), 420 | }), 421 | r => r, 422 | } 423 | } 424 | } 425 | 426 | #[cfg(test)] 427 | mod tests { 428 | use crate::serde::IndexedDeserializer; 429 | use serde::de::Deserialize; 430 | use std::collections::HashMap; 431 | 432 | const INPUT: &str = "1:hello:2:world"; 433 | 434 | #[test] 435 | fn test_deserialize_map_like_to_hashmap() { 436 | // Illustrates how to deserialize some arbitrary RobTop string into a HashMap, for easier analysis. 437 | let mut deserializer = IndexedDeserializer::new(INPUT, ":", true); 438 | 439 | let map = HashMap::<&str, &str>::deserialize(&mut deserializer).unwrap(); 440 | 441 | assert_eq!(map.len(), 2); 442 | assert_eq!(map.get("1"), Some(&"hello")); 443 | assert_eq!(map.get("2"), Some(&"world")); 444 | } 445 | 446 | #[test] 447 | fn test_deserialize_map_like_last_empty() { 448 | // Illustrates how to deserialize some arbitrary RobTop string into a HashMap, for easier analysis. 449 | let mut deserializer = IndexedDeserializer::new("1:hello:2:", ":", true); 450 | 451 | let map = HashMap::<&str, &str>::deserialize(&mut deserializer).unwrap(); 452 | 453 | assert_eq!(map.len(), 2); 454 | assert_eq!(map.get("1"), Some(&"hello")); 455 | assert_eq!(map.get("2"), Some(&"")); 456 | } 457 | 458 | #[test] 459 | fn test_deserialize_to_vec() { 460 | let mut deserializer = IndexedDeserializer::new(INPUT, ":", false); 461 | 462 | let vec = Vec::<&str>::deserialize(&mut deserializer).unwrap(); 463 | 464 | assert_eq!(vec, INPUT.split(':').collect::>()) 465 | } 466 | } 467 | -------------------------------------------------------------------------------- /src/serde/ser/request.rs: -------------------------------------------------------------------------------- 1 | //! Module containing a serializer for the data format robtop expects his requests to be in 2 | //! 3 | //! RobTop uses a non-standard variation of the `x-www-form-urlencoded` format for requests to 4 | //! his servers. Since that format only have a very small intersection with actual 5 | //! `x-www-form-urlencoded` it is easier to just implement a serializer from scratch instead of 6 | //! using the `serde-urlencoded` crate. Experiences gained from GDCF have shown that using the 7 | //! latter requires a _lot_ of `[serde(serialize_with = "...")]` attributes all over the code. 8 | //! 9 | //! The serializers makes the following assumptions, which makes it not standard-compliant: 10 | //! * It does not replace spaces with '+' (RobTop's does not perform this conversion) 11 | //! * It does not percent-encode unprintable/non-ASCII bytes (through the official client, inputting 12 | //! them isn't supported. What happens if we include them programmatically is something yet to be 13 | //! investigated) TODO GAME SPECIFIC 14 | 15 | use crate::serde::SerError as Error; 16 | use itoa::{Buffer, Integer}; 17 | use serde::{ 18 | ser::{Error as _, Impossible, SerializeStruct}, 19 | Serialize, Serializer, 20 | }; 21 | use std::{fmt::Display, io::Write}; 22 | 23 | #[allow(missing_debug_implementations)] 24 | pub struct RequestSerializer { 25 | writer: W, 26 | 27 | /// Value indicating whether this serializer has already serialized something. This is used to 28 | /// check if we need to prepend the delimiter to the next field. 29 | is_start: bool, 30 | } 31 | 32 | impl RequestSerializer { 33 | pub fn new(writer: W) -> Self { 34 | RequestSerializer { writer, is_start: true } 35 | } 36 | } 37 | 38 | macro_rules! unsupported { 39 | ($($method: ident: $t: ty),*) => { 40 | $( 41 | fn $method(self, _v: $t) -> Result { 42 | Err(Error::Unsupported(stringify!($method))) 43 | } 44 | )* 45 | }; 46 | } 47 | 48 | impl Serializer for &mut RequestSerializer { 49 | type Error = Error; 50 | type Ok = (); 51 | type SerializeMap = Impossible<(), Error>; 52 | type SerializeSeq = Impossible<(), Error>; 53 | type SerializeStruct = Self; 54 | type SerializeStructVariant = Impossible<(), Error>; 55 | type SerializeTuple = Impossible<(), Error>; 56 | type SerializeTupleStruct = Impossible<(), Error>; 57 | type SerializeTupleVariant = Impossible<(), Error>; 58 | 59 | unsupported!( 60 | serialize_bool: bool, 61 | serialize_i8: i8, 62 | serialize_i16: i16, 63 | serialize_i32: i32, 64 | serialize_i64: i64, 65 | serialize_u8: u8, 66 | serialize_u16: u16, 67 | serialize_u32: u32, 68 | serialize_u64: u64, 69 | serialize_f32: f32, 70 | serialize_f64: f64, 71 | serialize_char: char, 72 | serialize_str: &str, 73 | serialize_bytes: &[u8] 74 | ); 75 | 76 | fn serialize_none(self) -> Result { 77 | Err(Error::Unsupported("serialize_none")) 78 | } 79 | 80 | fn serialize_some(self, _value: &T) -> Result 81 | where 82 | T: Serialize + ?Sized, 83 | { 84 | Err(Error::Unsupported("serialize_some")) 85 | } 86 | 87 | fn serialize_unit(self) -> Result { 88 | Err(Error::Unsupported("serialize_unit")) 89 | } 90 | 91 | fn serialize_unit_struct(self, _name: &'static str) -> Result { 92 | Err(Error::Unsupported("serialize_unit_struct")) 93 | } 94 | 95 | fn serialize_unit_variant(self, _name: &'static str, _variant_index: u32, _variant: &'static str) -> Result { 96 | Err(Error::Unsupported("serialize_unit_variant")) 97 | } 98 | 99 | fn serialize_newtype_struct(self, _name: &'static str, _value: &T) -> Result 100 | where 101 | T: Serialize + ?Sized, 102 | { 103 | Err(Error::Unsupported("serialize_newtype_struct")) 104 | } 105 | 106 | fn serialize_newtype_variant( 107 | self, _name: &'static str, _variant_index: u32, _variant: &'static str, _value: &T, 108 | ) -> Result 109 | where 110 | T: Serialize + ?Sized, 111 | { 112 | Err(Error::Unsupported("serialize_newtype_variant")) 113 | } 114 | 115 | fn serialize_seq(self, _len: Option) -> Result { 116 | Err(Error::Unsupported("serialize_seq")) 117 | } 118 | 119 | fn serialize_tuple(self, _len: usize) -> Result { 120 | Err(Error::Unsupported("serialize_tuple")) 121 | } 122 | 123 | fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result { 124 | Err(Error::Unsupported("serialize_tuple_struct")) 125 | } 126 | 127 | fn serialize_tuple_variant( 128 | self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, 129 | ) -> Result { 130 | Err(Error::Unsupported("serialize_tuple_variant")) 131 | } 132 | 133 | fn serialize_map(self, _len: Option) -> Result { 134 | Err(Error::Unsupported("serialize_map")) 135 | } 136 | 137 | fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { 138 | Ok(self) 139 | } 140 | 141 | fn serialize_struct_variant( 142 | self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, 143 | ) -> Result { 144 | Err(Error::Unsupported("serialize_struct_variant")) 145 | } 146 | 147 | fn collect_str(self, _value: &T) -> Result 148 | where 149 | T: Display + ?Sized, 150 | { 151 | Err(Error::Unsupported("collect_str")) 152 | } 153 | } 154 | 155 | impl SerializeStruct for &mut RequestSerializer { 156 | type Ok = (); 157 | type Error = Error; 158 | 159 | fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> 160 | where 161 | T: Serialize + ?Sized, 162 | { 163 | if !self.is_start { 164 | self.writer.write(b"&").map_err(Error::custom)?; 165 | } 166 | 167 | // we cannot do self.is_start = false here because the first field might be a struct that was 168 | // inlined, meaning no key/value pair is directly constructed! It has to happen when we actually 169 | // write the first key, which occurs inside some nested ValueSerializer call. 170 | 171 | value.serialize(&mut ValueSerializer { 172 | key: Some(key), 173 | serializer: self, 174 | }) 175 | } 176 | 177 | fn end(self) -> Result { 178 | // All structs are inlined and flattened 179 | Ok(()) 180 | } 181 | } 182 | 183 | struct ValueSerializer<'ser, W: Write> { 184 | key: Option<&'static str>, 185 | serializer: &'ser mut RequestSerializer, 186 | } 187 | 188 | impl<'ser, W: Write> ValueSerializer<'ser, W> { 189 | fn write_key(&mut self) -> Result<(), Error> { 190 | if let Some(key) = self.key { 191 | self.serializer.writer.write_all(key.as_bytes()).map_err(Error::custom)?; 192 | self.serializer.writer.write(b"=").map_err(Error::custom)?; 193 | 194 | self.serializer.is_start = false; 195 | } 196 | Ok(()) 197 | } 198 | 199 | fn write_integer(&mut self, int: I) -> Result<(), Error> { 200 | self.write_key()?; 201 | 202 | let mut buffer = Buffer::new(); 203 | self.serializer.writer.write(buffer.format(int).as_bytes()).map_err(Error::custom)?; 204 | 205 | Ok(()) 206 | } 207 | 208 | fn write_display(&mut self, val: D) -> Result<(), Error> { 209 | self.write_key()?; 210 | 211 | write!(&mut self.serializer.writer, "{}", val).map_err(Error::custom)?; 212 | 213 | Ok(()) 214 | } 215 | } 216 | 217 | impl<'ser, 'a, W: Write> Serializer for &'a mut ValueSerializer<'ser, W> { 218 | type Error = Error; 219 | type Ok = (); 220 | type SerializeMap = Impossible<(), Error>; 221 | type SerializeSeq = SerializeSeq<'a, W>; 222 | type SerializeStruct = &'a mut RequestSerializer; 223 | type SerializeStructVariant = Impossible<(), Error>; 224 | type SerializeTuple = Impossible<(), Error>; 225 | type SerializeTupleStruct = Impossible<(), Error>; 226 | type SerializeTupleVariant = Impossible<(), Error>; 227 | 228 | fn serialize_bool(self, v: bool) -> Result { 229 | self.write_key()?; 230 | 231 | match v { 232 | true => self.serializer.writer.write(b"1"), 233 | false => self.serializer.writer.write(b"0"), 234 | } 235 | .map_err(Error::custom)?; 236 | 237 | Ok(()) 238 | } 239 | 240 | fn serialize_i8(self, v: i8) -> Result { 241 | self.write_integer(v) 242 | } 243 | 244 | fn serialize_i16(self, v: i16) -> Result { 245 | self.write_integer(v) 246 | } 247 | 248 | fn serialize_i32(self, v: i32) -> Result { 249 | self.write_integer(v) 250 | } 251 | 252 | fn serialize_i64(self, v: i64) -> Result { 253 | self.write_integer(v) 254 | } 255 | 256 | fn serialize_u8(self, v: u8) -> Result { 257 | self.write_integer(v) 258 | } 259 | 260 | fn serialize_u16(self, v: u16) -> Result { 261 | self.write_integer(v) 262 | } 263 | 264 | fn serialize_u32(self, v: u32) -> Result { 265 | self.write_integer(v) 266 | } 267 | 268 | fn serialize_u64(self, v: u64) -> Result { 269 | self.write_integer(v) 270 | } 271 | 272 | fn serialize_f32(self, v: f32) -> Result { 273 | self.write_display(v) 274 | } 275 | 276 | fn serialize_f64(self, v: f64) -> Result { 277 | self.write_display(v) 278 | } 279 | 280 | fn serialize_char(self, v: char) -> Result { 281 | self.write_key()?; 282 | 283 | // We don't need allocations for appending a single char 284 | // A buffer of size 4 is always enough to encode a char 285 | let mut char_buffer: [u8; 4] = [0; 4]; 286 | self.serializer 287 | .writer 288 | .write_all(v.encode_utf8(&mut char_buffer).as_bytes()) 289 | .map_err(Error::custom)?; 290 | 291 | Ok(()) 292 | } 293 | 294 | fn serialize_str(self, v: &str) -> Result { 295 | self.write_key()?; 296 | 297 | self.serializer.writer.write(v.as_bytes()).map_err(Error::custom)?; 298 | 299 | Ok(()) 300 | } 301 | 302 | fn serialize_bytes(self, _v: &[u8]) -> Result { 303 | Err(Error::Unsupported("serialize_bytes")) 304 | } 305 | 306 | fn serialize_none(self) -> Result { 307 | self.write_key() 308 | } 309 | 310 | fn serialize_some(self, value: &T) -> Result 311 | where 312 | T: Serialize + ?Sized, 313 | { 314 | value.serialize(self) 315 | } 316 | 317 | fn serialize_unit(self) -> Result { 318 | Err(Error::Unsupported("serialize_unit")) 319 | } 320 | 321 | fn serialize_unit_struct(self, _name: &'static str) -> Result { 322 | Err(Error::Unsupported("serialize_unit_struct")) 323 | } 324 | 325 | fn serialize_unit_variant(self, _name: &'static str, _variant_index: u32, _variant: &'static str) -> Result { 326 | Err(Error::Unsupported("serialize_unit_variant")) 327 | } 328 | 329 | fn serialize_newtype_struct(self, _name: &'static str, _value: &T) -> Result 330 | where 331 | T: Serialize + ?Sized, 332 | { 333 | Err(Error::Unsupported("serialize_newtype_struct")) 334 | } 335 | 336 | fn serialize_newtype_variant( 337 | self, _name: &'static str, _variant_index: u32, _variant: &'static str, _value: &T, 338 | ) -> Result 339 | where 340 | T: Serialize + ?Sized, 341 | { 342 | Err(Error::Unsupported("serialize_newtype_variant")) 343 | } 344 | 345 | fn serialize_seq(self, _len: Option) -> Result { 346 | if self.key.is_none() { 347 | return Err(Error::Unsupported("Nested sequences")); 348 | } 349 | 350 | self.write_key()?; 351 | 352 | // This is a horrible hack. In `LevelsRequest` there is one particular field, namely 353 | // 'completedLevels`, that represents a list of values. In the entire freaking API, this is the only 354 | // vector where serialization is required to surround the value list with parenthesis. We cannot 355 | // simply deal with this in a newtype wrapper around vec, since serde does not allows us (rightfully 356 | // so) to just randomly write parenthesis to an arbitrary serializer. Which is why we have to 357 | // special case that one field here, in the serializer for robtop's request data format. 358 | Ok(SerializeSeq { 359 | serializer: self.serializer, 360 | is_start: true, 361 | parenthesized: self.key == Some("completedLevels"), 362 | }) 363 | } 364 | 365 | fn serialize_tuple(self, _len: usize) -> Result { 366 | Err(Error::Unsupported("serialize_tuple")) 367 | } 368 | 369 | fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result { 370 | Err(Error::Unsupported("serialize_tuple_struct")) 371 | } 372 | 373 | fn serialize_tuple_variant( 374 | self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, 375 | ) -> Result { 376 | Err(Error::Unsupported("serialize_tuple_variant")) 377 | } 378 | 379 | fn serialize_map(self, _len: Option) -> Result { 380 | Err(Error::Unsupported("serialize_map")) 381 | } 382 | 383 | fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { 384 | if self.key.is_none() { 385 | return Err(Error::Unsupported("struct inside sequence")); 386 | } 387 | 388 | // If we inline a struct, that struct might not be the first field we serialize. However, we do not 389 | // know whether the value we serialize is a struct or not until we reach this method, so the value 390 | // serializer will already have appended an '&' for us. This means that we do not want to add 391 | // another one for the first field of this nested struct. 392 | self.serializer.is_start = true; 393 | 394 | Ok(self.serializer) 395 | } 396 | 397 | fn serialize_struct_variant( 398 | self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, 399 | ) -> Result { 400 | Err(Error::Unsupported("serialize_struct_variant")) 401 | } 402 | 403 | fn collect_str(self, _value: &T) -> Result 404 | where 405 | T: Display + ?Sized, 406 | { 407 | Err(Error::Unsupported("collect_str")) 408 | } 409 | } 410 | 411 | pub(crate) struct SerializeSeq<'ser, W: Write> { 412 | serializer: &'ser mut RequestSerializer, 413 | is_start: bool, 414 | parenthesized: bool, 415 | } 416 | 417 | impl<'write, W: Write> serde::ser::SerializeSeq for SerializeSeq<'write, W> { 418 | type Error = Error; 419 | type Ok = (); 420 | 421 | fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> 422 | where 423 | T: Serialize + ?Sized, 424 | { 425 | if !self.is_start { 426 | self.serializer.writer.write(b",").map_err(Error::custom)?; 427 | } else if self.parenthesized { 428 | self.serializer.writer.write(b"(").map_err(Error::custom)?; 429 | } 430 | 431 | self.is_start = false; 432 | value.serialize(&mut ValueSerializer { 433 | key: None, 434 | serializer: self.serializer, 435 | }) 436 | } 437 | 438 | fn end(self) -> Result { 439 | if self.is_start { 440 | self.serializer.writer.write(b"-").map_err(Error::custom)?; // empty sequence 441 | } 442 | if self.parenthesized { 443 | self.serializer.writer.write(b")").map_err(Error::custom)?; 444 | } 445 | Ok(()) 446 | } 447 | } 448 | 449 | #[cfg(test)] 450 | mod tests { 451 | use crate::{request::level::LevelRequest, serde::ser::request::RequestSerializer}; 452 | use serde::Serialize; 453 | 454 | #[test] 455 | fn test_serialization() { 456 | let level_request = LevelRequest::default(); 457 | let mut buffer = Vec::new(); 458 | 459 | let mut ser = RequestSerializer { 460 | writer: &mut buffer, 461 | is_start: true, 462 | }; 463 | level_request.serialize(&mut ser).unwrap(); 464 | 465 | assert_eq!( 466 | "gameVersion=22&binaryVersion=38&secret=Wmfd2893gb7&levelID=0&inc=0&extra=0", 467 | String::from_utf8(buffer).unwrap() 468 | ); 469 | } 470 | } 471 | --------------------------------------------------------------------------------