Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.4.01085.8 KB2026-10-160.3.21087.6 KB2026-10-160.3.11087.5 KB2026-10-160.3.0117.8 KB2026-10-160.2.1106.1 KB2026-10-150.2.0105.5 KB2026-10-15
Version
0.3.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-16
Size
117.8 KB
Downloads
24
Checksum
91f9899559d38e059baa788310473f349f3d218d16f6afbd045fc9d087ba00c3
Dependencies
rust/[email protected]
rust/[email protected]

text.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
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
//! Handling characters
//!
//! This covers telling Japanese text from Latin text, the characters that cannot go at the start
//! of a line or the end of a line, converting runs of symbols, and the forms of numbers and
//! strings written to PDF.

#[cfg(not(target_arch = "wasm32"))]
use std::time::{SystemTime, UNIX_EPOCH};


/// Characters that cannot go at the start of a line
const NOT_AT_START: &str = "、。,.・:;?!ゝゞヽヾ々ー〜)]}」』】〉》〕”’%,.:;?!)]}";


/// Characters that cannot go at the end of a line
const NOT_AT_END: &str = "([{「『【〈《〔“‘([{";


/// Small kana. They cannot go at the start of a line
const SMALL_KANA: &str = "ぁぃぅぇぉっゃゅょゎァィゥェォッャュョヮヵヶ";


/// The space between Japanese and Latin text (em)
pub const MIXED_GAP: f64 = 0.25;


/// Whether a character is full width
pub fn is_wide(character: char) -> bool {
    let code = character as u32;

    matches!(
        code,
        0x1100..=0x115f
            | 0x2e80..=0x303e
            | 0x3041..=0x33ff
            | 0x3400..=0x4dbf
            | 0x4e00..=0x9fff
            | 0xa000..=0xa4cf
            | 0xac00..=0xd7a3
            | 0xf900..=0xfaff
            | 0xfe30..=0xfe6f
            | 0xff00..=0xff60
            | 0xffe0..=0xffe6
            | 0x20000..=0x3fffd
    )
}


/// Whether a character cannot go at the start of a line
pub fn forbidden_at_start(character: char) -> bool {
    NOT_AT_START.contains(character) || SMALL_KANA.contains(character)
}


/// Whether a character cannot go at the end of a line
pub fn forbidden_at_end(character: char) -> bool {
    NOT_AT_END.contains(character)
}


/// Whether two adjacent characters need the space between Japanese and Latin text
///
/// It goes only between Japanese text and Latin letters or digits. It does not go next to a
/// symbol such as `{` or `(`, or next to Japanese punctuation such as U+3001 (ideographic comma)
/// or U+FF09 (fullwidth right parenthesis). These already have blank space of their own
pub fn needs_gap(left: char, right: char) -> bool {
    let (wide, narrow) = if is_wide(left) {
        if is_wide(right) {
            return false;
        }

        (left, right)
    } else {
        if !is_wide(right) {
            return false;
        }

        (right, left)
    };

    narrow.is_alphanumeric() && !forbidden_at_start(wide) && !forbidden_at_end(wide)
}


/// Converts runs of symbols into the characters used for typesetting
///
/// `---` becomes an em dash, `--` an en dash, and `` `` `` and `''` become quotation marks
pub fn ligature(text: &str) -> String {
    let source: Vec<char> = text.chars().collect();
    let mut out = String::with_capacity(text.len());
    let mut at = 0;

    while at < source.len() {
        let rest = source.len() - at;

        if source[at] == '-' && rest >= 3 && source[at + 1] == '-' && source[at + 2] == '-' {
            out.push('\u{2014}');
            at += 3;

        } else if source[at] == '-' && rest >= 2 && source[at + 1] == '-' {
            out.push('\u{2013}');
            at += 2;

        } else if source[at] == '`' && rest >= 2 && source[at + 1] == '`' {
            out.push('\u{201c}');
            at += 2;

        } else if source[at] == '\'' && rest >= 2 && source[at + 1] == '\'' {
            out.push('\u{201d}');
            at += 2;

        } else if source[at] == '`' {
            out.push('\u{2018}');
            at += 1;

        } else if source[at] == '\'' {
            out.push('\u{2019}');
            at += 1;

        } else {
            out.push(source[at]);
            at += 1;
        }
    }

    out
}


/// Today's date. Time zones are ignored, so just after the date changes, it can give the
/// previous day
pub fn today() -> String {
    let (year, month, day) = civil(seconds().div_euclid(86_400));

    format!("{year}年{month}月{day}日")
}


/// Seconds since January 1, 1970
#[cfg(not(target_arch = "wasm32"))]
fn seconds() -> i64 {
    match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(elapsed) => elapsed.as_secs() as i64,
        Err(_) => 0,
    }
}


/// Seconds since January 1, 1970. wasm cannot read the clock, so JavaScript gives the time
#[cfg(target_arch = "wasm32")]
fn seconds() -> i64 {
    #[link(wasm_import_module = "env")]
    unsafe extern "C" {
        fn now() -> f64;
    }

    unsafe { now() as i64 }
}


/// Converts the number of days since January 1, 1970 into a year, a month, and a day
fn civil(days: i64) -> (i64, i64, i64) {
    let shifted = days + 719_468;
    let era = shifted.div_euclid(146_097);
    let day_of_era = shifted.rem_euclid(146_097);
    let year_of_era =
        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
    let year = year_of_era + era * 400;
    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
    let shifted_month = (5 * day_of_year + 2) / 153;
    let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
    let month = if shifted_month < 10 {shifted_month + 3} else {shifted_month - 9};

    (if month <= 2 {year + 1} else {year}, month, day)
}


/// Returns the current time in the PDF date format. Time zones are ignored, so the time is
/// written in UTC
pub fn stamp() -> String {
    let seconds = seconds();
    let (year, month, day) = civil(seconds.div_euclid(86_400));
    let rest = seconds.rem_euclid(86_400);
    let hour = rest / 3_600;
    let minute = (rest % 3_600) / 60;
    let second = rest % 60;

    format!("D:{year:04}{month:02}{day:02}{hour:02}{minute:02}{second:02}Z")
}


/// Puts a number in a form that can be written in PDF. No exponent is used, and trailing zeros
/// are dropped
pub fn number(value: f64) -> String {
    if !value.is_finite() {
        return "0".to_string();
    }

    let rounded = (value * 1000.0).round() / 1000.0;

    if rounded == rounded.trunc() {
        return format!("{}", rounded as i64);
    }

    let mut text = format!("{rounded:.3}");

    while text.ends_with('0') {
        text.pop();
    }

    if text.ends_with('.') {
        text.pop();
    }

    text
}


/// Puts text in a form that can go in a PDF string enclosed in parentheses
pub fn escape_string(text: &str) -> String {
    let mut out = String::with_capacity(text.len());

    for character in text.chars() {
        match character {
            '\\' => out.push_str("\\\\"),
            '(' => out.push_str("\\("),
            ')' => out.push_str("\\)"),
            '\r' => out.push_str("\\r"),
            '\n' => out.push_str("\\n"),
            _ => out.push(character),
        }
    }

    out
}


/// Writes a string as UTF-16BE in hexadecimal. Used for things such as the title of the PDF
pub fn hex_string(text: &str) -> String {
    let mut out = String::from("FEFF");

    for unit in text.encode_utf16() {
        out.push_str(&format!("{unit:04X}"));
    }

    out
}


/// Writes a number as 4 hexadecimal digits
pub fn hex_number(value: u16) -> String {
    format!("{value:04X}")
}


/// Turns a number into Roman numerals. Used for the page numbers before the table of contents
pub fn roman(mut value: usize) -> String {
    const TABLE: &[(usize, &str)] = &[
        (1000, "m"),
        (900, "cm"),
        (500, "d"),
        (400, "cd"),
        (100, "c"),
        (90, "xc"),
        (50, "l"),
        (40, "xl"),
        (10, "x"),
        (9, "ix"),
        (5, "v"),
        (4, "iv"),
        (1, "i"),
    ];
    let mut out = String::new();

    for (size, mark) in TABLE {
        while value >= *size {
            out.push_str(mark);
            value -= size;
        }
    }

    out
}


/// Turns a number into A, B, C. Used for the headings in the appendix
pub fn alphabet(value: usize) -> String {
    if value == 0 {
        return String::new();
    }

    let mut out = String::new();
    let mut left = value;

    while left > 0 {
        let index = (left - 1) % 26;
        out.insert(0, (b'A' + index as u8) as char);
        left = (left - 1) / 26;
    }

    out
}


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

    #[test]
    fn wide_letters_are_told_apart() {
        assert!(is_wide('あ'));
        assert!(is_wide('漢'));
        assert!(is_wide('。'));
        assert!(!is_wide('a'));
        assert!(!is_wide('1'));
    }

    #[test]
    fn a_gap_goes_between_the_two_kinds() {
        assert!(needs_gap('あ', 'a'));
        assert!(needs_gap('a', 'あ'));
        assert!(needs_gap('あ', '1'));
        assert!(!needs_gap('あ', 'い'));
        assert!(!needs_gap('a', 'b'));
        assert!(!needs_gap('。', 'a'));
        assert!(!needs_gap('あ', ')'));
    }

    #[test]
    fn no_gap_goes_next_to_a_mark() {
        assert!(!needs_gap('{', '見'));
        assert!(!needs_gap('見', '}'));
        assert!(!needs_gap('(', '注'));
        assert!(!needs_gap('あ', '\u{2014}'));
    }

    #[test]
    fn marks_join_into_one_letter() {
        assert_eq!(ligature("a---b"), "a\u{2014}b");
        assert_eq!(ligature("a--b"), "a\u{2013}b");
        assert_eq!(ligature("``x''"), "\u{201c}x\u{201d}");
    }

    #[test]
    fn numbers_lose_their_trailing_zeros() {
        assert_eq!(number(1.0), "1");
        assert_eq!(number(1.5), "1.5");
        assert_eq!(number(1.2345), "1.235");
        assert_eq!(number(-0.0), "0");
    }

    #[test]
    fn a_known_day_comes_back_right() {
        assert_eq!(civil(0), (1970, 1, 1));
        assert_eq!(civil(19_000), (2022, 1, 8));
    }

    #[test]
    fn counters_have_other_shapes() {
        assert_eq!(roman(4), "iv");
        assert_eq!(roman(2026), "mmxxvi");
        assert_eq!(alphabet(1), "A");
        assert_eq!(alphabet(27), "AA");
    }
}