apr 0.4.3

Rust bindings for Apache Portable Runtime
Documentation
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! String utilities for safe C string handling.
use crate::pool::Pool;
use alloc::ffi::CString;
use alloc::string::String;
use core::ffi::{c_char, CStr};
use core::marker::PhantomData;

/// Borrowed byte string backed by pool memory
///
/// This represents bytes from C strings, potentially containing non-UTF-8 data.
/// Use this when you need zero-copy access to C string data.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BStr<'a> {
    data: &'a [u8],
    _pool: PhantomData<&'a Pool<'a>>,
}

impl<'a> BStr<'a> {
    /// Create a BStr from a C string pointer (unsafe)
    ///
    /// # Safety
    /// - ptr must be valid for the lifetime 'a
    /// - ptr must point to null-terminated string
    /// - The underlying pool must remain alive for 'a
    pub unsafe fn from_ptr(ptr: *const c_char) -> Self {
        if ptr.is_null() {
            BStr {
                data: &[],
                _pool: PhantomData,
            }
        } else {
            let cstr = CStr::from_ptr(ptr);
            BStr {
                data: cstr.to_bytes(),
                _pool: PhantomData,
            }
        }
    }

    /// Get the bytes as a slice
    pub fn as_bytes(&self) -> &[u8] {
        self.data
    }

    /// Try to convert to UTF-8 string
    pub fn to_str(&self) -> Result<&str, core::str::Utf8Error> {
        core::str::from_utf8(self.data)
    }

    /// Convert to UTF-8 string with lossy conversion
    pub fn to_string_lossy(&self) -> alloc::borrow::Cow<'_, str> {
        String::from_utf8_lossy(self.data)
    }

    /// Check if the string is empty
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Get the length in bytes
    pub fn len(&self) -> usize {
        self.data.len()
    }
}

impl<'a> AsRef<[u8]> for BStr<'a> {
    fn as_ref(&self) -> &[u8] {
        self.data
    }
}

impl<'a> core::ops::Deref for BStr<'a> {
    type Target = [u8];

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

impl<'a> core::fmt::Display for BStr<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", String::from_utf8_lossy(self.data))
    }
}

impl<'a> From<&'a [u8]> for BStr<'a> {
    fn from(data: &'a [u8]) -> Self {
        BStr {
            data,
            _pool: PhantomData,
        }
    }
}

impl<'a> From<&'a str> for BStr<'a> {
    fn from(s: &'a str) -> Self {
        BStr {
            data: s.as_bytes(),
            _pool: PhantomData,
        }
    }
}

impl<'a> core::borrow::Borrow<[u8]> for BStr<'a> {
    fn borrow(&self) -> &[u8] {
        self.data
    }
}

impl<'a> PartialEq<&str> for BStr<'a> {
    fn eq(&self, other: &&str) -> bool {
        self.data == other.as_bytes()
    }
}

impl<'a> PartialEq<str> for BStr<'a> {
    fn eq(&self, other: &str) -> bool {
        self.data == other.as_bytes()
    }
}

impl<'a> PartialEq<&[u8]> for BStr<'a> {
    fn eq(&self, other: &&[u8]) -> bool {
        self.data == *other
    }
}

/// UTF-8 validated borrowed string backed by pool memory
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BStrUtf8<'a> {
    data: &'a str,
    _pool: PhantomData<&'a Pool<'a>>,
}

impl<'a> BStrUtf8<'a> {
    /// Create a BStrUtf8 from a C string pointer, validating UTF-8
    ///
    /// # Safety  
    /// - ptr must be valid for the lifetime 'a
    /// - ptr must point to null-terminated string
    /// - The underlying pool must remain alive for 'a
    pub unsafe fn from_ptr(ptr: *const c_char) -> Result<Self, core::str::Utf8Error> {
        if ptr.is_null() {
            Ok(BStrUtf8 {
                data: "",
                _pool: PhantomData,
            })
        } else {
            let cstr = CStr::from_ptr(ptr);
            let s = cstr.to_str()?;
            Ok(BStrUtf8 {
                data: s,
                _pool: PhantomData,
            })
        }
    }

    /// Get the string slice
    pub fn as_str(&self) -> &str {
        self.data
    }

    /// Check if the string is empty
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Get the length in bytes
    pub fn len(&self) -> usize {
        self.data.len()
    }
}

impl<'a> AsRef<str> for BStrUtf8<'a> {
    fn as_ref(&self) -> &str {
        self.data
    }
}

impl<'a> core::ops::Deref for BStrUtf8<'a> {
    type Target = str;

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

impl<'a> core::fmt::Display for BStrUtf8<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.data)
    }
}

impl<'a> From<&'a str> for BStrUtf8<'a> {
    fn from(data: &'a str) -> Self {
        BStrUtf8 {
            data,
            _pool: PhantomData,
        }
    }
}

impl<'a> TryFrom<&'a [u8]> for BStrUtf8<'a> {
    type Error = core::str::Utf8Error;

    fn try_from(data: &'a [u8]) -> Result<Self, Self::Error> {
        let s = core::str::from_utf8(data)?;
        Ok(BStrUtf8 {
            data: s,
            _pool: PhantomData,
        })
    }
}

impl<'a> core::borrow::Borrow<str> for BStrUtf8<'a> {
    fn borrow(&self) -> &str {
        self.data
    }
}

impl<'a> PartialEq<&str> for BStrUtf8<'a> {
    fn eq(&self, other: &&str) -> bool {
        self.data == *other
    }
}

impl<'a> PartialEq<String> for BStrUtf8<'a> {
    fn eq(&self, other: &String) -> bool {
        self.data == other.as_str()
    }
}

/// Safe wrapper for pool-allocated C strings
pub struct PoolString<'a> {
    ptr: *const c_char,
    _marker: PhantomData<&'a Pool<'a>>,
}

impl<'a> PoolString<'a> {
    /// Get the raw C string pointer (for FFI calls)
    pub fn as_ptr(&self) -> *const c_char {
        self.ptr
    }

    /// Get as a BStr (borrowed bytes)
    pub fn as_bstr(&self) -> BStr<'a> {
        unsafe { BStr::from_ptr(self.ptr) }
    }

    /// Try to get as UTF-8 string
    pub fn as_str(&self) -> Result<&str, core::str::Utf8Error> {
        unsafe {
            let cstr = CStr::from_ptr(self.ptr);
            cstr.to_str()
        }
    }

    /// Get as bytes
    pub fn as_bytes(&self) -> &[u8] {
        unsafe {
            let cstr = CStr::from_ptr(self.ptr);
            cstr.to_bytes()
        }
    }

    /// Get length in bytes
    pub fn len(&self) -> usize {
        self.as_bstr().len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<'a> core::fmt::Display for PoolString<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self.as_str() {
            Ok(s) => write!(f, "{}", s),
            Err(_) => write!(f, "{:?}", self.as_bytes()),
        }
    }
}

impl<'a> core::fmt::Debug for PoolString<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self.as_str() {
            Ok(s) => write!(f, "PoolString({:?})", s),
            Err(_) => write!(f, "PoolString({:?})", self.as_bytes()),
        }
    }
}

/// Duplicate a Rust string into pool-allocated memory as a C string
pub fn pstrdup<'a>(s: &str, pool: &'a Pool) -> Result<PoolString<'a>, alloc::ffi::NulError> {
    let cstring = CString::new(s)?;
    let ptr = unsafe { apr_sys::apr_pstrdup(pool.as_mut_ptr(), cstring.as_ptr()) };
    Ok(PoolString {
        ptr,
        _marker: PhantomData,
    })
}

/// Get raw pointer version (for advanced users)
pub fn pstrdup_raw(s: &str, pool: &Pool<'_>) -> Result<*const c_char, alloc::ffi::NulError> {
    Ok(pstrdup(s, pool)?.as_ptr())
}

/// Create a pool-allocated C string from a Rust string
///
/// This is a convenience function that allocates a null-terminated C string
/// in the given pool's memory and returns it as a `CStr` reference.
///
/// # Example
/// ```
/// use apr::pool::Pool;
/// use apr::strings::make_cstring;
///
/// let pool = Pool::new();
/// let cstr = make_cstring("hello", &pool).unwrap();
/// assert_eq!(cstr.to_str().unwrap(), "hello");
/// ```
pub fn make_cstring<'a>(s: &str, pool: &'a Pool) -> Result<&'a CStr, alloc::ffi::NulError> {
    let ptr = pstrdup_raw(s, pool)?;
    Ok(unsafe { CStr::from_ptr(ptr) })
}

/// Duplicate a limited portion of a Rust string into pool-allocated memory
pub fn pstrndup<'a>(
    s: &str,
    n: usize,
    pool: &'a Pool,
) -> Result<PoolString<'a>, alloc::ffi::NulError> {
    let cstring = CString::new(s)?;
    let ptr = unsafe { apr_sys::apr_pstrndup(pool.as_mut_ptr(), cstring.as_ptr(), n) };
    Ok(PoolString {
        ptr,
        _marker: PhantomData,
    })
}

/// Copy bytes into pool-allocated memory (not null-terminated)
///
/// Returns an immutable slice since Pool is borrowed immutably
pub fn pmemdup<'a>(data: &[u8], pool: &'a Pool) -> &'a [u8] {
    unsafe {
        let ptr = apr_sys::apr_pmemdup(
            pool.as_mut_ptr(),
            data.as_ptr() as *const core::ffi::c_void,
            data.len(),
        ) as *const u8;
        core::slice::from_raw_parts(ptr, data.len())
    }
}

// Note: apr_pstrcat is a varargs function which is hard to call from Rust.
// If needed, concatenate strings manually and use pstrdup.

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::format;
    use alloc::string::ToString;

    #[test]
    fn test_bstr() {
        let test_str = "Hello, world!";
        let cstring = CString::new(test_str).unwrap();

        unsafe {
            let bstr = BStr::from_ptr(cstring.as_ptr());
            assert_eq!(bstr.as_bytes(), test_str.as_bytes());
            assert_eq!(bstr.to_str().unwrap(), test_str);
            assert!(!bstr.is_empty());
            assert_eq!(bstr.len(), test_str.len());
        }
    }

    #[test]
    fn test_bstr_utf8() {
        let test_str = "Hello, δΈ–η•Œ!";
        let cstring = CString::new(test_str).unwrap();

        unsafe {
            let bstr_utf8 = BStrUtf8::from_ptr(cstring.as_ptr()).unwrap();
            assert_eq!(bstr_utf8.as_str(), test_str);
            assert!(!bstr_utf8.is_empty());
            assert_eq!(bstr_utf8.len(), test_str.len());
        }
    }

    #[test]
    fn test_pool_string_operations() {
        let pool = Pool::new();

        let pooled = pstrdup("test string", &pool).unwrap();
        assert_eq!(pooled.as_str().unwrap(), "test string");
        assert_eq!(pooled.len(), 11);
        assert!(!pooled.is_empty());

        let bstr = pooled.as_bstr();
        assert_eq!(bstr.to_str().unwrap(), "test string");

        // Test pmemdup
        let data = b"binary data";
        let copied = pmemdup(data, &pool);
        assert_eq!(copied, data);
    }

    #[test]
    fn test_make_cstring() {
        let pool = Pool::new();

        // Test basic functionality
        let cstr = make_cstring("hello world", &pool).unwrap();
        assert_eq!(cstr.to_str().unwrap(), "hello world");
        assert_eq!(cstr.to_bytes(), b"hello world");

        // Test with empty string
        let empty_cstr = make_cstring("", &pool).unwrap();
        assert_eq!(empty_cstr.to_str().unwrap(), "");
        assert_eq!(empty_cstr.to_bytes(), b"");

        // Test with Unicode
        let unicode_cstr = make_cstring("Hello, δΈ–η•Œ!", &pool).unwrap();
        assert_eq!(unicode_cstr.to_str().unwrap(), "Hello, δΈ–η•Œ!");

        // Test that null bytes in the middle cause an error
        let result = make_cstring("hello\0world", &pool);
        assert!(result.is_err());
    }

    #[test]
    fn test_pool_string_display() {
        let pool = Pool::new();
        let pooled = pstrdup("hello", &pool).unwrap();
        assert_eq!(format!("{}", pooled), "hello");
        assert_eq!(format!("{:?}", pooled), "PoolString(\"hello\")");
    }

    #[test]
    fn test_bstr_traits() {
        let data = b"hello world";
        let bstr = BStr::from(&data[..]);

        // Test Clone, Copy
        let bstr2 = bstr;
        // Intentionally testing that Clone works even though Copy is implemented
        #[allow(clippy::clone_on_copy)]
        let bstr3 = bstr.clone();
        assert_eq!(bstr, bstr2);
        assert_eq!(bstr2, bstr3);

        // Test Display and Deref
        assert_eq!(format!("{}", bstr), "hello world");
        assert_eq!(bstr.len(), 11);
        assert_eq!(&bstr[0..5], b"hello");

        // Test From conversions
        let from_str = BStr::from("test");
        assert_eq!(from_str.as_bytes(), b"test");
    }

    #[test]
    fn test_bstr_utf8_traits() {
        let s = "hello πŸ¦€";
        let bstr_utf8 = BStrUtf8::from(s);

        // Test Clone, Copy, PartialEq
        let bstr2 = bstr_utf8;
        assert_eq!(bstr_utf8, bstr2);

        // Test Display and Deref
        assert_eq!(format!("{}", bstr_utf8), "hello πŸ¦€");
        assert_eq!(bstr_utf8.len(), 10); // UTF-8 bytes

        // Test TryFrom
        let from_bytes = BStrUtf8::try_from("hello".as_bytes()).unwrap();
        assert_eq!(from_bytes.as_str(), "hello");

        // Test invalid UTF-8
        let invalid = BStrUtf8::try_from(&[0xFF, 0xFF][..]);
        assert!(invalid.is_err());
    }

    #[test]
    fn test_advanced_string_traits() {
        // Test BStr with various PartialEq implementations
        let bstr = BStr::from("hello");
        assert_eq!(bstr, "hello");
        assert_eq!(bstr, "hello");
        assert_eq!(bstr, &b"hello"[..]);

        // Test Borrow trait
        let borrowed: &[u8] = core::borrow::Borrow::borrow(&bstr);
        assert_eq!(borrowed, b"hello");

        // Test BStrUtf8 PartialEq implementations
        let bstr_utf8 = BStrUtf8::from("hello");
        assert_eq!(bstr_utf8, "hello");
        assert_eq!(bstr_utf8, String::from("hello"));

        // Test Borrow trait for BStrUtf8
        let borrowed: &str = core::borrow::Borrow::borrow(&bstr_utf8);
        assert_eq!(borrowed, "hello");
    }
}