pub mod binary;
use crate::error::{PcgError, PcgResult};
use crate::model::result::GenerationResult;
pub use binary::{export_binary, import_binary};
pub const CURRENT_SCHEMA_VERSION: &str = "1.0.0";
pub fn export_json(result: &GenerationResult) -> PcgResult<String> {
serde_json::to_string_pretty(result)
.map_err(|e| PcgError::export_err(format!("JSON 序列化失败: {}", e), "json", e))
}
pub fn export_json_compact(result: &GenerationResult) -> PcgResult<String> {
serde_json::to_string(result)
.map_err(|e| PcgError::export_err(format!("JSON 序列化失败: {}", e), "json", e))
}
pub fn import_json(json: &str) -> PcgResult<(GenerationResult, Vec<String>)> {
let result: GenerationResult = serde_json::from_str(json)
.map_err(|e| PcgError::export_err(format!("JSON 反序列化失败: {}", e), "json", e))?;
if !is_valid_semver(&result.metadata.schema_version) {
return Err(PcgError::corrupted_data_with_version(
format!(
"schema_version 格式非法: '{}'(要求 X.Y.Z,三段均为非负整数)",
result.metadata.schema_version,
),
"json",
CURRENT_SCHEMA_VERSION,
&result.metadata.schema_version,
));
}
let imported_major = extract_major_version(&result.metadata.schema_version);
let current_major = extract_major_version(CURRENT_SCHEMA_VERSION);
if imported_major != current_major {
return Err(PcgError::corrupted_data_with_version(
format!(
"schema_version 不兼容: 导入版本为 '{}'(主版本 {}),当前版本为 '{}'(主版本 {})",
result.metadata.schema_version,
imported_major.unwrap_or(0),
CURRENT_SCHEMA_VERSION,
current_major.unwrap_or(0),
),
"json",
CURRENT_SCHEMA_VERSION,
&result.metadata.schema_version,
));
}
let mut warnings = Vec::new();
if is_valid_semver(&result.metadata.algorithm_version) {
let alg_imported_major = extract_major_version(&result.metadata.algorithm_version);
let alg_current_major = extract_major_version(env!("CARGO_PKG_VERSION"));
if alg_imported_major != alg_current_major {
warnings.push(format!(
"algorithm_version 主版本不一致: 导入版本为 '{}'(主版本 {}),当前版本为 '{}'(主版本 {})。\
生成结果的结构兼容,但算法行为可能不同",
result.metadata.algorithm_version,
alg_imported_major.unwrap_or(0),
env!("CARGO_PKG_VERSION"),
alg_current_major.unwrap_or(0),
));
}
}
result.validate_terrain_data()?;
Ok((result, warnings))
}
fn extract_major_version(version: &str) -> Option<u32> {
version
.split('.')
.next()
.and_then(|s| s.parse::<u32>().ok())
}
fn is_valid_semver(version: &str) -> bool {
let parts: Vec<&str> = version.split('.').collect();
if parts.len() != 3 {
return false;
}
parts.iter().all(|p| p.parse::<u32>().is_ok())
}
#[cfg(test)]
mod __tests__;