gix_object/traits/mod.rs
1use gix_error::Result;
2use std::io;
3
4use gix_error::ResultExt;
5
6use crate::Kind;
7
8/// Describe the capability to write git objects into an object store.
9pub trait Write {
10 /// Write objects using the intrinsic kind of [`hash`](gix_hash::Kind) into the database,
11 /// returning id to reference it in subsequent reads.
12 fn write(&self, object: &dyn WriteTo) -> Result<gix_hash::ObjectId> {
13 let mut buf = Vec::with_capacity(2048);
14 object.write_to(&mut buf).or_error()?;
15 self.write_stream(object.kind(), buf.len() as u64, &mut buf.as_slice())
16 }
17 /// As [`write`](Write::write), but takes an [`object` kind](Kind) along with its encoded bytes.
18 fn write_buf(&self, object: crate::Kind, mut from: &[u8]) -> Result<gix_hash::ObjectId> {
19 self.write_stream(object, from.len() as u64, &mut from)
20 }
21 /// As [`write_buf`](Write::write_buf), but the object `id` has already been computed by the caller.
22 ///
23 /// Implementations may trust the given `id` and avoid computing it again. Callers must make sure `id` matches
24 /// the provided `object` and `from` bytes.
25 fn write_buf_with_known_id(
26 &self,
27 object: crate::Kind,
28 from: &[u8],
29 id: gix_hash::ObjectId,
30 ) -> Result<gix_hash::ObjectId>;
31 /// As [`write`](Write::write), but takes an input stream.
32 /// This is commonly used for writing blobs directly without reading them to memory first.
33 fn write_stream(&self, kind: crate::Kind, size: u64, from: &mut dyn io::Read) -> Result<gix_hash::ObjectId>;
34 /// As [`write_stream`](Write::write_stream), but the object `id` has already been computed by the caller.
35 ///
36 /// Implementations may trust the given `id` and avoid computing it again. Callers must make sure `id` matches
37 /// the provided `kind`, `size` and stream contents.
38 fn write_stream_with_known_id(
39 &self,
40 kind: crate::Kind,
41 size: u64,
42 from: &mut dyn io::Read,
43 id: gix_hash::ObjectId,
44 ) -> Result<gix_hash::ObjectId>;
45}
46
47/// Writing of objects to a `Write` implementation
48pub trait WriteTo {
49 /// Write a representation of this instance to `out`.
50 fn write_to(&self, out: &mut dyn std::io::Write) -> std::io::Result<()>;
51
52 /// Returns the type of this object.
53 fn kind(&self) -> Kind;
54
55 /// Returns the size of this object's representation (the amount
56 /// of data which would be written by [`write_to`](Self::write_to)).
57 ///
58 /// [`size`](Self::size)'s value has no bearing on the validity of
59 /// the object, as such it's possible for [`size`](Self::size) to
60 /// return a sensible value but [`write_to`](Self::write_to) to
61 /// fail because the object was not actually valid in some way.
62 fn size(&self) -> u64;
63
64 /// Returns a loose object header based on the object's data
65 fn loose_header(&self) -> smallvec::SmallVec<[u8; 28]> {
66 crate::encode::loose_header(self.kind(), self.size())
67 }
68}
69
70mod _impls;
71
72mod find;
73pub use find::*;