1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! A crate for converting a string containing only printable ASCII and newlines
//! into a single unicode grapheme cluster and back.
//! Provides the non-macro functionality of the crate [`zalgo-codec`](https://docs.rs/zalgo-codec/latest/zalgo_codec/).
//!
//! There are two ways of interacting with the codec.
//! The first is to call the encoding and decoding functions directly,
//! and the second is to use the [`ZalgoString`] wrapper type.
//!
//! # Examples
//!
//! Encode a string to a grapheme cluster with [`zalgo_encode`]:
//! ```
//! # use zalgo_codec_common::{Error, zalgo_encode};
//! let s = "Zalgo";
//! let encoded = zalgo_encode(s)?;
//! assert_eq!(encoded, "É̺͇͌͏");
//! # Ok::<(), Error>(())
//! ```
//! Decode a grapheme cluster back into a string:
//! ```
//! # use zalgo_codec_common::zalgo_decode;
//! # use std::string::FromUtf8Error;
//! let encoded = "É̺͇͌͏";
//! let s = zalgo_decode(encoded)?;
//! assert_eq!(s, "Zalgo");
//! # Ok::<(), FromUtf8Error>(())
//! ```
//! The [`ZalgoString`] type can be used to encode a string and handle the result in various ways:
//! ```
//! # use zalgo_codec_common::{ZalgoString, Error};
//! let s = "Zalgo";
//! let zstr = ZalgoString::new(s)?;
//!
//! // Implements PartialEq with common string types
//! assert_eq!(zstr, "É̺͇͌͏");
//!
//! // Utility functions
//! assert_eq!(zstr.len(), 2 * s.len() + 1);
//! assert_eq!(zstr.decoded_len(), s.len());
//!
//! // Iterate over bytes and chars, in both encoded and decoded form
//! assert_eq!(zstr.bytes().next(), Some(69));
//! assert_eq!(zstr.decoded_bytes().nth_back(2), Some(b'l'));
//! assert_eq!(zstr.chars().nth(1), Some('\u{33a}'));
//! assert_eq!(zstr.decoded_chars().next_back(), Some('o'));
//!
//! // Decode inplace
//! assert_eq!(zstr.into_decoded_string(), "Zalgo");
//! # Ok::<(), Error>(())
//! ```
//!
//! # Features
//!
//! `std`: links the standard library and uses it to implement the [`std::error::Error`] trait for the provided [`Error`] type.
//! If this feature is not enabled the library is `no_std`, but still uses the `alloc` crate.
//!
//! `serde`: implements the [`Serialize`](serde::Serialize) and [`Deserialize`](serde::Deserialize) traits
//! from [`serde`](https://crates.io/crates/serde) for [`ZalgoString`].
//!
//! # Explanation
//!
//! Characters U+0300–U+036F are the combining characters for unicode Latin.
//! The fun thing about combining characters is that you can add as many of these characters
//! as you like to the original character and it does not create any new symbols,
//! it only adds symbols on top of the character. It's supposed to be used in order to
//! create characters such as `á` by taking a normal `a` and adding another character
//! to give it the mark (U+301, in this case). Fun fact: Unicode doesn't specify
//! any limit on the number of these characters.
//! Conveniently, this gives us 112 different characters we can map to,
//! which nicely maps to the ASCII character range 0x20 -> 0x7F, aka all the non-control characters.
//! The only issue is that we can't have new lines in this system, so to fix that,
//! we can simply map 0x7F (DEL) to 0x0A (LF).
//! This can be represented as `(CHARACTER - 11) % 133 - 21`, and decoded with `(CHARACTER + 22) % 133 + 10`.
//!
//! # Experiment with the codec
//!
//! There is an executable available for experimenting with the codec on text and files.
//! It can be installed with `cargo install zalgo-codec --features binary`.
//! You can optionally enable the `gui` feature during installation to include a rudimentary GUI mode for the program.

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::{
    format,
    string::{FromUtf8Error, String},
    vec,
    vec::Vec,
};
use core::{fmt, str};
#[cfg(feature = "std")]
use std::string::FromUtf8Error;

/// Contains the implementation of [`ZalgoString`] as well as related iterators.
pub mod zalgo_string;

pub use zalgo_string::ZalgoString;

/// Takes in an ASCII string without control characters (except newlines)
/// and encodes it into a single grapheme cluster using a reversible encoding scheme.
///
/// The resulting string is a single unicode grapheme cluster and should
/// only take up a single character space horizontally when displayed
/// (though this can vary between platforms depending on how they deal with unicode).
/// The resulting string will be ~2 times larger than the original in terms of bytes, and it
/// can be decoded to recover the original string with [`zalgo_decode`].
///
/// # Errors
///
/// Returns an error if the input contains a byte that does not correspond to a printable
/// ASCII character or newline.
///
/// # Example
///
/// Basic usage:
/// ```
/// # use zalgo_codec_common::{Error, zalgo_encode};
/// assert_eq!(zalgo_encode("Zalgo")?, "É̺͇͌͏");
/// # Ok::<(), Error>(())
/// ```
/// Can not encode ASCII control characters except newlines.
/// Notably this means that this function can not encode carriage returns,
/// which are present in e.g. line endings on Windows:
/// ```
/// # use zalgo_codec_common::zalgo_encode;
/// assert!(zalgo_encode("CRLF\r\n").is_err());
/// ```
#[must_use = "the function returns a new value and does not modify the input"]
pub fn zalgo_encode(string_to_encode: &str) -> Result<String, Error> {
    // The line we are currently encoding
    let mut line = 1;
    // The column on that line we are currently encoding
    let mut column = 1;
    // These are used for reporting a useful error if the encoding process fails.

    // Every byte in the input will encode to two bytes. The extra byte is for the initial letter
    // which is there in order for the output to be displayable in an intuitive way.
    let mut result = Vec::with_capacity(2 * string_to_encode.len() + 1);
    result.push(b'E');

    // We will encode this many bytes at a time before pushing onto the result vector.
    const BATCH_SIZE: usize = 16;

    for batch in string_to_encode.as_bytes().chunks(BATCH_SIZE) {
        let mut buffer = [0; 2 * BATCH_SIZE];
        let mut encoded = 0;
        for byte in batch {
            // Only encode ASCII bytes corresponding to printable characters or newlines.
            if (32..127).contains(byte) || *byte == b'\n' {
                if *byte == b'\n' {
                    line += 1;
                    // `column` is still 1-indexed since it gets incremented at the end of the current loop iteration.
                    column = 0;
                }

                let v = ((i16::from(*byte) - 11).rem_euclid(133) - 21) as u8;
                buffer[encoded] = (v >> 6) & 1 | 0b11001100;
                buffer[encoded + 1] = (v & 63) | 0b10000000;
                encoded += 2;
                column += 1;
            } else {
                match nonprintable_char_repr(*byte) {
                    Some(repr) => return Err(Error::UnencodableAscii(*byte, line, column, repr)),
                    None => return Err(Error::NotAscii(*byte, line, column)),
                }
            }
        }
        result.extend_from_slice(&buffer[..encoded]);
    }

    // Safety: the encoding process does not produce invalid UTF-8
    // if given valid printable ASCII + newlines,
    // which is checked before this point
    Ok(unsafe { String::from_utf8_unchecked(result) })
}

/// Takes in a string that was encoded by [`zalgo_encode`] and decodes it back into an ASCII string.
///
/// # Errors
///
/// Returns an error if the decoded string is not valid UTF-8.
/// This can happen if the input is a string that was not encoded by [`zalgo_encode`],
/// since the byte manipulations that this function does could result in invalid unicode in that case.
/// Even if no error is returned in such a case the results are not meaningful.
/// If you want to be able to decode without this check, consider using a [`ZalgoString`].
///
/// # Examples
/// Basic usage:
/// ```
/// # use zalgo_codec_common::zalgo_decode;
/// # use std::string::FromUtf8Error;
/// assert_eq!(zalgo_decode("É̺͇͌͏")?, "Zalgo");
/// # Ok::<(), FromUtf8Error>(())
/// ```
/// Decoding arbitrary strings that were not produced by [`zalgo_encode`] will most likely lead to errors:
/// ```
/// # use zalgo_codec_common::zalgo_decode;
/// assert!(zalgo_decode("Zalgo").is_err());
/// ```
/// If it doesn't the results are not meaningful:
/// ```
/// # use zalgo_codec_common::zalgo_decode;
/// assert_eq!(zalgo_decode("awö")?, "c");
/// # Ok::<(), std::string::FromUtf8Error>(())
/// ```
#[must_use = "the function returns a new value and does not modify the input"]
pub fn zalgo_decode(encoded: &str) -> Result<String, FromUtf8Error> {
    let mut res = vec![0; (encoded.len() - 1) / 2];
    let bytes = encoded.as_bytes();

    for (write, read) in (1..encoded.len()).step_by(2).enumerate() {
        match bytes.get(read + 1) {
            Some(next) => res[write] = decode_byte_pair(bytes[read], *next),
            None => break,
        }
    }

    String::from_utf8(res)
}

#[must_use = "the function returns a new value and does not modify its inputs"]
#[inline]
fn decode_byte_pair(odd: u8, even: u8) -> u8 {
    ((odd << 6 & 64 | even & 63) + 22) % 133 + 10
}

/// zalgo-encodes an ASCII string containing Python code and
/// wraps it in a decoder that decodes and executes it.
/// The resulting Python code should retain the functionality of the original.
///
/// # Example
/// Encode a simple hello world program in Python
/// ```
/// # use zalgo_codec_common::{Error, zalgo_wrap_python};
/// let py_hello_world = "print(\"Hello, world!\")\n";
/// let py_hello_world_enc = zalgo_wrap_python(py_hello_world)?;
/// assert_eq!(
///     py_hello_world_enc,
///     "b='Ę͉͎͔͐͒̈̂͌͌ͅ͏̌̀͗͏͒͌̈́́̂̉ͯ'.encode();exec(''.join(chr(((h<<6&64|c&63)+22)%133+10)for h,c in zip(b[1::2],b[2::2])))",
/// );
/// # Ok::<(), Error>(())
/// ```
/// If the contents of the variable `py_hello_world_enc` in
/// the above code snippet is saved to a file
/// you can run it with python and it will produce the output
/// that is expected of the code in the variable `py_hello_world`.
/// In the example below the file is named `enc.py`.
/// ```bash
/// $ python enc.py
/// Hello, world!
/// ```
///
/// # Known issues
///
/// May not work correctly on python versions before 3.10,
/// see [this github issue](https://github.com/DaCoolOne/DumbIdeas/issues/1) for more information.
#[must_use = "the function returns a new value and does not modify the input"]
pub fn zalgo_wrap_python(string_to_encode: &str) -> Result<String, Error> {
    let encoded_string = zalgo_encode(string_to_encode)?;
    Ok(format!("b='{encoded_string}'.encode();exec(''.join(chr(((h<<6&64|c&63)+22)%133+10)for h,c in zip(b[1::2],b[2::2])))"))
}

#[derive(Debug, Clone, Copy, PartialEq)]
/// The error returned by [`zalgo_encode`], [`ZalgoString::new`], and [`zalgo_wrap_python`]
/// if they encounter a byte they can not encode.
///
/// Only implements the [`Error`](std::error::Error) trait if the `std` feature is enabled.
pub enum Error {
    /// Represents a valid ASCII character that is outside of the encodable set.
    UnencodableAscii(u8, usize, usize, &'static str),
    /// Represents some other unicode character.
    NotAscii(u8, usize, usize),
}

impl Error {
    /// Returns the 1-indexed line number of the line on which the unencodable byte occured.
    /// # Examples
    /// ```
    /// # use zalgo_codec_common::{Error, zalgo_encode};
    /// assert_eq!(zalgo_encode("❤️").err().unwrap().line(), 1);
    /// assert_eq!(zalgo_encode("a\nb\nc\r\n").err().unwrap().line(), 3);
    /// ```
    #[must_use = "the method returns a new valus and does not modify `self`"]
    pub const fn line(&self) -> usize {
        match self {
            Self::UnencodableAscii(_, line, _, _) | Self::NotAscii(_, line, _) => *line,
        }
    }

    /// Returns the 1-indexed column where the unencodable byte occured.
    /// Columns are counted from left to right and the count resets for each new line.
    /// # Example
    /// ```
    /// # use zalgo_codec_common::{Error, zalgo_encode};
    /// assert_eq!(zalgo_encode("I ❤️ 🎂").err().unwrap().column(), 3);
    /// assert_eq!(zalgo_encode("I\n❤️\n🎂").err().unwrap().column(), 1);
    /// ```
    #[must_use = "the method returns a new valus and does not modify `self`"]
    pub const fn column(&self) -> usize {
        match self {
            Self::UnencodableAscii(_, _, column, _) | Self::NotAscii(_, _, column) => *column,
        }
    }

    /// Returns the value of the first byte of the unencodable character.
    /// # Examples
    /// ```
    /// # use zalgo_codec_common::{Error, zalgo_encode};
    /// assert_eq!(zalgo_encode("\r").err().unwrap().byte(), 13);
    /// ```
    /// Note that this might not be the complete representation of
    /// the character in unicode, just the first byte of it.
    /// ```
    /// # use zalgo_codec_common::{Error, zalgo_encode};
    /// assert_eq!(zalgo_encode("❤️").err().unwrap().byte(), 226);
    /// // Even though
    /// assert_eq!("❤️".as_bytes(), &[226, 157, 164, 239, 184, 143])
    /// ```
    #[must_use = "the method returns a new value and does not modify `self`"]
    pub const fn byte(&self) -> u8 {
        match self {
            Self::UnencodableAscii(byte, _, _, _) | Self::NotAscii(byte, _, _) => *byte,
        }
    }

    /// Return a representation of the unencodable byte.
    /// This exists if the character is an unencodable ASCII character.
    /// If it is some other unicode character we only know its first byte, so we can not
    /// accurately represent it.
    /// # Examples
    /// ```
    /// # use zalgo_codec_common::zalgo_encode;
    /// assert_eq!(zalgo_encode("\r").err().unwrap().representation(), Some("Carriage Return"));
    /// assert_eq!(zalgo_encode("❤️").err().unwrap().representation(), None);
    /// ```
    #[must_use = "the method returns a new value and does not modify `self`"]
    pub const fn representation(&self) -> Option<&'static str> {
        match self {
            Self::UnencodableAscii(_, _, _, repr) => Some(*repr),
            Self::NotAscii(_, _, _) => None,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::UnencodableAscii(byte, line, column, repr) => write!(
                f,
                "line {line} at column {column}: can not encode ASCII \"{repr}\" character with byte value {byte}"
            ),
            Self::NotAscii(byte, line, column) => write!(
                f,
                "line {line} at column {column}: byte value {byte} does not correspond to an ASCII character"
            ),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}

/// Returns the representation of the given ASCII byte if it's not printable.
#[inline]
#[must_use = "the function returns a new value and does not modify the input"]
const fn nonprintable_char_repr(byte: u8) -> Option<&'static str> {
    if byte < 10 {
        Some(
            [
                "Null",
                "Start Of Heading",
                "Start Of Text",
                "End Of Text",
                "End Of Transmission",
                "Enquiry",
                "Acknowledge",
                "Bell",
                "Backspace",
                "Horizontal Tab",
            ][byte as usize],
        )
    } else if byte >= 11 && byte < 32 {
        Some(
            [
                "Vertical Tab",
                "Form Feed",
                "Carriage Return",
                "Shift Out",
                "Shift In",
                "Data Link Escape",
                "Data Control 1",
                "Data Control 2",
                "Data Control 3",
                "Data Control 4",
                "Negative Acknowledge",
                "Synchronous Idle",
                "End Of Transmission Block",
                "Cancel",
                "End Of Medium",
                "Substitute",
                "Escape",
                "File Separator",
                "Group Separator",
                "Record Separator",
                "Unit Separator",
            ][byte as usize - 11],
        )
    } else if byte == 127 {
        Some("Delete")
    } else {
        None
    }
}