about summary refs log tree commit diff
path: root/library/core/src/array/ascii.rs
diff options
context:
space:
mode:
authorScott McMurray <scottmcm@users.noreply.github.com>2023-04-29 14:45:36 -0700
committerScott McMurray <scottmcm@users.noreply.github.com>2023-05-03 22:09:33 -0700
commit8c781b0906209e81f3540d1495becddae9894a25 (patch)
treed081346058cea327d2c659352cc2b52cd98489fb /library/core/src/array/ascii.rs
parent831c9298c8e6542e3ab395216e98aec21f60b470 (diff)
downloadrust-8c781b0906209e81f3540d1495becddae9894a25.tar.gz
rust-8c781b0906209e81f3540d1495becddae9894a25.zip
Add the basic `ascii::Char` type
Diffstat (limited to 'library/core/src/array/ascii.rs')
-rw-r--r--library/core/src/array/ascii.rs34
1 files changed, 34 insertions, 0 deletions
diff --git a/library/core/src/array/ascii.rs b/library/core/src/array/ascii.rs
new file mode 100644
index 00000000000..6750d7c0711
--- /dev/null
+++ b/library/core/src/array/ascii.rs
@@ -0,0 +1,34 @@
+use crate::ascii;
+
+#[cfg(not(test))]
+impl<const N: usize> [u8; N] {
+    /// Converts this array of bytes into a array of ASCII characters,
+    /// or returns `None` if any of the characters is non-ASCII.
+    #[unstable(feature = "ascii_char", issue = "110998")]
+    #[must_use]
+    #[inline]
+    pub fn as_ascii(&self) -> Option<&[ascii::Char; N]> {
+        if self.is_ascii() {
+            // SAFETY: Just checked that it's ASCII
+            Some(unsafe { self.as_ascii_unchecked() })
+        } else {
+            None
+        }
+    }
+
+    /// Converts this array of bytes into a array of ASCII characters,
+    /// without checking whether they're valid.
+    ///
+    /// # Safety
+    ///
+    /// Every byte in the array must be in `0..=127`, or else this is UB.
+    #[unstable(feature = "ascii_char", issue = "110998")]
+    #[must_use]
+    #[inline]
+    pub const unsafe fn as_ascii_unchecked(&self) -> &[ascii::Char; N] {
+        let byte_ptr: *const [u8; N] = self;
+        let ascii_ptr = byte_ptr as *const [ascii::Char; N];
+        // SAFETY: The caller promised all the bytes are ASCII
+        unsafe { &*ascii_ptr }
+    }
+}