use anyhow::{Context, Result};
use std::fs::{self, File};
use std::io::Write;
use std::path::Path;
pub fn init_zarr_v2_array(
dir: &Path,
shape: &[usize],
chunks: &[usize],
dtype: &str,
fill_value: serde_json::Value,
attrs: &serde_json::Value,
) -> Result<()> {
assert_eq!(
shape.len(),
chunks.len(),
"shape and chunks must have the same rank"
);
fs::create_dir_all(dir).with_context(|| format!("Failed to create {}", dir.display()))?;
let zarray = serde_json::json!({
"zarr_format": 2,
"shape": shape,
"chunks": chunks,
"dtype": dtype,
"compressor": serde_json::Value::Null,
"fill_value": fill_value,
"filters": serde_json::Value::Null,
"order": "C",
});
fs::write(dir.join(".zarray"), serde_json::to_string_pretty(&zarray)?)
.with_context(|| format!("Failed to write {}/.zarray", dir.display()))?;
fs::write(dir.join(".zattrs"), serde_json::to_string_pretty(attrs)?)
.with_context(|| format!("Failed to write {}/.zattrs", dir.display()))?;
Ok(())
}
pub fn write_chunk(dir: &Path, chunk_coord: &[usize], bytes: &[u8]) -> Result<()> {
let name: Vec<String> = chunk_coord.iter().map(|c| c.to_string()).collect();
let path = dir.join(name.join("."));
let mut f = File::create(&path)
.with_context(|| format!("Failed to create chunk {}", path.display()))?;
f.write_all(bytes)
.with_context(|| format!("Failed to write chunk {}", path.display()))?;
Ok(())
}