Skip to content

Commit 42a5324

Browse files
committed
Add trait IntoAsciiString to replace OwnedAsciiCast
Trait and method names are the only difference.
1 parent af931f0 commit 42a5324

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

src/ascii_string.rs

+38
Original file line numberDiff line numberDiff line change
@@ -551,6 +551,44 @@ impl<T> IndexMut<T> for AsciiString where AsciiStr: IndexMut<T> {
551551
}
552552
}
553553

554+
555+
/// Trait for converting vectors into `AsciiString`.
556+
pub trait IntoAsciiString<T: ?Sized+AsciiExt<Owned=Self>> : Sized+Borrow<T> {
557+
/// Convert to `AsciiString` without checking that every byte is less than 128.
558+
unsafe fn into_ascii_unchecked(self) -> AsciiString;
559+
/// Convert to `AsciiString`.
560+
fn into_ascii(self) -> Result<AsciiString,Self> {
561+
if self.borrow().is_ascii() {
562+
Ok(unsafe { self.into_ascii_unchecked() })
563+
} else {
564+
Err(self)
565+
}
566+
}
567+
}
568+
569+
#[cfg(feature = "unstable")]
570+
impl IntoAsciiString<AsciiStr> for AsciiString {
571+
fn into_ascii(self) -> Result<AsciiString,AsciiString> {
572+
Ok(self)
573+
}
574+
unsafe fn into_ascii_unchecked(self) -> AsciiString {
575+
self
576+
}
577+
}
578+
579+
impl IntoAsciiString<[u8]> for Vec<u8> {
580+
unsafe fn into_ascii_unchecked(self) -> AsciiString {
581+
AsciiString::from_bytes_unchecked(self)
582+
}
583+
}
584+
585+
impl IntoAsciiString<str> for String {
586+
unsafe fn into_ascii_unchecked(self) -> AsciiString {
587+
self.into_bytes().into_ascii_unchecked()
588+
}
589+
}
590+
591+
554592
#[cfg(test)]
555593
mod tests {
556594
use std::str::FromStr;

src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use std::borrow::Borrow;
2020
use std::ascii::AsciiExt;
2121

2222
pub use ascii::{Ascii, IntoAscii, IntoAsciiError};
23-
pub use ascii_string::AsciiString;
23+
pub use ascii_string::{AsciiString, IntoAsciiString};
2424
pub use ascii_str::AsciiStr;
2525

2626
/// Trait for converting into an ascii type.

0 commit comments

Comments
 (0)