Skip to main content

gen_core/
lib.rs

1use std::{convert::TryFrom, fmt, hash::Hash};
2
3use rand::Rng;
4use sha2::{Digest, Sha256};
5use xxhash_rust::xxh3::xxh3_128;
6
7pub mod config;
8pub mod errors;
9#[allow(clippy::all)]
10pub mod generated;
11pub mod path;
12pub mod range;
13pub mod region;
14pub mod strand;
15pub mod traits;
16
17pub use config::Workspace;
18use errors::HashError;
19pub use generated::gen_core_capnp;
20pub use path::PathBlock;
21#[cfg(feature = "python-bindings")]
22use pyo3::pyclass;
23pub use strand::Strand;
24
25pub static NO_CHROMOSOME_INDEX: i64 = -1;
26pub static PRESERVE_EDIT_SITE_CHROMOSOME_INDEX: i64 = -2;
27pub static INDETERMINATE_CHROMOSOME_INDEX: i64 = -3;
28/// Number of bytes in a native Dolt commit hash.
29pub const DOLT_HASH_SIZE: usize = 20;
30/// Number of bytes in a Gen domain identifier.
31pub const HASH_ID_SIZE: usize = 16;
32/// Number of bytes in a SHA-256 content hash.
33pub const SHA256_HASH_SIZE: usize = 32;
34
35// these are just the written out hex from the inserted values from sql migrations
36pub const PATH_START_NODE_ID: HashId = HashId([
37    0x84, 0xd6, 0xad, 0xbd, 0x53, 0x95, 0x28, 0x19, 0x33, 0xfe, 0x41, 0xe8, 0x77, 0xd3, 0xa7, 0xf0,
38]);
39pub const PATH_END_NODE_ID: HashId = HashId([
40    0x1c, 0x7d, 0xfc, 0x64, 0x97, 0x7b, 0x08, 0x38, 0xaf, 0x07, 0x62, 0xd7, 0x33, 0x3d, 0xcb, 0x64,
41]);
42pub const PATH_START_SEQUENCE_HASH: Sha256Hash = Sha256Hash([
43    0x84, 0xd6, 0xad, 0xbd, 0x53, 0x95, 0x28, 0x19, 0x33, 0xfe, 0x41, 0xe8, 0x77, 0xd3, 0xa7, 0xf0,
44    0x2a, 0x3b, 0x19, 0x90, 0xa6, 0x5b, 0xe1, 0x90, 0x1b, 0x2c, 0x91, 0xfc, 0x68, 0x5e, 0x08, 0x3b,
45]);
46pub const PATH_END_SEQUENCE_HASH: Sha256Hash = Sha256Hash([
47    0x1c, 0x7d, 0xfc, 0x64, 0x97, 0x7b, 0x08, 0x38, 0xaf, 0x07, 0x62, 0xd7, 0x33, 0x3d, 0xcb, 0x64,
48    0xc1, 0x75, 0xb1, 0x5e, 0x65, 0xa7, 0x00, 0x99, 0xec, 0x38, 0xf4, 0x6b, 0xf1, 0xa1, 0x5e, 0xa3,
49]);
50
51pub fn is_terminal(node_id: HashId) -> bool {
52    is_start_node(node_id) || is_end_node(node_id)
53}
54
55pub fn is_start_node(node_id: HashId) -> bool {
56    node_id == PATH_START_NODE_ID
57}
58
59pub fn is_end_node(node_id: HashId) -> bool {
60    node_id == PATH_END_NODE_ID
61}
62
63#[derive(
64    Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Deserialize, serde::Serialize,
65)]
66pub struct CommitRef(pub String);
67
68#[derive(
69    Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Deserialize, serde::Serialize,
70)]
71pub struct BranchName(pub String);
72
73#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
74pub struct DoltHashId(pub [u8; DOLT_HASH_SIZE]);
75
76impl serde::Serialize for DoltHashId {
77    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
78    where
79        S: serde::Serializer,
80    {
81        serializer.serialize_str(&self.to_string())
82    }
83}
84
85impl<'de> serde::Deserialize<'de> for DoltHashId {
86    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
87    where
88        D: serde::Deserializer<'de>,
89    {
90        struct DoltHashIdVisitor;
91
92        impl<'de> serde::de::Visitor<'de> for DoltHashIdVisitor {
93            type Value = DoltHashId;
94
95            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
96                formatter.write_str("a 40-character hex string")
97            }
98
99            fn visit_str<E>(self, value: &str) -> Result<DoltHashId, E>
100            where
101                E: serde::de::Error,
102            {
103                DoltHashId::try_from(value).map_err(E::custom)
104            }
105        }
106
107        deserializer.deserialize_str(DoltHashIdVisitor)
108    }
109}
110
111impl fmt::Display for DoltHashId {
112    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
113        for byte in &self.0 {
114            write!(formatter, "{byte:02x}")?;
115        }
116        Ok(())
117    }
118}
119
120impl fmt::Debug for DoltHashId {
121    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
122        write!(formatter, "DoltHashId({self})")
123    }
124}
125
126impl TryFrom<String> for DoltHashId {
127    type Error = HashError;
128
129    fn try_from(value: String) -> Result<Self, Self::Error> {
130        Self::try_from(value.as_str())
131    }
132}
133
134impl TryFrom<&str> for DoltHashId {
135    type Error = HashError;
136
137    fn try_from(value: &str) -> Result<Self, Self::Error> {
138        let bytes = hex::decode(value)?;
139        let actual = bytes.len();
140        let array = bytes.try_into().map_err(|_| HashError::InvalidLength {
141            expected: DOLT_HASH_SIZE,
142            actual,
143        })?;
144        Ok(Self(array))
145    }
146}
147
148impl TryFrom<&[u8]> for DoltHashId {
149    type Error = HashError;
150
151    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
152        let actual = value.len();
153        let array = value.try_into().map_err(|_| HashError::InvalidLength {
154            expected: DOLT_HASH_SIZE,
155            actual,
156        })?;
157        Ok(Self(array))
158    }
159}
160
161#[cfg_attr(feature = "python-bindings", pyclass(from_py_object))]
162#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
163/// A 128-bit Gen domain identifier, normally derived with XXH3-128.
164pub struct HashId(pub [u8; HASH_ID_SIZE]);
165
166#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
167/// A 256-bit SHA-256 content hash used for sequences and file checksums.
168pub struct Sha256Hash(pub [u8; SHA256_HASH_SIZE]);
169
170use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
171
172macro_rules! impl_fixed_hash {
173    ($hash_type:ident, $size:expr) => {
174        impl serde::Serialize for $hash_type {
175            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
176            where
177                S: serde::Serializer,
178            {
179                serializer.serialize_str(&self.to_string())
180            }
181        }
182
183        impl<'de> serde::Deserialize<'de> for $hash_type {
184            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
185            where
186                D: serde::Deserializer<'de>,
187            {
188                struct HashVisitor;
189
190                impl<'de> serde::de::Visitor<'de> for HashVisitor {
191                    type Value = $hash_type;
192
193                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
194                        write!(formatter, "a {}-character hex string", $size * 2)
195                    }
196
197                    fn visit_str<E>(self, value: &str) -> Result<$hash_type, E>
198                    where
199                        E: serde::de::Error,
200                    {
201                        $hash_type::try_from(value).map_err(E::custom)
202                    }
203                }
204
205                deserializer.deserialize_str(HashVisitor)
206            }
207        }
208
209        impl fmt::Display for $hash_type {
210            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
211                for byte in &self.0 {
212                    write!(formatter, "{byte:02x}")?;
213                }
214                Ok(())
215            }
216        }
217
218        impl fmt::Debug for $hash_type {
219            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
220                write!(formatter, "{}({self})", stringify!($hash_type))
221            }
222        }
223
224        impl TryFrom<String> for $hash_type {
225            type Error = HashError;
226
227            fn try_from(value: String) -> Result<Self, Self::Error> {
228                Self::try_from(value.as_str())
229            }
230        }
231
232        impl TryFrom<&str> for $hash_type {
233            type Error = HashError;
234
235            fn try_from(value: &str) -> Result<Self, Self::Error> {
236                let bytes = hex::decode(value)?;
237                let actual = bytes.len();
238                let array = bytes.try_into().map_err(|_| HashError::InvalidLength {
239                    expected: $size,
240                    actual,
241                })?;
242                Ok(Self(array))
243            }
244        }
245
246        impl TryFrom<&[u8]> for $hash_type {
247            type Error = HashError;
248
249            fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
250                let actual = value.len();
251                let array = value.try_into().map_err(|_| HashError::InvalidLength {
252                    expected: $size,
253                    actual,
254                })?;
255                Ok(Self(array))
256            }
257        }
258
259        impl PartialEq<[u8; $size]> for $hash_type {
260            fn eq(&self, other: &[u8; $size]) -> bool {
261                &self.0 == other
262            }
263        }
264
265        impl PartialEq<$hash_type> for [u8; $size] {
266            fn eq(&self, other: &$hash_type) -> bool {
267                self == &other.0
268            }
269        }
270
271        impl FromSql for $hash_type {
272            fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
273                match value {
274                    ValueRef::Blob(bytes) => {
275                        Self::try_from(bytes).map_err(|error| FromSqlError::Other(Box::new(error)))
276                    }
277                    _ => Err(FromSqlError::InvalidType),
278                }
279            }
280        }
281
282        impl ToSql for $hash_type {
283            fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
284                Ok(ToSqlOutput::from(self.0.as_ref()))
285            }
286        }
287
288        impl From<$hash_type> for Value {
289            fn from(hash: $hash_type) -> Self {
290                Value::Blob(hash.0.to_vec())
291            }
292        }
293    };
294}
295
296impl_fixed_hash!(HashId, HASH_ID_SIZE);
297impl_fixed_hash!(Sha256Hash, SHA256_HASH_SIZE);
298
299impl FromSql for DoltHashId {
300    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
301        match value {
302            ValueRef::Text(text) => {
303                let text = core::str::from_utf8(text).map_err(|error| {
304                    FromSqlError::Other(Box::new(std::io::Error::new(
305                        std::io::ErrorKind::InvalidData,
306                        error,
307                    )))
308                })?;
309                Self::try_from(text).map_err(|error| FromSqlError::Other(Box::new(error)))
310            }
311            ValueRef::Blob(bytes) => {
312                Self::try_from(bytes).map_err(|error| FromSqlError::Other(Box::new(error)))
313            }
314            _ => Err(FromSqlError::InvalidType),
315        }
316    }
317}
318
319impl ToSql for DoltHashId {
320    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
321        Ok(ToSqlOutput::Owned(rusqlite::types::Value::Text(
322            self.to_string(),
323        )))
324    }
325}
326
327use rusqlite::types::Value;
328
329impl From<uuid::Uuid> for HashId {
330    fn from(uuid: uuid::Uuid) -> Self {
331        Self(*uuid.as_bytes())
332    }
333}
334
335impl HashId {
336    /// Left-pads a hexadecimal fixture value to the full identifier width.
337    pub fn pad_str<T: ToString>(input: T) -> Self {
338        let s = input.to_string();
339        let hex = format!("{s:0>32}");
340        let bytes = hex::decode(hex).expect("invalid hex string");
341        HashId(bytes.try_into().expect("should contain 16 bytes"))
342    }
343
344    /// Derives a stable domain identifier from a string using XXH3-128.
345    pub fn convert_str(s: &str) -> Self {
346        HashId(calculate_hash(s))
347    }
348
349    pub fn random_str() -> Self {
350        let mut rng = rand::rng();
351        let mut random_bytes = [0u8; HASH_ID_SIZE];
352        rng.fill_bytes(&mut random_bytes);
353        Self(random_bytes)
354    }
355
356    pub fn uuid7() -> Self {
357        uuid::Uuid::now_v7().into()
358    }
359
360    // this is a hack for the library code, which we have a hack for chromosome_index to be the edge_id
361    pub fn extract_digits(&self) -> i64 {
362        let hex = format!("{self}");
363        let digits: String = hex
364            .chars()
365            .map(|c| {
366                if c.is_ascii_digit() {
367                    c
368                } else {
369                    // ascii digits start at 48, alphabet at 97 so subtract 49 to get char digits. We add 1 to make 'a' = 1
370                    // to prevent leading zeros
371                    (c.to_ascii_lowercase() as u8 - 49 + 1) as char
372                }
373            })
374            .take(15) // limit to first 15 digits if you want
375            .collect();
376
377        digits.parse().unwrap_or(0)
378    }
379
380    pub fn starts_with(&self, prefix: &str) -> bool {
381        if prefix.len() > HASH_ID_SIZE * 2 || prefix.is_empty() {
382            return false;
383        }
384
385        let end_byte = prefix.len() / 2 + prefix.len() % 2;
386        let encoded = hex::encode(&self.0[..end_byte]);
387        encoded.starts_with(prefix)
388    }
389}
390
391impl Sha256Hash {
392    /// Calculates the SHA-256 digest of a string.
393    pub fn convert_str(value: &str) -> Self {
394        Self(calculate_sha256(value))
395    }
396}
397
398#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
399pub struct NodeIntervalBlock {
400    pub node_id: HashId,
401    pub start: i64,
402    pub end: i64,
403    pub sequence_start: i64,
404    pub sequence_end: i64,
405    pub strand: Strand,
406}
407
408/// Calculates a 128-bit XXH3 Gen domain identifier.
409pub fn calculate_hash(value: &str) -> [u8; HASH_ID_SIZE] {
410    xxh3_128(value.as_bytes()).to_le_bytes()
411}
412
413/// Calculates a SHA-256 content hash.
414pub fn calculate_sha256(value: &str) -> [u8; SHA256_HASH_SIZE] {
415    let mut hasher = Sha256::new();
416    hasher.update(value);
417    let result = hasher.finalize();
418    result.into()
419}
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424
425    #[test]
426    fn test_hash_id_uses_xxh3_128() {
427        let result = HashId::convert_str("a test");
428        assert_eq!(calculate_hash("a test"), result);
429        assert_eq!(result.to_string(), "88f0cfc88597fce07ca40a6af6070b00");
430        assert_eq!(std::mem::size_of::<HashId>(), HASH_ID_SIZE);
431        assert_ne!(result, HashId::convert_str("another test"));
432    }
433
434    #[test]
435    fn test_calculate_sha256() {
436        let result: Sha256Hash = "a82639b6f8c3a6e536d8cc562c3b86ff4b012c84ab230c1e5be649aa9ad26d21"
437            .try_into()
438            .unwrap();
439        assert_eq!(calculate_sha256("a test"), result);
440        assert_eq!(std::mem::size_of::<Sha256Hash>(), SHA256_HASH_SIZE);
441    }
442
443    #[cfg(test)]
444    mod hashid {
445        use super::*;
446
447        #[test]
448        fn test_starts_with() {
449            let hash = HashId::convert_str("a test");
450            let encoded = hash.to_string();
451            assert!(hash.starts_with(&encoded[..4]));
452            assert!(hash.starts_with(&encoded));
453            assert!(!hash.starts_with("ffff"));
454            assert!(!hash.starts_with(&format!("{encoded}0")));
455            assert!(!hash.starts_with(""));
456            assert!(!hash.starts_with(&format!("{encoded}9")));
457        }
458    }
459
460    mod dolt_hash_id {
461        use super::*;
462
463        #[test]
464        fn test_round_trips_dolt_hash_hex() {
465            let hex = "8a7f64798afa5f3f66b37357717c3e57fa7cdf06";
466            let hash = DoltHashId::try_from(hex).unwrap();
467
468            assert_eq!(hash.to_string(), hex);
469        }
470
471        #[test]
472        fn test_rejects_non_dolt_hash_length() {
473            let error = DoltHashId::try_from(
474                "0000000000000000000000008a7f64798afa5f3f66b37357717c3e57fa7cdf06",
475            )
476            .unwrap_err();
477
478            assert_eq!(
479                error,
480                HashError::InvalidLength {
481                    expected: DOLT_HASH_SIZE,
482                    actual: 32,
483                }
484            );
485        }
486    }
487}