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

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

use core::num::{NonZeroU8, NonZeroU16};

/*
#[cfg(feature = "std")]
impl BinRead for CString {
    type Args = ();

    fn read_options<R: Read + Seek>(reader: &mut R, options: &ReadOptions, args: Self::Args) -> BinResult<Self> 
    {
        <Vec<NonZeroU8>>::read_options(reader, options, args)
            .map(|bytes| bytes.into())
    }
}*/

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

    fn read_options<R: Read + Seek>(reader: &mut R, _: &ReadOptions, _: Self::Args) -> BinResult<Self>
    {
        reader
            .iter_bytes()
            .take_while(|x| if let Ok(0) = x { false } else { true })
            .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:** Does not include the null.
#[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. 
#[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 Into<NullWideString> for Vec<NonZeroU16> {
    fn into(self) -> NullWideString {
        let vals: Vec<u16> = self.into_iter().map(|x| x.get()).collect();
        NullWideString(vals)
    }
}

impl Into<NullString> for Vec<NonZeroU8> {
    fn into(self) -> NullString {
        let vals: Vec<u8> = self.into_iter().map(|x| x.get()).collect();
        NullString(vals)
    }
}

impl Into<Vec<u16>> for NullWideString {
    fn into(self) -> Vec<u16> {
        self.0
    }
}

impl Into<Vec<u8>> for NullString {
    fn into(self) -> Vec<u8> {
        self.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 mut options = options.clone();

        #[cfg(feature = "debug_template")] {
            let pos = reader.seek(SeekFrom::Current(0)).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;
        }
        <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.seek(SeekFrom::Current(0)).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())
                );
            }
        }
        <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 std::ops::Deref for NullString {
    type Target = Vec<u8>;

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

impl std::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)
    }
}