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
//! Const equivalents of [`CStr`] methods

#[cfg(test)]
mod err_tests;

use crate::slice::slice_up_to;

use core::{ffi::CStr, fmt};

////////////////////////////////////////////////////////////////////////////////

/// Error returned by [`from_bytes_until_nul`] when the input slice either
/// does not terminate with nul.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FromBytesUntilNulError(());

impl FromBytesUntilNulError {
    /// Const equivalent of `FromBytesUntilNulError::clone`
    pub const fn copy(&self) -> Self {
        Self(())
    }

    /// Panics with this type's error message
    #[track_caller]
    pub const fn panic(&self) -> ! {
        panic!("{}", self.err_msg())
    }
    const fn err_msg(&self) -> &str {
        "data provided does not contain a nul"
    }
}

impl fmt::Display for FromBytesUntilNulError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.err_msg())
    }
}

////////////////////////////////////////////////////////////////////////////////

/// Error returned by [`from_bytes_with_nul`] when the input slice either
/// does not terminate with nul, or contains inner nul bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FromBytesWithNulError {
    kind: HuntNulError,
}

impl FromBytesWithNulError {
    /// Const equivalent of `FromBytesWithNulError::clone`
    pub const fn copy(&self) -> Self {
        Self { kind: self.kind }
    }

    const fn err_msg(&self) -> (&str, Option<usize>) {
        match self.kind {
            HuntNulError::InternalNul(pos) => {
                ("input bytes contain an internal nul byte at: ", Some(pos))
            }
            HuntNulError::NotNulTerminated => ("input bytes don't terminate with nul", None),
        }
    }

    /// Panics with this type's error message
    #[track_caller]
    pub const fn panic(&self) -> ! {
        use const_panic::{concat_panic, FmtArg, PanicVal};

        let (msg, num) = self.err_msg();

        concat_panic(&[&[
            PanicVal::write_str(msg),
            match num {
                Some(x) => PanicVal::from_usize(x, FmtArg::DEBUG),
                None => PanicVal::EMPTY,
            },
        ]])
    }
}

impl fmt::Display for FromBytesWithNulError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (msg, num) = self.err_msg();
        f.write_str(msg)?;
        if let Some(num) = num {
            write!(f, "{num}")?;
        }
        Ok(())
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum HuntNulError {
    InternalNul(usize),
    NotNulTerminated,
}

////////////////////////////////////////////////////////////////////////////////

struct CStrAndLen<'a> {
    cstr: &'a CStr,
    length_with_nul: usize,
}

const fn from_bytes_until_nul_inner(
    bytes: &[u8],
) -> Result<CStrAndLen<'_>, FromBytesUntilNulError> {
    crate::for_range! {i in 0..bytes.len() =>
        if bytes[i] == 0 {
            let sub = slice_up_to(bytes, i + 1);
            unsafe {
                return Ok(CStrAndLen{
                    cstr: CStr::from_bytes_with_nul_unchecked(sub),
                    length_with_nul: i + 1,
                });
            }
        }
    }

    Err(FromBytesUntilNulError(()))
}

/// Converts a byte slice which contains any amount of nul bytes into a `&CStr`.
/// Const equivalent of [`CStr::from_bytes_until_nul`]
///
/// # Example
///
/// ```rust
/// use konst::{ffi::cstr, unwrap_ctx};
///
/// use std::ffi::CStr;
///
///
/// const CS: &CStr = unwrap_ctx!(cstr::from_bytes_until_nul(b"hello\0world"));
///
/// assert_eq!(CS.to_str().unwrap(), "hello");
///
/// ```
///
pub const fn from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError> {
    match from_bytes_until_nul_inner(bytes) {
        Ok(CStrAndLen { cstr, .. }) => Ok(cstr),
        Err(e) => Err(e),
    }
}

/// Converts a nul-terminated byte slice into a `&CStr`.
/// Const equivalent of [`CStr::from_bytes_with_nul`]
///
/// # Example
///
/// ```rust
/// use konst::{ffi::cstr, unwrap_ctx};
///
/// use std::ffi::CStr;
///
///
/// const CS: &CStr = unwrap_ctx!(cstr::from_bytes_with_nul(b"foo bar\0"));
///
/// assert_eq!(CS.to_str().unwrap(), "foo bar");
///
/// ```
///
pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
    const fn make_not_null_term_err<T>() -> Result<T, FromBytesWithNulError> {
        Err(FromBytesWithNulError {
            kind: HuntNulError::NotNulTerminated,
        })
    }

    match from_bytes_until_nul_inner(bytes) {
        Ok(CStrAndLen {
            cstr,
            length_with_nul,
        }) if length_with_nul == bytes.len() => Ok(cstr),
        Ok(_) if bytes[bytes.len() - 1] != 0 => make_not_null_term_err(),
        Err(_) => make_not_null_term_err(),
        Ok(CStrAndLen {
            length_with_nul, ..
        }) => Err(FromBytesWithNulError {
            kind: HuntNulError::InternalNul(length_with_nul - 1),
        }),
    }
}

/// Converts this CStr to a byte slice, including the nul terminator.
/// Const equivalent of [`CStr::to_bytes_with_nul`]
///
/// # Performance
///
/// This function takes linear time to run, proportional to the length of `this`.
///
/// # Example
///
/// ```rust
/// use konst::{ffi::cstr, unwrap_ctx};
///
/// use std::ffi::CStr;
///
///
/// const CS: &CStr = unwrap_ctx!(cstr::from_bytes_with_nul(b"example\0"));
///
/// const BYTES: &[u8] = cstr::to_bytes_with_nul(CS);
///
/// assert_eq!(BYTES, b"example\0");
///
/// ```
pub const fn to_bytes_with_nul(this: &CStr) -> &[u8] {
    let start = this.as_ptr().cast::<u8>();
    let mut i = 0;

    unsafe {
        while *start.add(i) != 0 {
            i += 1;
        }

        core::slice::from_raw_parts(start, i + 1)
    }
}

/// Converts this CStr to a byte slice, excluding the nul terminator.
/// Const equivalent of [`CStr::to_bytes`]
///
/// # Performance
///
/// This function takes linear time to run, proportional to the length of `this`.
///
/// # Example
///
/// ```rust
/// use konst::{ffi::cstr, unwrap_ctx};
///
/// use std::ffi::CStr;
///
///
/// const CS: &CStr = unwrap_ctx!(cstr::from_bytes_with_nul(b"hmm...\0"));
///
/// const BYTES: &[u8] = cstr::to_bytes(CS);
///
/// assert_eq!(BYTES, b"hmm...");
///
/// ```
pub const fn to_bytes(this: &CStr) -> &[u8] {
    match to_bytes_with_nul(this) {
        [rem @ .., 0] => rem,
        _ => unreachable!(),
    }
}

/// Converts this CStr to a string slice, excluding the nul terminator.
/// Const equivalent of [`CStr::to_str`]
///
/// # Performance
///
/// This function takes linear time to run, proportional to the length of `this`.
///
/// # Example
///
/// ```rust
/// use konst::{ffi::cstr, unwrap_ctx};
///
/// use std::ffi::CStr;
///
///
/// const CS: &CStr = unwrap_ctx!(cstr::from_bytes_with_nul(b"of beads\0"));
///
/// const STRING: &str = unwrap_ctx!(cstr::to_str(CS));
///
/// assert_eq!(STRING, "of beads");
///
/// ```
pub const fn to_str(this: &CStr) -> Result<&str, crate::string::Utf8Error> {
    crate::string::from_utf8(to_bytes(this))
}