muzzman_lib/
data.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{
4    prelude::{TypeTag, TypeValidation},
5    types::Type,
6};
7
8use bytes_kman::TBytes;
9
10use std::{
11    collections::HashMap,
12    fs::File,
13    hash::Hash,
14    path::PathBuf,
15    sync::{Arc, Mutex},
16};
17
18#[derive(Debug, Default, Clone, Serialize, Deserialize, Hash, bytes_kman::Bytes)]
19pub struct Bytes {
20    pub data: Vec<u8>,
21    pub coursor: usize,
22    pub fast_invert: bool,
23}
24
25impl From<Vec<u8>> for Bytes {
26    fn from(value: Vec<u8>) -> Self {
27        Self {
28            coursor: value.len(),
29            data: value,
30            fast_invert: false,
31        }
32    }
33}
34impl From<&[u8]> for Bytes {
35    fn from(value: &[u8]) -> Self {
36        Self {
37            coursor: value.len(),
38            data: value.to_vec(),
39            fast_invert: false,
40        }
41    }
42}
43
44impl std::io::Write for Bytes {
45    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
46        let len = buf.len();
47        for b in buf {
48            if self.data.len() == self.coursor {
49                self.data.push(*b);
50            } else {
51                self.data[self.coursor] = *b;
52                self.coursor += 1;
53            }
54        }
55        Ok(len)
56    }
57
58    fn flush(&mut self) -> std::io::Result<()> {
59        Ok(())
60    }
61}
62
63impl std::io::Read for Bytes {
64    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
65        let mut readed = 0;
66        for byte in buf.iter_mut() {
67            if self.coursor == self.data.len() {
68                break;
69            }
70            if self.coursor == 0 {
71                break;
72            }
73
74            *byte = if self.fast_invert {
75                self.data[self.data.len() - self.coursor]
76            } else {
77                self.data[self.coursor]
78            };
79
80            readed += 1;
81            self.coursor += 1;
82
83            if self.coursor == self.data.len() {
84                break;
85            }
86            if self.coursor == 0 {
87                break;
88            }
89        }
90        Ok(readed)
91    }
92}
93
94impl std::io::Seek for Bytes {
95    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
96        match pos {
97            std::io::SeekFrom::Start(pos) => {
98                let res = pos;
99                if res >= self.data.len() as u64 {
100                    Err(std::io::Error::from_raw_os_error(25))
101                } else {
102                    self.coursor = res as usize;
103                    Ok(res)
104                }
105            }
106            std::io::SeekFrom::End(pos) => {
107                let res = (self.data.len() as i64) + pos;
108                if res >= self.data.len() as i64 {
109                    Err(std::io::Error::from_raw_os_error(24))
110                } else {
111                    self.coursor = res as usize;
112                    Ok(res as u64)
113                }
114            }
115            std::io::SeekFrom::Current(pos) => {
116                let res = pos + self.coursor as i64;
117                if res >= self.data.len() as i64 {
118                    Err(std::io::Error::from_raw_os_error(25))
119                } else {
120                    self.coursor = res as usize;
121                    Ok(res as u64)
122                }
123            }
124        }
125    }
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize, Hash, bytes_kman::Bytes)]
129pub struct Value {
130    pub value: Type,
131    pub should_be: Vec<TypeTag>,
132    pub validators: Vec<TypeValidation>,
133    pub default: Type,
134    pub desc: String,
135    pub editabile: bool,
136}
137
138impl Value {
139    pub fn new(
140        value: Type,
141        should_be: Vec<TypeTag>,
142        validators: Vec<TypeValidation>,
143        editabile: bool,
144        desc: impl Into<String>,
145    ) -> Self {
146        Self {
147            value: value.clone(),
148            default: value,
149            should_be,
150            validators,
151            desc: desc.into(),
152            editabile,
153        }
154    }
155}
156
157impl From<Type> for Value {
158    fn from(value: Type) -> Self {
159        Self {
160            value: value.clone(),
161            should_be: vec![value.to_tag()],
162            validators: vec![],
163            default: value,
164            desc: String::new(),
165            editabile: true,
166        }
167    }
168}
169
170#[derive(Debug, Clone, Default, Serialize, Deserialize, bytes_kman::Bytes)]
171pub struct Data {
172    pub data: HashMap<String, Value>,
173    pub locked: bool,
174}
175
176impl Hash for Data {
177    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
178        self.locked.hash(state);
179        for (k, v) in self.data.iter() {
180            k.hash(state);
181            v.hash(state)
182        }
183    }
184}
185
186impl Data {
187    pub fn new() -> Self {
188        Self {
189            data: HashMap::new(),
190            locked: false,
191        }
192    }
193
194    pub fn set(&mut self, key: &str, value: Type) -> Option<Type> {
195        let Some(data) = self.data.get_mut(key) else{
196            return None;
197        };
198
199        let mut value = value;
200        std::mem::swap(&mut data.value, &mut value);
201        Some(value)
202    }
203
204    pub fn reset(&mut self, key: &str) -> Option<Type> {
205        let Some(data) = self.data.get(key)else{return None};
206
207        self.set(key, data.default.clone())
208    }
209
210    pub fn get(&self, key: &str) -> Option<&Type> {
211        let Some(data) = self.data.get(key) else{
212            return None;
213        };
214        Some(&data.value)
215    }
216
217    pub fn get_mut(&mut self, key: &str) -> Option<&mut Type> {
218        let Some(data) = self.data.get_mut(key) else{
219            return None;
220        };
221        Some(&mut data.value)
222    }
223
224    /// if has a result that's mean that has an error!
225    pub fn validate(&self) -> Option<String> {
226        let mut errors = String::new();
227
228        for (key, value) in self.iter() {
229            let mut has_correct_type = false;
230            for should_be in value.should_be.iter() {
231                let t = value.value.to_tag();
232                if *should_be == t {
233                    has_correct_type = true;
234                    break;
235                }
236            }
237
238            if !has_correct_type {
239                let mut buff = format!("`{key}` should be: ");
240                for (i, should_be) in value.should_be.iter().enumerate() {
241                    if i > 0 {
242                        buff.push(',');
243                    }
244                    buff.push_str(&should_be.to_string());
245                }
246                errors.push_str(&buff);
247            }
248
249            // TODO: Implement validators!
250            //let mut is_valid = true;
251
252            if !has_correct_type
253            /* | !is_valid */
254            {
255                return Some(errors);
256            }
257        }
258        None
259    }
260
261    pub fn get_value(&self, key: &str) -> Option<&Value> {
262        self.data.get(key)
263    }
264
265    pub fn get_mut_value(&mut self, key: &str) -> Option<&mut Value> {
266        self.data.get_mut(key)
267    }
268
269    /// should not be used!
270    pub fn remove(&mut self, key: &str) -> Option<Value> {
271        self.data.remove(key)
272    }
273
274    /// only should be used by the module
275    pub fn add(&mut self, key: &str, value: impl Into<Value>) {
276        if !self.locked {
277            self.data.insert(key.to_owned(), value.into());
278        }
279    }
280
281    /// only should be used by module
282    pub fn lock(&mut self) {
283        self.locked = true;
284    }
285
286    /// should not be used!!!
287    pub fn unlock(&mut self) {
288        self.locked = false;
289    }
290
291    pub fn iter(&self) -> std::collections::hash_map::Iter<String, Value> {
292        self.data.iter()
293    }
294
295    /// you should only modify value
296    pub fn iter_mut(&mut self) -> std::collections::hash_map::IterMut<String, Value> {
297        self.data.iter_mut()
298    }
299}
300
301#[derive(Debug, Clone, Serialize, Deserialize)]
302pub enum FileOrData {
303    File(PathBuf, #[serde(skip)] Option<Arc<Mutex<std::fs::File>>>),
304    Bytes(Bytes),
305}
306
307impl TBytes for FileOrData {
308    fn size(&self) -> usize {
309        match self {
310            FileOrData::File(p, _) => p.size() + 1,
311            FileOrData::Bytes(v) => v.size() + 1,
312        }
313    }
314
315    fn to_bytes(&self) -> Vec<u8> {
316        match self {
317            FileOrData::File(path, _) => {
318                let mut buff = Vec::with_capacity(self.size());
319
320                buff.push(0);
321                buff.append(&mut path.to_bytes());
322
323                buff
324            }
325            FileOrData::Bytes(bytes) => {
326                let mut buff = Vec::with_capacity(self.size());
327
328                buff.push(1);
329                buff.append(&mut bytes.to_bytes());
330
331                buff
332            }
333        }
334    }
335
336    fn from_bytes(buffer: &mut Vec<u8>) -> Option<Self>
337    where
338        Self: Sized,
339    {
340        let variant = buffer.pop()?;
341
342        match variant {
343            0 => Some(Self::File(PathBuf::from_bytes(buffer)?, None)),
344            1 => Some(Self::Bytes(Bytes::from_bytes(buffer)?)),
345            _ => None,
346        }
347    }
348}
349
350impl Hash for FileOrData {
351    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
352        match self {
353            FileOrData::File(f, _) => f.hash(state),
354            FileOrData::Bytes(b) => b.hash(state),
355        }
356    }
357}
358
359impl std::io::Write for FileOrData {
360    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
361        match self {
362            FileOrData::File(file_path, file) => {
363                if let Some(file) = file {
364                    file.lock().unwrap().write(buf)
365                } else {
366                    let mut f = File::options()
367                        .create(true)
368                        .write(true)
369                        .read(true)
370                        .open(file_path)?;
371                    let res = f.write(buf);
372                    *file = Some(Arc::new(Mutex::new(f)));
373                    res
374                }
375            }
376            FileOrData::Bytes(bytes) => bytes.write(buf),
377        }
378    }
379
380    fn flush(&mut self) -> std::io::Result<()> {
381        match self {
382            FileOrData::File(_, file) => {
383                if let Some(file) = file {
384                    file.lock().unwrap().flush()
385                } else {
386                    Ok(())
387                }
388            }
389            FileOrData::Bytes(_) => Ok(()),
390        }
391    }
392}
393
394impl std::io::Read for FileOrData {
395    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
396        match self {
397            FileOrData::File(file_path, file) => {
398                if let Some(file) = file {
399                    file.lock().unwrap().read(buf)
400                } else {
401                    let mut f = File::options().read(true).write(true).open(file_path)?;
402                    let res = f.read(buf);
403                    *file = Some(Arc::new(Mutex::new(f)));
404                    res
405                }
406            }
407            FileOrData::Bytes(bytes) => bytes.read(buf),
408        }
409    }
410}
411
412impl std::io::Seek for FileOrData {
413    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
414        match self {
415            FileOrData::File(file_path, file) => {
416                if let Some(file) = file {
417                    file.lock().unwrap().seek(pos)
418                } else {
419                    let mut f = File::options().read(true).write(true).open(file_path)?;
420                    let res = f.seek(pos);
421                    *file = Some(Arc::new(Mutex::new(f)));
422                    res
423                }
424            }
425            FileOrData::Bytes(bytes) => bytes.seek(pos),
426        }
427    }
428}