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
use super::*;

// #[cfg(feature = "std")]
// use std::{
//     ffi::CString,
// };

#[cfg(not(feature = "std"))]
use alloc::{
    string::{String, ToString},
    vec,
};
use core::num::{NonZeroU16, NonZeroU8};

impl BinRead for Vec<NonZeroU8> {
    type Args = ();

    fn read_options<R: Read + Seek>(
        reader: &mut R,
        _: &ReadOptions,
        _: Self::Args,
    ) -> BinResult<Self> {
        reader
            .bytes()
            .take_while(|x| !matches!(x, Ok(0)))
            .map(|x| Ok(x.map(|byte| unsafe { NonZeroU8::new_unchecked(byte) })?))
            .collect()
    }
}

/// A null terminated UTF-8 string designed to make reading any null-terminated data easier.
///
/// **Note:** Result does not include the null, but the null is consumed from the Reader.
///
/// ```rust
/// use binread::{BinRead, BinReaderExt, NullString, io::Cursor};
///
/// let mut null_separated_strings = Cursor::new(b"null terminated strings? in my system's language?\0no thanks\0");
///
/// assert_eq!(
///     null_separated_strings.read_be::<NullString>().unwrap().into_string(),
///     "null terminated strings? in my system's language?"
/// );
///
/// assert_eq!(
///     null_separated_strings.read_be::<NullString>().unwrap().into_string(),
///     "no thanks"
/// );
/// ```
#[derive(Clone, PartialEq, Default)]
pub struct NullString(pub Vec<u8>);

/// A null terminated UTF-16 string designed to make reading any 16 bit wide null-terminated data easier.
///
/// **Note:** Does not include the null.
///
/// **Note:** This is endian dependent on a per-character basis. Will read `u16`s until a `0u16` is found.
///
/// ```rust
/// use binread::{BinRead, BinReaderExt, NullWideString, io::Cursor};
///
/// const WIDE_STRINGS: &[u8] = b"w\0i\0d\0e\0 \0s\0t\0r\0i\0n\0g\0s\0\0\0";
/// const ARE_ENDIAN_DEPENDENT: &[u8] = b"\0a\0r\0e\0 \0e\0n\0d\0i\0a\0n\0 \0d\0e\0p\0e\0n\0d\0e\0n\0t\0\0";
///
/// let mut wide_strings = Cursor::new(WIDE_STRINGS);
/// let mut are_endian_dependent = Cursor::new(ARE_ENDIAN_DEPENDENT);
///
/// assert_eq!(
///     // notice: read_le
///     wide_strings.read_le::<NullWideString>().unwrap().into_string(),
///     "wide strings"
/// );
///
/// assert_eq!(
///     // notice: read_be
///     are_endian_dependent.read_be::<NullWideString>().unwrap().into_string(),
///     "are endian dependent"
/// );
/// ```
#[derive(Clone, PartialEq, Default)]
pub struct NullWideString(pub Vec<u16>);

impl NullString {
    pub fn into_string(self) -> String {
        String::from_utf8_lossy(&self.0).into()
    }

    pub fn into_string_lossless(self) -> Result<String, alloc::string::FromUtf8Error> {
        String::from_utf8(self.0)
    }
}

impl NullWideString {
    pub fn into_string(self) -> String {
        String::from_utf16_lossy(&self.0)
    }

    pub fn into_string_lossless(self) -> Result<String, alloc::string::FromUtf16Error> {
        String::from_utf16(&self.0)
    }
}

impl From<Vec<NonZeroU16>> for NullWideString {
    fn from(v: Vec<NonZeroU16>) -> NullWideString {
        NullWideString(v.into_iter().map(|x| x.get()).collect())
    }
}

impl From<Vec<NonZeroU8>> for NullString {
    fn from(v: Vec<NonZeroU8>) -> Self {
        NullString(v.into_iter().map(|x| x.get()).collect())
    }
}

impl From<NullWideString> for Vec<u16> {
    fn from(s: NullWideString) -> Self {
        s.0
    }
}

impl From<NullString> for Vec<u8> {
    fn from(s: NullString) -> Self {
        s.0
    }
}

impl BinRead for Vec<NonZeroU16> {
    type Args = ();

    fn read_options<R: Read + Seek>(
        reader: &mut R,
        options: &ReadOptions,
        _: Self::Args,
    ) -> BinResult<Self> {
        let mut values = vec![];

        loop {
            let val = <u16>::read_options(reader, options, ())?;
            if val == 0 {
                return Ok(values);
            }
            values.push(unsafe { NonZeroU16::new_unchecked(val) });
        }
    }
}

impl BinRead for NullWideString {
    type Args = ();

    fn read_options<R: Read + Seek>(
        reader: &mut R,
        options: &ReadOptions,
        args: Self::Args,
    ) -> BinResult<Self> {
        #[cfg(feature = "debug_template")]
        let options = {
            let mut options = *options;
            let pos = reader.stream_pos().unwrap();

            if !options.dont_output_to_template {
                binary_template::write_named(
                    options.endian,
                    pos,
                    "wstring",
                    &options
                        .variable_name
                        .map(ToString::to_string)
                        .unwrap_or_else(binary_template::get_next_var_name),
                );
            }
            options.dont_output_to_template = true;
            options
        };

        // https://github.com/rust-lang/rust-clippy/issues/6447
        #[allow(clippy::unit_arg)]
        <Vec<NonZeroU16>>::read_options(reader, &options, args).map(|chars| chars.into())
    }
}

impl BinRead for NullString {
    type Args = ();

    fn read_options<R: Read + Seek>(
        reader: &mut R,
        options: &ReadOptions,
        args: Self::Args,
    ) -> BinResult<Self> {
        #[cfg(feature = "debug_template")]
        {
            let pos = reader.stream_pos().unwrap();

            if !options.dont_output_to_template {
                binary_template::write_named(
                    options.endian,
                    pos,
                    "string",
                    &options
                        .variable_name
                        .map(ToString::to_string)
                        .unwrap_or_else(binary_template::get_next_var_name),
                );
            }
        }

        // https://github.com/rust-lang/rust-clippy/issues/6447
        #[allow(clippy::unit_arg)]
        <Vec<NonZeroU8>>::read_options(reader, options, args).map(|chars| chars.into())
    }
}

use core::fmt;

impl fmt::Debug for NullString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "NullString({:?})", self.clone().into_string())
    }
}

impl fmt::Debug for NullWideString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "NullWideString({:?})", self.clone().into_string())
    }
}

impl core::ops::Deref for NullString {
    type Target = Vec<u8>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl core::ops::Deref for NullWideString {
    type Target = Vec<u16>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl ToString for NullString {
    fn to_string(&self) -> String {
        core::str::from_utf8(&self).unwrap().to_string()
    }
}

impl ToString for NullWideString {
    fn to_string(&self) -> String {
        String::from_utf16_lossy(self)
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn null_wide_strings() {
        use crate::{io::Cursor, BinReaderExt, NullWideString};

        const WIDE_STRINGS: &[u8] = b"w\0i\0d\0e\0 \0s\0t\0r\0i\0n\0g\0s\0\0\0";
        const ARE_ENDIAN_DEPENDENT: &[u8] =
            b"\0a\0r\0e\0 \0e\0n\0d\0i\0a\0n\0 \0d\0e\0p\0e\0n\0d\0e\0n\0t\0\0";

        let mut wide_strings = Cursor::new(WIDE_STRINGS);
        let mut are_endian_dependent = Cursor::new(ARE_ENDIAN_DEPENDENT);

        let wide_strings: NullWideString = wide_strings.read_le().unwrap();
        let are_endian_dependent: NullWideString = are_endian_dependent.read_be().unwrap();

        assert_eq!(
            // notice: read_le
            wide_strings.into_string(),
            "wide strings"
        );

        assert_eq!(
            // notice: read_be
            are_endian_dependent.into_string(),
            "are endian dependent"
        );
    }

    #[test]
    fn null_strings() {
        use crate::{io::Cursor, BinReaderExt, NullString};

        let mut null_separated_strings =
            Cursor::new(b"null terminated strings? in my system's language?\0no thanks\0");

        assert_eq!(
            null_separated_strings
                .read_be::<NullString>()
                .unwrap()
                .into_string(),
            "null terminated strings? in my system's language?"
        );

        assert_eq!(
            null_separated_strings
                .read_be::<NullString>()
                .unwrap()
                .into_string(),
            "no thanks"
        );
    }
}