raylib 6.0.0

Safe Rust bindings for Raylib.
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
//! File manipulation functions. Should be parity with std::fs except on emscripten
use crate::ffi;

use crate::core::RaylibHandle;
use std::ffi::{CStr, CString, OsString, c_char};

/// Build a [`CString`] from any [`OsString`]-convertible value, stripping any
/// interior NUL bytes first.
///
/// `to_string_lossy` only repairs invalid UTF-8 — a NUL byte is valid UTF-8, so
/// it is *not* removed and would otherwise make `CString::new` fail and panic on
/// `.unwrap()` for a path containing an interior NUL (see #220). Stripping NULs up
/// front keeps construction infallible.
fn os_to_cstring(s: impl Into<OsString>) -> CString {
    let stripped = s.into().to_string_lossy().replace('\0', "");
    CString::new(stripped).expect("interior NUL bytes are stripped above")
}

/// Borrowed iterator over the UTF-8 paths in a [`FilePathList`] or [`DroppedFilePathList`].
///
/// Returned by `FilePathList::iter` / `DroppedFilePathList::iter`. Yields `&str` slices that
/// borrow the underlying raylib-allocated C strings, so the parent list must outlive the
/// iterator — the lifetime parameter enforces this. Implements [`DoubleEndedIterator`] and
/// [`ExactSizeIterator`].
///
/// # Panics
///
/// `next` / `next_back` / `nth` / `nth_back` / `last` panic if a path entry is null or if a
/// path is not valid UTF-8. Construction via the internal `new` panics if the backing array
/// is null or unaligned.
///
/// # Examples
///
/// ```no_run
/// use raylib::prelude::*;
///
/// let (rl, _thread) = raylib::init().size(640, 480).title("files").build();
/// let list = rl.load_directory_files("assets");
/// for path in list.iter() {
///     println!("found {path}");
/// }
/// ```
#[derive(Debug, Clone)]
pub struct FilePathIter<'a> {
    iter: std::slice::Iter<'a, Option<&'a c_char>>,
}
impl<'a> FilePathIter<'a> {
    /// # Safety
    /// The memory pointed to by `list` must not be mutated for `'a`.
    /// Every `*mut c_char` in `list` must outlive `'a`.
    ///
    /// ## Examples
    ///
    /// The following is invalid, because `list` is dropped while `it` is still borrowing it.
    /// ```compile_fail
    /// # use raylib::{ffi, file::*};
    /// # use std::{mem::ManuallyDrop, ffi::CStr};
    /// let mut it;
    /// let s;
    /// {
    ///     let mut paths = [
    ///         c"apple".as_ptr().cast_mut(),
    ///     ];
    ///     let mut list = ManuallyDrop::new(unsafe {
    ///         FilePathList::from_raw(ffi::FilePathList {
    ///             count: 1,
    ///             paths: paths.as_mut_ptr(),
    ///         })
    ///     });
    ///     it = list.iter(); // expect error[E0597]
    ///     //   ^^^^ borrowed value does not live long enough
    ///     s = it.next();
    ///     assert_eq!(s, Some("apple"));
    /// } // `list` dropped here while still borrowed
    /// assert_eq!(s, Some("apple")); // borrow later used here
    /// ```
    ///
    /// The following is invalid, because `list` is mutated while `it` is still borrowing it.
    /// ```compile_fail
    /// # use raylib::{ffi, file::*};
    /// # use std::{mem::ManuallyDrop, ffi::CStr};
    /// let mut paths = [
    ///     c"apple".as_ptr().cast_mut(),
    /// ];
    /// let mut list = ManuallyDrop::new(unsafe {
    ///     FilePathList::from_raw(ffi::FilePathList {
    ///         count: 1,
    ///         paths: paths.as_mut_ptr(),
    ///     })
    /// });
    /// let mut it = list.iter();
    /// //           ---- immutable borrow occurs here
    /// let s = it.next();
    /// assert_eq!(s, Some("apple"));
    /// unsafe { *(*list.paths) = b'@' as std::ffi::c_char; } // expect error[E0502]
    /// //          ^^^^ mutable borrow occurs here
    /// assert_eq!(s, Some("apple")); // immutable borrow later used here
    /// ```
    unsafe fn new(list: *mut *mut c_char, count: u32) -> Self {
        // No new items are being created that get dropped here, these are just changes in perspective of how to borrow-check the pointers.
        assert!(!list.is_null(), "file path array cannot be null");
        assert!(list.is_aligned(), "file path array must be aligned");
        let list = list.cast::<Option<&'a c_char>>();
        let iter = unsafe { std::slice::from_raw_parts(list, count as usize) }.iter();
        Self { iter }
    }
    fn func(f: &Option<&'a c_char>) -> &'a str {
        // CStr isn't being "constructed", it's essentially an adapter on &[c_char]
        let s = std::slice::from_ref(f.expect("file path string cannot be null"));
        unsafe { CStr::from_ptr(s.as_ptr()) }.to_str().unwrap()
    }
}
impl<'a> Iterator for FilePathIter<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(Self::func)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }

    #[inline]
    fn count(self) -> usize {
        self.len()
    }

    fn last(self) -> Option<Self::Item> {
        self.iter.last().map(Self::func)
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.iter.nth(n).map(Self::func)
    }
}
impl DoubleEndedIterator for FilePathIter<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter.next_back().map(Self::func)
    }

    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        self.iter.nth_back(n).map(Self::func)
    }
}
impl ExactSizeIterator for FilePathIter<'_> {
    #[inline]
    fn len(&self) -> usize {
        self.iter.len()
    }
}

// SOUNDNESS: readonly — P1 (paths slice trusts paths×count) + P2 (Drop=UnloadDirectoryFiles frees paths and each string).
make_thin_wrapper!(
    FilePathList,
    ffi::FilePathList,
    ffi::UnloadDirectoryFiles,
    readonly
);
// SOUNDNESS: readonly — P1/P2 like FilePathList (Drop=UnloadDroppedFiles).
make_thin_wrapper!(
    DroppedFilePathList,
    ffi::FilePathList,
    ffi::UnloadDroppedFiles,
    readonly
);

impl FilePathList {
    /// Length of the file path list
    #[inline]
    pub const fn count(&self) -> u32 {
        self.0.count
    }
    /// The paths held in this list.
    /// This function is NOT constant and the inner array will be copied into the returned Vec every time you call this.
    pub fn paths(&self) -> Vec<&str> {
        unsafe { std::slice::from_raw_parts(self.0.paths, self.count() as usize) }
            .iter()
            .map(|f| unsafe { CStr::from_ptr(*f) }.to_str().unwrap())
            .collect()
    }
    /// An iterator over the paths held in this list.
    pub fn iter(&self) -> FilePathIter<'_> {
        unsafe { FilePathIter::new(self.0.paths, self.count()) }
    }
}

impl DroppedFilePathList {
    /// Length of the file path list
    #[inline]
    pub const fn count(&self) -> u32 {
        self.0.count
    }
    /// The paths held in this list.
    /// This function is NOT constant and the inner array will be copied into the returned Vec every time you call this.
    pub fn paths(&self) -> Vec<&str> {
        unsafe { std::slice::from_raw_parts(self.0.paths, self.count() as usize) }
            .iter()
            .map(|f| unsafe { CStr::from_ptr(*f) }.to_str().unwrap())
            .collect()
    }
    /// An iterator over the paths held in this list.
    pub fn iter(&self) -> FilePathIter<'_> {
        unsafe { FilePathIter::new(self.0.paths, self.count()) }
    }
}

impl RaylibHandle {
    /// Checks if a file has been dropped into the window.
    #[inline]
    pub fn is_file_dropped(&self) -> bool {
        unsafe { ffi::IsFileDropped() }
    }

    /// Checks a file's extension.
    #[inline]
    pub fn is_file_extension<A>(&self, file_name: A, file_ext: A) -> bool
    where
        A: Into<OsString>,
    {
        let file_name = os_to_cstring(file_name);
        let file_ext = os_to_cstring(file_ext);
        unsafe { ffi::IsFileExtension(file_name.as_ptr(), file_ext.as_ptr()) }
    }
    /// Get the directory of the running application.
    pub fn application_directory(&self) -> String {
        unsafe {
            let st = ffi::GetApplicationDirectory();
            let c_str = CStr::from_ptr(st);

            // If this ever errors out, yell at @ioi_xd on Discord,
            c_str.to_str().unwrap().to_string()
        }
    }

    /// Get file length in bytes.
    ///
    /// Any interior NUL bytes in `filename` are stripped before the FFI call.
    pub fn get_file_length<A>(&self, filename: A) -> i32
    where
        A: Into<OsString>,
    {
        let c_str = os_to_cstring(filename);
        unsafe { ffi::GetFileLength(c_str.as_ptr()) }
    }

    /// Check if a given path is a file or a directory
    ///
    /// Any interior NUL bytes in `filename` are stripped before the FFI call.
    #[must_use]
    pub fn is_path_file<A>(&self, filename: A) -> bool
    where
        A: Into<OsString>,
    {
        let c_str = os_to_cstring(filename);
        unsafe { ffi::IsPathFile(c_str.as_ptr()) }
    }

    /// Load directory filepaths
    pub fn load_directory_files<A>(&self, dir_path: A) -> FilePathList
    where
        A: Into<OsString>,
    {
        unsafe {
            let c_str = os_to_cstring(dir_path);
            FilePathList(ffi::LoadDirectoryFiles(c_str.as_ptr()))
        }
    }

    /// Load directory filepaths with extension filtering and recursive directory scan
    pub fn load_directory_files_ex<A>(
        &self,
        dir_path: A,
        filter: String,
        scan_sub_dirs: bool,
    ) -> FilePathList
    where
        A: Into<OsString>,
    {
        unsafe {
            let dir_c_str = os_to_cstring(dir_path);
            let filter_c_str = CString::new(filter.replace('\0', "")).unwrap();
            FilePathList(ffi::LoadDirectoryFilesEx(
                dir_c_str.as_ptr(),
                filter_c_str.as_ptr(),
                scan_sub_dirs,
            ))
        }
    }

    /// Check if a file has been dropped into window
    #[inline]
    pub fn load_dropped_files(&self) -> DroppedFilePathList {
        unsafe { DroppedFilePathList(ffi::LoadDroppedFiles()) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::mem::ManuallyDrop;

    #[test]
    fn os_to_cstring_strips_interior_nul() {
        // `to_string_lossy` keeps NUL bytes (they are valid UTF-8), so the
        // previous `CString::new(...).unwrap()` panicked on a path containing an
        // interior NUL (#220). The helper must strip NULs and never panic.
        assert_eq!(os_to_cstring("a\0b\0c").to_str().unwrap(), "abc");
        assert_eq!(os_to_cstring("clean/path").to_str().unwrap(), "clean/path");
        assert_eq!(os_to_cstring("\0").to_str().unwrap(), "");
    }

    #[test]
    #[should_panic(expected = "file path array cannot be null")]
    fn test_null_list() {
        let list = ManuallyDrop::new(FilePathList(ffi::FilePathList {
            count: 0,
            paths: std::ptr::null_mut(),
        }));
        let _it = list.iter();
        // should have panicked while calling .iter()
    }

    #[test]
    #[should_panic(expected = "file path string cannot be null")]
    fn test_null_item() {
        let mut paths = [std::ptr::null_mut()];
        let list = ManuallyDrop::new(FilePathList(ffi::FilePathList {
            count: 1,
            paths: paths.as_mut_ptr(),
        }));
        let mut it = list.iter();
        let _f = it.next();
        // should have panicked while calling .next()
    }

    #[test]
    #[should_panic(expected = "file path string cannot be null")]
    fn test_null_item_double_ended() {
        let mut paths = [std::ptr::null_mut()];
        let list = ManuallyDrop::new(FilePathList(ffi::FilePathList {
            count: 1,
            paths: paths.as_mut_ptr(),
        }));
        let mut it = list.iter();
        let _f = it.next_back();
        // should have panicked while calling .next_back()
    }

    #[test]
    fn test_len() {
        let mut paths = [
            c"apple".as_ptr().cast_mut(),
            c"orange".as_ptr().cast_mut(),
            c"banana".as_ptr().cast_mut(),
            c"mango".as_ptr().cast_mut(),
            c"pineapple".as_ptr().cast_mut(),
        ];
        let list = ManuallyDrop::new(FilePathList(ffi::FilePathList {
            count: 5,
            paths: paths.as_mut_ptr(),
        }));
        let mut it = list.iter();
        assert_eq!(it.len(), 5);
        assert_eq!(it.next(), Some("apple"));
        assert_eq!(it.len(), 4);
        assert_eq!(it.next(), Some("orange"));
        assert_eq!(it.len(), 3);
        assert_eq!(it.next(), Some("banana"));
        assert_eq!(it.len(), 2);
        assert_eq!(it.next(), Some("mango"));
        assert_eq!(it.len(), 1);
        assert_eq!(it.next(), Some("pineapple"));
        assert_eq!(it.len(), 0);
        assert_eq!(it.next(), None);
    }

    #[test]
    fn test_len_double_ended() {
        let mut paths = [
            c"apple".as_ptr().cast_mut(),
            c"orange".as_ptr().cast_mut(),
            c"banana".as_ptr().cast_mut(),
            c"mango".as_ptr().cast_mut(),
            c"pineapple".as_ptr().cast_mut(),
        ];
        let list = ManuallyDrop::new(FilePathList(ffi::FilePathList {
            count: 5,
            paths: paths.as_mut_ptr(),
        }));
        let mut it = list.iter();
        assert_eq!(it.len(), 5);
        assert_eq!(it.next_back(), Some("pineapple"));
        assert_eq!(it.len(), 4);
        assert_eq!(it.next_back(), Some("mango"));
        assert_eq!(it.len(), 3);
        assert_eq!(it.next_back(), Some("banana"));
        assert_eq!(it.len(), 2);
        assert_eq!(it.next_back(), Some("orange"));
        assert_eq!(it.len(), 1);
        assert_eq!(it.next_back(), Some("apple"));
        assert_eq!(it.len(), 0);
        assert_eq!(it.next_back(), None);
    }
}