Onset: version control where nobody waits and nothing gets lost. The on command, its core and onset-server.
| 6 |
| 7 | #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 8 | pub struct Id(pub [u8; 32]); |
| 9 |
| 10 | impl Id { |
| 11 | pub const ZERO: Id = Id([0; 32]); |
| 12 |
| 13 | /// The ID of an object of `kind` holding `data`. |
| 14 | pub fn of(kind: u8, data: &[u8]) -> Id { |
| 15 | let mut h = Sha256::new(); |
| 16 | h.update([kind]); |
| 17 | h.update(data); |
| 18 | Id(h.finalize().into()) |
| 19 | } |
| 20 |
| 21 | pub fn hex(&self) -> String { |
| 22 | let mut s = String::with_capacity(64); |
| 23 | for b in self.0 { |
| 24 | s.push(char::from_digit((b >> 4) as u32, 16).unwrap()); |
| 25 | s.push(char::from_digit((b & 15) as u32, 16).unwrap()); |
| 26 | } |
| 27 | s |
| 28 | } |
| 29 |
| 30 | pub fn parse(text: &str) -> Option<Id> { |
| 31 | if text.len() != 64 { |
| 32 | return None; |
| 33 | } |
| 34 | let mut out = [0u8; 32]; |
| 35 | for (i, chunk) in text.as_bytes().chunks(2).enumerate() { |
| 36 | let hi = (chunk[0] as char).to_digit(16)?; |
| 37 | let lo = (chunk[1] as char).to_digit(16)?; |
| 38 | out[i] = (hi * 16 + lo) as u8; |
| 39 | } |
| 40 | Some(Id(out)) |
| 41 | } |
| 42 |
| 43 | pub fn from_slice(bytes: &[u8]) -> Option<Id> { |
| 44 | Some(Id(bytes.try_into().ok()?)) |
| 45 | } |
| 46 |
| 47 | pub fn short(&self) -> String { |
| 48 | self.hex()[..12].to_string() |
| 49 | } |
| 50 | } |
| 51 |
| 52 | impl fmt::Display for Id { |
| 53 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 54 | f.write_str(&self.hex()) |
| 55 | } |
| 56 | } |
| 57 |
| 58 | impl fmt::Debug for Id { |
| 59 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 60 | write!(f, "Id({})", self.short()) |
| 61 | } |
| 62 | } |
| 63 |
| 64 | impl serde::Serialize for Id { |
| 65 | fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { |
| 66 | s.serialize_str(&self.hex()) |
| 67 | } |
| 68 | } |
| 69 |
| 70 | impl<'de> serde::Deserialize<'de> for Id { |
| 71 | fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Id, D::Error> { |
| 72 | let text = String::deserialize(d)?; |
| 73 | Id::parse(&text).ok_or_else(|| serde::de::Error::custom("not an object id")) |
| 74 | } |
| 75 | } |
| 76 |
| 77 | /// SHA-256 of arbitrary bytes, for version IDs. |
| 78 | pub fn sha256(parts: &[&[u8]]) -> Id { |
| 79 | let mut h = Sha256::new(); |
| 80 | for p in parts { |
| 81 | h.update(p); |
| 82 | } |
| 83 | Id(h.finalize().into()) |
| 84 | } |
| 85 |
| 86 | #[cfg(test)] |
| 87 | mod tests { |
| 88 | use super::*; |
| 89 |
| 90 | #[test] |
| 91 | fn hex_round_trip() { |
| 92 | let id = Id::of(1, b"hello\n"); |
| 93 | assert_eq!(Id::parse(&id.hex()), Some(id)); |
| 94 | assert_ne!(Id::of(1, b"x"), Id::of(2, b"x")); |
| 95 | } |
| 96 | } |
| 97 |