use std::collections::HashMap;
use std::fs::File;
use std::io::{Cursor, Read, Write};
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::{anyhow, bail, ensure, Result};
use arrow::array::{
Array, BooleanArray, BooleanBuilder, FixedSizeBinaryArray, FixedSizeBinaryBuilder, Int8Array,
Int8Builder, StringArray, StringBuilder, UInt32Array, UInt32Builder, UInt64Array,
UInt64Builder,
};
use arrow::datatypes::{DataType, Field, Schema};
use arrow::ipc::reader::StreamReader;
use arrow::record_batch::RecordBatch;
use crate::index::{data_subindex_schema, ChunkLoc, RESERVED_PKG_TYPE};
use crate::meta_sink::GroupKey;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct Group {
pub pkg_type: i8,
pub repo: String,
}
impl Group {
pub fn new(pkg_type: i8, repo: impl Into<String>) -> Self {
Self {
pkg_type,
repo: repo.into(),
}
}
pub fn is_default(&self) -> bool {
self.pkg_type == 0 && self.repo.is_empty()
}
pub fn key(&self) -> GroupKey {
GroupKey {
pkg_type: self.pkg_type,
repo: self.repo.clone(),
module_name: String::new(),
}
}
pub(crate) fn check(&self) -> Result<()> {
ensure!(
self.pkg_type != RESERVED_PKG_TYPE,
"pkg_type {} is reserved for the archive's own sections",
RESERVED_PKG_TYPE
);
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlobRef {
pub pack: Option<u64>,
pub chunks: Vec<ChunkLoc>,
}
impl BlobRef {
pub fn size(&self) -> u64 {
(self.chunks.iter())
.map(|c| c.fdata_offset.saturating_add(c.uncompressed_size))
.max()
.unwrap_or(0)
}
pub fn stored_bytes(&self) -> u64 {
self.chunks.iter().map(|c| c.blob_size).sum()
}
pub fn checksum(&self) -> Option<[u8; 32]> {
match self.chunks.as_slice() {
[c] if c.fdata_offset == 0 => Some(c.checksum),
_ => None,
}
}
pub(crate) fn end(&self) -> u64 {
(self.chunks.iter())
.map(|c| c.blob_offset.saturating_add(c.blob_size))
.max()
.unwrap_or(0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Lookup {
Absent,
Ended,
Live(BlobRef),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RowEntry {
pub group: Group,
pub name: String,
pub slot: Option<BlobRef>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Was {
New,
Live,
Ended,
}
#[derive(Debug, Default, Clone)]
pub(crate) struct RowIndex {
order: Vec<Group>,
groups: HashMap<Group, GroupRows>,
live: u64,
ended: u64,
}
#[derive(Debug, Default, Clone)]
struct GroupRows {
names: Vec<String>,
slots: Vec<Option<BlobRef>>,
at: HashMap<String, usize>,
}
impl RowIndex {
pub fn lookup(&self, group: &Group, name: &str) -> Lookup {
let Some(rows) = self.groups.get(group) else {
return Lookup::Absent;
};
match rows.at.get(name) {
None => Lookup::Absent,
Some(&i) => match &rows.slots[i] {
Some(b) => Lookup::Live(b.clone()),
None => Lookup::Ended,
},
}
}
pub fn set(&mut self, group: Group, name: String, slot: Option<BlobRef>) -> Was {
if !self.groups.contains_key(&group) {
self.order.push(group.clone());
}
let rows = self.groups.entry(group).or_default();
let now_live = slot.is_some();
let was = match rows.at.get(&name).copied() {
Some(i) => {
let was = if rows.slots[i].is_some() {
Was::Live
} else {
Was::Ended
};
rows.slots[i] = slot;
was
}
None => {
rows.at.insert(name.clone(), rows.names.len());
rows.names.push(name);
rows.slots.push(slot);
Was::New
}
};
match was {
Was::Live => self.live -= 1,
Was::Ended => self.ended -= 1,
Was::New => {}
}
if now_live {
self.live += 1;
} else {
self.ended += 1;
}
was
}
pub fn apply(&mut self, e: RowEntry) -> Was {
self.set(e.group, e.name, e.slot)
}
pub fn live(&self) -> u64 {
self.live
}
pub fn has_rows(&self) -> bool {
self.live + self.ended > 0
}
pub fn groups(&self) -> &[Group] {
&self.order
}
pub fn names(&self, group: &Group) -> Vec<String> {
let Some(rows) = self.groups.get(group) else {
return Vec::new();
};
(rows.names.iter().zip(&rows.slots))
.filter(|(_, s)| s.is_some())
.map(|(n, _)| n.clone())
.collect()
}
pub fn slots(&self, group: &Group) -> impl Iterator<Item = (&str, &Option<BlobRef>)> {
(self.groups.get(group).into_iter())
.flat_map(|rows| rows.names.iter().map(String::as_str).zip(&rows.slots))
}
pub fn same_as(&self, other: &RowIndex) -> bool {
if self.live != other.live || self.ended != other.ended {
return false;
}
(self.order.iter()).all(|g| {
self.slots(g).all(|(name, slot)| {
let theirs = other.lookup(g, name);
match slot {
Some(b) => theirs == Lookup::Live(b.clone()),
None => theirs == Lookup::Ended,
}
})
})
}
}
pub(crate) fn changed_keys(old: &RowIndex, new: &RowIndex) -> Vec<(Group, String)> {
let mut out = Vec::new();
for g in new.groups() {
for (name, slot) in new.slots(g) {
let now = match slot {
Some(b) => Lookup::Live(b.clone()),
None => Lookup::Ended,
};
if old.lookup(g, name) != now {
out.push((g.clone(), name.to_string()));
}
}
}
for g in old.groups() {
for (name, _) in old.slots(g) {
if new.lookup(g, name) == Lookup::Absent {
out.push((g.clone(), name.to_string()));
}
}
}
out
}
pub(crate) fn own_bytes_end(e: &RowEntry) -> u64 {
e.slot
.as_ref()
.filter(|b| b.pack.is_none())
.map_or(0, BlobRef::end)
}
pub(crate) const COL_GROUP_TYPE: &str = "group_type";
pub(crate) const COL_GROUP_REPO: &str = "group_repo";
pub(crate) const COL_PACK: &str = "pack";
pub(crate) const COL_ENDED: &str = "ended";
pub(crate) fn rows_schema(extra: &HashMap<String, String>) -> Arc<Schema> {
let base = data_subindex_schema();
let mut fields: Vec<Field> = base.fields().iter().map(|f| f.as_ref().clone()).collect();
fields.push(Field::new(COL_GROUP_TYPE, DataType::Int8, false));
fields.push(Field::new(COL_GROUP_REPO, DataType::Utf8, false));
fields.push(Field::new(COL_PACK, DataType::UInt64, true));
fields.push(Field::new(COL_ENDED, DataType::Boolean, false));
let mut metadata = base.metadata().clone();
metadata.extend(extra.iter().map(|(k, v)| (k.clone(), v.clone())));
Arc::new(Schema::new_with_metadata(fields, metadata))
}
pub(crate) fn is_v2(schema: &Schema) -> bool {
schema.field_with_name(COL_ENDED).is_ok()
}
pub(crate) fn fits_v1(entries: &[RowEntry]) -> bool {
(entries.iter())
.all(|e| e.group.is_default() && e.slot.as_ref().is_some_and(|b| b.pack.is_none()))
}
pub(crate) fn rows_batch(schema: &Arc<Schema>, entries: &[RowEntry]) -> Result<RecordBatch> {
if !is_v2(schema) {
ensure!(
fits_v1(entries),
"a V1 journal holds only own rows of the default group"
);
let mut paths = Vec::new();
let mut locs = Vec::new();
for e in entries {
for c in &e.slot.as_ref().expect("checked by fits_v1").chunks {
paths.push(e.name.clone());
locs.push(c.clone());
}
}
let order: Vec<usize> = (0..paths.len()).collect();
return crate::meta_sink_append::base_batch_permuted(
Arc::clone(schema),
&paths,
&locs,
&order,
);
}
let n: usize = entries
.iter()
.map(|e| e.slot.as_ref().map_or(1, |b| b.chunks.len()))
.sum();
let mut path_b = StringBuilder::with_capacity(n, n * 16);
let mut seq_b = UInt32Builder::with_capacity(n);
let mut fdata_b = UInt64Builder::with_capacity(n);
let mut comp_b = BooleanBuilder::with_capacity(n);
let mut usz_b = UInt64Builder::with_capacity(n);
let mut boff_b = UInt64Builder::with_capacity(n);
let mut bsz_b = UInt64Builder::with_capacity(n);
let mut ck_b = FixedSizeBinaryBuilder::with_capacity(n, 32);
let mut gt_b = Int8Builder::with_capacity(n);
let mut gr_b = StringBuilder::with_capacity(n, n * 4);
let mut pack_b = UInt64Builder::with_capacity(n);
let mut end_b = BooleanBuilder::with_capacity(n);
let ended = ChunkLoc {
chunk_seq: 0,
fdata_offset: 0,
blob_offset: 0,
blob_size: 0,
uncompressed_size: 0,
compressed: false,
checksum: [0u8; 32],
};
for e in entries {
let (pack, chunks, is_end) = match &e.slot {
Some(b) => (b.pack, b.chunks.as_slice(), false),
None => (None, std::slice::from_ref(&ended), true),
};
for c in chunks {
path_b.append_value(&e.name);
seq_b.append_value(c.chunk_seq);
fdata_b.append_value(c.fdata_offset);
comp_b.append_value(c.compressed);
usz_b.append_value(c.uncompressed_size);
boff_b.append_value(c.blob_offset);
bsz_b.append_value(c.blob_size);
ck_b.append_value(c.checksum)?;
gt_b.append_value(e.group.pkg_type);
gr_b.append_value(&e.group.repo);
pack_b.append_option(pack);
end_b.append_value(is_end);
}
}
Ok(RecordBatch::try_new(
Arc::clone(schema),
vec![
Arc::new(path_b.finish()),
Arc::new(seq_b.finish()),
Arc::new(fdata_b.finish()),
Arc::new(comp_b.finish()),
Arc::new(usz_b.finish()),
Arc::new(boff_b.finish()),
Arc::new(bsz_b.finish()),
Arc::new(ck_b.finish()),
Arc::new(gt_b.finish()),
Arc::new(gr_b.finish()),
Arc::new(pack_b.finish()),
Arc::new(end_b.finish()),
],
)?)
}
pub(crate) struct FlatRow {
pub group: Group,
pub name: String,
pub pack: Option<u64>,
pub chunk: Option<ChunkLoc>,
}
fn column<'b, T: 'static>(batch: &'b RecordBatch, name: &str) -> Result<&'b T> {
let c = (batch.column_by_name(name)).ok_or_else(|| anyhow!("rows: no column {name}"))?;
(c.as_any().downcast_ref::<T>())
.ok_or_else(|| anyhow!("rows: column {name} is of another type"))
}
fn optional<'b, T: 'static>(batch: &'b RecordBatch, name: &str) -> Result<Option<&'b T>> {
match batch.column_by_name(name) {
None => Ok(None),
Some(c) => (c.as_any().downcast_ref::<T>())
.map(Some)
.ok_or_else(|| anyhow!("rows: column {name} is of another type")),
}
}
pub(crate) fn decode_flat(batch: &RecordBatch, group: &Group) -> Result<Vec<FlatRow>> {
let paths = column::<StringArray>(batch, "relative_path")?;
let seq = column::<UInt32Array>(batch, "chunk_seq")?;
let fdata = column::<UInt64Array>(batch, "fdata_offset")?;
let comp = column::<BooleanArray>(batch, "compressed")?;
let usz = column::<UInt64Array>(batch, "uncompressed_size")?;
let boff = column::<UInt64Array>(batch, "blob_offset")?;
let bsz = column::<UInt64Array>(batch, "blob_size")?;
let ck = column::<FixedSizeBinaryArray>(batch, "checksum")?;
ensure!(
ck.value_length() == 32,
"rows: checksum is {} bytes wide, not 32",
ck.value_length()
);
let gt = optional::<Int8Array>(batch, COL_GROUP_TYPE)?;
let gr = optional::<StringArray>(batch, COL_GROUP_REPO)?;
let pack = optional::<UInt64Array>(batch, COL_PACK)?;
let ended = optional::<BooleanArray>(batch, COL_ENDED)?;
let mut out = Vec::with_capacity(batch.num_rows());
for i in 0..batch.num_rows() {
let group = match (gt, gr) {
(Some(t), Some(r)) => Group {
pkg_type: t.value(i),
repo: r.value(i).to_string(),
},
_ => group.clone(),
};
let chunk = if ended.is_some_and(|e| e.value(i)) {
None
} else {
let mut checksum = [0u8; 32];
checksum.copy_from_slice(ck.value(i));
Some(ChunkLoc {
chunk_seq: seq.value(i),
fdata_offset: fdata.value(i),
blob_offset: boff.value(i),
blob_size: bsz.value(i),
uncompressed_size: usz.value(i),
compressed: comp.value(i),
checksum,
})
};
out.push(FlatRow {
group,
name: paths.value(i).to_string(),
pack: pack.and_then(|p| (!p.is_null(i)).then(|| p.value(i))),
chunk,
});
}
Ok(out)
}
pub(crate) fn entries_in_order(rows: Vec<FlatRow>) -> Result<Vec<RowEntry>> {
let mut out: Vec<RowEntry> = Vec::new();
for r in rows {
match r.chunk {
None => out.push(RowEntry {
group: r.group,
name: r.name,
slot: None,
}),
Some(c) if c.chunk_seq == 0 => out.push(RowEntry {
group: r.group,
name: r.name,
slot: Some(BlobRef {
pack: r.pack,
chunks: vec![c],
}),
}),
Some(c) => {
let last = out
.last_mut()
.filter(|e| e.group == r.group && e.name == r.name);
let Some(b) = last
.and_then(|e| e.slot.as_mut())
.filter(|b| b.pack == r.pack)
else {
bail!(
"rows: chunk {} of {} comes without its chunk 0",
c.chunk_seq,
r.name
);
};
b.chunks.push(c);
}
}
}
for e in &mut out {
if let Some(b) = &mut e.slot {
b.chunks.sort_by_key(|c| c.fdata_offset);
}
}
Ok(out)
}
pub(crate) fn decode_stream(
bytes: &[u8],
tolerant: bool,
) -> Result<(Vec<RowEntry>, HashMap<String, String>)> {
let reader = StreamReader::try_new(Cursor::new(bytes), None)
.map_err(|e| anyhow!("rows: stream: {e}"))?;
let metadata = reader.schema().metadata().clone();
let mut out = Vec::new();
for batch in reader {
match batch {
Ok(b) => out.extend(entries_in_order(decode_flat(&b, &Group::default())?)?),
Err(_) if tolerant => break,
Err(e) => bail!("rows: batch: {e}"),
}
}
Ok((out, metadata))
}
pub(crate) struct SegmentCursor {
pub number: u32,
pub path: PathBuf,
schema: Vec<u8>,
consumed: u64,
pub metadata: Option<HashMap<String, String>>,
}
impl SegmentCursor {
pub fn new(number: u32, path: PathBuf) -> Self {
Self {
number,
path,
schema: Vec::new(),
consumed: 0,
metadata: None,
}
}
pub fn read_more(&mut self, tolerant: bool) -> Result<(Vec<RowEntry>, u64)> {
let file =
File::open(&self.path).map_err(|e| anyhow!("journal {}: {e}", self.path.display()))?;
let len = file.metadata()?.len();
ensure!(
len >= self.consumed,
"journal {} shrank",
self.path.display()
);
if len == self.consumed {
return Ok((Vec::new(), 0));
}
let mut fresh = vec![0u8; usize::try_from(len - self.consumed)?];
file.read_exact_at(&mut fresh, self.consumed)?;
let read = fresh.len() as u64;
if self.schema.is_empty() {
let whole = crate::ipc_guard::valid_prefix(&fresh);
let Some(schema_len) = crate::ipc_guard::first_message_len(whole) else {
return Ok((Vec::new(), read));
};
let (entries, metadata) = decode_stream(whole, tolerant)?;
self.schema = whole[..schema_len].to_vec();
self.metadata = Some(metadata);
self.consumed = whole.len() as u64;
return Ok((entries, read));
}
let mut buf = Vec::with_capacity(self.schema.len() + fresh.len());
buf.extend_from_slice(&self.schema);
buf.extend_from_slice(&fresh);
let whole = crate::ipc_guard::valid_prefix(&buf);
if whole.len() <= self.schema.len() {
return Ok((Vec::new(), read));
}
let (entries, _) = decode_stream(whole, tolerant)?;
self.consumed += (whole.len() - self.schema.len()) as u64;
Ok((entries, read))
}
}
pub const STREAM_PIECE: usize = 4 << 20;
#[derive(Clone)]
pub struct Blob {
file: Arc<File>,
at: BlobRef,
}
impl std::fmt::Debug for Blob {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Blob").field("at", &self.at).finish()
}
}
impl Blob {
pub(crate) fn new(file: Arc<File>, at: BlobRef) -> Self {
Self { file, at }
}
pub fn location(&self) -> &BlobRef {
&self.at
}
pub(crate) fn file(&self) -> &File {
&self.file
}
pub fn size(&self) -> u64 {
self.at.size()
}
pub fn checksum(&self) -> Option<[u8; 32]> {
self.at.checksum()
}
pub fn read(&self) -> Result<Vec<u8>> {
self.collect(false)
}
pub fn read_verified(&self) -> Result<Vec<u8>> {
self.collect(true)
}
fn collect(&self, verify: bool) -> Result<Vec<u8>> {
let cap = self.size().min(self.file.metadata()?.len()).min(64 << 20);
let mut out = Vec::with_capacity(usize::try_from(cap)?);
self.write_to(&mut out, verify)?;
Ok(out)
}
pub fn write_to(&self, out: &mut dyn Write, verify: bool) -> Result<u64> {
let mut n = 0u64;
for piece in self.pieces(STREAM_PIECE, verify)? {
let piece = piece?;
out.write_all(&piece)?;
n += piece.len() as u64;
}
Ok(n)
}
pub fn pieces(&self, piece: usize, verify: bool) -> Result<Pieces> {
let file_len = self.file.metadata()?.len();
Ok(Pieces {
file: Arc::clone(&self.file),
chunks: self.at.chunks.clone(),
piece: piece.max(1),
verify,
file_len,
i: 0,
at: 0,
hasher: blake3::Hasher::new(),
pending: Vec::new(),
pending_at: 0,
done: false,
})
}
}
pub struct Pieces {
file: Arc<File>,
chunks: Vec<ChunkLoc>,
piece: usize,
verify: bool,
file_len: u64,
i: usize,
at: u64,
hasher: blake3::Hasher,
pending: Vec<u8>,
pending_at: usize,
done: bool,
}
impl Pieces {
fn step(&mut self) -> Result<Option<Vec<u8>>> {
loop {
if self.pending_at < self.pending.len() {
let end = (self.pending_at + self.piece).min(self.pending.len());
let out = self.pending[self.pending_at..end].to_vec();
self.pending_at = end;
return Ok(Some(out));
}
let Some(c) = self.chunks.get(self.i).cloned() else {
return Ok(None);
};
let end = c.blob_offset.checked_add(c.blob_size);
ensure!(
end.is_some_and(|end| end <= self.file_len),
"chunk {} names bytes {}+{} past the file's end {}",
c.chunk_seq,
c.blob_offset,
c.blob_size,
self.file_len
);
if c.compressed {
let mut blob = vec![0u8; usize::try_from(c.blob_size)?];
self.file.read_exact_at(&mut blob, c.blob_offset)?;
let most = usize::try_from(c.uncompressed_size)?;
let mut out = Vec::new();
let n = crate::codec::decompress_into_budgeted(&blob, &mut out, most)?;
out.truncate(n);
ensure!(
out.len() as u64 == c.uncompressed_size,
"chunk {} opens to {} bytes, its row says {}",
c.chunk_seq,
out.len(),
c.uncompressed_size
);
if self.verify && *blake3::hash(&out).as_bytes() != c.checksum {
bail!("chunk {}: the bytes are not its BLAKE3", c.chunk_seq);
}
self.pending = out;
self.pending_at = 0;
self.i += 1;
continue;
}
ensure!(
c.blob_size == c.uncompressed_size,
"stored chunk {} is {} bytes, its row says {}",
c.chunk_seq,
c.blob_size,
c.uncompressed_size
);
let left = c.blob_size - self.at;
let n = usize::try_from(left).map_or(self.piece, |l| l.min(self.piece));
let mut out = vec![0u8; n];
self.file.read_exact_at(&mut out, c.blob_offset + self.at)?;
if self.verify {
self.hasher.update(&out);
}
self.at += n as u64;
if self.at == c.blob_size {
if self.verify && *self.hasher.finalize().as_bytes() != c.checksum {
bail!("chunk {}: the bytes are not its BLAKE3", c.chunk_seq);
}
self.hasher = blake3::Hasher::new();
self.at = 0;
self.i += 1;
}
if n > 0 {
return Ok(Some(out));
}
}
}
}
impl Iterator for Pieces {
type Item = Result<Vec<u8>>;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
match self.step() {
Ok(Some(p)) => Some(Ok(p)),
Ok(None) => {
self.done = true;
None
}
Err(e) => {
self.done = true;
Some(Err(e))
}
}
}
}
pub(crate) fn fill(body: &mut dyn Read, buf: &mut [u8]) -> Result<usize> {
let mut n = 0;
while n < buf.len() {
match body.read(&mut buf[n..]) {
Ok(0) => break,
Ok(k) => n += k,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => return Err(anyhow!("reading the body: {e}")),
}
}
Ok(n)
}
pub(crate) fn sync_dir_of(path: &Path) {
let parent = match path.parent() {
Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
_ => PathBuf::from("."),
};
if let Ok(f) = File::open(parent) {
let _ = f.sync_all();
}
}
#[cfg(test)]
mod tests {
use super::*;
fn loc(seq: u32, at: u64, n: u64) -> ChunkLoc {
ChunkLoc {
chunk_seq: seq,
fdata_offset: u64::from(seq) * n,
blob_offset: at,
blob_size: n,
uncompressed_size: n,
compressed: false,
checksum: [seq as u8; 32],
}
}
#[test]
fn v2_rows_read_back_as_written() {
let entries = vec![
RowEntry {
group: Group::new(1, "7"),
name: "a".into(),
slot: Some(BlobRef {
pack: None,
chunks: vec![loc(0, 0, 10), loc(1, 10, 10)],
}),
},
RowEntry {
group: Group::new(2, "9"),
name: "a".into(),
slot: Some(BlobRef {
pack: Some(3),
chunks: vec![loc(0, 40, 5)],
}),
},
RowEntry {
group: Group::default(),
name: "gone".into(),
slot: None,
},
];
let schema = rows_schema(&HashMap::new());
let batch = rows_batch(&schema, &entries).unwrap();
assert_eq!(batch.num_rows(), 4);
let back = entries_in_order(decode_flat(&batch, &Group::default()).unwrap()).unwrap();
assert_eq!(back, entries);
}
#[test]
fn base_columns_read_as_the_group_named() {
let entries = vec![RowEntry {
group: Group::default(),
name: "x".into(),
slot: Some(BlobRef {
pack: None,
chunks: vec![loc(0, 0, 3)],
}),
}];
let batch = rows_batch(&data_subindex_schema(), &entries).unwrap();
assert_eq!(batch.num_columns(), 8, "V1 is the base columns alone");
let back = decode_flat(&batch, &Group::new(1, "r")).unwrap();
assert_eq!(back[0].group, Group::new(1, "r"));
assert_eq!(back[0].pack, None);
assert!(
rows_batch(
&data_subindex_schema(),
&[RowEntry {
group: Group::new(1, "r"),
name: "y".into(),
slot: None
}]
)
.is_err(),
"V1 cannot carry a group or an end"
);
}
#[test]
fn a_lone_later_chunk_is_refused() {
let rows = vec![FlatRow {
group: Group::default(),
name: "a".into(),
pack: None,
chunk: Some(loc(1, 0, 1)),
}];
assert!(entries_in_order(rows).is_err());
}
#[test]
fn the_index_keeps_places_and_counts() {
let mut ix = RowIndex::default();
let b = |at| {
Some(BlobRef {
pack: None,
chunks: vec![loc(0, at, 1)],
})
};
let g = Group::default();
assert_eq!(ix.set(g.clone(), "a".into(), b(0)), Was::New);
assert_eq!(ix.set(g.clone(), "b".into(), b(1)), Was::New);
assert_eq!(ix.set(g.clone(), "a".into(), b(2)), Was::Live);
assert_eq!(ix.set(g.clone(), "b".into(), None), Was::Live);
assert_eq!(ix.names(&g), ["a"]);
assert_eq!(ix.live(), 1);
assert_eq!(ix.lookup(&g, "b"), Lookup::Ended);
assert_eq!(ix.set(g.clone(), "b".into(), b(3)), Was::Ended);
assert_eq!(ix.names(&g), ["a", "b"], "b keeps its first place");
assert_eq!(ix.live(), 2);
let mut other = RowIndex::default();
other.set(g.clone(), "b".into(), b(3));
other.set(g.clone(), "a".into(), b(2));
assert!(ix.same_as(&other));
}
}