use std::collections::{HashMap, VecDeque};
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak};
use std::time::{Duration, Instant};
use rusqlite::Connection;
use super::entry::{self, Entry, Head, Kind, MAGIC, Point};
use crate::probe::Probe;
use crate::sqlite::{Commit, Observe, Position};
use crate::{Error, ErrorKind, Result};
#[derive(Clone, Copy, Debug)]
pub(crate) struct Bounds {
pub(crate) segment: u64,
pub(crate) keep: u64,
pub(crate) keep_free: u64,
}
const KEPT_FOR_A_NODE: u64 = 4;
impl Default for Bounds {
fn default() -> Self {
Bounds { segment: 16 << 20, keep: 256 << 20, keep_free: 0 }
}
}
#[derive(Default)]
pub(crate) struct Notify {
appended: Mutex<u64>,
changed: Condvar,
served: AtomicU64,
}
impl Notify {
pub(crate) fn seen(&self) -> u64 {
*self.appended.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn wait_past(&self, seen: u64, at_most: Duration) {
let appended = self.appended.lock().unwrap_or_else(PoisonError::into_inner);
let _ = self.changed.wait_timeout_while(appended, at_most, |appended| *appended == seen);
}
pub(crate) fn appended(&self) {
*self.appended.lock().unwrap_or_else(PoisonError::into_inner) += 1;
self.changed.notify_all();
}
pub(crate) fn served_changed(&self) {
self.served.fetch_add(1, Ordering::SeqCst);
}
pub(crate) fn served(&self) -> u64 {
self.served.load(Ordering::SeqCst)
}
}
#[derive(Default)]
pub(crate) struct Acks {
held: Mutex<Held>,
changed: Condvar,
chosen: Vec<String>,
said: AtomicBool,
pub(crate) unheld: AtomicU64,
pub(crate) probe: std::sync::OnceLock<Arc<Probe>>,
}
#[derive(Default)]
struct Held {
entries: HashMap<(String, String), u64>,
linked: HashMap<String, (String, usize)>,
}
pub(super) const ACK_WAIT: Duration = Duration::from_secs(5);
impl Acks {
pub(crate) fn waiting_for(chosen: Vec<String>) -> Acks {
Acks { chosen, ..Acks::default() }
}
pub(crate) fn behind(&self, file: &str, last: u64) -> Vec<(String, u64)> {
let held = self.held.lock().unwrap_or_else(PoisonError::into_inner);
let behind = |node: &String| {
let at = held.entries.get(&(node.clone(), file.to_owned())).copied().unwrap_or(0);
(node.clone(), last.saturating_sub(at))
};
held.linked.keys().map(behind).collect()
}
pub(crate) fn floor(&self, file: &str) -> Option<u64> {
let held = self.held.lock().unwrap_or_else(PoisonError::into_inner);
let holds = |node: &String| held.entries.get(&(node.clone(), file.to_owned())).copied().unwrap_or(0);
held.linked.keys().map(holds).min()
}
pub(crate) fn held(&self, node: &str, file: &str, sequence: u64) {
let mut held = self.held.lock().unwrap_or_else(PoisonError::into_inner);
let at = held.entries.entry((node.to_owned(), file.to_owned())).or_default();
if sequence > *at {
*at = sequence;
self.changed.notify_all();
}
}
pub(crate) fn forget(&self, node: &str, file: &str) {
let mut held = self.held.lock().unwrap_or_else(PoisonError::into_inner);
held.entries.remove(&(node.to_owned(), file.to_owned()));
}
pub(crate) fn linked(&self, node: &str, address: &str) {
let mut held = self.held.lock().unwrap_or_else(PoisonError::into_inner);
held.linked.entry(node.to_owned()).or_insert_with(|| (address.to_owned(), 0)).1 += 1;
}
pub(crate) fn unlinked(&self, node: &str) {
let mut held = self.held.lock().unwrap_or_else(PoisonError::into_inner);
if let Some((_, links)) = held.linked.get_mut(node) {
*links -= 1;
if *links == 0 {
held.linked.remove(node);
}
}
self.changed.notify_all();
}
fn wait(&self, file: &str, sequence: u64) -> Result<()> {
let started = Instant::now();
let waited = self.wait_for_a_copy(file, sequence, started + ACK_WAIT);
if let Some(probe) = self.probe.get() {
let file = crate::probe::label(file);
let labels = [("file", file.as_str())];
probe.time("tinystore_replication_ack_wait_ms", &labels, started.elapsed());
if waited.is_err() {
probe.count("tinystore_replication_committed_locally_total", &labels, 1.0);
}
}
waited
}
fn wait_for_a_copy(&self, file: &str, sequence: u64, deadline: Instant) -> Result<()> {
let mut held = self.held.lock().unwrap_or_else(PoisonError::into_inner);
loop {
let counted: Vec<&String> = held
.linked
.iter()
.filter(|(node, (address, _))| self.counts(node, address))
.map(|(node, _)| node)
.collect();
let holding = |node: &&String| {
held.entries.get(&((*node).clone(), file.to_owned())).is_some_and(|&at| at >= sequence)
};
if counted.iter().any(holding) {
self.said.store(false, Ordering::SeqCst);
return Ok(());
}
let now = Instant::now();
if counted.is_empty() || now >= deadline {
self.unheld.fetch_add(1, Ordering::Relaxed);
let why = if counted.is_empty() { "no node it waits for copies it" } else { "none held it in time" };
if !self.said.swap(true, Ordering::SeqCst) {
tracing::warn!(
target: "tinystore",
file,
entry = sequence,
why,
"a synchronous commit no copy held",
);
}
return Err(Error::new(
ErrorKind::CommittedLocally,
format!("{file}: a synchronous commit, entry {sequence}, is in its home's file alone: {why}"),
));
}
held = self.changed.wait_timeout(held, deadline - now).unwrap_or_else(PoisonError::into_inner).0;
}
}
fn counts(&self, node: &str, address: &str) -> bool {
self.chosen.is_empty() || self.chosen.iter().any(|chosen| chosen == node || chosen == address)
}
#[cfg(test)]
#[allow(dead_code, reason = "the link tests call it, and they build only with every engine")]
pub(crate) fn holds(&self, node: &str, file: &str) -> Option<u64> {
let held = self.held.lock().unwrap_or_else(PoisonError::into_inner);
held.entries.get(&(node.to_owned(), file.to_owned())).copied()
}
}
pub(crate) struct Log {
dir: PathBuf,
bounds: Bounds,
notify: Arc<Notify>,
followers: Option<(String, Arc<Acks>)>,
synchronous: bool,
writer: Mutex<Option<Weak<Mutex<Connection>>>>,
tail: Mutex<Tail>,
fenced: AtomicU64,
lease: Mutex<Option<Instant>>,
leased: Condvar,
stopping: AtomicBool,
}
pub(super) const LEASE_WAIT: Duration = Duration::from_secs(3);
pub(crate) const FENCED: &str = "fenced";
struct Tail {
segments: VecDeque<Segment>,
appending: Option<fs::File>,
next: u64,
epoch: u64,
check: [u8; 16],
last: Option<Position>,
unsynced: bool,
named: bool,
torn: bool,
#[cfg(test)]
tears_at: Option<usize>,
}
struct Segment {
first: u64,
bytes: u64,
}
impl Tail {
fn append(&mut self, bytes: &[u8]) -> io::Result<()> {
let file = self.appending.as_mut().expect("the last segment is open");
#[cfg(test)]
if let Some(torn) = self.tears_at.take() {
file.write_all(&bytes[..torn])?;
return Err(io::Error::new(io::ErrorKind::StorageFull, "the disk is full, as a test made it"));
}
file.write_all(bytes)
}
}
fn cut_to(path: &Path, bytes: u64) -> io::Result<()> {
let file = OpenOptions::new().write(true).open(path)?;
file.set_len(bytes).and_then(|()| file.sync_data())
}
impl Log {
pub(crate) fn open(dir: PathBuf, bounds: Bounds, notify: Arc<Notify>) -> Result<Log> {
fs::create_dir_all(&dir).map_err(|error| Error::io(format!("log {}", dir.display()), error))?;
let mut tail = Tail {
segments: VecDeque::new(),
appending: None,
next: 1,
epoch: 1,
check: [0; 16],
last: None,
unsynced: false,
named: false,
torn: false,
#[cfg(test)]
tears_at: None,
};
for first in segments_in(&dir)? {
let path = segment_path(&dir, first);
let bytes = fs::metadata(&path).map_err(|error| Error::io(path.display().to_string(), error))?.len();
tail.segments.push_back(Segment { first, bytes });
}
let fenced = AtomicU64::new(Self::fenced_in(&dir)?.unwrap_or(0));
let log = Log {
dir,
bounds,
notify,
followers: None,
synchronous: false,
writer: Mutex::new(None),
tail: Mutex::new(tail),
fenced,
lease: Mutex::new(None),
leased: Condvar::new(),
stopping: AtomicBool::new(false),
};
log.find_the_end().map_err(|error| error.within(format!("log {}", log.dir.display())))?;
log.go_on_from_a_promotion()?;
Ok(log)
}
pub(crate) fn followed(mut self, name: &str, acks: Arc<Acks>) -> Log {
self.followers = Some((name.to_owned(), acks));
self
}
pub(crate) fn judged(self, until: Instant) -> Log {
*self.lease.lock().unwrap_or_else(PoisonError::into_inner) = Some(until);
self
}
pub(crate) fn epoch(&self) -> u64 {
self.lock().epoch
}
pub(crate) fn stop_waiting(&self) {
let _held = self.lease.lock().unwrap_or_else(PoisonError::into_inner);
self.stopping.store(true, Ordering::SeqCst);
self.leased.notify_all();
}
pub(crate) fn lease_until(&self, until: Instant) {
let mut lease = self.lease.lock().unwrap_or_else(PoisonError::into_inner);
if lease.is_some_and(|held| held < until) {
*lease = Some(until);
self.leased.notify_all();
}
}
fn wait_for_a_lease(&self) -> Result<()> {
let deadline = Instant::now() + LEASE_WAIT;
let mut lease = self.lease.lock().unwrap_or_else(PoisonError::into_inner);
while let Some(until) = *lease {
let now = Instant::now();
if now < until {
return Ok(());
}
if now >= deadline || self.stopping.load(Ordering::SeqCst) {
return Err(Error::new(
ErrorKind::Unavailable,
"this node holds no lease of this file from its witness now: it writes again once it renews one",
));
}
lease = self.leased.wait_timeout(lease, deadline - now).unwrap_or_else(PoisonError::into_inner).0;
}
Ok(())
}
pub(crate) fn synchronous(mut self) -> Log {
self.synchronous = true;
self
}
pub(crate) fn read(dir: &Path, mut each: impl FnMut(Entry<'_>) -> Result<()>) -> Result<()> {
for first in segments_in(dir)? {
let bytes = read_segment(&segment_path(dir, first))?;
let mut at = MAGIC.len();
while let Some((entry, used)) = entry::decode(&bytes[at..])? {
each(entry)?;
at += used;
}
}
Ok(())
}
pub(crate) fn last_in(dir: &Path) -> Result<Option<Point>> {
for first in segments_in(dir)?.into_iter().rev() {
let path = segment_path(dir, first);
let bytes = read_segment(&path)?;
let mut at = MAGIC.len();
let mut last = None;
while let Some((entry, used)) = next_whole(&path, &bytes[at..])? {
if last.is_some_and(|point| !entry.follows(&point)) {
break;
}
last = Some(entry.point());
at += used;
}
if last.is_some() {
return Ok(last);
}
}
Ok(None)
}
pub(crate) fn clear(dir: &Path) -> Result<()> {
for first in segments_in(dir)? {
let path = segment_path(dir, first);
fs::remove_file(&path).map_err(|error| io_error(&path, error))?;
}
Self::unfence_in(dir)
}
pub(crate) fn unfence(&self) -> Result<()> {
Self::unfence_in(&self.dir)?;
self.fenced.store(0, Ordering::SeqCst);
Ok(())
}
pub(crate) fn unfence_in(dir: &Path) -> Result<()> {
super::copy::remove_if_there(&dir.join(FENCED))
}
pub(crate) fn fenced_as_kept(&self) -> Result<()> {
self.fenced.store(Self::fenced_in(&self.dir)?.unwrap_or(0), Ordering::SeqCst);
Ok(())
}
pub(crate) fn fence(&self, epoch: u64) -> Result<()> {
self.fenced.fetch_max(epoch, Ordering::SeqCst);
Self::fence_in(&self.dir, epoch)
}
pub(crate) fn fence_in(dir: &Path, epoch: u64) -> Result<()> {
fs::create_dir_all(dir).map_err(|error| io_error(dir, error))?;
let (path, beside) = (dir.join(FENCED), dir.join(format!("{FENCED}.new")));
let mut file = fs::File::create(&beside).map_err(|error| io_error(&beside, error))?;
file.write_all(epoch.to_string().as_bytes())
.and_then(|()| file.sync_all())
.map_err(|error| io_error(&beside, error))?;
drop(file);
fs::rename(&beside, &path).map_err(|error| io_error(&path, error))?;
crate::durable::sync_directory(dir).map_err(|error| io_error(dir, error))
}
pub(crate) fn fenced_in(dir: &Path) -> Result<Option<u64>> {
match fs::read_to_string(dir.join(FENCED)) {
Ok(kept) => kept
.trim()
.parse()
.map(Some)
.map_err(|_| Error::corrupt(format!("{}: no epoch", dir.join(FENCED).display()))),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(io_error(&dir.join(FENCED), error)),
}
}
pub(crate) fn stable(&self) -> Point {
let writer = self.writer.lock().unwrap_or_else(PoisonError::into_inner).as_ref().and_then(Weak::upgrade);
let _held = writer.as_ref().map(|writer| writer.lock().unwrap_or_else(PoisonError::into_inner));
let tail = self.lock();
Point { sequence: tail.next - 1, epoch: tail.epoch, check: tail.check }
}
pub(crate) fn holding<T>(&self, read: impl FnOnce(Point) -> Result<T>) -> Result<T> {
let writer = self.writer.lock().unwrap_or_else(PoisonError::into_inner).as_ref().and_then(Weak::upgrade);
let _held = writer.as_ref().map(|writer| writer.lock().unwrap_or_else(PoisonError::into_inner));
let point = {
let tail = self.lock();
Point { sequence: tail.next - 1, epoch: tail.epoch, check: tail.check }
};
read(point)
}
pub(crate) fn keep(&self, entry: &Entry<'_>, bytes: &[u8]) -> Result<()> {
let mut tail = self.lock();
let empty = tail.segments.is_empty();
if !empty && !entry.follows(&Point { sequence: tail.next - 1, epoch: tail.epoch, check: tail.check }) {
return Err(Error::new(
ErrorKind::Conflict,
format!(
"log {}: entry {} does not follow its last, {}",
self.dir.display(),
entry.sequence,
tail.next - 1
),
));
}
if empty {
tail.next = entry.sequence;
}
self.write(&mut tail, bytes)?;
(tail.next, tail.epoch, tail.check, tail.last) =
(entry.sequence + 1, entry.epoch, entry.check, Some(entry.position));
drop(tail);
self.notify.appended();
Ok(())
}
pub(crate) fn go_on_at(&self, epoch: u64) -> Result<()> {
let mut tail = self.lock();
let point = Point { sequence: tail.next - 1, epoch, check: tail.check };
super::copy::Position::read(self.dir.join(super::promote::PROMOTED))?.keep_durably(point)?;
tail.epoch = tail.epoch.max(epoch);
Ok(())
}
pub(crate) fn go_on_at_in(dir: &Path, epoch: u64) -> Result<()> {
let last = Self::last_in(dir)?.or(super::promote::promoted_at(dir)?).unwrap_or_default();
let point = Point { epoch, ..last };
super::copy::Position::read(dir.join(super::promote::PROMOTED))?.keep_durably(point)
}
fn go_on_from_a_promotion(&self) -> Result<()> {
let Some(point) = super::promote::promoted_at(&self.dir)? else {
return Ok(());
};
let mut tail = self.lock();
if tail.segments.is_empty() {
(tail.next, tail.check, tail.last) = (point.sequence + 1, point.check, Some(Position::default()));
}
tail.epoch = tail.epoch.max(point.epoch);
Ok(())
}
fn find_the_end(&self) -> Result<()> {
let mut tail = self.lock();
while let Some(segment) = tail.segments.back() {
let path = segment_path(&self.dir, segment.first);
let bytes = read_segment(&path)?;
let mut at = MAGIC.len();
let mut last: Option<(Point, Position)> = None;
while let Some((entry, used)) = next_whole(&path, &bytes[at..])? {
if last.is_some_and(|(point, _)| !entry.follows(&point)) {
break;
}
last = Some((entry.point(), entry.position));
at += used;
}
let Some((point, position)) = last else {
fs::remove_file(&path).map_err(|error| Error::io(path.display().to_string(), error))?;
tail.segments.pop_back();
continue;
};
if at < bytes.len() {
let file = OpenOptions::new().write(true).open(&path).map_err(|error| io_error(&path, error))?;
file.set_len(at as u64).and_then(|()| file.sync_data()).map_err(|error| io_error(&path, error))?;
}
tail.segments.back_mut().expect("the segment just read").bytes = at as u64;
(tail.next, tail.epoch, tail.check, tail.last) =
(point.sequence + 1, point.epoch, point.check, Some(position));
tail.appending = Some(OpenOptions::new().append(true).open(&path).map_err(|error| io_error(&path, error))?);
return Ok(());
}
Ok(())
}
fn append(&self, kind: Kind, position: Position, page_size: u32, size: u32, pages: &[(u32, &[u8])]) -> Result<()> {
let mut tail = self.lock();
let head =
Head { kind, sequence: tail.next, epoch: tail.epoch, previous: tail.check, position, page_size, size };
let (bytes, check) = entry::encode(&head, pages);
self.write(&mut tail, &bytes)?;
(tail.next, tail.check, tail.last) = (head.sequence + 1, check, Some(position));
drop(tail);
self.notify.appended();
let answering = crate::sqlite::answering();
if let (Kind::Commit, true, true, Some((file, acks))) = (kind, self.synchronous, answering, &self.followers) {
acks.wait(file, head.sequence)?;
}
Ok(())
}
fn write(&self, tail: &mut Tail, bytes: &[u8]) -> Result<()> {
if tail.torn {
return Err(Error::new(
ErrorKind::Unavailable,
format!("log {}: an append failed partway: it takes entries again once it opens", self.dir.display()),
));
}
let full = tail.segments.back().is_none_or(|segment| segment.bytes >= self.bounds.segment);
if full {
self.start_segment(tail)?;
}
let segment = tail.segments.back().expect("a segment to append to");
let (path, whole) = (segment_path(&self.dir, segment.first), segment.bytes);
if let Err(error) = tail.append(bytes) {
tail.torn = cut_to(&path, whole).is_err();
return Err(io_error(&path, error));
}
tail.segments.back_mut().expect("the segment just written").bytes += bytes.len() as u64;
tail.unsynced = true;
Ok(())
}
fn start_segment(&self, tail: &mut Tail) -> Result<()> {
if let Some(file) = tail.appending.take() {
file.sync_data().map_err(|error| Error::io(format!("log {}", self.dir.display()), error))?;
}
let path = segment_path(&self.dir, tail.next);
let mut file =
OpenOptions::new().append(true).create_new(true).open(&path).map_err(|error| io_error(&path, error))?;
file.write_all(MAGIC).map_err(|error| io_error(&path, error))?;
if tail.segments.is_empty() {
self.notify.served_changed();
}
tail.segments.push_back(Segment { first: tail.next, bytes: MAGIC.len() as u64 });
tail.appending = Some(file);
tail.named = true;
let low_on_disk = self.bounds.keep_free > 0
&& crate::space::available(&self.dir).is_ok_and(|available| available < self.bounds.keep_free);
let applied = self.followers.as_ref().and_then(|(file, acks)| acks.floor(file));
while tail.segments.len() > 1 {
let bytes = tail.segments.iter().map(|segment| segment.bytes).sum::<u64>();
let needed = applied.is_some_and(|applied| applied + 1 < tail.segments[1].first);
let kept = if needed { self.bounds.keep.saturating_mul(KEPT_FOR_A_NODE) } else { self.bounds.keep };
if !low_on_disk && bytes <= kept {
break;
}
let oldest = tail.segments.pop_front().expect("more than one segment");
let path = segment_path(&self.dir, oldest.first);
fs::remove_file(&path).map_err(|error| io_error(&path, error))?;
}
Ok(())
}
pub(crate) fn last(&self) -> u64 {
self.lock().next.saturating_sub(1)
}
#[cfg(test)]
pub(crate) fn tear_next_append(&self, at: usize) {
self.lock().tears_at = Some(at);
}
#[cfg(test)]
pub(crate) fn unsynced(&self) -> bool {
self.lock().unsynced
}
#[cfg(test)]
pub(crate) fn leased_until(&self) -> Option<Instant> {
*self.lease.lock().unwrap_or_else(PoisonError::into_inner)
}
fn lock(&self) -> MutexGuard<'_, Tail> {
self.tail.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl Observe for Log {
fn last(&self) -> Option<Position> {
self.lock().last
}
fn begin(&self, position: Position, size: u32) -> Result<()> {
self.append(Kind::Begin, position, 0, size, &[])
}
fn committed(&self, commit: &Commit<'_>) -> Result<()> {
self.append(Kind::Commit, commit.position, commit.page_size, commit.size, &commit.pages)
}
fn gap(&self, position: Position) -> Result<()> {
tracing::warn!(
target: "tinystore",
log = %self.dir.display(),
"the file was written beside the store's writer: a copy of it starts again from a snapshot"
);
self.append(Kind::Gap, position, 0, 0, &[])
}
fn sync(&self) -> Result<()> {
let mut tail = self.lock();
if tail.unsynced {
let file = tail.appending.as_ref().expect("an entry was appended");
file.sync_data().map_err(|error| Error::io(format!("log {}", self.dir.display()), error))?;
tail.unsynced = false;
}
if tail.named {
crate::durable::sync_directory(&self.dir)
.map_err(|error| Error::io(format!("log {}", self.dir.display()), error))?;
tail.named = false;
}
Ok(())
}
fn writer(&self, writer: Weak<Mutex<Connection>>) {
*self.writer.lock().unwrap_or_else(PoisonError::into_inner) = Some(writer);
}
fn refuse(&self) -> Result<()> {
self.wait_for_a_lease()?;
self.refuse_when_fenced()
}
fn refuse_commit(&self) -> Result<()> {
let lease = *self.lease.lock().unwrap_or_else(PoisonError::into_inner);
if lease.is_some_and(|until| Instant::now() >= until) {
return Err(Error::new(
ErrorKind::Unavailable,
"this node's lease of this file from its witness ran out while the transaction ran: it commits \
nothing, and the file takes writes again once the lease is renewed",
));
}
self.refuse_when_fenced()
}
}
impl Log {
fn refuse_when_fenced(&self) -> Result<()> {
let epoch = self.fenced.load(Ordering::SeqCst);
if epoch == 0 {
return Ok(());
}
Err(Error::new(
ErrorKind::Conflict,
format!(
"another node writes this file at epoch {epoch}: this node is its old home, which takes no more writes \
of it until `tinystore demote` makes it a copy"
),
))
}
}
pub(crate) fn segments_in(dir: &Path) -> Result<Vec<u64>> {
let mut firsts = Vec::new();
let listed = match fs::read_dir(dir) {
Ok(listed) => listed,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(firsts),
Err(error) => return Err(io_error(dir, error)),
};
for found in listed {
let found = found.map_err(|error| io_error(dir, error))?;
let name = found.file_name();
let first = name.to_str().and_then(|name| name.strip_suffix(".log")).and_then(|first| first.parse().ok());
if let Some(first) = first {
firsts.push(first);
}
}
firsts.sort_unstable();
Ok(firsts)
}
pub(crate) fn segment_path(dir: &Path, first: u64) -> PathBuf {
dir.join(format!("{first:020}.log"))
}
fn next_whole<'a>(path: &Path, rest: &'a [u8]) -> Result<Option<(Entry<'a>, usize)>> {
match entry::decode(rest) {
Err(_) if entry::torn(rest) => Ok(None),
decoded => decoded.map_err(|error| error.within(path.display())),
}
}
fn read_segment(path: &Path) -> Result<Vec<u8>> {
let bytes = fs::read(path).map_err(|error| io_error(path, error))?;
if bytes.len() < MAGIC.len() {
return Ok(MAGIC.to_vec());
}
if bytes[..MAGIC.len()] != MAGIC[..] {
return Err(Error::new(ErrorKind::Corrupt, format!("{}: a segment of another format", path.display())));
}
Ok(bytes)
}
use super::copy::io_error;