ferrocat-po 1.2.1

Performance-first PO parsing, serialization, and catalog update primitives for ferrocat.
Documentation
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use crate::{ParseError, ParsePosition};

mod backend {
    use memchr::{memchr, memchr2, memchr3, memrchr};

    #[inline]
    pub fn find_byte(byte: u8, haystack: &[u8]) -> Option<usize> {
        memchr(byte, haystack)
    }

    #[inline]
    pub fn find_either(first: u8, second: u8, haystack: &[u8]) -> Option<usize> {
        memchr2(first, second, haystack)
    }

    #[inline]
    pub fn find_last_byte(byte: u8, haystack: &[u8]) -> Option<usize> {
        memrchr(byte, haystack)
    }

    #[inline]
    pub fn find_escapable_byte(haystack: &[u8]) -> Option<usize> {
        find_escapable_byte_impl(haystack)
    }

    #[cfg(target_arch = "aarch64")]
    #[inline]
    fn find_escapable_byte_impl(haystack: &[u8]) -> Option<usize> {
        // Apple Silicon is our primary target, so this is the first place where
        // a dedicated NEON path is worth the maintenance cost.
        // SAFETY: `neon_find_escapable_byte` only reads within `haystack`, and this
        // branch is compiled exclusively for `aarch64` targets with NEON enabled.
        unsafe { neon_find_escapable_byte(haystack) }
    }

    #[cfg(not(target_arch = "aarch64"))]
    #[inline]
    fn find_escapable_byte_impl(haystack: &[u8]) -> Option<usize> {
        fallback_find_escapable_byte(haystack)
    }

    #[inline]
    fn fallback_find_escapable_byte(haystack: &[u8]) -> Option<usize> {
        min_option3(
            memchr3(b'"', b'\\', b'\n', haystack),
            memchr3(b'\t', b'\r', b'\x0b', haystack),
            memchr3(b'\x07', b'\x08', b'\x0c', haystack),
        )
    }

    #[inline]
    fn min_option3(
        first: Option<usize>,
        second: Option<usize>,
        third: Option<usize>,
    ) -> Option<usize> {
        min_option(min_option(first, second), third)
    }

    #[inline]
    fn min_option(first: Option<usize>, second: Option<usize>) -> Option<usize> {
        match (first, second) {
            (Some(left), Some(right)) => Some(left.min(right)),
            (Some(value), None) | (None, Some(value)) => Some(value),
            (None, None) => None,
        }
    }

    #[cfg(target_arch = "aarch64")]
    #[target_feature(enable = "neon")]
    unsafe fn neon_find_escapable_byte(haystack: &[u8]) -> Option<usize> {
        use core::arch::aarch64::{vceqq_u8, vdupq_n_u8, vld1q_u8, vmaxvq_u8, vorrq_u8};

        let mut offset = 0usize;
        while offset + 16 <= haystack.len() {
            // SAFETY: the loop guard guarantees a full 16-byte chunk remains, so the
            // pointer arithmetic and NEON load stay within the slice bounds.
            let matched = unsafe {
                let chunk = vld1q_u8(haystack.as_ptr().add(offset));
                let mut matched = vceqq_u8(chunk, vdupq_n_u8(b'"'));
                matched = vorrq_u8(matched, vceqq_u8(chunk, vdupq_n_u8(b'\\')));
                matched = vorrq_u8(matched, vceqq_u8(chunk, vdupq_n_u8(b'\n')));
                matched = vorrq_u8(matched, vceqq_u8(chunk, vdupq_n_u8(b'\t')));
                matched = vorrq_u8(matched, vceqq_u8(chunk, vdupq_n_u8(b'\r')));
                matched = vorrq_u8(matched, vceqq_u8(chunk, vdupq_n_u8(b'\x0b')));
                matched = vorrq_u8(matched, vceqq_u8(chunk, vdupq_n_u8(b'\x07')));
                matched = vorrq_u8(matched, vceqq_u8(chunk, vdupq_n_u8(b'\x08')));
                vorrq_u8(matched, vceqq_u8(chunk, vdupq_n_u8(b'\x0c')))
            };
            // SAFETY: some supported toolchains expose this NEON reduction as
            // unsafe; newer toolchains treat it as safe.
            #[allow(unused_unsafe)]
            let has_match = unsafe { vmaxvq_u8(matched) } != 0;
            if has_match {
                return haystack[offset..offset + 16]
                    .iter()
                    .position(|byte| {
                        matches!(
                            *byte,
                            b'"' | b'\\'
                                | b'\x07'
                                | b'\x08'
                                | b'\t'
                                | b'\n'
                                | b'\x0b'
                                | b'\x0c'
                                | b'\r'
                        )
                    })
                    .map(|index| offset + index);
            }
            offset += 16;
        }

        fallback_find_escapable_byte(&haystack[offset..]).map(|index| offset + index)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Keyword {
    Id,
    IdPlural,
    Str,
    Ctxt,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommentKind {
    Translator,
    Reference,
    Flags,
    Extracted,
    Metadata,
    Other,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineKind {
    Continuation,
    Comment(CommentKind),
    Keyword(Keyword),
    Other,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Line<'a> {
    pub trimmed: &'a [u8],
    pub obsolete: bool,
    pub position: ParsePosition,
}

pub struct LineScanner<'a> {
    bytes: &'a [u8],
    offset: usize,
    line_number: usize,
    finished: bool,
}

impl<'a> LineScanner<'a> {
    pub fn new(bytes: &'a [u8]) -> Self {
        Self {
            bytes,
            offset: 0,
            line_number: 1,
            finished: false,
        }
    }
}

impl<'a> Iterator for LineScanner<'a> {
    type Item = Line<'a>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        while !self.finished {
            if self.offset == self.bytes.len() {
                self.finished = true;
                return None;
            }
            let raw_offset = self.offset;
            let line_end = find_either(b'\n', b'\r', &self.bytes[self.offset..])
                .map_or(self.bytes.len(), |relative| self.offset + relative);
            let separator = self.bytes.get(line_end).copied();
            let line_number = self.line_number;
            self.line_number += 1;
            let raw = &self.bytes[self.offset..line_end];

            self.offset = match separator {
                Some(b'\r') if self.bytes.get(line_end + 1) == Some(&b'\n') => line_end + 2,
                Some(b'\r' | b'\n') => line_end + 1,
                Some(_) => unreachable!("line separator search only returns CR or LF"),
                None => self.bytes.len(),
            };

            let mut trimmed = trim_ascii_start(raw);
            let mut content_offset = raw_offset + raw.len() - trimmed.len();
            if trimmed.is_empty() {
                if self.offset == self.bytes.len() {
                    return None;
                }
                continue;
            }

            let mut obsolete = false;
            if trimmed.starts_with(b"#~") {
                let after_marker = &trimmed[2..];
                trimmed = trim_ascii_start(after_marker);
                content_offset += 2 + after_marker.len() - trimmed.len();
                obsolete = true;
                if trimmed.is_empty() {
                    if self.offset == self.bytes.len() {
                        return None;
                    }
                    continue;
                }
            }

            let column = content_offset - raw_offset + 1;

            return Some(Line {
                trimmed,
                obsolete,
                position: ParsePosition::new(content_offset, line_number, column),
            });
        }

        None
    }
}

#[inline]
pub fn trim_ascii(bytes: &[u8]) -> &[u8] {
    let trimmed = trim_ascii_start(bytes);
    let mut end = trimmed.len();

    while end > 0 && trimmed[end - 1].is_ascii_whitespace() {
        end -= 1;
    }

    &trimmed[..end]
}

#[inline]
pub fn trim_ascii_start(bytes: &[u8]) -> &[u8] {
    let mut start = 0;
    while start < bytes.len() && bytes[start].is_ascii_whitespace() {
        start += 1;
    }

    &bytes[start..]
}

#[inline]
pub fn find_byte(byte: u8, haystack: &[u8]) -> Option<usize> {
    backend::find_byte(byte, haystack)
}

#[inline]
pub fn find_last_byte(byte: u8, haystack: &[u8]) -> Option<usize> {
    backend::find_last_byte(byte, haystack)
}

pub fn find_either(first: u8, second: u8, haystack: &[u8]) -> Option<usize> {
    backend::find_either(first, second, haystack)
}

#[inline]
pub fn has_byte(byte: u8, haystack: &[u8]) -> bool {
    find_byte(byte, haystack).is_some()
}

#[cfg(test)]
pub fn find_quote_or_backslash(haystack: &[u8]) -> Option<usize> {
    find_either(b'"', b'\\', haystack)
}

#[inline]
pub fn find_escapable_byte(haystack: &[u8]) -> Option<usize> {
    backend::find_escapable_byte(haystack)
}

#[inline]
pub fn split_once_byte(haystack: &[u8], needle: u8) -> Option<(&[u8], &[u8])> {
    let index = find_byte(needle, haystack)?;
    Some((&haystack[..index], &haystack[index + 1..]))
}

#[inline]
pub fn classify_line(line: &[u8]) -> LineKind {
    match line.first().copied() {
        Some(b'"') => LineKind::Continuation,
        Some(b'#') => match line.get(1).copied() {
            Some(b':') => LineKind::Comment(CommentKind::Reference),
            Some(b',') => LineKind::Comment(CommentKind::Flags),
            Some(b'.') => LineKind::Comment(CommentKind::Extracted),
            Some(b'@') => LineKind::Comment(CommentKind::Metadata),
            Some(b' ') | None => LineKind::Comment(CommentKind::Translator),
            _ => LineKind::Comment(CommentKind::Other),
        },
        Some(b'm')
            if line.starts_with(b"msgid_plural") && has_keyword_boundary(line, 12, false) =>
        {
            LineKind::Keyword(Keyword::IdPlural)
        }
        Some(b'm') if line.starts_with(b"msgid") && has_keyword_boundary(line, 5, false) => {
            LineKind::Keyword(Keyword::Id)
        }
        Some(b'm') if line.starts_with(b"msgstr") && has_keyword_boundary(line, 6, true) => {
            LineKind::Keyword(Keyword::Str)
        }
        Some(b'm') if line.starts_with(b"msgctxt") && has_keyword_boundary(line, 7, false) => {
            LineKind::Keyword(Keyword::Ctxt)
        }
        _ => LineKind::Other,
    }
}

pub fn unrecognized_po_line(position: ParsePosition) -> ParseError {
    ParseError::with_position("unrecognized PO syntax", position)
}

#[inline]
fn has_keyword_boundary(line: &[u8], keyword_len: usize, allow_plural_index: bool) -> bool {
    match line.get(keyword_len).copied() {
        None | Some(b'"') => true,
        Some(b'[') if allow_plural_index => true,
        Some(byte) => byte.is_ascii_whitespace(),
    }
}

#[inline]
pub fn find_quoted_bounds(bytes: &[u8]) -> Option<(usize, usize)> {
    let first_quote = find_byte(b'"', bytes)?;
    let last_quote = find_last_byte(b'"', bytes)?;
    if last_quote > first_quote {
        Some((first_quote + 1, last_quote))
    } else {
        None
    }
}

#[inline]
pub fn parse_plural_index(line: &[u8]) -> Option<usize> {
    if line.get(6) != Some(&b'[') {
        return Some(0);
    }

    let close = find_byte(b']', &line[7..]).map(|offset| 7 + offset)?;
    let value = std::str::from_utf8(&line[7..close]).ok()?;
    value.parse::<usize>().ok()
}

#[cfg(test)]
mod tests {
    use super::{
        CommentKind, Keyword, LineKind, LineScanner, classify_line, find_byte, find_escapable_byte,
        find_last_byte, find_quote_or_backslash, find_quoted_bounds, parse_plural_index,
        split_once_byte, trim_ascii, trim_ascii_start,
    };

    #[test]
    fn scans_trimmed_lines_and_obsolete_marker() {
        let input = b"  msgid \"x\"  \n#~ msgstr \"y\"\n\n";
        let mut scanner = LineScanner::new(input);

        let first = scanner.next().expect("first line");
        assert_eq!(first.trimmed, b"msgid \"x\"  ");
        assert!(!first.obsolete);
        assert_eq!(first.position.offset(), 2);
        assert_eq!(first.position.line(), 1);
        assert_eq!(first.position.column(), 3);

        let second = scanner.next().expect("second line");
        assert_eq!(second.trimmed, b"msgstr \"y\"");
        assert!(second.obsolete);
        assert_eq!(second.position.offset(), 17);
        assert_eq!(second.position.line(), 2);
        assert_eq!(second.position.column(), 4);

        assert!(scanner.next().is_none());
    }

    #[test]
    fn scans_crlf_and_bare_cr_line_endings() {
        let input = b"msgid \"x\"\r\nmsgstr \"y\"\r#~ msgid \"old\"\r\n";
        let mut scanner = LineScanner::new(input);

        let first = scanner.next().expect("first line");
        assert_eq!(first.trimmed, b"msgid \"x\"");
        assert_eq!(first.position.line(), 1);

        let second = scanner.next().expect("second line");
        assert_eq!(second.trimmed, b"msgstr \"y\"");
        assert_eq!(second.position.line(), 2);

        let third = scanner.next().expect("third line");
        assert_eq!(third.trimmed, b"msgid \"old\"");
        assert!(third.obsolete);
        assert_eq!(third.position.line(), 3);

        assert!(scanner.next().is_none());
    }

    #[test]
    fn byte_helpers_work() {
        assert_eq!(trim_ascii(b"  abc \t"), b"abc");
        assert_eq!(trim_ascii_start(b"  abc \t"), b"abc \t");
        assert_eq!(find_byte(b':', b"a:b"), Some(1));
        assert_eq!(find_last_byte(b'"', br#""a" "b""#), Some(6));
        assert_eq!(find_quote_or_backslash(br#"abc\""#), Some(3));
        assert_eq!(split_once_byte(b"a:b", b':'), Some((&b"a"[..], &b"b"[..])));
        assert_eq!(find_quoted_bounds(br#"msgid "abc""#), Some((7, 10)));
        assert_eq!(find_escapable_byte(b"plain\ttext"), Some(5));
        assert_eq!(find_escapable_byte(b"plain\\text"), Some(5));
        assert_eq!(find_escapable_byte(b"plain text"), None);
        assert_eq!(parse_plural_index(b"msgstr[12] \"x\""), Some(12));
        assert_eq!(parse_plural_index(b"msgstr \"x\""), Some(0));
        assert_eq!(
            classify_line(b"#: src/main.rs:1"),
            LineKind::Comment(CommentKind::Reference)
        );
        assert_eq!(
            classify_line(b"msgid \"x\""),
            LineKind::Keyword(Keyword::Id)
        );
        assert_eq!(
            classify_line(b"msgid_plural \"xs\""),
            LineKind::Keyword(Keyword::IdPlural)
        );
        assert_eq!(
            classify_line(b"msgstr[0] \"x\""),
            LineKind::Keyword(Keyword::Str)
        );
        assert_eq!(classify_line(b"msgstr_ \"x\""), LineKind::Other);
        assert_eq!(classify_line(b"msgid_plurality \"x\""), LineKind::Other);
        assert_eq!(classify_line(br#""continued""#), LineKind::Continuation);
    }
}