yang_pcg/export/binary/
mod.rs1use crate::error::{PcgError, PcgResult};
14use crate::export::CURRENT_SCHEMA_VERSION;
15use crate::model::result::GenerationResult;
16
17const BINARY_MAGIC: &[u8; 4] = b"YPCG";
19
20const HEADER_SIZE: usize = 16;
22
23const CRC32_SIZE: usize = 4;
25
26const MIN_FILE_SIZE: usize = HEADER_SIZE + 1 + CRC32_SIZE;
28
29pub fn export_binary(result: &GenerationResult) -> PcgResult<Vec<u8>> {
64 let body = serde_json::to_vec(result)
69 .map_err(|e| PcgError::export_err(format!("二进制序列化失败: {}", e), "binary", e))?;
70
71 let body_len = body.len();
72
73 if body_len > u32::MAX as usize {
75 return Err(PcgError::export_with_format(
76 format!("数据体过大,超过 4GB 限制: {} 字节", body_len),
77 "binary",
78 None,
79 ));
80 }
81
82 let (major, minor) = parse_schema_version(CURRENT_SCHEMA_VERSION)?;
84
85 let total_size = HEADER_SIZE + body_len + CRC32_SIZE;
87 let mut buffer = Vec::with_capacity(total_size);
88
89 buffer.extend_from_slice(BINARY_MAGIC);
91
92 buffer.extend_from_slice(&major.to_le_bytes());
94 buffer.extend_from_slice(&minor.to_le_bytes());
95
96 buffer.extend_from_slice(&[0u8; 4]);
98
99 buffer.extend_from_slice(&(body_len as u32).to_le_bytes());
101
102 buffer.extend_from_slice(&body);
104
105 let crc = crc32fast::hash(&buffer);
107 buffer.extend_from_slice(&crc.to_le_bytes());
108
109 Ok(buffer)
110}
111
112pub fn import_binary(data: &[u8]) -> PcgResult<GenerationResult> {
142 if data.len() < MIN_FILE_SIZE {
144 return Err(PcgError::corrupted_data_with_type(
145 format!(
146 "数据长度不足: 期望至少 {} 字节,实际 {} 字节",
147 MIN_FILE_SIZE,
148 data.len()
149 ),
150 "binary",
151 ));
152 }
153
154 let magic = &data[0..4];
156 if magic != BINARY_MAGIC {
157 return Err(PcgError::corrupted_data_with_type(
158 format!(
159 "Magic 标识不匹配: 期望 {:?},实际 {:?}",
160 BINARY_MAGIC, magic
161 ),
162 "binary",
163 ));
164 }
165
166 let file_major = u16::from_le_bytes([data[4], data[5]]);
168 let _file_minor = u16::from_le_bytes([data[6], data[7]]);
169
170 let (current_major, _current_minor) = parse_schema_version(CURRENT_SCHEMA_VERSION)?;
172 if file_major != current_major {
173 return Err(PcgError::corrupted_data_with_version(
174 format!(
175 "Schema 主版本号不兼容: 文件版本 {},当前版本 {}",
176 file_major, current_major
177 ),
178 "binary",
179 &format!("{}", current_major),
180 &format!("{}", file_major),
181 ));
182 }
183
184 let body_len = u32::from_le_bytes([data[12], data[13], data[14], data[15]]) as usize;
189
190 let expected_total = HEADER_SIZE + body_len + CRC32_SIZE;
192 if data.len() != expected_total {
193 return Err(PcgError::corrupted_data_with_type(
194 format!(
195 "数据长度不匹配: 头部声明 body 长度 {},期望总长度 {},实际总长度 {}",
196 body_len,
197 expected_total,
198 data.len()
199 ),
200 "binary",
201 ));
202 }
203
204 let payload = &data[..data.len() - CRC32_SIZE];
206 let stored_crc = u32::from_le_bytes([
207 data[data.len() - 4],
208 data[data.len() - 3],
209 data[data.len() - 2],
210 data[data.len() - 1],
211 ]);
212 let computed_crc = crc32fast::hash(payload);
213
214 if stored_crc != computed_crc {
215 return Err(PcgError::corrupted_data_with_type(
216 format!(
217 "CRC32 校验和不匹配: 存储值 0x{:08X},计算值 0x{:08X},数据可能已损坏",
218 stored_crc, computed_crc
219 ),
220 "binary",
221 ));
222 }
223
224 let body = &data[HEADER_SIZE..HEADER_SIZE + body_len];
226 let result: GenerationResult = serde_json::from_slice(body)
227 .map_err(|e| PcgError::export_err(format!("二进制反序列化失败: {}", e), "binary", e))?;
228
229 result.validate_terrain_data()?;
230 Ok(result)
231}
232
233fn parse_schema_version(version: &str) -> PcgResult<(u16, u16)> {
237 let parts: Vec<&str> = version.split('.').collect();
238 if parts.len() < 2 {
239 return Err(PcgError::export_with_format(
240 format!("无效的版本格式: '{}',期望 semver 格式", version),
241 "binary",
242 None,
243 ));
244 }
245
246 let major = parts[0].parse::<u16>().map_err(|_| {
247 PcgError::export_with_format(format!("无法解析主版本号: '{}'", parts[0]), "binary", None)
248 })?;
249
250 let minor = parts[1].parse::<u16>().map_err(|_| {
251 PcgError::export_with_format(format!("无法解析次版本号: '{}'", parts[1]), "binary", None)
252 })?;
253
254 Ok((major, minor))
255}
256
257#[cfg(test)]
258mod __tests__;