sudachi/dic/
header.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/*
 * Copyright (c) 2021-2024 Works Applications Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use nom::{bytes::complete::take, number::complete::le_u64};
use std::io::Write;
use std::time::{Duration, SystemTime};
use thiserror::Error;

use crate::error::{SudachiError, SudachiNomResult, SudachiResult};

/// Sudachi error
#[derive(Error, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum HeaderError {
    #[error("Invalid header version")]
    InvalidVersion,

    #[error("Invalid system dictionary version")]
    InvalidSystemDictVersion,

    #[error("Invalid user dictionary version")]
    InvalidUserDictVersion,

    #[error("Unable to parse")]
    CannotParse,
}

/// Header version
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HeaderVersion {
    SystemDict(SystemDictVersion),
    UserDict(UserDictVersion),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SystemDictVersion {
    // we cannot set value since value can be larger than isize
    Version1,
    Version2,
}

impl HeaderVersion {
    pub fn to_u64(&self) -> u64 {
        #[allow(unreachable_patterns)]
        match self {
            HeaderVersion::SystemDict(SystemDictVersion::Version1) => {
                HeaderVersion::SYSTEM_DICT_VERSION_1
            }
            HeaderVersion::SystemDict(SystemDictVersion::Version2) => {
                HeaderVersion::SYSTEM_DICT_VERSION_2
            }
            HeaderVersion::UserDict(UserDictVersion::Version1) => {
                HeaderVersion::USER_DICT_VERSION_1
            }
            HeaderVersion::UserDict(UserDictVersion::Version2) => {
                HeaderVersion::USER_DICT_VERSION_2
            }
            HeaderVersion::UserDict(UserDictVersion::Version3) => {
                HeaderVersion::USER_DICT_VERSION_3
            }
            _ => panic!("unknown version {:?}", self),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UserDictVersion {
    Version1,
    Version2,
    Version3,
}
impl HeaderVersion {
    /// the first version of system dictionaries
    const SYSTEM_DICT_VERSION_1: u64 = 0x7366d3f18bd111e7;
    /// the second version of system dictionaries
    const SYSTEM_DICT_VERSION_2: u64 = 0xce9f011a92394434;
    /// the first version of user dictionaries
    const USER_DICT_VERSION_1: u64 = 0xa50f31188bd211e7;
    /// the second version of user dictionaries
    const USER_DICT_VERSION_2: u64 = 0x9fdeb5a90168d868;
    /// the third version of user dictionaries
    const USER_DICT_VERSION_3: u64 = 0xca9811756ff64fb0;

    pub fn from_u64(v: u64) -> Option<Self> {
        match v {
            HeaderVersion::SYSTEM_DICT_VERSION_1 => {
                Some(Self::SystemDict(SystemDictVersion::Version1))
            }
            HeaderVersion::SYSTEM_DICT_VERSION_2 => {
                Some(Self::SystemDict(SystemDictVersion::Version2))
            }
            HeaderVersion::USER_DICT_VERSION_1 => Some(Self::UserDict(UserDictVersion::Version1)),
            HeaderVersion::USER_DICT_VERSION_2 => Some(Self::UserDict(UserDictVersion::Version2)),
            HeaderVersion::USER_DICT_VERSION_3 => Some(Self::UserDict(UserDictVersion::Version3)),
            _ => None,
        }
    }
}

/// Dictionary header
///
/// Contains version, create_time, and description
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Header {
    pub version: HeaderVersion,
    pub create_time: u64,
    pub description: String,
}

impl Default for Header {
    fn default() -> Self {
        Self::new()
    }
}

impl Header {
    const DESCRIPTION_SIZE: usize = 256;
    pub const STORAGE_SIZE: usize = 8 + 8 + Header::DESCRIPTION_SIZE;

    /// Creates new system dictionary header
    /// Its version field should be modified to create user dictionary header
    pub fn new() -> Self {
        let unix_time = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .expect("unix time error");

        Self {
            version: HeaderVersion::SystemDict(SystemDictVersion::Version2),
            create_time: unix_time.as_secs(),
            description: String::new(),
        }
    }

    /// Set creation time
    pub fn set_time(&mut self, time: SystemTime) -> SystemTime {
        let unix_time = time
            .duration_since(SystemTime::UNIX_EPOCH)
            .expect("unix time error");

        let old_unix_secs = std::mem::replace(&mut self.create_time, unix_time.as_secs());

        SystemTime::UNIX_EPOCH + Duration::from_secs(old_unix_secs)
    }

    /// Creates a new header from a dictionary bytes
    pub fn parse(bytes: &[u8]) -> Result<Header, HeaderError> {
        let (_rest, (version, create_time, description)) =
            header_parser(bytes).map_err(|_| HeaderError::CannotParse)?;

        let version = HeaderVersion::from_u64(version).ok_or(HeaderError::InvalidVersion)?;

        Ok(Header {
            version,
            create_time,
            description,
        })
    }

    /// Returns if this header version has grammar
    pub fn has_grammar(&self) -> bool {
        matches!(
            self.version,
            HeaderVersion::SystemDict(_)
                | HeaderVersion::UserDict(UserDictVersion::Version2)
                | HeaderVersion::UserDict(UserDictVersion::Version3)
        )
    }

    /// Returns if this header version has synonym group ids
    pub fn has_synonym_group_ids(&self) -> bool {
        matches!(
            self.version,
            HeaderVersion::SystemDict(SystemDictVersion::Version2)
                | HeaderVersion::UserDict(UserDictVersion::Version3)
        )
    }

    pub fn write_to<W: Write>(&self, w: &mut W) -> SudachiResult<usize> {
        if self.description.len() > Header::DESCRIPTION_SIZE {
            return Err(SudachiError::InvalidDataFormat(
                Header::DESCRIPTION_SIZE,
                self.description.clone(),
            ));
        }

        w.write_all(&self.version.to_u64().to_le_bytes())?;
        w.write_all(&self.create_time.to_le_bytes())?;
        w.write_all(self.description.as_bytes())?;
        for _ in 0..Header::DESCRIPTION_SIZE - self.description.len() {
            w.write_all(&[0])?;
        }
        Ok(Header::STORAGE_SIZE)
    }
}

/// Create String from UTF-8 bytes up to NUL byte or end of slice (whichever is first)
fn nul_terminated_str_from_slice(buf: &[u8]) -> String {
    let str_bytes: &[u8] = if let Some(nul_idx) = buf.iter().position(|b| *b == 0) {
        &buf[..nul_idx]
    } else {
        buf
    };
    String::from_utf8_lossy(str_bytes).to_string()
}

fn description_parser(input: &[u8]) -> SudachiNomResult<&[u8], String> {
    let (rest, description_bytes) = take(Header::DESCRIPTION_SIZE)(input)?;
    Ok((rest, nul_terminated_str_from_slice(description_bytes)))
}

fn header_parser(input: &[u8]) -> SudachiNomResult<&[u8], (u64, u64, String)> {
    nom::sequence::tuple((le_u64, le_u64, description_parser))(input)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn header_from_parts<T: AsRef<[u8]>>(
        version: u64,
        create_time: u64,
        description: T,
    ) -> Result<Header, HeaderError> {
        let mut bytes = Vec::new();
        bytes.extend(&version.to_le_bytes());
        bytes.extend(&create_time.to_le_bytes());
        bytes.extend(description.as_ref());

        Header::parse(&bytes)
    }

    #[test]
    fn graceful_failure() {
        // Too small
        assert_eq!(Header::parse(&[]), Err(HeaderError::CannotParse));

        assert_eq!(
            header_from_parts(42, 0, vec![0; Header::DESCRIPTION_SIZE]),
            Err(HeaderError::InvalidVersion)
        );
    }

    #[test]
    fn simple_header() {
        let mut description: Vec<u8> = Vec::new();
        let description_str = "My Description";
        description.extend(description_str.bytes());
        description.extend(&vec![0; Header::DESCRIPTION_SIZE]);

        assert_eq!(
            header_from_parts(HeaderVersion::SYSTEM_DICT_VERSION_1, 1337, &description),
            Ok(Header {
                version: HeaderVersion::SystemDict(SystemDictVersion::Version1),
                description: description_str.to_string(),
                create_time: 1337,
            })
        );
    }

    #[test]
    fn write_system() {
        let header = Header::new();
        let mut data: Vec<u8> = Vec::new();
        assert_eq!(header.write_to(&mut data).unwrap(), Header::STORAGE_SIZE);
        let header2 = Header::parse(&data).unwrap();
        assert_eq!(header, header2);
    }

    #[test]
    fn write_user() {
        let mut header = Header::new();
        header.version = HeaderVersion::UserDict(UserDictVersion::Version3);
        header.description = String::from("some great header");
        let mut data: Vec<u8> = Vec::new();
        assert_eq!(header.write_to(&mut data).unwrap(), Header::STORAGE_SIZE);
        let header2 = Header::parse(&data).unwrap();
        assert_eq!(header, header2);
    }
}