qlib_rs/data/
entity_id.rs

1use crate::data::EntityType;
2use serde::{Deserialize, Serialize};
3
4
5#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
6pub struct EntityId {
7    typ: EntityType,
8    id: u64,
9}
10
11impl EntityId {
12    const SEPARATOR: &str = "$";
13
14    pub fn new(typ: impl Into<EntityType>, id: u64) -> Self {
15        Self {
16            typ: typ.into(),
17            id,
18        }
19    }
20
21    pub fn get_type(&self) -> &EntityType {
22        &self.typ
23    }
24
25    pub fn get_id(&self) -> String {
26        format!("{}{}{}", self.get_type(), EntityId::SEPARATOR, self.id)
27    }
28}
29
30impl TryFrom<&str> for EntityId {
31    type Error = String;
32
33    fn try_from(value: &str) -> Result<Self, Self::Error> {
34        let parts: Vec<&str> = value.split(&EntityId::SEPARATOR).collect();
35
36        if parts.len() != 2 {
37            return Err("Invalid EntityId format, expected 'type&id'".to_string());
38        }
39
40        let typ = parts[0].to_string();
41        let id = parts[1].parse::<u64>().map_err(|e| format!("Invalid id: {}", e))?;
42
43        Ok(EntityId { typ: typ.into(), id })
44    }
45}
46
47impl Into<String> for EntityId {
48    fn into(self) -> String {
49        self.get_id()
50    }
51}
52
53impl std::fmt::Display for EntityId {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        write!(f, "{}", self.get_id())
56    }
57}
58
59impl AsRef<EntityId> for EntityId {
60    fn as_ref(&self) -> &EntityId {
61        self
62    }
63}