micropdf 0.15.15

A pure Rust PDF library - A pure Rust PDF library with fz_/pdf_ API compatibility
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//! C FFI for advanced string handling - MicroPDF compatible
//! Safe Rust implementation of fz_string utilities

use super::Handle;
use std::ffi::{CStr, c_char};

/// Unicode normalization form
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NormalizationForm {
    /// Canonical decomposition (NFD)
    NFD = 0,
    /// Canonical decomposition followed by canonical composition (NFC)
    NFC = 1,
    /// Compatibility decomposition (NFKD)
    NFKD = 2,
    /// Compatibility decomposition followed by canonical composition (NFKC)
    NFKC = 3,
}

/// BiDi direction
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BiDiDirection {
    /// Left to right
    LTR = 0,
    /// Right to left
    RTL = 1,
    /// Mixed/neutral
    Mixed = 2,
}

/// Script category (simplified)
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScriptCategory {
    /// Unknown/common
    Common = 0,
    /// Latin
    Latin = 1,
    /// Greek
    Greek = 2,
    /// Cyrillic
    Cyrillic = 3,
    /// Arabic
    Arabic = 4,
    /// Hebrew
    Hebrew = 5,
    /// CJK (Chinese/Japanese/Korean)
    CJK = 6,
    /// Devanagari
    Devanagari = 7,
    /// Thai
    Thai = 8,
    /// Other
    Other = 255,
}

/// Word break type
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WordBreakType {
    /// No break
    NoBreak = 0,
    /// Optional break (soft hyphen)
    Soft = 1,
    /// Mandatory break (space, etc.)
    Hard = 2,
    /// Line break opportunity
    Line = 3,
}

// ============================================================================
// Unicode Normalization
// ============================================================================

/// Normalize a UTF-8 string
///
/// # Safety
/// - `input` must be a valid null-terminated UTF-8 string
/// - `output` must point to at least `output_size` bytes
#[unsafe(no_mangle)]
pub extern "C" fn fz_normalize_string(
    _ctx: Handle,
    input: *const c_char,
    output: *mut c_char,
    output_size: usize,
    form: i32,
) -> usize {
    if input.is_null() || output.is_null() || output_size == 0 {
        return 0;
    }

    let input_str = match unsafe { CStr::from_ptr(input) }.to_str() {
        Ok(s) => s,
        Err(_) => return 0,
    };

    let _norm_form = match form {
        1 => NormalizationForm::NFC,
        2 => NormalizationForm::NFKD,
        3 => NormalizationForm::NFKC,
        _ => NormalizationForm::NFD,
    };

    // Decompose common ligatures and normalize for PDF text extraction.
    // Handles the ligatures most frequently encountered in PDF fonts.
    let normalized = normalize_simple(input_str);

    let bytes = normalized.as_bytes();
    let copy_len = bytes.len().min(output_size - 1);

    let output_slice = unsafe { std::slice::from_raw_parts_mut(output as *mut u8, copy_len + 1) };
    output_slice[..copy_len].copy_from_slice(&bytes[..copy_len]);
    output_slice[copy_len] = 0;

    copy_len
}

fn normalize_simple(s: &str) -> String {
    // Basic normalization: decompose common ligatures and accented chars
    let mut result = String::with_capacity(s.len());

    for c in s.chars() {
        match c {
            // Common ligatures
            '' => result.push_str("fi"),
            '' => result.push_str("fl"),
            '' => result.push_str("ff"),
            '' => result.push_str("ffi"),
            '' => result.push_str("ffl"),
            'IJ' => result.push_str("IJ"),
            'ij' => result.push_str("ij"),
            // Everything else passes through
            _ => result.push(c),
        }
    }

    result
}

/// Check if string is normalized
#[unsafe(no_mangle)]
pub extern "C" fn fz_string_is_normalized(_ctx: Handle, input: *const c_char, form: i32) -> i32 {
    if input.is_null() {
        return 1;
    }

    let input_str = match unsafe { CStr::from_ptr(input) }.to_str() {
        Ok(s) => s,
        Err(_) => return 0,
    };

    let _form = match form {
        1 => NormalizationForm::NFC,
        2 => NormalizationForm::NFKD,
        3 => NormalizationForm::NFKC,
        _ => NormalizationForm::NFD,
    };

    // Simple check: no ligatures = normalized
    let has_ligatures = input_str
        .chars()
        .any(|c| matches!(c, '' | '' | '' | '' | ''));

    if has_ligatures { 0 } else { 1 }
}

// ============================================================================
// BiDi Processing
// ============================================================================

/// Get base direction of text
#[unsafe(no_mangle)]
pub extern "C" fn fz_get_bidi_direction(_ctx: Handle, text: *const c_char) -> i32 {
    if text.is_null() {
        return BiDiDirection::LTR as i32;
    }

    let text_str = match unsafe { CStr::from_ptr(text) }.to_str() {
        Ok(s) => s,
        Err(_) => return BiDiDirection::LTR as i32,
    };

    // Detect RTL by checking for RTL characters
    let mut has_rtl = false;
    let mut has_ltr = false;

    for c in text_str.chars() {
        if is_rtl_char(c) {
            has_rtl = true;
        } else if is_strong_ltr_char(c) {
            has_ltr = true;
        }
    }

    if has_rtl && has_ltr {
        BiDiDirection::Mixed as i32
    } else if has_rtl {
        BiDiDirection::RTL as i32
    } else {
        BiDiDirection::LTR as i32
    }
}

fn is_rtl_char(c: char) -> bool {
    // Arabic: U+0600-U+06FF, U+0750-U+077F, U+08A0-U+08FF
    // Hebrew: U+0590-U+05FF
    matches!(c,
        '\u{0590}'..='\u{05FF}' |  // Hebrew
        '\u{0600}'..='\u{06FF}' |  // Arabic
        '\u{0750}'..='\u{077F}' |  // Arabic Supplement
        '\u{08A0}'..='\u{08FF}'    // Arabic Extended-A
    )
}

fn is_strong_ltr_char(c: char) -> bool {
    // Latin, Greek, Cyrillic and most other scripts are LTR
    c.is_alphabetic() && !is_rtl_char(c)
}

/// Reorder text for display (visual order)
///
/// # Safety
/// - `input` must be valid UTF-8
/// - `output` must have space for reordered text
#[unsafe(no_mangle)]
pub extern "C" fn fz_bidi_reorder(
    _ctx: Handle,
    input: *const c_char,
    output: *mut c_char,
    output_size: usize,
    base_dir: i32,
) -> usize {
    if input.is_null() || output.is_null() || output_size == 0 {
        return 0;
    }

    let input_str = match unsafe { CStr::from_ptr(input) }.to_str() {
        Ok(s) => s,
        Err(_) => return 0,
    };

    let base_rtl = base_dir == BiDiDirection::RTL as i32;

    // Simple BiDi: reverse RTL segments
    let reordered = bidi_reorder_simple(input_str, base_rtl);

    let bytes = reordered.as_bytes();
    let copy_len = bytes.len().min(output_size - 1);

    let output_slice = unsafe { std::slice::from_raw_parts_mut(output as *mut u8, copy_len + 1) };
    output_slice[..copy_len].copy_from_slice(&bytes[..copy_len]);
    output_slice[copy_len] = 0;

    copy_len
}

fn bidi_reorder_simple(s: &str, _base_rtl: bool) -> String {
    // Simple implementation: identify RTL runs and reverse them
    let mut result = String::new();
    let mut current_run = String::new();
    let mut in_rtl = false;

    for c in s.chars() {
        let char_rtl = is_rtl_char(c);

        if char_rtl != in_rtl && !current_run.is_empty() {
            if in_rtl {
                result.extend(current_run.chars().rev());
            } else {
                result.push_str(&current_run);
            }
            current_run.clear();
        }

        in_rtl = char_rtl;
        current_run.push(c);
    }

    // Handle last run
    if !current_run.is_empty() {
        if in_rtl {
            result.extend(current_run.chars().rev());
        } else {
            result.push_str(&current_run);
        }
    }

    result
}

// ============================================================================
// Text Segmentation
// ============================================================================

/// Find word boundaries
///
/// # Safety
/// - `text` must be valid UTF-8
/// - `breaks` must have space for at least `max_breaks` values
#[unsafe(no_mangle)]
pub extern "C" fn fz_find_word_breaks(
    _ctx: Handle,
    text: *const c_char,
    breaks: *mut i32,
    max_breaks: usize,
) -> usize {
    if text.is_null() || breaks.is_null() || max_breaks == 0 {
        return 0;
    }

    let text_str = match unsafe { CStr::from_ptr(text) }.to_str() {
        Ok(s) => s,
        Err(_) => return 0,
    };

    let breaks_slice = unsafe { std::slice::from_raw_parts_mut(breaks, max_breaks) };
    let mut break_count = 0;
    let mut prev_was_space = true;

    for (i, c) in text_str.char_indices() {
        let is_space = c.is_whitespace();

        // Word starts after space
        if prev_was_space && !is_space && break_count < max_breaks {
            breaks_slice[break_count] = i as i32;
            break_count += 1;
        }

        prev_was_space = is_space;
    }

    break_count
}

/// Get word at position
#[unsafe(no_mangle)]
pub extern "C" fn fz_get_word_at(
    _ctx: Handle,
    text: *const c_char,
    position: usize,
    word_start: *mut usize,
    word_end: *mut usize,
) -> i32 {
    if text.is_null() {
        return 0;
    }

    let text_str = match unsafe { CStr::from_ptr(text) }.to_str() {
        Ok(s) => s,
        Err(_) => return 0,
    };

    if position >= text_str.len() {
        return 0;
    }

    // Find word boundaries around position
    let bytes = text_str.as_bytes();
    let mut start = position;
    let mut end = position;

    // Scan backward for word start
    while start > 0 && !bytes[start - 1].is_ascii_whitespace() {
        start -= 1;
    }

    // Scan forward for word end
    while end < bytes.len() && !bytes[end].is_ascii_whitespace() {
        end += 1;
    }

    if !word_start.is_null() {
        unsafe { *word_start = start };
    }
    if !word_end.is_null() {
        unsafe { *word_end = end };
    }

    1
}

/// Find line break opportunities
#[unsafe(no_mangle)]
pub extern "C" fn fz_find_line_breaks(
    _ctx: Handle,
    text: *const c_char,
    breaks: *mut i32,
    max_breaks: usize,
) -> usize {
    if text.is_null() || breaks.is_null() || max_breaks == 0 {
        return 0;
    }

    let text_str = match unsafe { CStr::from_ptr(text) }.to_str() {
        Ok(s) => s,
        Err(_) => return 0,
    };

    let breaks_slice = unsafe { std::slice::from_raw_parts_mut(breaks, max_breaks) };
    let mut break_count = 0;

    for (i, c) in text_str.char_indices() {
        // Break after spaces, hyphens, and CJK characters
        let is_break_after = c.is_whitespace()
            || c == '-'
            || c == '\u{00AD}' // Soft hyphen
            || is_cjk_char(c);

        if is_break_after && break_count < max_breaks {
            breaks_slice[break_count] = (i + c.len_utf8()) as i32;
            break_count += 1;
        }
    }

    break_count
}

fn is_cjk_char(c: char) -> bool {
    matches!(c,
        '\u{4E00}'..='\u{9FFF}' |   // CJK Unified Ideographs
        '\u{3400}'..='\u{4DBF}' |   // CJK Extension A
        '\u{3000}'..='\u{303F}' |   // CJK Punctuation
        '\u{3040}'..='\u{309F}' |   // Hiragana
        '\u{30A0}'..='\u{30FF}' |   // Katakana
        '\u{AC00}'..='\u{D7AF}'     // Hangul
    )
}

// ============================================================================
// Script Detection
// ============================================================================

/// Detect script of text
#[unsafe(no_mangle)]
pub extern "C" fn fz_detect_script(_ctx: Handle, text: *const c_char) -> i32 {
    if text.is_null() {
        return ScriptCategory::Common as i32;
    }

    let text_str = match unsafe { CStr::from_ptr(text) }.to_str() {
        Ok(s) => s,
        Err(_) => return ScriptCategory::Common as i32,
    };

    // Find first strong script character
    for c in text_str.chars() {
        let script = char_script(c);
        if script != ScriptCategory::Common {
            return script as i32;
        }
    }

    ScriptCategory::Common as i32
}

fn char_script(c: char) -> ScriptCategory {
    match c {
        'A'..='Z' | 'a'..='z' | '\u{00C0}'..='\u{00FF}' => ScriptCategory::Latin,
        '\u{0370}'..='\u{03FF}' => ScriptCategory::Greek,
        '\u{0400}'..='\u{04FF}' => ScriptCategory::Cyrillic,
        '\u{0600}'..='\u{06FF}' | '\u{0750}'..='\u{077F}' => ScriptCategory::Arabic,
        '\u{0590}'..='\u{05FF}' => ScriptCategory::Hebrew,
        '\u{4E00}'..='\u{9FFF}' | '\u{3040}'..='\u{30FF}' | '\u{AC00}'..='\u{D7AF}' => {
            ScriptCategory::CJK
        }
        '\u{0900}'..='\u{097F}' => ScriptCategory::Devanagari,
        '\u{0E00}'..='\u{0E7F}' => ScriptCategory::Thai,
        _ => ScriptCategory::Common,
    }
}

// ============================================================================
// Language-Aware Operations
// ============================================================================

/// Case-fold string for comparison
#[unsafe(no_mangle)]
pub extern "C" fn fz_casefold(
    _ctx: Handle,
    input: *const c_char,
    output: *mut c_char,
    output_size: usize,
) -> usize {
    if input.is_null() || output.is_null() || output_size == 0 {
        return 0;
    }

    let input_str = match unsafe { CStr::from_ptr(input) }.to_str() {
        Ok(s) => s,
        Err(_) => return 0,
    };

    let folded: String = input_str.chars().flat_map(|c| c.to_lowercase()).collect();

    let bytes = folded.as_bytes();
    let copy_len = bytes.len().min(output_size - 1);

    let output_slice = unsafe { std::slice::from_raw_parts_mut(output as *mut u8, copy_len + 1) };
    output_slice[..copy_len].copy_from_slice(&bytes[..copy_len]);
    output_slice[copy_len] = 0;

    copy_len
}

/// Compare strings with collation
#[unsafe(no_mangle)]
pub extern "C" fn fz_strcoll(
    _ctx: Handle,
    s1: *const c_char,
    s2: *const c_char,
    _locale: *const c_char,
) -> i32 {
    if s1.is_null() && s2.is_null() {
        return 0;
    }
    if s1.is_null() {
        return -1;
    }
    if s2.is_null() {
        return 1;
    }

    let str1 = unsafe { CStr::from_ptr(s1) }.to_str().unwrap_or("");
    let str2 = unsafe { CStr::from_ptr(s2) }.to_str().unwrap_or("");

    // Case-insensitive comparison using Unicode case folding
    let s1_lower: String = str1.chars().flat_map(|c| c.to_lowercase()).collect();
    let s2_lower: String = str2.chars().flat_map(|c| c.to_lowercase()).collect();

    match s1_lower.cmp(&s2_lower) {
        std::cmp::Ordering::Less => -1,
        std::cmp::Ordering::Equal => 0,
        std::cmp::Ordering::Greater => 1,
    }
}

/// Count characters (grapheme clusters)
#[unsafe(no_mangle)]
pub extern "C" fn fz_string_char_count(_ctx: Handle, s: *const c_char) -> usize {
    if s.is_null() {
        return 0;
    }

    let str = match unsafe { CStr::from_ptr(s) }.to_str() {
        Ok(s) => s,
        Err(_) => return 0,
    };

    str.chars().count()
}

/// Get byte offset for character index
#[unsafe(no_mangle)]
pub extern "C" fn fz_char_to_byte_offset(_ctx: Handle, s: *const c_char, char_index: usize) -> i32 {
    if s.is_null() {
        return -1;
    }

    let str = match unsafe { CStr::from_ptr(s) }.to_str() {
        Ok(s) => s,
        Err(_) => return -1,
    };

    for (i, (byte_idx, _)) in str.char_indices().enumerate() {
        if i == char_index {
            return byte_idx as i32;
        }
    }

    -1
}

/// Get character index for byte offset
#[unsafe(no_mangle)]
pub extern "C" fn fz_byte_to_char_offset(
    _ctx: Handle,
    s: *const c_char,
    byte_offset: usize,
) -> i32 {
    if s.is_null() {
        return -1;
    }

    let str = match unsafe { CStr::from_ptr(s) }.to_str() {
        Ok(s) => s,
        Err(_) => return -1,
    };

    for (char_idx, (byte_idx, _)) in str.char_indices().enumerate() {
        if byte_idx == byte_offset {
            return char_idx as i32;
        }
    }

    -1
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_normalize_ligatures() {
        let input = c"finding flowers";
        let mut output = [0u8; 64];

        let len = fz_normalize_string(
            0,
            input.as_ptr(),
            output.as_mut_ptr().cast(),
            64,
            NormalizationForm::NFC as i32,
        );

        let result = std::str::from_utf8(&output[..len]).unwrap();
        assert!(result.contains("fi"));
        assert!(result.contains("fl"));
    }

    #[test]
    fn test_bidi_detection() {
        let ltr = c"Hello World";
        let rtl = c"\u{05E9}\u{05DC}\u{05D5}\u{05DD}"; // Hebrew "Shalom"

        assert_eq!(
            fz_get_bidi_direction(0, ltr.as_ptr()),
            BiDiDirection::LTR as i32
        );
        assert_eq!(
            fz_get_bidi_direction(0, rtl.as_ptr()),
            BiDiDirection::RTL as i32
        );
    }

    #[test]
    fn test_word_breaks() {
        let text = c"Hello world test string";
        let mut breaks = [0i32; 10];

        let count = fz_find_word_breaks(0, text.as_ptr(), breaks.as_mut_ptr(), 10);

        assert_eq!(count, 4); // 4 words
        assert_eq!(breaks[0], 0); // "Hello"
        assert_eq!(breaks[1], 6); // "world"
    }

    #[test]
    fn test_script_detection() {
        let latin = c"Hello";
        let arabic = c"\u{0645}\u{0631}\u{062D}\u{0628}\u{0627}"; // "Marhaba"
        let cjk = c"\u{4E2D}\u{6587}"; // "Chinese"

        assert_eq!(
            fz_detect_script(0, latin.as_ptr()),
            ScriptCategory::Latin as i32
        );
        assert_eq!(
            fz_detect_script(0, arabic.as_ptr()),
            ScriptCategory::Arabic as i32
        );
        assert_eq!(
            fz_detect_script(0, cjk.as_ptr()),
            ScriptCategory::CJK as i32
        );
    }

    #[test]
    fn test_casefold() {
        let input = c"Hello WORLD";
        let mut output = [0u8; 32];

        let len = fz_casefold(0, input.as_ptr(), output.as_mut_ptr().cast(), 32);
        let result = std::str::from_utf8(&output[..len]).unwrap();

        assert_eq!(result, "hello world");
    }

    #[test]
    fn test_char_count() {
        let ascii = c"Hello";
        let unicode = c"\u{1F600}Hello"; // Emoji + Hello

        assert_eq!(fz_string_char_count(0, ascii.as_ptr()), 5);
        assert_eq!(fz_string_char_count(0, unicode.as_ptr()), 6);
    }

    #[test]
    fn test_char_byte_offset() {
        let s = c"H\u{00E9}llo"; // "Héllo" - é is 2 bytes

        // 'H' is at char 0, byte 0
        assert_eq!(fz_char_to_byte_offset(0, s.as_ptr(), 0), 0);
        // 'é' is at char 1, byte 1
        assert_eq!(fz_char_to_byte_offset(0, s.as_ptr(), 1), 1);
        // 'l' is at char 2, byte 3 (after 2-byte é)
        assert_eq!(fz_char_to_byte_offset(0, s.as_ptr(), 2), 3);
    }

    #[test]
    fn test_strcoll() {
        let a = c"apple";
        let b = c"Banana";
        let c = c"Apple";

        // Case-insensitive comparison
        assert!(fz_strcoll(0, a.as_ptr(), b.as_ptr(), std::ptr::null()) < 0);
        assert_eq!(fz_strcoll(0, a.as_ptr(), c.as_ptr(), std::ptr::null()), 0);
    }
}