pub struct ZalgoString(/* private fields */);
Expand description
A String
that has been encoded with zalgo_encode
.
This struct can be decoded in-place and also allows iteration over its characters and bytes, both in
decoded and encoded form.
Implementations§
Source§impl ZalgoString
impl ZalgoString
Sourcepub fn new(s: &str) -> Result<ZalgoString, EncodeError>
pub fn new(s: &str) -> Result<ZalgoString, EncodeError>
Encodes the given string slice with zalgo_encode
and stores the result in a new allocation.
§Errors
Returns an error if the input string contains bytes that don’t correspond to printable ASCII characters or newlines.
§Examples
assert_eq!(ZalgoString::new("Zalgo")?, "É̺͇͌͏");
Can only encode printable ASCII and newlines:
assert!(ZalgoString::new("❤️").is_err());
assert!(ZalgoString::new("\r").is_err());
Sourcepub fn with_capacity(capacity: NonZero<usize>) -> ZalgoString
pub fn with_capacity(capacity: NonZero<usize>) -> ZalgoString
Creates a new ZalgoString
with at least the specified capacity.
A ZalgoString always has an allocated buffer with an “E” in it, so the capacity can not be zero.
If you want the ZalgoString to have capacity for x encoded characters you must reserve a capacity of 2x + 1.
§Example
use core::num::NonZeroUsize;
// Reserve capacity for two encoded characters
let capacity = NonZeroUsize::new(2*2 + 1).unwrap();
let mut zs = ZalgoString::with_capacity(capacity);
// This ZalgoString would decode into an empty string
assert_eq!(zs.decoded_len(), 0);
// This allocates,
let zs2 = ZalgoString::new("Hi")?;
// but this does not reallocate `zs`
let cap = zs.capacity();
zs.push_zalgo_str(&zs2);
assert_eq!(zs.capacity(), cap);
Sourcepub fn as_str(&self) -> &str
pub fn as_str(&self) -> &str
Returns the encoded contents of self
as a string slice.
§Example
Basic usage
let zs = ZalgoString::new("Oh boy!")?;
assert_eq!(zs.as_str(), "È̯͈͂͏͙́");
Note that ZalgoString
implements PartialEq
with common string types,
so the comparison in the above example could also be done directly
assert_eq!(zs, "È̯͈͂͏͙́");
Sourcepub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<str>>::Output>where
I: SliceIndex<str>,
pub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<str>>::Output>where
I: SliceIndex<str>,
Returns a subslice of self
.
Same as str::get
.
This is the non-panicking alternative to indexing the ZalgoString
. Returns None
whenever
the equivalent indexing operation would panic.
§Example
let zs = ZalgoString::new("Zalgo")?;
assert_eq!(zs.get(0..3), Some("E\u{33a}"));
// indices not on UTF-8 sequence boundaries
assert!(zs.get(0..4).is_none());
// out of bounds
assert!(zs.get(..42).is_none());
Sourcepub unsafe fn get_unchecked<I>(
&self,
index: I,
) -> &<I as SliceIndex<str>>::Outputwhere
I: SliceIndex<str>,
pub unsafe fn get_unchecked<I>(
&self,
index: I,
) -> &<I as SliceIndex<str>>::Outputwhere
I: SliceIndex<str>,
Returns an unchecked subslice of self
.
This is the unchecked alternative to indexing a ZalgoString
.
§Safety
This function has the same safety requirements as str::get_unchecked
:
- The starting index must not exceed the ending index;
- Indexes must be within bounds of the original slice;
- Indexes must lie on UTF-8 sequence boundaries.
§Example
let zs = ZalgoString::new("Zalgo")?;
unsafe {
assert_eq!(zs.get_unchecked(..3), "E\u{33a}");
}
Sourcepub fn chars(&self) -> Chars<'_>
pub fn chars(&self) -> Chars<'_>
Returns an iterator over the encoded characters of the ZalgoString
.
The first character is an “E”, the others are unicode combining characters.
§Example
Iterate through the encoded char
s:
let zs = ZalgoString::new("42")?;
let mut chars = zs.chars();
assert_eq!(chars.next(), Some('E'));
assert_eq!(chars.next(), Some('\u{314}'));
Sourcepub fn char_indices(&self) -> CharIndices<'_>
pub fn char_indices(&self) -> CharIndices<'_>
Returns an iterator over the encoded characters of the ZalgoString
and their positions.
§Example
Combining characters lie deep in the dark depths of Unicode, and may not match with your intuition of what a character is.
let zs = ZalgoString::new("Zalgo")?;
let mut ci = zs.char_indices();
assert_eq!(ci.next(), Some((0, 'E')));
assert_eq!(ci.next(), Some((1,'\u{33a}')));
// Note the 3 here, the combining characters take up two bytes.
assert_eq!(ci.next(), Some((3, '\u{341}')));
// The final character begins at position 9
assert_eq!(ci.next_back(), Some((9, '\u{34f}')));
// even though the length in bytes is 11
assert_eq!(zs.len(), 11);
Sourcepub fn decoded_chars(&self) -> DecodedChars<'_> ⓘ
pub fn decoded_chars(&self) -> DecodedChars<'_> ⓘ
Returns an iterator over the decoded characters of the ZalgoString
.
These characters are guaranteed to be valid ASCII.
§Example
let zs = ZalgoString::new("Zlgoa")?;
let mut decoded_chars = zs.decoded_chars();
assert_eq!(decoded_chars.next(), Some('Z'));
assert_eq!(decoded_chars.next_back(), Some('a'));
assert_eq!(decoded_chars.next(), Some('l'));
assert_eq!(decoded_chars.next(), Some('g'));
assert_eq!(decoded_chars.next_back(), Some('o'));
assert_eq!(decoded_chars.next(), None);
assert_eq!(decoded_chars.next_back(), None);
Sourcepub fn into_string(self) -> String
pub fn into_string(self) -> String
Converts self
into a String
.
This simply returns the underlying String
without any cloning or decoding.
§Example
Basic usage
let zs = ZalgoString::new("Zalgo\n He comes!")?;
assert_eq!(zs.into_string(), "É̺͇͌͏̨ͯ̀̀̓ͅ͏͍͓́ͅ");
Sourcepub fn into_decoded_string(self) -> String
pub fn into_decoded_string(self) -> String
Decodes self
into a String
in-place.
This method has no effect on the allocated capacity.
§Example
Basic usage
let s = "Zalgo";
let zs = ZalgoString::new(s)?;
assert_eq!(s, zs.into_decoded_string());
Sourcepub fn as_bytes(&self) -> &[u8] ⓘ
pub fn as_bytes(&self) -> &[u8] ⓘ
Returns the encoded contents of self
as a byte slice.
The first byte is always 69, after that the bytes no longer correspond to ASCII characters.
§Example
Basic usage
let zs = ZalgoString::new("Zalgo")?;
let bytes = zs.as_bytes();
assert_eq!(bytes[0], 69);
assert_eq!(&bytes[1..5], &[204, 186, 205, 129]);
Sourcepub fn bytes(&self) -> Bytes<'_>
pub fn bytes(&self) -> Bytes<'_>
Returns an iterator over the encoded bytes of the ZalgoString
.
Since a ZalgoString
always begins with an “E”, the first byte is always 69.
After that the bytes no longer correspond to ASCII values.
§Example
Basic usage
let zs = ZalgoString::new("Bytes")?;
let mut bytes = zs.bytes();
assert_eq!(bytes.next(), Some(69));
assert_eq!(bytes.nth(5), Some(148));
Sourcepub fn decoded_bytes(&self) -> DecodedBytes<'_> ⓘ
pub fn decoded_bytes(&self) -> DecodedBytes<'_> ⓘ
Returns an iterator over the decoded bytes of the ZalgoString
.
These bytes are guaranteed to represent valid ASCII.
§Example
let zs = ZalgoString::new("Zalgo")?;
let mut decoded_bytes = zs.decoded_bytes();
assert_eq!(decoded_bytes.next(), Some(90));
assert_eq!(decoded_bytes.next_back(), Some(111));
assert_eq!(decoded_bytes.collect::<Vec<u8>>(), vec![97, 108, 103]);
Sourcepub fn into_bytes(self) -> Vec<u8> ⓘ
pub fn into_bytes(self) -> Vec<u8> ⓘ
Converts self
into a byte vector.
This simply returns the underlying buffer without any cloning or decoding.
§Example
Basic usage
let zs = ZalgoString::new("Zalgo")?;
assert_eq!(zs.into_bytes(), vec![69, 204, 186, 205, 129, 205, 140, 205, 135, 205, 143]);
Sourcepub fn into_decoded_bytes(self) -> Vec<u8> ⓘ
pub fn into_decoded_bytes(self) -> Vec<u8> ⓘ
Decodes self
into a byte vector in-place.
This method has no effect on the allocated capacity.
§Example
Basic usage
let zs = ZalgoString::new("Zalgo")?;
assert_eq!(b"Zalgo".to_vec(), zs.into_decoded_bytes());
Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the length of self
in bytes.
This length is twice the length of the original String
plus one.
§Example
Basic usage
let zs = ZalgoString::new("Z")?;
assert_eq!(zs.len(), 3);
Sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the capacity of the underlying encoded string in bytes.
The ZalgoString
is preallocated to the needed capacity of twice the length
of the original unencoded String
plus one.
However, this size is not guaranteed since the allocator can choose to allocate more space.
Sourcepub fn decoded_len(&self) -> usize
pub fn decoded_len(&self) -> usize
Returns the length of the ZalgoString
in bytes if it were to be decoded.
This is computed without any decoding.
§Example
Basic usage
let s = "Zalgo, He comes!";
let zs = ZalgoString::new(s)?;
assert_eq!(s.len(), zs.decoded_len());
Sourcepub fn decoded_is_empty(&self) -> bool
pub fn decoded_is_empty(&self) -> bool
Returns whether the string would be empty if decoded.
§Example
Basic usage
let zs = ZalgoString::new("")?;
assert!(zs.decoded_is_empty());
let zs = ZalgoString::new("Blargh")?;
assert!(!zs.decoded_is_empty());
Sourcepub fn as_combining_chars(&self) -> &str
pub fn as_combining_chars(&self) -> &str
Returns a string slice of just the combining characters of the ZalgoString
without the inital ‘E’.
Note that zalgo_decode
assumes that the initial ‘E’ is present,
and can not decode the result of this method.
§Example
let zs = ZalgoString::new("Hi")?;
assert_eq!(zs.as_combining_chars(), "\u{328}\u{349}");
Sourcepub fn into_combining_chars(self) -> String
pub fn into_combining_chars(self) -> String
Converts self
into a String that contains only the combining characters of the grapheme cluster.
This is an O(n)
operation since after it has removed the initial “E” it needs to copy every byte
of the string down one index.
It is the same as calling ZalgoString::into_string()
followed by String::remove(0)
.
Just like as_combining_chars
the result of this method can not
be decoded by zalgo_decode
.
§Example
let zs = ZalgoString::new("Hi")?;
let s = zs.into_combining_chars();
assert_eq!(s, "\u{328}\u{349}");
Sourcepub fn push_zalgo_str(&mut self, zalgo_string: &ZalgoString)
pub fn push_zalgo_str(&mut self, zalgo_string: &ZalgoString)
Appends the combining characters of a different ZalgoString
to the end of self
.
§Example
let (s1, s2) = ("Zalgo", ", He comes!");
let mut zs1 = ZalgoString::new(s1)?;
let zs2 = ZalgoString::new(s2)?;
zs1.push_zalgo_str(&zs2);
assert_eq!(zs1.into_decoded_string(), format!("{s1}{s2}"));
Sourcepub fn encode_and_push_str(&mut self, string: &str) -> Result<(), EncodeError>
pub fn encode_and_push_str(&mut self, string: &str) -> Result<(), EncodeError>
Encodes the given string and pushes it onto self
.
This method encodes the input string into an intermediate allocation and then appends
the combining characters of the result to the end of self
. The append step can
also reallocate if the capacity is not large enough.
See push_zalgo_str
for a method that does not hide the
intermediate allocation.
§Errors
Returns an error if the given string contains a character that’s not a printable ASCII or newline character.
§Example
let (s1, s2) = ("Zalgo", ", He comes!");
let mut zs = ZalgoString::new(s1)?;
zs.encode_and_push_str(s2)?;
assert_eq!(zs.into_decoded_string(), format!("{s1}{s2}"));
Sourcepub fn reserve(&mut self, additional: usize)
pub fn reserve(&mut self, additional: usize)
Reserves capacity for at least additional
bytes more than the current length.
Same as String::reserve
.
The allocator may reserve more space to speculatively avoid frequent allocations.
After calling reserve, capacity will be greater than or equal to self.len() + additional
.
Does nothing if the capacity is already sufficient.
Keep in mind that an encoded ASCII character takes up two bytes, and that a ZalgoString
always begins with an unencoded “E” which means that the total length in bytes is always an odd number.
§Example
let mut zs = ZalgoString::new("Zalgo")?;
let c = zs.capacity();
zs.reserve(5);
assert!(zs.capacity() >= c + 5);
Sourcepub fn reserve_exact(&mut self, additional: usize)
pub fn reserve_exact(&mut self, additional: usize)
Reserves capacity for exactly additional
bytes more than the current length.
Same as String::reserve_exact
.
Unlike reserve
, this will not deliberately over-allocate
to speculatively avoid frequent allocations.
After calling reserve_exact
, capacity will be greater than or equal to self.len() + additional
.
Does nothing if the capacity is already sufficient.
Keep in mind that an encoded ASCII character takes up two bytes, and that a ZalgoString
always begins with an unencoded “E” which means that the total length in bytes is always an odd number.
§Example
let mut zs = ZalgoString::new("Zalgo")?;
let c = zs.capacity();
zs.reserve_exact(5);
assert!(zs.capacity() >= c + 5);
Sourcepub fn truncate(&mut self, new_len: usize)
pub fn truncate(&mut self, new_len: usize)
Shortens the ZalgoString
to the specified length.
A ZalgoString
always takes up an odd number of bytes as the first “E” takes up one,
and all subsequent characters take up two.
If new_len
is larger than its current length, this has no effect.
This method has no effect of the allocated capacity.
§Panics
Panics if new_len
is even.
§Examples
let mut zs = ZalgoString::new("Zalgo")?;
zs.truncate(5);
assert_eq!(zs, "E\u{33a}\u{341}");
assert_eq!(zs.into_decoded_string(), "Za");
Panics if new_len
is even:
let mut zs = ZalgoString::new("Zalgo")?;
zs.truncate(0);
Sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Truncates this ZalgoString
, removing all contents except the initial “E”.
This means the ZalgoString will have a length of one, but it does not affect its capacity.
§Example
let mut zs = ZalgoString::new("Zalgo")?;
zs.clear();
assert_eq!(zs, "E");
assert!(zs.decoded_is_empty());
Trait Implementations§
Source§impl Add<&ZalgoString> for ZalgoString
Implements the +
operator for concaternating two ZalgoString
s.
Memorywise it works the same as the Add
implementation for the normal
String
type: it consumes the lefthand side, extends its buffer, and
copies the combining characters of the right hand side into it.
impl Add<&ZalgoString> for ZalgoString
Implements the +
operator for concaternating two ZalgoString
s.
Memorywise it works the same as the Add
implementation for the normal
String
type: it consumes the lefthand side, extends its buffer, and
copies the combining characters of the right hand side into it.
Source§type Output = ZalgoString
type Output = ZalgoString
+
operator.Source§fn add(self, rhs: &ZalgoString) -> <ZalgoString as Add<&ZalgoString>>::Output
fn add(self, rhs: &ZalgoString) -> <ZalgoString as Add<&ZalgoString>>::Output
+
operation. Read moreSource§impl AddAssign<&ZalgoString> for ZalgoString
Implements the +=
operator for appending to a ZalgoString
.
impl AddAssign<&ZalgoString> for ZalgoString
Implements the +=
operator for appending to a ZalgoString
.
This just calls push_zalgo_str
.
Source§fn add_assign(&mut self, rhs: &ZalgoString)
fn add_assign(&mut self, rhs: &ZalgoString)
+=
operation. Read moreSource§impl Archive for ZalgoString
impl Archive for ZalgoString
Source§const COPY_OPTIMIZATION: CopyOptimization<ZalgoString>
const COPY_OPTIMIZATION: CopyOptimization<ZalgoString>
serialize
. Read moreSource§type Archived = ArchivedZalgoString
type Archived = ArchivedZalgoString
Source§type Resolver = ZalgoStringResolver
type Resolver = ZalgoStringResolver
Source§impl<__C> CheckBytes<__C> for ZalgoStringwhere
__C: Fallible + ?Sized,
<__C as Fallible>::Error: Trace,
ZalgoString: Verify<__C>,
String: CheckBytes<__C>,
impl<__C> CheckBytes<__C> for ZalgoStringwhere
__C: Fallible + ?Sized,
<__C as Fallible>::Error: Trace,
ZalgoString: Verify<__C>,
String: CheckBytes<__C>,
Source§impl Clone for ZalgoString
impl Clone for ZalgoString
Source§fn clone(&self) -> ZalgoString
fn clone(&self) -> ZalgoString
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moreSource§impl Debug for ZalgoString
impl Debug for ZalgoString
Source§impl Default for ZalgoString
Allocates a String
that contains only the character “E” and no encoded content.
impl Default for ZalgoString
Allocates a String
that contains only the character “E” and no encoded content.
Source§fn default() -> ZalgoString
fn default() -> ZalgoString
Source§impl<'de> Deserialize<'de> for ZalgoString
impl<'de> Deserialize<'de> for ZalgoString
Source§fn deserialize<__D>(
__deserializer: __D,
) -> Result<ZalgoString, <__D as Deserializer<'de>>::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(
__deserializer: __D,
) -> Result<ZalgoString, <__D as Deserializer<'de>>::Error>where
__D: Deserializer<'de>,
Source§impl<__D> Deserialize<ZalgoString, __D> for <ZalgoString as Archive>::Archived
impl<__D> Deserialize<ZalgoString, __D> for <ZalgoString as Archive>::Archived
Source§fn deserialize(
&self,
deserializer: &mut __D,
) -> Result<ZalgoString, <__D as Fallible>::Error>
fn deserialize( &self, deserializer: &mut __D, ) -> Result<ZalgoString, <__D as Fallible>::Error>
Source§impl Display for ZalgoString
Displays the encoded form of the ZalgoString
.
impl Display for ZalgoString
Displays the encoded form of the ZalgoString
.
Source§impl Hash for ZalgoString
impl Hash for ZalgoString
Source§impl<I> Index<I> for ZalgoStringwhere
I: SliceIndex<str>,
impl<I> Index<I> for ZalgoStringwhere
I: SliceIndex<str>,
Source§impl Ord for ZalgoString
impl Ord for ZalgoString
Source§fn cmp(&self, other: &ZalgoString) -> Ordering
fn cmp(&self, other: &ZalgoString) -> Ordering
1.21.0 · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
Source§impl PartialEq<&str> for ZalgoString
impl PartialEq<&str> for ZalgoString
Source§impl PartialEq<String> for ZalgoString
impl PartialEq<String> for ZalgoString
Source§impl PartialEq<ZalgoString> for &str
impl PartialEq<ZalgoString> for &str
Source§impl PartialEq<ZalgoString> for str
impl PartialEq<ZalgoString> for str
Source§impl PartialEq<str> for ZalgoString
impl PartialEq<str> for ZalgoString
Source§impl PartialEq for ZalgoString
impl PartialEq for ZalgoString
Source§impl PartialOrd for ZalgoString
impl PartialOrd for ZalgoString
Source§impl<__S> Serialize<__S> for ZalgoString
impl<__S> Serialize<__S> for ZalgoString
Source§impl Serialize for ZalgoString
impl Serialize for ZalgoString
Source§fn serialize<__S>(
&self,
__serializer: __S,
) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where
__S: Serializer,
fn serialize<__S>(
&self,
__serializer: __S,
) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where
__S: Serializer,
Source§impl TryFrom<MaybeZalgoString> for ZalgoString
impl TryFrom<MaybeZalgoString> for ZalgoString
Source§type Error = DecodeError
type Error = DecodeError
Source§fn try_from(
_: MaybeZalgoString,
) -> Result<ZalgoString, <ZalgoString as TryFrom<MaybeZalgoString>>::Error>
fn try_from( _: MaybeZalgoString, ) -> Result<ZalgoString, <ZalgoString as TryFrom<MaybeZalgoString>>::Error>
Source§impl<C> Verify<C> for ZalgoString
impl<C> Verify<C> for ZalgoString
impl Eq for ZalgoString
impl StructuralPartialEq for ZalgoString
Auto Trait Implementations§
impl Freeze for ZalgoString
impl RefUnwindSafe for ZalgoString
impl Send for ZalgoString
impl Sync for ZalgoString
impl Unpin for ZalgoString
impl UnwindSafe for ZalgoString
Blanket Implementations§
Source§impl<T> ArchivePointee for T
impl<T> ArchivePointee for T
Source§type ArchivedMetadata = ()
type ArchivedMetadata = ()
Source§fn pointer_metadata(
_: &<T as ArchivePointee>::ArchivedMetadata,
) -> <T as Pointee>::Metadata
fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata
Source§impl<T> ArchiveUnsized for Twhere
T: Archive,
impl<T> ArchiveUnsized for Twhere
T: Archive,
Source§type Archived = <T as Archive>::Archived
type Archived = <T as Archive>::Archived
Archive
, it may be
unsized. Read moreSource§fn archived_metadata(
&self,
) -> <<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata
fn archived_metadata( &self, ) -> <<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<T> LayoutRaw for T
impl<T> LayoutRaw for T
Source§fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>
fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>
Source§impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
Source§unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
Source§fn resolve_niched(out: Place<NichedOption<T, N1>>)
fn resolve_niched(out: Place<NichedOption<T, N1>>)
out
indicating that a T
is niched.