lindera_dictionary/loader/
connection_cost_matrix.rs1use std::path::Path;
2
3use crate::LinderaResult;
4#[cfg(feature = "compress")]
5use crate::decompress::{CompressedData, decompress};
6use crate::dictionary::connection_cost_matrix::ConnectionCostMatrix;
7#[cfg(feature = "compress")]
8use crate::error::LinderaErrorKind;
9#[cfg(feature = "mmap")]
10use crate::util::mmap_file;
11use crate::util::read_file;
12
13pub struct ConnectionCostMatrixLoader {}
14
15impl ConnectionCostMatrixLoader {
16 #[allow(unused_mut)]
17 pub fn load(input_dir: &Path) -> LinderaResult<ConnectionCostMatrix> {
18 let mut data = read_file(input_dir.join("matrix.mtx").as_path())?;
19
20 #[cfg(feature = "compress")]
21 {
22 let mut aligned_data = rkyv::util::AlignedVec::<16>::new();
23 aligned_data.extend_from_slice(&data);
24
25 let compressed_data: CompressedData =
26 rkyv::from_bytes::<CompressedData, rkyv::rancor::Error>(&aligned_data).map_err(
27 |err| {
28 LinderaErrorKind::Deserialize
29 .with_error(anyhow::anyhow!(err.to_string()))
30 .add_context("Failed to deserialize matrix.mtx data")
31 },
32 )?;
33 data = decompress(compressed_data).map_err(|err| {
34 LinderaErrorKind::Compression
35 .with_error(err)
36 .add_context("Failed to decompress connection cost matrix data")
37 })?;
38 }
39
40 Ok(ConnectionCostMatrix::load(data))
41 }
42
43 #[cfg(feature = "mmap")]
44 pub fn load_mmap(input_dir: &Path) -> LinderaResult<ConnectionCostMatrix> {
45 let data = mmap_file(input_dir.join("matrix.mtx").as_path())?;
46
47 Ok(ConnectionCostMatrix::load(data))
48 }
49}