steamid-rs 2.1.2

A SteamID library for parsing, validating, and converting Steam IDs between Steam2, Steam3, and SteamID64 formats.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! SteamID struct and implementation.

use std::{fmt, str::FromStr, sync::LazyLock};

use regex::Regex;

use crate::{
    enums::{chat_instance_flags, masks, AccountType, Instance, Universe},
    error::SteamIdError,
};

// Compiled regex patterns (lazily initialized)
static STEAM2_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^STEAM_([0-5]):([0-1]):([0-9]+)$").unwrap());
static STEAM3_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[([a-zA-Z]):([0-5]):([0-9]+)(:[0-9]+)?\]$").unwrap());
static STEAMID64_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\d+$").unwrap());

/// Represents a Steam ID with all its components.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SteamID {
    /// The Steam universe this ID belongs to.
    pub universe: Universe,
    /// The type of account this ID represents.
    pub account_type: AccountType,
    /// The instance of the account.
    pub instance: u32,
    /// The unique account identifier.
    pub account_id: u32,
}

impl Default for SteamID {
    fn default() -> Self {
        Self::new()
    }
}

impl SteamID {
    /// Creates a new invalid SteamID.
    pub fn new() -> Self {
        SteamID {
            universe: Universe::Invalid,
            account_type: AccountType::Invalid,
            instance: Instance::All as u32,
            account_id: 0,
        }
    }

    /// Creates a SteamID from an individual account ID.
    ///
    /// This is a convenience method for creating a typical user SteamID
    /// in the public universe with a desktop instance.
    pub fn from_individual_account_id(account_id: u32) -> Self {
        SteamID {
            universe: Universe::Public,
            account_type: AccountType::Individual,
            instance: Instance::Desktop as u32,
            account_id,
        }
    }

    /// Parse a SteamID from a 64-bit integer.
    pub fn from_steam_id64(id: u64) -> Self {
        let account_id = (id & masks::ACCOUNT_ID_MASK) as u32;
        let instance = ((id >> 32) & masks::ACCOUNT_INSTANCE_MASK as u64) as u32;
        let account_type = AccountType::from_u8(((id >> 52) & 0xF) as u8);
        let universe = Universe::from_u8((id >> 56) as u8);

        SteamID { universe, account_type, instance, account_id }
    }

    /// Returns whether Steam would consider this ID to be "valid".
    ///
    /// This does not check whether the given ID belongs to a real account,
    /// nor does it check that the given ID is for an individual account
    /// or in the public universe.
    pub fn is_valid(&self) -> bool {
        // Type must be valid
        if self.account_type == AccountType::Invalid || (self.account_type as u8) > 10 {
            return false;
        }

        // Universe must be valid
        if self.universe == Universe::Invalid || (self.universe as u8) > 4 {
            return false;
        }

        // Individual accounts need valid account_id and instance <= WEB
        if self.account_type == AccountType::Individual && (self.account_id == 0 || self.instance > Instance::Web as u32) {
            return false;
        }

        // Clans need valid account_id and instance must be ALL
        if self.account_type == AccountType::Clan && (self.account_id == 0 || self.instance != Instance::All as u32) {
            return false;
        }

        // Game servers need valid account_id
        if self.account_type == AccountType::GameServer && self.account_id == 0 {
            return false;
        }

        true
    }

    /// Returns whether this SteamID is valid and belongs to an individual user
    /// in the public universe with a desktop instance.
    ///
    /// This is what most people think of when they think of a SteamID.
    /// Does not check whether the account actually exists.
    pub fn is_valid_individual(&self) -> bool {
        self.universe == Universe::Public && self.account_type == AccountType::Individual && self.instance == Instance::Desktop as u32 && self.is_valid()
    }

    /// Checks whether this ID is for a legacy group chat.
    pub fn is_group_chat(&self) -> bool {
        self.account_type == AccountType::Chat && (self.instance & chat_instance_flags::CLAN) != 0
    }

    /// Checks whether this ID is for a game lobby.
    pub fn is_lobby(&self) -> bool {
        self.account_type == AccountType::Chat && ((self.instance & chat_instance_flags::LOBBY) != 0 || (self.instance & chat_instance_flags::MMS_LOBBY) != 0)
    }

    /// Renders the ID in Steam2 format (e.g. "STEAM_0:0:23071901").
    ///
    /// # Arguments
    /// * `newer_format` - If true, use 1 as the first digit instead of 0 for
    ///   the public universe.
    ///
    /// # Errors
    /// Returns an error if this is not an individual account type.
    pub fn steam2(&self, newer_format: bool) -> Result<String, SteamIdError> {
        if self.account_type != AccountType::Individual {
            return Err(SteamIdError::NotIndividual);
        }

        let universe = if !newer_format && self.universe == Universe::Public { 0 } else { self.universe as u8 };

        Ok(format!("STEAM_{}:{}:{}", universe, self.account_id & 1, self.account_id / 2))
    }

    /// Renders the ID in Steam3 format (e.g. "[U:1:46143802]").
    pub fn steam3(&self) -> String {
        let mut type_char = self.account_type.to_char();

        // Special handling for chat types
        if (self.instance & chat_instance_flags::CLAN) != 0 {
            type_char = 'c';
        } else if (self.instance & chat_instance_flags::LOBBY) != 0 {
            type_char = 'L';
        }

        let should_render_instance = self.account_type == AccountType::AnonGameServer || self.account_type == AccountType::Multiseat || (self.account_type == AccountType::Individual && self.instance != Instance::Desktop as u32);

        if should_render_instance {
            format!("[{}:{}:{}:{}]", type_char, self.universe as u8, self.account_id, self.instance)
        } else {
            format!("[{}:{}:{}]", type_char, self.universe as u8, self.account_id)
        }
    }

    /// Renders the ID in 64-bit decimal format.
    pub fn steam_id64(&self) -> u64 {
        let universe = (self.universe as u64) << 56;
        let account_type = (self.account_type as u64) << 52;
        let instance = (self.instance as u64) << 32;
        let account_id = self.account_id as u64;

        universe | account_type | instance | account_id
    }

    // Private parsing methods
    fn parse_steam2(input: &str) -> Option<Self> {
        let caps = STEAM2_REGEX.captures(input)?;

        let universe_num: u8 = caps.get(1)?.as_str().parse().ok()?;
        let mod_num: u32 = caps.get(2)?.as_str().parse().ok()?;
        let account_id_half: u32 = caps.get(3)?.as_str().parse().ok()?;

        // If universe is 0, treat it as PUBLIC (1)
        let universe = if universe_num == 0 { Universe::Public } else { Universe::from_u8(universe_num) };

        Some(SteamID {
            universe,
            account_type: AccountType::Individual,
            instance: Instance::Desktop as u32,
            account_id: (account_id_half * 2) + mod_num,
        })
    }

    fn parse_steam3(input: &str) -> Option<Self> {
        let caps = STEAM3_REGEX.captures(input)?;

        let type_char = caps.get(1)?.as_str().chars().next()?;
        let universe_num: u8 = caps.get(2)?.as_str().parse().ok()?;
        let account_id: u32 = caps.get(3)?.as_str().parse().ok()?;

        let universe = Universe::from_u8(universe_num);

        let mut instance: u32 = Instance::All as u32;
        if let Some(instance_match) = caps.get(4) {
            // Remove leading colon and parse
            let instance_str = &instance_match.as_str()[1..];
            instance = instance_str.parse().ok()?;
        }

        let account_type = match type_char {
            'U' => {
                // Individual - default to DESKTOP if no explicit instance
                if caps.get(4).is_none() {
                    instance = Instance::Desktop as u32;
                }
                AccountType::Individual
            }
            'c' => {
                instance |= chat_instance_flags::CLAN;
                AccountType::Chat
            }
            'L' => {
                instance |= chat_instance_flags::LOBBY;
                AccountType::Chat
            }
            _ => AccountType::from_char(type_char),
        };

        Some(SteamID { universe, account_type, instance, account_id })
    }

    fn parse_steam_id64(input: &str) -> Option<Self> {
        if !STEAMID64_REGEX.is_match(input) {
            return None;
        }

        let id: u64 = input.parse().ok()?;
        Some(Self::from_steam_id64(id))
    }
}

impl FromStr for SteamID {
    type Err = SteamIdError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        // Try Steam2 format
        if let Some(sid) = Self::parse_steam2(input) {
            return Ok(sid);
        }

        // Try Steam3 format
        if let Some(sid) = Self::parse_steam3(input) {
            return Ok(sid);
        }

        // Try SteamID64 format
        if let Some(sid) = Self::parse_steam_id64(input) {
            return Ok(sid);
        }

        Err(SteamIdError::InvalidFormat(input.to_string()))
    }
}

impl TryFrom<&str> for SteamID {
    type Error = SteamIdError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        value.parse()
    }
}

impl TryFrom<String> for SteamID {
    type Error = SteamIdError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        value.parse()
    }
}

impl From<u64> for SteamID {
    fn from(value: u64) -> Self {
        Self::from_steam_id64(value)
    }
}

impl fmt::Display for SteamID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.steam_id64())
    }
}

impl serde::Serialize for SteamID {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_u64(self.steam_id64())
    }
}

impl<'de> serde::Deserialize<'de> for SteamID {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct SteamIDVisitor;

        impl<'de> serde::de::Visitor<'de> for SteamIDVisitor {
            type Value = SteamID;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a SteamID64 as a number or string")
            }

            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(SteamID::from(value))
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                value.parse().map_err(serde::de::Error::custom)
            }
        }

        deserializer.deserialize_any(SteamIDVisitor)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parameterless_construction() {
        let sid = SteamID::new();
        assert_eq!(sid.universe, Universe::Invalid);
        assert_eq!(sid.account_type, AccountType::Invalid);
        assert_eq!(sid.instance, Instance::All as u32);
        assert_eq!(sid.account_id, 0);
    }

    #[test]
    fn test_from_individual_account_id() {
        let sid = SteamID::from_individual_account_id(46143802);
        assert_eq!(sid.universe, Universe::Public);
        assert_eq!(sid.account_type, AccountType::Individual);
        assert_eq!(sid.instance, Instance::Desktop as u32);
        assert_eq!(sid.account_id, 46143802);
        assert!(sid.is_valid());
        assert!(sid.is_valid_individual());
    }

    #[test]
    fn test_steam2id_construction_universe_0() {
        let sid: SteamID = "STEAM_0:0:23071901".parse().unwrap();
        assert_eq!(sid.universe, Universe::Public);
        assert_eq!(sid.account_type, AccountType::Individual);
        assert_eq!(sid.instance, Instance::Desktop as u32);
        assert_eq!(sid.account_id, 46143802);
    }

    #[test]
    fn test_steam2id_construction_universe_1() {
        let sid: SteamID = "STEAM_1:1:23071901".parse().unwrap();
        assert_eq!(sid.universe, Universe::Public);
        assert_eq!(sid.account_type, AccountType::Individual);
        assert_eq!(sid.instance, Instance::Desktop as u32);
        assert_eq!(sid.account_id, 46143803);
    }

    #[test]
    fn test_steam3id_construction_individual() {
        let sid: SteamID = "[U:1:46143802]".parse().unwrap();
        assert_eq!(sid.universe, Universe::Public);
        assert_eq!(sid.account_type, AccountType::Individual);
        assert_eq!(sid.instance, Instance::Desktop as u32);
        assert_eq!(sid.account_id, 46143802);
    }

    #[test]
    fn test_steam3id_construction_gameserver() {
        let sid: SteamID = "[G:1:31]".parse().unwrap();
        assert_eq!(sid.universe, Universe::Public);
        assert_eq!(sid.account_type, AccountType::GameServer);
        assert_eq!(sid.instance, Instance::All as u32);
        assert_eq!(sid.account_id, 31);
        assert!(sid.is_valid());
        assert!(!sid.is_valid_individual());
    }

    #[test]
    fn test_steam3id_construction_anon_gameserver() {
        let sid: SteamID = "[A:1:46124:11245]".parse().unwrap();
        assert_eq!(sid.universe, Universe::Public);
        assert_eq!(sid.account_type, AccountType::AnonGameServer);
        assert_eq!(sid.instance, 11245);
        assert_eq!(sid.account_id, 46124);
    }

    #[test]
    fn test_steam3id_construction_lobby() {
        let sid: SteamID = "[L:1:12345]".parse().unwrap();
        assert_eq!(sid.universe, Universe::Public);
        assert_eq!(sid.account_type, AccountType::Chat);
        assert_eq!(sid.instance, chat_instance_flags::LOBBY);
        assert_eq!(sid.account_id, 12345);
    }

    #[test]
    fn test_steam3id_construction_lobby_with_instanceid() {
        let sid: SteamID = "[L:1:12345:55]".parse().unwrap();
        assert_eq!(sid.universe, Universe::Public);
        assert_eq!(sid.account_type, AccountType::Chat);
        assert_eq!(sid.instance, chat_instance_flags::LOBBY | 55);
        assert_eq!(sid.account_id, 12345);
    }

    #[test]
    fn test_steamid64_construction_individual() {
        let sid: SteamID = "76561198006409530".parse().unwrap();
        assert_eq!(sid.universe, Universe::Public);
        assert_eq!(sid.account_type, AccountType::Individual);
        assert_eq!(sid.instance, Instance::Desktop as u32);
        assert_eq!(sid.account_id, 46143802);
    }

    #[test]
    fn test_steamid64_construction_clan() {
        let sid: SteamID = "103582791434202956".parse().unwrap();
        assert_eq!(sid.universe, Universe::Public);
        assert_eq!(sid.account_type, AccountType::Clan);
        assert_eq!(sid.instance, Instance::All as u32);
        assert_eq!(sid.account_id, 4681548);
    }

    #[test]
    fn test_steamid64_from_u64() {
        let sid = SteamID::from(76561198006409530u64);
        assert_eq!(sid.universe, Universe::Public);
        assert_eq!(sid.account_type, AccountType::Individual);
        assert_eq!(sid.instance, Instance::Desktop as u32);
        assert_eq!(sid.account_id, 46143802);
    }

    #[test]
    fn test_invalid_construction() {
        let result: Result<SteamID, _> = "invalid input".parse();
        assert!(result.is_err());
    }

    #[test]
    fn test_steam2id_rendering_universe_0() {
        let mut sid = SteamID::new();
        sid.universe = Universe::Public;
        sid.account_type = AccountType::Individual;
        sid.instance = Instance::Desktop as u32;
        sid.account_id = 46143802;
        assert_eq!(sid.steam2(false).unwrap(), "STEAM_0:0:23071901");
    }

    #[test]
    fn test_steam2id_rendering_universe_1() {
        let mut sid = SteamID::new();
        sid.universe = Universe::Public;
        sid.account_type = AccountType::Individual;
        sid.instance = Instance::Desktop as u32;
        sid.account_id = 46143802;
        assert_eq!(sid.steam2(true).unwrap(), "STEAM_1:0:23071901");
    }

    #[test]
    fn test_steam2id_rendering_non_individual() {
        let mut sid = SteamID::new();
        sid.universe = Universe::Public;
        sid.account_type = AccountType::Clan;
        sid.instance = Instance::Desktop as u32;
        sid.account_id = 4681548;
        assert!(sid.steam2(false).is_err());
    }

    #[test]
    fn test_steam3id_rendering_individual() {
        let mut sid = SteamID::new();
        sid.universe = Universe::Public;
        sid.account_type = AccountType::Individual;
        sid.instance = Instance::Desktop as u32;
        sid.account_id = 46143802;
        assert_eq!(sid.steam3(), "[U:1:46143802]");
    }

    #[test]
    fn test_steam3id_rendering_anon_gameserver() {
        let mut sid = SteamID::new();
        sid.universe = Universe::Public;
        sid.account_type = AccountType::AnonGameServer;
        sid.instance = 41511;
        sid.account_id = 43253156;
        assert_eq!(sid.steam3(), "[A:1:43253156:41511]");
    }

    #[test]
    fn test_steam3id_rendering_lobby() {
        let mut sid = SteamID::new();
        sid.universe = Universe::Public;
        sid.account_type = AccountType::Chat;
        sid.instance = chat_instance_flags::LOBBY;
        sid.account_id = 451932;
        assert_eq!(sid.steam3(), "[L:1:451932]");
    }

    #[test]
    fn test_steamid64_rendering_individual() {
        let mut sid = SteamID::new();
        sid.universe = Universe::Public;
        sid.account_type = AccountType::Individual;
        sid.instance = Instance::Desktop as u32;
        sid.account_id = 46143802;
        assert_eq!(sid.steam_id64(), 76561198006409530);
        assert_eq!(sid.to_string(), "76561198006409530");
    }

    #[test]
    fn test_steamid64_rendering_anon_gameserver() {
        let mut sid = SteamID::new();
        sid.universe = Universe::Public;
        sid.account_type = AccountType::AnonGameServer;
        sid.instance = 188991;
        sid.account_id = 42135013;
        assert_eq!(sid.steam_id64(), 90883702753783269);
    }

    #[test]
    fn test_invalid_new_id() {
        let sid = SteamID::new();
        assert!(!sid.is_valid());
    }

    #[test]
    fn test_invalid_individual_instance() {
        let sid: SteamID = "[U:1:46143802:10]".parse().unwrap();
        assert!(!sid.is_valid());
        assert!(!sid.is_valid_individual());
    }

    #[test]
    fn test_invalid_non_all_clan_instance() {
        let sid: SteamID = "[g:1:4681548:2]".parse().unwrap();
        assert!(!sid.is_valid());
    }

    #[test]
    fn test_invalid_gameserver_accountid_0() {
        let sid: SteamID = "[G:1:0]".parse().unwrap();
        assert!(!sid.is_valid());
    }

    #[test]
    fn test_is_group_chat() {
        let mut sid = SteamID::new();
        sid.account_type = AccountType::Chat;
        sid.instance = chat_instance_flags::CLAN;
        assert!(sid.is_group_chat());
        assert!(!sid.is_lobby());
    }

    #[test]
    fn test_is_lobby() {
        let mut sid = SteamID::new();
        sid.account_type = AccountType::Chat;
        sid.instance = chat_instance_flags::LOBBY;
        assert!(!sid.is_group_chat());
        assert!(sid.is_lobby());
    }
}