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.2.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-15
Size
105.5 KB
Downloads
24
Checksum
f438a48f6f2fc61d892f930eb4fb56fb5a8e302e733a8c3a6283d0ff7350cd08
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
//! 文字の扱い
//!
//! 和文か欧文かの見分け、行頭と行末に置けない文字、続いた記号の直し、
//! それに PDF へ書き出すときの数と文字列の形を持つ。

use std::time::{SystemTime, UNIX_EPOCH};


/// 行頭に置けない文字
const NOT_AT_START: &str = "、。,.・:;?!ゝゞヽヾ々ー〜)]}」』】〉》〕”’%,.:;?!)]}";


/// 行末に置けない文字
const NOT_AT_END: &str = "([{「『【〈《〔“‘([{";


/// 小書きの仮名。行頭に置けない
const SMALL_KANA: &str = "ぁぃぅぇぉっゃゅょゎァィゥェォッャュョヮヵヶ";


/// 和文と欧文のあいだに入れる空き(em)
pub const MIXED_GAP: f64 = 0.25;


/// 全角の文字かどうか
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
    )
}


/// 行頭に置けない文字かどうか
pub fn forbidden_at_start(character: char) -> bool {
    NOT_AT_START.contains(character) || SMALL_KANA.contains(character)
}


/// 行末に置けない文字かどうか
pub fn forbidden_at_end(character: char) -> bool {
    NOT_AT_END.contains(character)
}


/// 2 つの文字のあいだに和欧間の空きを入れるかどうか
///
/// 入れるのは和文と欧文の英数字のあいだだけである。`{` や `(` のような記号の隣、
/// 「、」や「)」のような約物の隣には入れない。もともと余白を持っている
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)
}


/// 続けて書いた記号を、組むときの文字に直す
///
/// `---` は全角ダッシュ、`--` は半角ダッシュ、`` `` `` と `''` は引用符になる
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
}


/// 今日の日付。時差は見ないので、日付の変わり目では前日になることがある
pub fn today() -> String {
    let seconds = match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(elapsed) => elapsed.as_secs() as i64,
        Err(_) => 0,
    };
    let (year, month, day) = civil(seconds.div_euclid(86_400));

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


/// 1970 年 1 月 1 日からの日数を、年月日に直す
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)
}


/// いまの時刻を PDF の日付の形で返す。時差は見ないので UTC で書く
pub fn stamp() -> String {
    let seconds = match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(elapsed) => elapsed.as_secs() as i64,
        Err(_) => 0,
    };
    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")
}


/// 数を PDF に書ける形にする。指数は使わず、末尾の 0 は落とす
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
}


/// PDF の丸括弧で囲む文字列に入れられる形にする
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
}


/// 文字列を UTF-16BE の 16 進で書く。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
}


/// 数を 16 進 4 桁で書く
pub fn hex_number(value: u16) -> String {
    format!("{value:04X}")
}


/// 番号をローマ数字にする。目次より前のページ番号に使う
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
}


/// 番号を A, B, C にする。付録の見出しに使う
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");
    }
}