From 6de230c382a4329df00bc11cc1ffb90390b13159 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Mon, 24 May 2021 08:55:14 +0300 Subject: refactor: make metadata be part of datachunk This makes it harder to lose the metadata for a chunk, or to use unrelated metadata and chunk. Also, soon I will refactor things for encrypting chunks, which will need metadata embedded in the encrypted chunk. Sponsored-by: author --- src/chunk.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) (limited to 'src/chunk.rs') diff --git a/src/chunk.rs b/src/chunk.rs index 0eed38a..50a2fc7 100644 --- a/src/chunk.rs +++ b/src/chunk.rs @@ -1,4 +1,6 @@ +use crate::checksummer::sha256; use crate::chunkid::ChunkId; +use crate::chunkmeta::ChunkMeta; use serde::{Deserialize, Serialize}; use std::default::Default; @@ -11,18 +13,24 @@ use std::default::Default; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DataChunk { data: Vec, + meta: ChunkMeta, } impl DataChunk { /// Construct a new chunk. - pub fn new(data: Vec) -> Self { - Self { data } + pub fn new(data: Vec, meta: ChunkMeta) -> Self { + Self { data, meta } } /// Return a chunk's data. pub fn data(&self) -> &[u8] { &self.data } + + /// Return a chunk's metadata. + pub fn meta(&self) -> &ChunkMeta { + &self.meta + } } #[derive(Default, Debug, Serialize, Deserialize)] @@ -69,8 +77,12 @@ impl GenerationChunk { self.chunk_ids.iter() } - pub fn to_data_chunk(&self) -> GenerationChunkResult { - let json = serde_json::to_string(self).map_err(GenerationChunkError::JsonGenerate)?; - Ok(DataChunk::new(json.as_bytes().to_vec())) + pub fn to_data_chunk(&self, ended: &str) -> GenerationChunkResult { + let json: String = + serde_json::to_string(self).map_err(GenerationChunkError::JsonGenerate)?; + let bytes = json.as_bytes().to_vec(); + let sha = sha256(&bytes); + let meta = ChunkMeta::new_generation(&sha, ended); + Ok(DataChunk::new(bytes, meta)) } } -- cgit v1.2.1