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
use std::borrow::Cow;
use std::ffi::{CStr, CString, OsStr};
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;
#[cfg(target_os = "wasi")]
use std::os::wasi::ffi::OsStrExt;
use std::{io, str};

/// Convert a byte sequence which is either plain UTF-8 or an ARF encoding into
/// a `CString` ready for use in POSIX-style APIs.
pub fn bytes_to_host(bytes: &[u8]) -> io::Result<CString> {
    let s = str::from_utf8(bytes).map_err(|_| encoding_error())?;
    str_to_host(s)
}

/// Convert a `&str` which is either plain UTF-8 or an ARF encoding into a
/// `CString` ready for use in POSIX-style APIs.
pub fn str_to_host(s: &str) -> io::Result<CString> {
    match CString::new(s) {
        Ok(c_string) => Ok(c_string),
        Err(e) => from_arf(s, e.nul_position()),
    }
}

/// Convert an `&OsStr` produced by POSIX-style APIs into a `Cow<str>` which
/// is either plain UTF-8 or an ARF encoding. Returns an error if the input
/// string contains NUL bytes.
pub fn host_os_str_to_str(host: &OsStr) -> io::Result<Cow<str>> {
    if host.as_bytes().contains(&b'\0') {
        return Err(encoding_error());
    }
    Ok(if let Ok(s) = str::from_utf8(host.as_bytes()) {
        Cow::Borrowed(s)
    } else {
        Cow::Owned(to_arf(host.as_bytes()))
    })
}

/// Convert an `&OsStr` produced by POSIX-style APIs into a `Cow<[u8]>` which
/// is either plain UTF-8 or an ARF encoding. Returns an error if the input
/// string contains NUL bytes.
pub fn host_os_str_to_bytes(host: &OsStr) -> io::Result<Cow<[u8]>> {
    Ok(match host_os_str_to_str(host)? {
        Cow::Borrowed(b) => Cow::Borrowed(b.as_bytes()),
        Cow::Owned(b) => Cow::Owned(b.into_bytes()),
    })
}

/// Convert an `&CStr` produced by POSIX-style APIs into a `Cow<str>` which
/// is either plain UTF-8 or an ARF encoding.
pub fn host_c_str_to_str(host: &CStr) -> Cow<str> {
    if let Ok(s) = str::from_utf8(host.to_bytes()) {
        Cow::Borrowed(s)
    } else {
        Cow::Owned(to_arf(host.to_bytes()))
    }
}

/// Convert an `&CStr` produced by POSIX-style APIs into a `Cow<[u8]>` which
/// is either plain UTF-8 or an ARF encoding.
pub fn host_c_str_to_bytes(host: &CStr) -> Cow<[u8]> {
    let bytes = host_c_str_to_str(host);
    match bytes {
        Cow::Borrowed(b) => Cow::Borrowed(b.as_bytes()),
        Cow::Owned(b) => Cow::Owned(b.into_bytes()),
    }
}

/// Slow path for `str_to_host`.
#[cold]
fn from_arf(s: &str, nul: usize) -> io::Result<CString> {
    if !s.starts_with('\u{feff}') {
        return Err(encoding_error());
    }

    let mut lossy = s.bytes().skip('\u{feff}'.len_utf8());
    let mut nul_escaped = s.bytes().skip(nul + 1);
    let mut any_invalid = false;
    let mut vec = Vec::new();
    while let Some(b) = nul_escaped.next() {
        if b == b'\0' {
            let more = nul_escaped.next().ok_or_else(encoding_error)?;
            if (more & 0x80) != 0 {
                return Err(encoding_error());
            }
            // Test for U+FFFD.
            let l0 = lossy.next().ok_or_else(encoding_error)?;
            let l1 = lossy.next().ok_or_else(encoding_error)?;
            let l2 = lossy.next().ok_or_else(encoding_error)?;
            if [l0, l1, l2] != [0xef, 0xbf, 0xbd] {
                return Err(encoding_error());
            }
            any_invalid = true;
            vec.push(more | 0x80);
        } else {
            if lossy.next() != Some(b) {
                return Err(encoding_error());
            }
            vec.push(b);
        }
    }
    if !any_invalid {
        return Err(encoding_error());
    }
    if lossy.next() != Some(b'\0') {
        return Err(encoding_error());
    }

    // Validation succeeded.
    Ok(unsafe { CString::from_vec_unchecked(vec) })
}

/// Slow path for `host_to_bytes`.
#[cold]
fn to_arf(bytes: &[u8]) -> String {
    let mut data = String::new();

    data.push('\u{feff}');

    let mut input = bytes;

    // This loop and `unsafe` follow the example in the documentation:
    // <https://doc.rust-lang.org/std/str/struct.Utf8Error.html#examples>
    loop {
        match std::str::from_utf8(input) {
            Ok(valid) => {
                data.push_str(valid);
                break;
            }
            Err(error) => {
                let (valid, after_valid) = input.split_at(error.valid_up_to());
                unsafe { data.push_str(str::from_utf8_unchecked(valid)) }
                data.push('\u{FFFD}');

                if let Some((_, remaining)) = after_valid.split_first() {
                    input = remaining;
                } else {
                    break;
                }
            }
        }
    }

    data.push('\0');

    // This loop and `unsafe` follow the example in the documentation
    // mentioned above.
    let mut input = bytes;
    loop {
        match std::str::from_utf8(input) {
            Ok(valid) => {
                data.push_str(valid);
                break;
            }
            Err(error) => {
                let (valid, after_valid) = input.split_at(error.valid_up_to());

                unsafe { data.push_str(str::from_utf8_unchecked(valid)) }
                if let Some((byte, remaining)) = after_valid.split_first() {
                    data.push('\0');
                    data.push((byte & 0x7f) as char);
                    input = remaining;
                } else {
                    break;
                }
            }
        }
    }

    data
}

#[cold]
fn encoding_error() -> io::Error {
    ::rustix::io::Errno::ILSEQ.into()
}

#[test]
fn utf8_inputs() {
    assert_eq!(str_to_host("").unwrap().to_bytes(), b"");
    assert_eq!(str_to_host("f").unwrap().to_bytes(), b"f");
    assert_eq!(str_to_host("foo").unwrap().to_bytes(), b"foo");
    assert_eq!(
        str_to_host("\u{fffd}").unwrap().to_bytes(),
        "\u{fffd}".as_bytes()
    );
    assert_eq!(
        str_to_host("\u{fffd}foo").unwrap().to_bytes(),
        "\u{fffd}foo".as_bytes()
    );
    assert_eq!(
        str_to_host("\u{feff}foo").unwrap().to_bytes(),
        "\u{feff}foo".as_bytes()
    );
}

#[test]
fn arf_inputs() {
    assert_eq!(
        str_to_host("\u{feff}hello\u{fffd}world\0hello\0\x05world")
            .unwrap()
            .to_bytes(),
        b"hello\x85world"
    );
    assert_eq!(
        str_to_host("\u{feff}hello\u{fffd}\0hello\0\x05")
            .unwrap()
            .to_bytes(),
        b"hello\x85"
    );
}

#[test]
fn errors_from_bytes() {
    assert!(bytes_to_host(b"\xfe").is_err());
    assert!(bytes_to_host(b"\xc0\xff").is_err());
}

#[test]
fn errors_from_str() {
    assert!(str_to_host("\u{feff}hello world\0hello world").is_err());
    assert!(str_to_host("\u{feff}hello world\0\0hello world\0").is_err());
    assert!(str_to_host("\u{feff}hello\u{fffd}world\0\0hello\0\x05world\0").is_err());
    assert!(str_to_host("\u{fffe}hello\u{fffd}world\0hello\0\x05world").is_err());
    assert!(str_to_host("\u{feff}hello\u{fffd}\0hello\0").is_err());
}

#[test]
fn valid_utf8() {
    assert_eq!(host_os_str_to_str(OsStr::from_bytes(b"")).unwrap(), "");
    assert_eq!(
        host_os_str_to_str(OsStr::from_bytes(b"foo")).unwrap(),
        "foo"
    );

    // Same thing, now with `CStr`s.
    assert_eq!(
        host_c_str_to_str(CStr::from_bytes_with_nul(b"\0").unwrap()),
        ""
    );
    assert_eq!(
        host_c_str_to_str(CStr::from_bytes_with_nul(b"foo\0").unwrap()),
        "foo"
    );
}

#[test]
fn not_utf8() {
    assert_eq!(
        host_os_str_to_str(OsStr::from_bytes(b"\xfe")).unwrap(),
        "\u{feff}\u{fffd}\0\0\u{7e}"
    );
    assert_eq!(
        host_os_str_to_str(OsStr::from_bytes(b"\xc0\xff")).unwrap(),
        "\u{feff}\u{fffd}\u{fffd}\0\0\u{40}\0\u{7f}"
    );
    assert_eq!(
        host_os_str_to_str(OsStr::from_bytes(b"\xef\xbb\xbf")).unwrap(),
        "\u{feff}"
    );
    assert_eq!(
        host_os_str_to_str(OsStr::from_bytes(b"\xef\xbb\xbf\xfd")).unwrap(),
        "\u{feff}\u{feff}\u{fffd}\0\u{feff}\0\x7d"
    );
    assert_eq!(
        host_os_str_to_str(OsStr::from_bytes(b"\xe2\x98")).unwrap(),
        "\u{feff}\u{fffd}\u{fffd}\0\0\u{62}\0\u{18}"
    );
    assert_eq!(
        host_os_str_to_str(OsStr::from_bytes(b"\xf0\x9f")).unwrap(),
        "\u{feff}\u{fffd}\u{fffd}\0\0\u{70}\0\u{1f}"
    );
    assert_eq!(
        host_os_str_to_str(OsStr::from_bytes(b"\xf0\x9f\x92")).unwrap(),
        "\u{feff}\u{fffd}\u{fffd}\u{fffd}\0\0\u{70}\0\u{1f}\0\u{12}"
    );

    // Same thing, now with `CStr`s.
    assert_eq!(
        host_c_str_to_str(CStr::from_bytes_with_nul(b"\xfe\0").unwrap()),
        "\u{feff}\u{fffd}\0\0\u{7e}"
    );
    assert_eq!(
        host_c_str_to_str(CStr::from_bytes_with_nul(b"\xc0\xff\0").unwrap()),
        "\u{feff}\u{fffd}\u{fffd}\0\0\u{40}\0\u{7f}"
    );
    assert_eq!(
        host_c_str_to_str(CStr::from_bytes_with_nul(b"\xef\xbb\xbf\0").unwrap()),
        "\u{feff}"
    );
    assert_eq!(
        host_c_str_to_str(CStr::from_bytes_with_nul(b"\xef\xbb\xbf\xfd\0").unwrap()),
        "\u{feff}\u{feff}\u{fffd}\0\u{feff}\0\x7d"
    );
    assert_eq!(
        host_c_str_to_str(CStr::from_bytes_with_nul(b"\xe2\x98\0").unwrap()),
        "\u{feff}\u{fffd}\u{fffd}\0\0\u{62}\0\u{18}"
    );
    assert_eq!(
        host_c_str_to_str(CStr::from_bytes_with_nul(b"\xf0\x9f\0").unwrap()),
        "\u{feff}\u{fffd}\u{fffd}\0\0\u{70}\0\u{1f}"
    );
    assert_eq!(
        host_c_str_to_str(CStr::from_bytes_with_nul(b"\xf0\x9f\x92\0").unwrap()),
        "\u{feff}\u{fffd}\u{fffd}\u{fffd}\0\0\u{70}\0\u{1f}\0\u{12}"
    );
}

#[test]
fn round_trip() {
    assert_eq!(
        host_os_str_to_str(OsStr::from_bytes(bytes_to_host(b"").unwrap().as_bytes())).unwrap(),
        ""
    );
    assert_eq!(
        host_os_str_to_str(OsStr::from_bytes(
            bytes_to_host(b"hello").unwrap().as_bytes()
        ))
        .unwrap(),
        "hello"
    );
    assert_eq!(
        str_to_host(&host_os_str_to_str(OsStr::from_bytes(b"hello")).unwrap())
            .unwrap()
            .as_bytes(),
        b"hello"
    );
    assert_eq!(
        str_to_host(&host_os_str_to_str(OsStr::from_bytes(b"h\xc0ello\xc1")).unwrap())
            .unwrap()
            .as_bytes(),
        b"h\xc0ello\xc1"
    );
    assert_eq!(
        str_to_host(&host_os_str_to_str(OsStr::from_bytes(b"\xf5\xff")).unwrap())
            .unwrap()
            .as_bytes(),
        b"\xf5\xff"
    );
    assert_eq!(
        str_to_host(&host_os_str_to_str(OsStr::from_bytes(b"")).unwrap())
            .unwrap()
            .as_bytes(),
        b""
    );
    assert_eq!(
        str_to_host(&host_os_str_to_str(OsStr::from_bytes(b"\xe6\x96")).unwrap())
            .unwrap()
            .as_bytes(),
        b"\xe6\x96"
    );

    // Same thing, now with `CStr`s.
    assert_eq!(
        str_to_host(&host_c_str_to_str(
            CStr::from_bytes_with_nul(b"hello\0").unwrap()
        ))
        .unwrap()
        .as_bytes(),
        b"hello"
    );
    assert_eq!(
        str_to_host(&host_c_str_to_str(
            CStr::from_bytes_with_nul(b"h\xc0ello\xc1\0").unwrap()
        ))
        .unwrap()
        .as_bytes(),
        b"h\xc0ello\xc1"
    );
    assert_eq!(
        str_to_host(&host_c_str_to_str(
            CStr::from_bytes_with_nul(b"\xf5\xff\0").unwrap()
        ))
        .unwrap()
        .as_bytes(),
        b"\xf5\xff"
    );
    assert_eq!(
        str_to_host(&host_c_str_to_str(
            CStr::from_bytes_with_nul(b"\0").unwrap()
        ))
        .unwrap()
        .as_bytes(),
        b""
    );
    assert_eq!(
        str_to_host(&host_c_str_to_str(
            CStr::from_bytes_with_nul(b"\xe6\x96\0").unwrap()
        ))
        .unwrap()
        .as_bytes(),
        b"\xe6\x96"
    );
}