use std::collections::BTreeMap;
use sha2::{Digest, Sha256};
use crate::Error;
use crate::canon::{CanonReader, CanonWriter, RecordWriter, list_value, map_value};
use crate::content::{ContentStore, to_hex};
use crate::status::EpistemicStatus;
pub use crate::content::BlobId;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Text {
pub bytes: Vec<u8>,
pub encoding: Option<String>,
}
impl Text {
#[must_use]
pub fn utf8(s: &str) -> Self {
Self {
bytes: s.as_bytes().to_vec(),
encoding: None,
}
}
#[must_use]
pub fn as_utf8(&self) -> Option<&str> {
std::str::from_utf8(&self.bytes).ok()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Time {
pub seconds: i64,
pub offset_minutes: Option<i16>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SourceKind {
Git,
Hg,
Svn,
Cvs,
Other(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Signature {
pub label: String,
pub bytes: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Extra {
pub label: String,
pub bytes: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SourceIdentity {
pub kind: SourceKind,
pub repo_id: Vec<u8>,
pub atom_id: Vec<u8>,
pub signatures: Vec<Signature>,
pub extras: Vec<Extra>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Content {
Blob {
blob: BlobId,
mode: u32,
},
Submodule {
commit: Vec<u8>,
},
}
impl Content {
#[must_use]
pub fn blob(blob: BlobId, mode: u32) -> Self {
Self::Blob { blob, mode }
}
#[must_use]
pub fn submodule(commit: Vec<u8>) -> Self {
Self::Submodule { commit }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathOp {
Add {
path: String,
content: Content,
status: EpistemicStatus,
},
Modify {
path: String,
content: Content,
status: EpistemicStatus,
},
Delete {
path: String,
status: EpistemicStatus,
},
Replace {
path: String,
content: Content,
status: EpistemicStatus,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CopyRecord {
pub from: String,
pub from_atom: AtomId,
pub to: String,
pub status: EpistemicStatus,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Identity {
pub name: Text,
pub email: Option<Text>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MetadataClaims {
pub author: Option<Identity>,
pub author_time: Option<Time>,
pub committer: Option<Identity>,
pub commit_time: Option<Time>,
pub message: Option<Text>,
}
impl MetadataClaims {
#[must_use]
pub fn is_empty(&self) -> bool {
self.author.is_none()
&& self.author_time.is_none()
&& self.committer.is_none()
&& self.commit_time.is_none()
&& self.message.is_none()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AtomId(pub [u8; 32]);
impl AtomId {
#[must_use]
pub fn to_hex(&self) -> String {
to_hex(&self.0)
}
}
impl std::fmt::Display for AtomId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.to_hex())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChangeAtom {
pub id: AtomId,
pub parents: Vec<AtomId>,
pub ops: Vec<PathOp>,
pub copies: Vec<CopyRecord>,
pub metadata: MetadataClaims,
pub source: SourceIdentity,
pub status: EpistemicStatus,
}
impl ChangeAtom {
#[must_use]
pub fn is_move(&self, copy: &CopyRecord) -> bool {
self.parents.first() == Some(©.from_atom)
&& self
.ops
.iter()
.any(|op| matches!(op, PathOp::Delete { path, .. } if path == ©.from))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum RefKind {
Branch,
Tag,
Bookmark,
NamedBranch,
Other(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Annotation {
pub tagger: Option<Identity>,
pub time: Option<Time>,
pub message: Option<Text>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefRecord {
pub name: String,
pub kind: RefKind,
pub target: AtomId,
pub status: EpistemicStatus,
pub source: Option<SourceIdentity>,
pub annotation: Option<Annotation>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LossClass {
Representation,
AdvisoryUnreliable,
Other,
Transform,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DropRecord {
pub class: LossClass,
pub what: String,
pub reason: String,
pub step: Option<u64>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LossBoundary {
pub dropped: Vec<DropRecord>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlagKind {
ConventionViolation,
BelowConfidenceFloor,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Flag {
pub kind: FlagKind,
pub what: String,
pub count: u64,
pub reason: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportProvenance {
pub source: SourceIdentity,
pub brygge_version: String,
pub decoder: String,
pub decoder_version: String,
pub params: BTreeMap<String, String>,
}
#[derive(Debug, PartialEq, Eq)]
pub struct Ir {
pub atoms: Vec<ChangeAtom>,
pub refs: Vec<RefRecord>,
pub provenance: ImportProvenance,
pub loss: LossBoundary,
pub flags: Vec<Flag>,
pub content: ContentStore,
pub transforms: Vec<TransformRecord>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ChangedPart {
Author,
AuthorTime,
Committer,
CommitTime,
Message,
Ops,
Copies,
Parents,
Blob,
Mode,
Path,
Annotation,
Kind,
Name,
Target,
}
impl ChangedPart {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Author => "author",
Self::AuthorTime => "author-time",
Self::Committer => "committer",
Self::CommitTime => "commit-time",
Self::Message => "message",
Self::Ops => "ops",
Self::Copies => "copies",
Self::Parents => "parents",
Self::Blob => "blob",
Self::Mode => "mode",
Self::Path => "path",
Self::Annotation => "annotation",
Self::Kind => "kind",
Self::Name => "name",
Self::Target => "target",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
Some(match s {
"author" => Self::Author,
"author-time" => Self::AuthorTime,
"committer" => Self::Committer,
"commit-time" => Self::CommitTime,
"message" => Self::Message,
"ops" => Self::Ops,
"copies" => Self::Copies,
"parents" => Self::Parents,
"blob" => Self::Blob,
"mode" => Self::Mode,
"path" => Self::Path,
"annotation" => Self::Annotation,
"kind" => Self::Kind,
"name" => Self::Name,
"target" => Self::Target,
_ => return None,
})
}
#[must_use]
pub fn valid_on_atom(&self) -> bool {
matches!(
self,
Self::Author
| Self::AuthorTime
| Self::Committer
| Self::CommitTime
| Self::Message
| Self::Ops
| Self::Copies
| Self::Parents
)
}
#[must_use]
pub fn valid_on_op(&self) -> bool {
matches!(self, Self::Blob | Self::Mode | Self::Path)
}
#[must_use]
pub fn valid_on_ref(&self) -> bool {
matches!(
self,
Self::Annotation | Self::Kind | Self::Name | Self::Target
)
}
}
fn is_lower_hex_atom_id(s: &str) -> bool {
s.len() == 64
&& s.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
fn is_valid_transform_drop_what(what: &str) -> bool {
if let Some(id) = what.strip_prefix("atom ") {
return is_lower_hex_atom_id(id);
}
if let Some(rest) = what.strip_prefix("op ") {
return rest
.split_once(' ')
.is_some_and(|(id, _path)| is_lower_hex_atom_id(id));
}
if let Some(rest) = what.strip_prefix("copy ") {
return rest
.split_once(' ')
.is_some_and(|(id, _to)| is_lower_hex_atom_id(id));
}
if let Some(rest) = what.strip_prefix("ref ") {
return rest.split_once(' ').is_some_and(|(kind, _name)| {
matches!(kind, "branch" | "tag" | "bookmark" | "named-branch")
|| kind.starts_with("other:")
});
}
false
}
fn is_valid_transform_name(s: &str) -> bool {
let bytes = s.as_bytes();
if bytes.is_empty() || bytes.len() > 64 {
return false;
}
let is_lower_alnum = |b: u8| b.is_ascii_lowercase() || b.is_ascii_digit();
match bytes.split_first() {
Some((&first, rest)) => {
is_lower_alnum(first) && rest.iter().all(|&b| is_lower_alnum(b) || b == b'-')
}
None => false,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransformRecord {
pub name: String,
pub version: String,
pub params: BTreeMap<String, String>,
pub consumed: [u8; 32],
}
impl SourceKind {
fn encode(&self) -> Vec<u8> {
let mut w = CanonWriter::new();
let variant = match self {
Self::Git => 0,
Self::Hg => 1,
Self::Svn => 2,
Self::Cvs => 3,
Self::Other(_) => 4,
};
w.uvarint(variant);
let mut rw = RecordWriter::new();
if let Self::Other(label) = self {
rw.field(1, true, label.as_bytes().to_vec());
}
rw.finish_into(&mut w);
w.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
match r.uvarint()? {
v @ 0..=3 => {
r.record_fields("SourceKind", |_, _, _| Ok(false))?;
Ok(match v {
0 => Self::Git,
1 => Self::Hg,
2 => Self::Svn,
_ => Self::Cvs,
})
}
4 => {
let mut label = None;
r.record_fields("SourceKind::Other", |r, id, len| {
if id == 1 {
label = Some(r.text(len)?);
Ok(true)
} else {
Ok(false)
}
})?;
Ok(Self::Other(label.ok_or_else(|| {
Error::NonCanonical("SourceKind::Other missing field 1 (label)".to_string())
})?))
}
o => Err(Error::Decode(format!("unknown SourceKind variant {o}"))),
}
}
}
impl Text {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
rw.field(1, true, self.bytes.clone());
if let Some(enc) = &self.encoding {
rw.field(2, true, enc.as_bytes().to_vec());
}
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut bytes = None;
let mut encoding = None;
r.record_fields("Text", |r, id, len| match id {
1 => {
bytes = Some(r.bytes_exact(len)?);
Ok(true)
}
2 => {
encoding = Some(r.text(len)?);
Ok(true)
}
_ => Ok(false),
})?;
Ok(Self {
bytes: bytes
.ok_or_else(|| Error::NonCanonical("Text missing field 1 (bytes)".to_string()))?,
encoding,
})
}
}
impl Time {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
rw.field(1, true, crate::canon::svarint_value(self.seconds));
if let Some(off) = self.offset_minutes {
rw.field(2, true, crate::canon::svarint_value(i64::from(off)));
}
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut seconds = None;
let mut offset_minutes = None;
r.record_fields("Time", |r, id, _len| match id {
1 => {
seconds = Some(r.svarint()?);
Ok(true)
}
2 => {
let v = r.svarint()?;
let v = i16::try_from(v).map_err(|_| {
Error::NonCanonical("Time.offset_minutes does not fit i16".to_string())
})?;
offset_minutes = Some(v);
Ok(true)
}
_ => Ok(false),
})?;
Ok(Self {
seconds: seconds
.ok_or_else(|| Error::NonCanonical("Time missing field 1 (seconds)".to_string()))?,
offset_minutes,
})
}
}
impl Signature {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
rw.field(1, true, self.label.as_bytes().to_vec());
rw.field(2, true, self.bytes.clone());
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut label = None;
let mut bytes = None;
r.record_fields("Signature", |r, id, len| match id {
1 => {
label = Some(r.text(len)?);
Ok(true)
}
2 => {
bytes = Some(r.bytes_exact(len)?);
Ok(true)
}
_ => Ok(false),
})?;
Ok(Self {
label: label.ok_or_else(|| {
Error::NonCanonical("Signature missing field 1 (label)".to_string())
})?,
bytes: bytes.ok_or_else(|| {
Error::NonCanonical("Signature missing field 2 (bytes)".to_string())
})?,
})
}
}
impl Extra {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
rw.field(1, true, self.label.as_bytes().to_vec());
rw.field(2, true, self.bytes.clone());
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut label = None;
let mut bytes = None;
r.record_fields("Extra", |r, id, len| match id {
1 => {
label = Some(r.text(len)?);
Ok(true)
}
2 => {
bytes = Some(r.bytes_exact(len)?);
Ok(true)
}
_ => Ok(false),
})?;
Ok(Self {
label: label
.ok_or_else(|| Error::NonCanonical("Extra missing field 1 (label)".to_string()))?,
bytes: bytes
.ok_or_else(|| Error::NonCanonical("Extra missing field 2 (bytes)".to_string()))?,
})
}
}
impl SourceIdentity {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
rw.field(1, true, self.kind.encode());
rw.field(2, true, self.repo_id.clone());
rw.field(3, true, self.atom_id.clone());
if !self.signatures.is_empty() {
rw.field(
4,
true,
list_value(self.signatures.iter().map(Signature::encode)),
);
}
if !self.extras.is_empty() {
rw.field(5, true, list_value(self.extras.iter().map(Extra::encode)));
}
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut kind = None;
let mut repo_id = None;
let mut atom_id = None;
let mut signatures = Vec::new();
let mut extras = Vec::new();
r.record_fields("SourceIdentity", |r, id, len| match id {
1 => {
kind = Some(SourceKind::decode(r)?);
Ok(true)
}
2 => {
repo_id = Some(r.bytes_exact(len)?);
Ok(true)
}
3 => {
atom_id = Some(r.bytes_exact(len)?);
Ok(true)
}
4 => {
signatures = r.list(Signature::decode)?;
non_empty_list("SourceIdentity.signatures", &signatures)?;
Ok(true)
}
5 => {
extras = r.list(Extra::decode)?;
non_empty_list("SourceIdentity.extras", &extras)?;
Ok(true)
}
_ => Ok(false),
})?;
Ok(Self {
kind: kind.ok_or_else(|| {
Error::NonCanonical("SourceIdentity missing field 1 (kind)".to_string())
})?,
repo_id: repo_id.ok_or_else(|| {
Error::NonCanonical("SourceIdentity missing field 2 (repo_id)".to_string())
})?,
atom_id: atom_id.ok_or_else(|| {
Error::NonCanonical("SourceIdentity missing field 3 (atom_id)".to_string())
})?,
signatures,
extras,
})
}
}
fn non_empty_list<T>(field: &'static str, v: &[T]) -> Result<(), Error> {
if v.is_empty() {
Err(Error::NonCanonical(format!("{field} encoded but empty")))
} else {
Ok(())
}
}
impl PathOp {
#[must_use]
pub fn path(&self) -> &str {
match self {
Self::Add { path, .. }
| Self::Modify { path, .. }
| Self::Delete { path, .. }
| Self::Replace { path, .. } => path,
}
}
#[must_use]
pub fn status(&self) -> &EpistemicStatus {
match self {
Self::Add { status, .. }
| Self::Modify { status, .. }
| Self::Delete { status, .. }
| Self::Replace { status, .. } => status,
}
}
#[must_use]
pub fn content(&self) -> Option<&Content> {
match self {
Self::Add { content, .. }
| Self::Modify { content, .. }
| Self::Replace { content, .. } => Some(content),
Self::Delete { .. } => None,
}
}
fn encode(&self) -> Vec<u8> {
let mut w = CanonWriter::new();
let (variant, path, content, status) = match self {
Self::Add {
path,
content,
status,
} => (0, path, Some(content), status),
Self::Modify {
path,
content,
status,
} => (1, path, Some(content), status),
Self::Delete { path, status } => (2, path, None, status),
Self::Replace {
path,
content,
status,
} => (3, path, Some(content), status),
};
w.uvarint(variant);
let mut rw = RecordWriter::new();
rw.field(1, true, path.as_bytes().to_vec());
match content {
Some(Content::Blob { blob, mode }) => {
rw.field(2, true, blob.as_bytes().to_vec());
rw.field(3, true, crate::canon::uvarint_value(u64::from(*mode)));
rw.field(4, true, status.encode());
}
Some(Content::Submodule { commit }) => {
rw.field(4, true, status.encode());
rw.field(5, true, commit.clone());
}
None => {
rw.field(4, true, status.encode());
}
}
rw.finish_into(&mut w);
w.into_bytes()
}
fn decode(r: &mut CanonReader, minor: u32) -> Result<Self, Error> {
let variant = r.uvarint()?;
let mut path = None;
let mut blob = None;
let mut mode = None;
let mut commit = None;
let mut status = None;
let handle = |r: &mut CanonReader, id: u64, len: usize| match id {
1 => {
path = Some(r.text(len)?);
Ok(true)
}
2 => {
blob = Some(BlobId(r.raw32()?));
Ok(true)
}
3 => {
mode = Some(read_u32(r)?);
Ok(true)
}
4 => {
status = Some(EpistemicStatus::decode(r, 0)?);
Ok(true)
}
5 if minor >= 4 => {
commit = Some(r.bytes_exact(len)?);
Ok(true)
}
_ => Ok(false),
};
r.record_fields("PathOp", handle)?;
let path =
path.ok_or_else(|| Error::NonCanonical("PathOp missing field 1 (path)".to_string()))?;
let status = status
.ok_or_else(|| Error::NonCanonical("PathOp missing field 4 (status)".to_string()))?;
let mut need_content = |what: &'static str| -> Result<Content, Error> {
match (blob, mode, commit.take()) {
(Some(blob), Some(mode), None) => Ok(Content::Blob { blob, mode }),
(None, None, Some(commit)) => {
if commit.len() != 20 && commit.len() != 32 {
return Err(Error::NonCanonical(format!(
"PathOp::{what} field 5 (submodule) is {} bytes, must be 20 or 32",
commit.len()
)));
}
Ok(Content::Submodule { commit })
}
(None, None, None) => Err(Error::NonCanonical(format!(
"PathOp::{what} has neither a blob (fields 2 and 3) nor a submodule (field 5)"
))),
_ => Err(Error::NonCanonical(format!(
"PathOp::{what} has both a blob and a submodule, or an incomplete blob (field 2 \
without 3, or field 3 without 2)"
))),
}
};
Ok(match variant {
0 => Self::Add {
path,
content: need_content("Add")?,
status,
},
1 => Self::Modify {
path,
content: need_content("Modify")?,
status,
},
2 => Self::Delete { path, status },
3 => Self::Replace {
path,
content: need_content("Replace")?,
status,
},
o => return Err(Error::Decode(format!("unknown PathOp variant {o}"))),
})
}
}
impl CopyRecord {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
rw.field(1, true, self.from.as_bytes().to_vec());
rw.field(2, true, self.from_atom.0.to_vec());
rw.field(3, true, self.to.as_bytes().to_vec());
rw.field(4, true, self.status.encode());
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut from = None;
let mut from_atom = None;
let mut to = None;
let mut status = None;
r.record_fields("CopyRecord", |r, id, len| match id {
1 => {
from = Some(r.text(len)?);
Ok(true)
}
2 => {
from_atom = Some(AtomId(r.raw32()?));
Ok(true)
}
3 => {
to = Some(r.text(len)?);
Ok(true)
}
4 => {
status = Some(EpistemicStatus::decode(r, 0)?);
Ok(true)
}
_ => Ok(false),
})?;
Ok(Self {
from: from.ok_or_else(|| {
Error::NonCanonical("CopyRecord missing field 1 (from)".to_string())
})?,
from_atom: from_atom.ok_or_else(|| {
Error::NonCanonical("CopyRecord missing field 2 (from_atom)".to_string())
})?,
to: to.ok_or_else(|| {
Error::NonCanonical("CopyRecord missing field 3 (to)".to_string())
})?,
status: status.ok_or_else(|| {
Error::NonCanonical("CopyRecord missing field 4 (status)".to_string())
})?,
})
}
}
impl Identity {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
rw.field(1, true, self.name.encode());
if let Some(email) = &self.email {
rw.field(2, true, email.encode());
}
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut name = None;
let mut email = None;
r.record_fields("Identity", |r, id, _len| match id {
1 => {
name = Some(Text::decode(r)?);
Ok(true)
}
2 => {
email = Some(Text::decode(r)?);
Ok(true)
}
_ => Ok(false),
})?;
Ok(Self {
name: name.ok_or_else(|| {
Error::NonCanonical("Identity missing field 1 (name)".to_string())
})?,
email,
})
}
}
impl MetadataClaims {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
if let Some(a) = &self.author {
rw.field(1, true, a.encode());
}
if let Some(t) = &self.author_time {
rw.field(2, true, t.encode());
}
if let Some(c) = &self.committer {
rw.field(3, true, c.encode());
}
if let Some(t) = &self.commit_time {
rw.field(4, true, t.encode());
}
if let Some(m) = &self.message {
rw.field(5, true, m.encode());
}
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut out = Self::default();
r.record_fields("MetadataClaims", |r, id, _len| match id {
1 => {
out.author = Some(Identity::decode(r)?);
Ok(true)
}
2 => {
out.author_time = Some(Time::decode(r)?);
Ok(true)
}
3 => {
out.committer = Some(Identity::decode(r)?);
Ok(true)
}
4 => {
out.commit_time = Some(Time::decode(r)?);
Ok(true)
}
5 => {
out.message = Some(Text::decode(r)?);
Ok(true)
}
_ => Ok(false),
})?;
Ok(out)
}
}
fn read_u32(r: &mut CanonReader) -> Result<u32, Error> {
u32::try_from(r.uvarint()?).map_err(|_| Error::Decode("mode out of range".to_string()))
}
impl ChangeAtom {
fn encode_body(&self, rw: &mut RecordWriter) {
if !self.parents.is_empty() {
rw.field(
2,
true,
list_value(self.parents.iter().map(|id| id.0.to_vec())),
);
}
if !self.ops.is_empty() {
rw.field(3, true, list_value(self.ops.iter().map(PathOp::encode)));
}
if !self.copies.is_empty() {
rw.field(
4,
true,
list_value(self.copies.iter().map(CopyRecord::encode)),
);
}
if !self.metadata.is_empty() {
rw.field(5, true, self.metadata.encode());
}
rw.field(6, true, self.source.encode());
rw.field(7, true, self.status.encode());
}
#[must_use]
pub(crate) fn compute_id(&self) -> AtomId {
let mut rw = RecordWriter::new();
self.encode_body(&mut rw);
let mut hasher = Sha256::new();
hasher.update(rw.into_bytes());
AtomId(hasher.finalize().into())
}
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
rw.field(1, true, self.id.0.to_vec());
self.encode_body(&mut rw);
rw.into_bytes()
}
fn decode(r: &mut CanonReader, minor: u32) -> Result<Self, Error> {
let mut id = None;
let mut parents = Vec::new();
let mut ops = Vec::new();
let mut copies = Vec::new();
let mut metadata = MetadataClaims::default();
let mut source = None;
let mut status = None;
r.record_fields("ChangeAtom", |r, fid, _len| match fid {
1 => {
id = Some(AtomId(r.raw32()?));
Ok(true)
}
2 => {
parents = r.list(|r| Ok(AtomId(r.raw32()?)))?;
non_empty_list("ChangeAtom.parents", &parents)?;
Ok(true)
}
3 => {
ops = r.list(|r| PathOp::decode(r, minor))?;
non_empty_list("ChangeAtom.ops", &ops)?;
Ok(true)
}
4 => {
copies = r.list(CopyRecord::decode)?;
non_empty_list("ChangeAtom.copies", &copies)?;
Ok(true)
}
5 => {
metadata = MetadataClaims::decode(r)?;
if metadata.is_empty() {
return Err(Error::NonCanonical(
"ChangeAtom.metadata encoded but every claim absent".to_string(),
));
}
Ok(true)
}
6 => {
source = Some(SourceIdentity::decode(r)?);
Ok(true)
}
7 => {
status = Some(EpistemicStatus::decode(r, 0)?);
Ok(true)
}
_ => Ok(false),
})?;
let id =
id.ok_or_else(|| Error::NonCanonical("ChangeAtom missing field 1 (id)".to_string()))?;
for (a, b) in ops.iter().zip(ops.iter().skip(1)) {
if a.path() >= b.path() {
return Err(Error::NonCanonical(
"ChangeAtom.ops are not strictly ascending by path".to_string(),
));
}
}
for (a, b) in copies.iter().zip(copies.iter().skip(1)) {
let ka = (&a.to, &a.from, a.from_atom);
let kb = (&b.to, &b.from, b.from_atom);
if ka >= kb {
return Err(Error::NonCanonical(
"ChangeAtom.copies are not strictly ascending by (to, from, from_atom)"
.to_string(),
));
}
}
let atom = Self {
id,
parents,
ops,
copies,
metadata,
source: source.ok_or_else(|| {
Error::NonCanonical("ChangeAtom missing field 6 (source)".to_string())
})?,
status: status.ok_or_else(|| {
Error::NonCanonical("ChangeAtom missing field 7 (status)".to_string())
})?,
};
if atom.compute_id() != id {
return Err(Error::Decode(
"atom id does not match its contents".to_string(),
));
}
Ok(atom)
}
}
impl RefKind {
pub(crate) fn variant(&self) -> u8 {
match self {
Self::Branch => 0,
Self::Tag => 1,
Self::Bookmark => 2,
Self::NamedBranch => 3,
Self::Other(_) => 4,
}
}
fn encode(&self) -> Vec<u8> {
let mut w = CanonWriter::new();
w.uvarint(u64::from(self.variant()));
let mut rw = RecordWriter::new();
if let Self::Other(label) = self {
rw.field(1, true, label.as_bytes().to_vec());
}
rw.finish_into(&mut w);
w.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
match r.uvarint()? {
v @ 0..=3 => {
r.record_fields("RefKind", |_, _, _| Ok(false))?;
Ok(match v {
0 => Self::Branch,
1 => Self::Tag,
2 => Self::Bookmark,
_ => Self::NamedBranch,
})
}
4 => {
let mut label = None;
r.record_fields("RefKind::Other", |r, id, len| {
if id == 1 {
label = Some(r.text(len)?);
Ok(true)
} else {
Ok(false)
}
})?;
Ok(Self::Other(label.ok_or_else(|| {
Error::NonCanonical("RefKind::Other missing field 1 (label)".to_string())
})?))
}
o => Err(Error::Decode(format!("unknown RefKind variant {o}"))),
}
}
}
impl Annotation {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
if let Some(t) = &self.tagger {
rw.field(1, true, t.encode());
}
if let Some(t) = &self.time {
rw.field(2, true, t.encode());
}
if let Some(m) = &self.message {
rw.field(3, true, m.encode());
}
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut out = Self::default();
r.record_fields("Annotation", |r, id, _len| match id {
1 => {
out.tagger = Some(Identity::decode(r)?);
Ok(true)
}
2 => {
out.time = Some(Time::decode(r)?);
Ok(true)
}
3 => {
out.message = Some(Text::decode(r)?);
Ok(true)
}
_ => Ok(false),
})?;
Ok(out)
}
}
impl RefRecord {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
rw.field(1, true, self.name.as_bytes().to_vec());
rw.field(2, true, self.kind.encode());
rw.field(3, true, self.target.0.to_vec());
rw.field(4, true, self.status.encode());
if let Some(s) = &self.source {
rw.field(5, true, s.encode());
}
if let Some(a) = &self.annotation {
rw.field(6, true, a.encode());
}
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut name = None;
let mut kind = None;
let mut target = None;
let mut status = None;
let mut source = None;
let mut annotation = None;
r.record_fields("RefRecord", |r, id, len| match id {
1 => {
name = Some(r.text(len)?);
Ok(true)
}
2 => {
kind = Some(RefKind::decode(r)?);
Ok(true)
}
3 => {
target = Some(AtomId(r.raw32()?));
Ok(true)
}
4 => {
status = Some(EpistemicStatus::decode(r, 0)?);
Ok(true)
}
5 => {
source = Some(SourceIdentity::decode(r)?);
Ok(true)
}
6 => {
annotation = Some(Annotation::decode(r)?);
Ok(true)
}
_ => Ok(false),
})?;
Ok(Self {
name: name.ok_or_else(|| {
Error::NonCanonical("RefRecord missing field 1 (name)".to_string())
})?,
kind: kind.ok_or_else(|| {
Error::NonCanonical("RefRecord missing field 2 (kind)".to_string())
})?,
target: target.ok_or_else(|| {
Error::NonCanonical("RefRecord missing field 3 (target)".to_string())
})?,
status: status.ok_or_else(|| {
Error::NonCanonical("RefRecord missing field 4 (status)".to_string())
})?,
source,
annotation,
})
}
}
impl LossClass {
pub(crate) fn variant(self) -> u8 {
match self {
Self::Representation => 0,
Self::AdvisoryUnreliable => 1,
Self::Other => 2,
Self::Transform => 3,
}
}
fn encode(&self) -> Vec<u8> {
let mut w = CanonWriter::new();
w.uvarint(u64::from(self.variant()));
RecordWriter::new().finish_into(&mut w);
w.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let variant = r.uvarint()?;
r.record_fields("LossClass", |_, _, _| Ok(false))?;
Ok(match variant {
0 => Self::Representation,
1 => Self::AdvisoryUnreliable,
2 => Self::Other,
3 => Self::Transform,
o => return Err(Error::Decode(format!("unknown LossClass variant {o}"))),
})
}
}
impl DropRecord {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
rw.field(1, true, self.class.encode());
rw.field(2, true, self.what.as_bytes().to_vec());
rw.field(3, true, self.reason.as_bytes().to_vec());
if let Some(step) = self.step {
rw.field(4, true, crate::canon::uvarint_value(step));
}
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut class = None;
let mut what = None;
let mut reason = None;
let mut step = None;
r.record_fields("DropRecord", |r, id, len| match id {
1 => {
class = Some(LossClass::decode(r)?);
Ok(true)
}
2 => {
what = Some(r.text(len)?);
Ok(true)
}
3 => {
reason = Some(r.text(len)?);
Ok(true)
}
4 => {
step = Some(r.uvarint()?);
Ok(true)
}
_ => Ok(false),
})?;
let class = class
.ok_or_else(|| Error::NonCanonical("DropRecord missing field 1 (class)".to_string()))?;
match (class, step) {
(LossClass::Transform, None) => {
return Err(Error::NonCanonical(
"DropRecord.class is Transform but field 4 (step) is missing".to_string(),
));
}
(c, Some(_)) if c != LossClass::Transform => {
return Err(Error::NonCanonical(
"DropRecord field 4 (step) is present but class is not Transform".to_string(),
));
}
_ => {}
}
let what = what
.ok_or_else(|| Error::NonCanonical("DropRecord missing field 2 (what)".to_string()))?;
if class == LossClass::Transform && !is_valid_transform_drop_what(&what) {
return Err(Error::Decode(format!(
"DropRecord.what {what:?} does not match the Transform-drop grammar"
)));
}
Ok(Self {
class,
what,
reason: reason.ok_or_else(|| {
Error::NonCanonical("DropRecord missing field 3 (reason)".to_string())
})?,
step,
})
}
}
impl FlagKind {
pub(crate) fn variant(self) -> u8 {
match self {
Self::ConventionViolation => 0,
Self::BelowConfidenceFloor => 1,
}
}
fn encode(&self) -> Vec<u8> {
let mut w = CanonWriter::new();
w.uvarint(u64::from(self.variant()));
RecordWriter::new().finish_into(&mut w);
w.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let variant = r.uvarint()?;
r.record_fields("FlagKind", |_, _, _| Ok(false))?;
Ok(match variant {
0 => Self::ConventionViolation,
1 => Self::BelowConfidenceFloor,
o => return Err(Error::Decode(format!("unknown FlagKind variant {o}"))),
})
}
}
impl Flag {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
rw.field(1, true, self.kind.encode());
rw.field(2, true, self.what.as_bytes().to_vec());
rw.field(3, true, crate::canon::uvarint_value(self.count));
rw.field(4, true, self.reason.as_bytes().to_vec());
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut kind = None;
let mut what = None;
let mut count = None;
let mut reason = None;
r.record_fields("Flag", |r, id, len| match id {
1 => {
kind = Some(FlagKind::decode(r)?);
Ok(true)
}
2 => {
what = Some(r.text(len)?);
Ok(true)
}
3 => {
count = Some(r.uvarint()?);
Ok(true)
}
4 => {
reason = Some(r.text(len)?);
Ok(true)
}
_ => Ok(false),
})?;
let count =
count.ok_or_else(|| Error::NonCanonical("Flag missing field 3 (count)".to_string()))?;
if count < 1 {
return Err(Error::NonCanonical(
"Flag.count must be at least 1".to_string(),
));
}
Ok(Self {
kind: kind
.ok_or_else(|| Error::NonCanonical("Flag missing field 1 (kind)".to_string()))?,
what: what
.ok_or_else(|| Error::NonCanonical("Flag missing field 2 (what)".to_string()))?,
count,
reason: reason
.ok_or_else(|| Error::NonCanonical("Flag missing field 4 (reason)".to_string()))?,
})
}
}
impl TransformRecord {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
rw.field(1, true, self.name.as_bytes().to_vec());
rw.field(2, true, self.version.as_bytes().to_vec());
if !self.params.is_empty() {
rw.field(
3,
true,
map_value(self.params.iter().map(|(k, v)| (k.as_str(), v.as_str()))),
);
}
rw.field(4, true, self.consumed.to_vec());
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut name = None;
let mut version = None;
let mut params = BTreeMap::new();
let mut consumed = None;
r.record_fields("TransformRecord", |r, id, len| match id {
1 => {
name = Some(r.text(len)?);
Ok(true)
}
2 => {
version = Some(r.text(len)?);
Ok(true)
}
3 => {
params = r.map()?;
if params.is_empty() {
return Err(Error::NonCanonical(
"TransformRecord.params encoded but empty".to_string(),
));
}
Ok(true)
}
4 => {
consumed = Some(r.raw32()?);
Ok(true)
}
_ => Ok(false),
})?;
let name = name.ok_or_else(|| {
Error::NonCanonical("TransformRecord missing field 1 (name)".to_string())
})?;
if !is_valid_transform_name(&name) {
return Err(Error::Decode(format!(
"TransformRecord.name {name:?} does not match the plugin grammar"
)));
}
let version = version.ok_or_else(|| {
Error::NonCanonical("TransformRecord missing field 2 (version)".to_string())
})?;
if version.is_empty() {
return Err(Error::NonCanonical(
"TransformRecord.version is empty".to_string(),
));
}
let consumed = consumed.ok_or_else(|| {
Error::NonCanonical("TransformRecord missing field 4 (consumed)".to_string())
})?;
Ok(Self {
name,
version,
params,
consumed,
})
}
}
impl ImportProvenance {
fn encode(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
rw.field(1, true, self.source.encode());
rw.field(2, true, self.brygge_version.as_bytes().to_vec());
rw.field(3, true, self.decoder.as_bytes().to_vec());
rw.field(4, true, self.decoder_version.as_bytes().to_vec());
if !self.params.is_empty() {
rw.field(
5,
true,
map_value(self.params.iter().map(|(k, v)| (k.as_str(), v.as_str()))),
);
}
rw.into_bytes()
}
fn decode(r: &mut CanonReader) -> Result<Self, Error> {
let mut source = None;
let mut brygge_version = None;
let mut decoder = None;
let mut decoder_version = None;
let mut params = BTreeMap::new();
r.record_fields("ImportProvenance", |r, id, len| match id {
1 => {
source = Some(SourceIdentity::decode(r)?);
Ok(true)
}
2 => {
brygge_version = Some(r.text(len)?);
Ok(true)
}
3 => {
decoder = Some(r.text(len)?);
Ok(true)
}
4 => {
decoder_version = Some(r.text(len)?);
Ok(true)
}
5 => {
params = r.map()?;
if params.is_empty() {
return Err(Error::NonCanonical(
"ImportProvenance.params encoded but empty".to_string(),
));
}
Ok(true)
}
_ => Ok(false),
})?;
Ok(Self {
source: source.ok_or_else(|| {
Error::NonCanonical("ImportProvenance missing field 1 (source)".to_string())
})?,
brygge_version: brygge_version.ok_or_else(|| {
Error::NonCanonical("ImportProvenance missing field 2 (brygge_version)".to_string())
})?,
decoder: decoder.ok_or_else(|| {
Error::NonCanonical("ImportProvenance missing field 3 (decoder)".to_string())
})?,
decoder_version: decoder_version.ok_or_else(|| {
Error::NonCanonical(
"ImportProvenance missing field 4 (decoder_version)".to_string(),
)
})?,
params,
})
}
}
impl Ir {
pub(crate) fn encode_metadata(&self) -> Vec<u8> {
let mut rw = RecordWriter::new();
if !self.atoms.is_empty() {
rw.field(
1,
true,
list_value(self.atoms.iter().map(ChangeAtom::encode)),
);
}
if !self.refs.is_empty() {
rw.field(2, true, list_value(self.refs.iter().map(RefRecord::encode)));
}
rw.field(3, true, self.provenance.encode());
if !self.loss.dropped.is_empty() {
rw.field(
4,
true,
list_value(self.loss.dropped.iter().map(DropRecord::encode)),
);
}
if !self.flags.is_empty() {
rw.field(5, true, list_value(self.flags.iter().map(Flag::encode)));
}
if !self.transforms.is_empty() {
rw.field(
6,
true,
list_value(self.transforms.iter().map(TransformRecord::encode)),
);
}
rw.into_bytes()
}
pub(crate) fn decode_metadata(r: &mut CanonReader, minor: u32) -> Result<Self, Error> {
let mut atoms = Vec::new();
let mut refs = Vec::new();
let mut provenance = None;
let mut dropped = Vec::new();
let mut flags = Vec::new();
let mut transforms = Vec::new();
r.record_fields("Ir", |r, id, _len| match id {
1 => {
atoms = r.list(|r| ChangeAtom::decode(r, minor))?;
non_empty_list("Ir.atoms", &atoms)?;
Ok(true)
}
2 => {
refs = r.list(RefRecord::decode)?;
non_empty_list("Ir.refs", &refs)?;
Ok(true)
}
3 => {
provenance = Some(ImportProvenance::decode(r)?);
Ok(true)
}
4 => {
dropped = r.list(DropRecord::decode)?;
non_empty_list("Ir.dropped", &dropped)?;
Ok(true)
}
5 => {
flags = r.list(Flag::decode)?;
non_empty_list("Ir.flags", &flags)?;
Ok(true)
}
6 => {
transforms = r.list(TransformRecord::decode)?;
non_empty_list("Ir.transforms", &transforms)?;
if transforms.len() > 64 {
return Err(Error::NonCanonical(
"Ir.transforms holds more than 64 records".to_string(),
));
}
Ok(true)
}
_ => Ok(false),
})?;
for (a, b) in refs.iter().zip(refs.iter().skip(1)) {
let ka = (&a.name, a.kind.variant());
let kb = (&b.name, b.kind.variant());
if ka >= kb {
return Err(Error::NonCanonical(
"Ir.refs are not strictly ascending by (name, kind variant)".to_string(),
));
}
}
for (a, b) in dropped.iter().zip(dropped.iter().skip(1)) {
let ka = (a.class.variant(), a.step, &a.what);
let kb = (b.class.variant(), b.step, &b.what);
if ka >= kb {
return Err(Error::NonCanonical(
"Ir.dropped is not strictly ascending by (class variant, step, what)"
.to_string(),
));
}
}
for (a, b) in flags.iter().zip(flags.iter().skip(1)) {
let ka = (a.kind.variant(), &a.what);
let kb = (b.kind.variant(), &b.what);
if ka >= kb {
return Err(Error::NonCanonical(
"Ir.flags are not strictly ascending by (kind variant, what)".to_string(),
));
}
}
Ok(Self {
atoms,
refs,
provenance: provenance.ok_or_else(|| {
Error::NonCanonical("Ir missing field 3 (provenance)".to_string())
})?,
loss: LossBoundary { dropped },
flags,
content: ContentStore::new(),
transforms,
})
}
}
#[cfg(test)]
mod tests;