apr_format/v2/
v2format_error.rs1use super::{ShardInfo, ShardManifest};
7use std::collections::HashMap;
8
9impl ShardManifest {
10 #[must_use]
12 pub fn new(shard_count: usize) -> Self {
13 Self {
14 version: "2.0".to_string(),
15 shard_count,
16 total_size: 0,
17 tensor_count: 0,
18 shards: Vec::with_capacity(shard_count),
19 weight_map: HashMap::new(),
20 }
21 }
22
23 pub fn add_shard(&mut self, info: ShardInfo) {
25 for tensor in &info.tensors {
26 self.weight_map.insert(tensor.clone(), info.index);
27 }
28 self.tensor_count += info.tensors.len();
29 self.total_size += info.size;
30 self.shards.push(info);
31 }
32
33 #[must_use]
35 pub fn shard_for_tensor(&self, name: &str) -> Option<usize> {
36 self.weight_map.get(name).copied()
37 }
38
39 pub fn to_json(&self) -> Result<String, V2FormatError> {
44 serde_json::to_string_pretty(self).map_err(|e| V2FormatError::MetadataError(e.to_string()))
45 }
46
47 pub fn from_json(json: &str) -> Result<Self, V2FormatError> {
52 serde_json::from_str(json).map_err(|e| V2FormatError::MetadataError(e.to_string()))
53 }
54}
55
56#[derive(Debug, Clone, PartialEq)]
62pub enum V2FormatError {
63 InvalidMagic([u8; 4]),
65 InvalidHeader(String),
67 InvalidTensorIndex(String),
69 MetadataError(String),
71 ChecksumMismatch,
73 AlignmentError(String),
75 IoError(String),
77 CompressionError(String),
79}
80
81impl std::fmt::Display for V2FormatError {
82 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83 match self {
84 Self::InvalidMagic(magic) => {
85 write!(
86 f,
87 "Invalid magic: {:02x}{:02x}{:02x}{:02x}",
88 magic[0], magic[1], magic[2], magic[3]
89 )
90 }
91 Self::InvalidHeader(msg) => write!(f, "Invalid header: {msg}"),
92 Self::InvalidTensorIndex(msg) => write!(f, "Invalid tensor index: {msg}"),
93 Self::MetadataError(msg) => write!(f, "Metadata error: {msg}"),
94 Self::ChecksumMismatch => write!(f, "Checksum mismatch"),
95 Self::AlignmentError(msg) => write!(f, "Alignment error: {msg}"),
96 Self::IoError(msg) => write!(f, "I/O error: {msg}"),
97 Self::CompressionError(msg) => write!(f, "Compression error: {msg}"),
98 }
99 }
100}
101
102impl std::error::Error for V2FormatError {}
103
104