rich_sdl2_rust/file/
mode.rs

1//! A file open mode for opening a file conveniently.
2
3use std::ffi::CString;
4
5/// A builder for an open mode of [`super::RwOps`].
6#[derive(Debug, Default, Clone)]
7pub struct OpenMode {
8    read: bool,
9    create: bool,
10    append: bool,
11    write: bool,
12    truncate: bool,
13    binary: bool,
14}
15
16impl OpenMode {
17    /// Constructs an empty mode. Please do not pass this into [`super::RwOps`] as is.
18    #[must_use]
19    pub fn new() -> Self {
20        Self::default()
21    }
22
23    /// Sets to be able to read.
24    pub fn read(&mut self, read: bool) -> &mut Self {
25        self.read = read;
26        self
27    }
28    /// Sets to be able to create a new file.
29    pub fn create(&mut self, create: bool) -> &mut Self {
30        self.create = create;
31        self
32    }
33    /// Sets to force to append. Setting true will disable to be able to write.
34    pub fn append(&mut self, append: bool) -> &mut Self {
35        self.append = append;
36        if self.write {
37            self.write = false;
38        }
39        self
40    }
41    /// Sets to force to write. Setting true will disable to be able to append.
42    pub fn write(&mut self, write: bool) -> &mut Self {
43        self.write = write;
44        if self.append {
45            self.append = false;
46        }
47        self
48    }
49    /// Sets to force to truncate, overwriting all of a file.
50    pub fn truncate(&mut self, truncate: bool) -> &mut Self {
51        self.truncate = truncate;
52        self
53    }
54    /// Sets to be able to read as the binary mode. Setting false will be the text mode.
55    pub fn binary(&mut self, binary: bool) -> &mut Self {
56        self.binary = binary;
57        self
58    }
59    /// Sets to be able to read as the text mode. Setting false will be the binary mode.
60    pub fn text(&mut self, text: bool) -> &mut Self {
61        self.binary = !text;
62        self
63    }
64
65    pub(super) fn into_raw(self) -> CString {
66        let mut string = if self.read && self.write && self.truncate {
67            "w+"
68        } else if self.read && self.write {
69            "r+"
70        } else if self.read && self.append {
71            "a+"
72        } else if self.write {
73            "w"
74        } else if self.read {
75            "r"
76        } else if self.append {
77            "a"
78        } else {
79            panic!("the open mode was empty");
80        }
81        .to_owned();
82        if self.binary {
83            string.push('b');
84        }
85        CString::new(string).unwrap()
86    }
87}