Skip to main content

mecab_ko_dict/trie/
backend.rs

1//! Trie 백엔드 통합 타입
2
3use std::path::Path;
4
5use smallvec::SmallVec;
6
7use crate::error::Result;
8
9use super::{mmap::MmapTrie, Trie};
10
11/// Trie 백엔드 통합 타입
12///
13/// 소유 벡터 또는 mmap 중 하나를 런타임에 선택합니다.
14pub enum TrieBackend {
15    /// 소유 바이트 벡터 백엔드 (압축 해제 포함)
16    Owned(Trie<'static>),
17    /// 메모리 맵 백엔드
18    Mmap(MmapTrie),
19}
20
21/// 공통 접두사 검색 결과 타입.
22/// 형태소 분석에서 한 위치의 매칭은 보통 1~5건이므로
23/// 스택 버퍼 16으로 대부분 힙 할당 없이 처리됩니다.
24pub type PrefixSearchResult = SmallVec<[(u32, usize); 16]>;
25
26impl TrieBackend {
27    /// 파일을 읽어 소유 벡터로 로드
28    ///
29    /// # Errors
30    ///
31    /// 파일을 읽을 수 없는 경우 에러를 반환합니다.
32    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
33        Ok(Self::Owned(Trie::from_file(path)?))
34    }
35
36    /// 파일을 메모리 맵으로 로드
37    ///
38    /// # Errors
39    ///
40    /// 파일을 열거나 매핑할 수 없는 경우 에러를 반환합니다.
41    pub fn from_mmap_file<P: AsRef<Path>>(path: P) -> Result<Self> {
42        Ok(Self::Mmap(MmapTrie::from_file(path)?))
43    }
44
45    /// 압축 파일에서 소유 벡터로 로드 (zstd)
46    ///
47    /// # Errors
48    ///
49    /// 파일을 읽거나 압축 해제할 수 없는 경우 에러를 반환합니다.
50    pub fn from_compressed_file<P: AsRef<Path>>(path: P) -> Result<Self> {
51        Ok(Self::Owned(Trie::from_compressed_file(path)?))
52    }
53
54    /// 정확히 일치하는 키 검색
55    #[must_use]
56    pub fn exact_match(&self, key: &str) -> Option<u32> {
57        match self {
58            Self::Owned(t) => t.exact_match(key),
59            Self::Mmap(t) => t.exact_match(key),
60        }
61    }
62
63    /// 바이트 키로 정확히 일치하는 키 검색
64    #[must_use]
65    pub fn exact_match_bytes(&self, key: &[u8]) -> Option<u32> {
66        match self {
67            Self::Owned(t) => t.exact_match_bytes(key),
68            Self::Mmap(t) => t.exact_match_bytes(key),
69        }
70    }
71
72    /// 공통 접두사 검색
73    #[must_use]
74    pub fn common_prefix_search(&self, text: &str) -> PrefixSearchResult {
75        match self {
76            Self::Owned(t) => t.common_prefix_search(text).collect(),
77            Self::Mmap(t) => t.common_prefix_search(text).collect(),
78        }
79    }
80
81    /// 바이트 키로 공통 접두사 검색
82    #[must_use]
83    pub fn common_prefix_search_bytes(&self, key: &[u8]) -> PrefixSearchResult {
84        match self {
85            Self::Owned(t) => t.common_prefix_search_bytes(key).collect(),
86            Self::Mmap(t) => t.common_prefix_search_bytes(key).collect(),
87        }
88    }
89
90    /// 특정 위치에서 공통 접두사 검색
91    #[must_use]
92    pub fn common_prefix_search_at(&self, text: &str, start_byte: usize) -> PrefixSearchResult {
93        match self {
94            Self::Owned(t) => t.common_prefix_search_at(text, start_byte),
95            Self::Mmap(t) => t.common_prefix_search_at(text, start_byte),
96        }
97    }
98}