10000 Remove unreachable errors and prevent unreachable panics from being g… · rust-osdev/ucs2-rs@7f64559 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7f64559

Browse files
Zachery GyurkovitzGabrielMajeri
authored andcommitted
Remove unreachable errors and prevent unreachable panics from being generated
1 parent 0234624 commit 7f64559

File tree

1 file changed

+14
-21
lines changed

1 file changed

+14
-21
lines changed

src/lib.rs

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,12 @@
22
33
#![no_std]
44

5-
#[deny(missing_docs, unsafe_code)]
5+
#[deny(missing_docs)]
66
#[cfg_attr(feature = "cargo-clippy", deny(clippy))]
77

88
/// Possible errors returned by the API.
99
#[derive(Debug, Copy, Clone)]
1010
pub enum Error {
11-
/// Input contains an invalid character.
12-
InvalidData,
13-
/// Input contained the start of a multi-byte character but its tail was missing.
14-
BufferUnderflow,
15 10000 11
/// Not enough space left in the output buffer.
1612
BufferOverflow,
1713
/// Input contained a character which cannot be represented in UCS-2.
@@ -60,29 +56,25 @@ where
6056
i += 1;
6157
} else if bytes[i] & 0b1110_0000 == 0b1100_0000 {
6258
// 2 byte codepoint
63-
if i + 1 == len {
64-
// Buffer underflow
65-
return Err(Error::BufferUnderflow);
66-
}
67-
if bytes[i + 1] & 0b1100_0000 != 0b1000_0000 {
68-
// Invalid data
69-
return Err(Error::InvalidData);
59+
if i + 1 >= len {
60+
// safe: len is the length of bytes,
61+
// and bytes is a direct view into the
62+
// buffer of input, which in order to be a valid
63+
// utf-8 string _must_ contain `i + 1`.
64+
unsafe { core::hint::unreachable_unchecked() }
7065
}
66+
7167
let a = u16::from(bytes[i] & 0b0001_1111);
7268
let b = u16::from(bytes[i + 1] & 0b0011_1111);
7369
ch = a << 6 | b;
7470
i += 2;
7571
} else if bytes[i] & 0b1111_0000 == 0b1110_0000 {
7672
// 3 byte codepoint
77-
if i + 2 >= len {
78-
return Err(Error::BufferUnderflow);
79-
}
80-
if bytes[i + 1] & 0b1100_0000 != 0b1000_0000
81-
|| bytes[i + 2] & 0b1100_0000 != 0b1000_0000
82-
{
83-
// Invalid data
84-
return Err(Error::InvalidData);
73+
if i + 2 >= len || i + 1 >= len {
74+
// safe: impossible utf-8 string.
75+
unsafe { core::hint::unreachable_unchecked() }
8576
}
77+
8678
let a = u16::from(bytes[i] & 0b0000_1111);
8779
let b = u16::from(bytes[i + 1] & 0b0011_1111);
8880
let c = u16::from(bytes[i + 2] & 0b0011_1111);
@@ -91,7 +83,8 @@ where
9183
} else if bytes[i] & 0b1111_0000 == 0b1111_0000 {
9284
return Err(Error::MultiByte); // UTF-16
9385
} else {
94-
return Err(Error::InvalidData);
86+
// safe: impossible utf-8 string.
87+
unsafe { core::hint::unreachable_unchecked() }
9588
}
9689
output(ch)?;
9790
}

0 commit comments

Comments
 (0)
0