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
/** Unicode character set handling for Glk API.
 */

/** Placeholder for characters that are invalid unicode. */
pub const UNKNOWN: char = '\u{fffd}';

/** u32 from Glk to rust char. Invalid characters will be replaced with the placeholder character
 * (U+fffd).
 */
pub fn to_char(ch: u32) -> char {
    std::char::from_u32(ch).unwrap_or(UNKNOWN)
}
/**
 * u32 buffer from Glk to rust string. Invalid characters will be replaced with the placeholder character
 * (U+fffd).
 */
pub fn to_string(ch: &[u32]) -> String {
    return ch.iter().copied().map(to_char).collect::<String>();
}

/** Rust string to Glk u32 buffer. Truncates the output if it doesn't fit.
 * Returns the number of characters that would have been written without truncation.
 */
pub fn from_string(buf: &mut [u32], s: &str) -> usize {
    let mut idx = 0;
    for ch in s.chars() {
        buf.get_mut(idx).map(|x| *x = u32::from(ch));
        idx += 1;
    }
    idx
}