Skip to content

Commit ea1565c

Browse files
committed
Add trait IntoAsciiString to replace OwnedAsciiCast
Trait and method names are the only difference.
1 parent 610dcbd commit ea1565c

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/ascii_string.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -551,6 +551,40 @@ impl<T> IndexMut<T> for AsciiString where AsciiStr: IndexMut<T> {
551551
}
552552
}
553553

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

src/lib.rs

Lines changed: 1 addition & 1 deletion
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)