Skip to main content

gen_core/
lib.rs

1use std::{convert::TryFrom, fmt, hash::Hash};
2
3use rand::Rng;
4use sha2::{Digest, Sha256};
5
6pub mod config;
7pub mod errors;
8#[allow(clippy::all)]
9pub mod generated;
10pub mod path;
11pub mod range;
12pub mod region;
13pub mod strand;
14pub mod traits;
15
16pub use config::Workspace;
17use errors::HashError;
18pub use generated::gen_core_capnp;
19pub use path::PathBlock;
20#[cfg(feature = "python-bindings")]
21use pyo3::pyclass;
22pub use strand::Strand;
23
24pub static NO_CHROMOSOME_INDEX: i64 = -1;
25pub static PRESERVE_EDIT_SITE_CHROMOSOME_INDEX: i64 = -2;
26pub static INDETERMINATE_CHROMOSOME_INDEX: i64 = -3;
27
28// these are just the written out hex from the inserted values from sql migrations
29pub const PATH_START_NODE_ID: HashId = HashId([
30    0x84, 0xd6, 0xad, 0xbd, 0x53, 0x95, 0x28, 0x19, 0x33, 0xfe, 0x41, 0xe8, 0x77, 0xd3, 0xa7, 0xf0,
31    0x2a, 0x3b, 0x19, 0x90, 0xa6, 0x5b, 0xe1, 0x90, 0x1b, 0x2c, 0x91, 0xfc, 0x68, 0x5e, 0x08, 0x3b,
32]);
33pub const PATH_END_NODE_ID: HashId = HashId([
34    0x1c, 0x7d, 0xfc, 0x64, 0x97, 0x7b, 0x08, 0x38, 0xaf, 0x07, 0x62, 0xd7, 0x33, 0x3d, 0xcb, 0x64,
35    0xc1, 0x75, 0xb1, 0x5e, 0x65, 0xa7, 0x00, 0x99, 0xec, 0x38, 0xf4, 0x6b, 0xf1, 0xa1, 0x5e, 0xa3,
36]);
37
38pub fn is_terminal(node_id: HashId) -> bool {
39    is_start_node(node_id) || is_end_node(node_id)
40}
41
42pub fn is_start_node(node_id: HashId) -> bool {
43    node_id == PATH_START_NODE_ID
44}
45
46pub fn is_end_node(node_id: HashId) -> bool {
47    node_id == PATH_END_NODE_ID
48}
49
50#[cfg_attr(feature = "python-bindings", pyclass)]
51#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
52pub struct HashId(pub [u8; 32]);
53
54impl serde::Serialize for HashId {
55    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
56    where
57        S: serde::Serializer,
58    {
59        let hex_str = hex::encode(self.0);
60        serializer.serialize_str(&hex_str)
61    }
62}
63
64impl<'de> serde::Deserialize<'de> for HashId {
65    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
66    where
67        D: serde::Deserializer<'de>,
68    {
69        struct HashIdVisitor;
70
71        impl<'de> serde::de::Visitor<'de> for HashIdVisitor {
72            type Value = HashId;
73
74            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
75                formatter.write_str("a 64-character hex string")
76            }
77
78            fn visit_str<E>(self, v: &str) -> Result<HashId, E>
79            where
80                E: serde::de::Error,
81            {
82                let bytes = hex::decode(v).map_err(E::custom)?;
83                if bytes.len() != 32 {
84                    return Err(E::custom("expected 32 bytes"));
85                }
86                let mut arr = [0u8; 32];
87                arr.copy_from_slice(&bytes);
88                Ok(HashId(arr))
89            }
90        }
91
92        deserializer.deserialize_str(HashIdVisitor)
93    }
94}
95
96impl fmt::Display for HashId {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        for byte in &self.0 {
99            write!(f, "{byte:02x}")?;
100        }
101        Ok(())
102    }
103}
104
105impl TryFrom<String> for HashId {
106    type Error = HashError;
107
108    fn try_from(s: String) -> Result<Self, Self::Error> {
109        HashId::try_from(s.as_str())
110    }
111}
112
113impl fmt::Debug for HashId {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        write!(f, "HashId({})", hex::encode(self.0))
116    }
117}
118
119impl TryFrom<&[u8]> for HashId {
120    type Error = &'static str;
121
122    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
123        if slice.len() != 32 {
124            return Err("slice must be exactly 32 bytes long");
125        }
126
127        let mut array = [0u8; 32];
128        array.copy_from_slice(slice);
129        Ok(HashId(array))
130    }
131}
132
133impl TryFrom<&str> for HashId {
134    type Error = HashError;
135
136    fn try_from(s: &str) -> Result<Self, Self::Error> {
137        let bytes = hex::decode(s)?;
138        let len = bytes.len();
139        let array: [u8; 32] = bytes
140            .try_into()
141            .map_err(|_| HashError::InvalidLength(len))?;
142        Ok(HashId(array))
143    }
144}
145
146impl PartialEq<[u8; 32]> for HashId {
147    fn eq(&self, other: &[u8; 32]) -> bool {
148        &self.0 == other
149    }
150}
151
152impl PartialEq<HashId> for [u8; 32] {
153    fn eq(&self, other: &HashId) -> bool {
154        self == &other.0
155    }
156}
157
158use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
159
160impl FromSql for HashId {
161    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
162        match value {
163            ValueRef::Blob(b) => {
164                if b.len() == 32 {
165                    let mut arr = [0u8; 32];
166                    arr.copy_from_slice(b);
167                    Ok(HashId(arr))
168                } else {
169                    Err(FromSqlError::Other(Box::new(std::io::Error::new(
170                        std::io::ErrorKind::InvalidData,
171                        format!("expected 32-byte blob, got {}", b.len()),
172                    ))))
173                }
174            }
175            _ => Err(FromSqlError::InvalidType),
176        }
177    }
178}
179
180impl ToSql for HashId {
181    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
182        Ok(ToSqlOutput::from(self.0.as_ref())) // &[u8]
183    }
184}
185
186use rusqlite::types::Value;
187
188impl From<HashId> for Value {
189    fn from(h: HashId) -> Self {
190        Value::Blob(h.0.to_vec())
191    }
192}
193
194impl From<uuid::Uuid> for HashId {
195    fn from(uuid: uuid::Uuid) -> Self {
196        let mut buf = [0u8; 32];
197        buf[..16].copy_from_slice(uuid.as_bytes());
198        Self(buf)
199    }
200}
201
202impl HashId {
203    pub fn pad_str<T: ToString>(input: T) -> Self {
204        let s = input.to_string();
205        let hex = format!("{s:0>64}"); // pad to 64 hex chars
206        let bytes = hex::decode(hex).expect("invalid hex string");
207        HashId(bytes.try_into().expect("not 32 bytes"))
208    }
209
210    pub fn convert_str(s: &str) -> Self {
211        HashId(calculate_hash(s))
212    }
213
214    pub fn random_str() -> Self {
215        let mut rng = rand::rng();
216        let mut random_bytes = [0u8; 32];
217        rng.fill_bytes(&mut random_bytes);
218        Self(random_bytes)
219    }
220
221    pub fn uuid7() -> Self {
222        uuid::Uuid::now_v7().into()
223    }
224
225    // this is a hack for the library code, which we have a hack for chromosome_index to be the edge_id
226    pub fn extract_digits(&self) -> i64 {
227        let hex = format!("{self}");
228        let digits: String = hex
229            .chars()
230            .map(|c| {
231                if c.is_ascii_digit() {
232                    c
233                } else {
234                    // ascii digits start at 48, alphabet at 97 so subtract 49 to get char digits. We add 1 to make 'a' = 1
235                    // to prevent leading zeros
236                    (c.to_ascii_lowercase() as u8 - 49 + 1) as char
237                }
238            })
239            .take(15) // limit to first 15 digits if you want
240            .collect();
241
242        digits.parse().unwrap_or(0)
243    }
244
245    pub fn starts_with(&self, prefix: &str) -> bool {
246        if prefix.len() > 64 || prefix.is_empty() {
247            return false;
248        }
249
250        let end_byte = prefix.len() / 2 + prefix.len() % 2;
251        let encoded = hex::encode(&self.0[..end_byte]);
252        encoded.starts_with(prefix)
253    }
254}
255
256#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
257pub struct NodeIntervalBlock {
258    pub node_id: HashId,
259    pub start: i64,
260    pub end: i64,
261    pub sequence_start: i64,
262    pub sequence_end: i64,
263    pub strand: Strand,
264}
265
266pub fn calculate_hash(t: &str) -> [u8; 32] {
267    let mut hasher = Sha256::new();
268    hasher.update(t);
269    let result = hasher.finalize();
270    result.into()
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276
277    #[test]
278    fn it_hashes() {
279        let result: HashId = "a82639b6f8c3a6e536d8cc562c3b86ff4b012c84ab230c1e5be649aa9ad26d21"
280            .try_into()
281            .unwrap();
282        assert_eq!(calculate_hash("a test"), result);
283    }
284
285    #[cfg(test)]
286    mod hashid {
287        use super::*;
288
289        #[test]
290        fn test_starts_with() {
291            let hash: HashId = "a82639b6f8c3a6e536d8cc562c3b86ff4b012c84ab230c1e5be649aa9ad26d21"
292                .try_into()
293                .unwrap();
294            assert!(hash.starts_with("a826"));
295            assert!(
296                hash.starts_with(
297                    "a82639b6f8c3a6e536d8cc562c3b86ff4b012c84ab230c1e5be649aa9ad26d21"
298                )
299            );
300            assert!(!hash.starts_with("b826"));
301            assert!(
302                !hash.starts_with(
303                    "a82639b6f8c3a6e536d8cc562c3b86ff4b012c84ab230c1e5be649aa9ad26d210"
304                )
305            );
306            assert!(!hash.starts_with(""));
307            assert!(
308                !hash.starts_with(
309                    "a82639b6f8c3a6e536d8cc562c3b86ff4b012c84ab230c1e5be649aa9ad26d219"
310                )
311            );
312        }
313    }
314}