binconf 0.3.0

Save and load from a binary configuration file with ease.
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use std::io::{Read, Write};
use xxhash_rust::xxh3::xxh3_128;

use crate::{ConfigError, ConfigLocation, ConfigType};

const HASH_BYTE_LENGTH: usize = 16;

pub use bitcode::{Decode, DecodeOwned, Encode};

/// Loads a config file from the config, cache, cwd, or local data directory of the current user. In `binary` format.
///
/// It will load a config file, deserialize it and return it.
///
/// If the flag `reset_conf_on_err` is set to `true`, the config file will be reset to the default config if
/// the deserialization fails, if set to `false` an error will be returned.
///
/// # Errors
///
/// This function will return an error if the config, cache or local data directory could not be found or created, or if something went wrong while deserializing the config.
///
/// If the flag `reset_conf_on_err` is set to `false` and the deserialization fails, an error will be returned. If it is set to `true` the config file will be reset to the default config.
///
/// # Example
///
/// ```
/// use binconf::ConfigLocation::{Cache, Config, LocalData, Cwd};
/// use binconf::{Encode, Decode};
///
/// #[derive(Default, PartialEq, Debug, Encode, Decode)]
/// struct TestConfig {
///    test: String,
///    test_vec: Vec<u8>,
/// }
///
/// let config = binconf::load_bin::<TestConfig>("test-binconf-read-bin", None, Config, false).unwrap();
/// assert_eq!(config, TestConfig::default());
/// ```
pub fn load_bin<T>(
    app_name: impl AsRef<str>,
    config_name: Option<&str>,
    location: impl AsRef<ConfigLocation>,
    reset_conf_on_err: bool,
) -> Result<T, ConfigError>
where
    T: Default + Encode,
    for<'de> T: Decode<'de>,
{
    load_bin_internal(
        app_name.as_ref(),
        config_name,
        location.as_ref(),
        reset_conf_on_err,
        false,
    )
}

/// Loads a config file from the config, cache, cwd, or local data directory of the current user. **Without verifying the hash**. In `binary` format.
///
/// This is a fallback function, if the hash verification fails, you could try to load the config with this function. Only use this function if you get a [`ConfigError::HashMismatch`] error,
/// other errors **will not be handled** by this function.
///
/// It's **not recommended** to use this function over the [`load_bin`], as it could lead to corrupted data being loaded.
///
/// If the deserialization fails with the flag `reset_conf_on_err` set to `true`, the config file will be reset to the default config and a new hash will be generated.
///
/// Even with the flag `reset_conf_on_err` is set to `true`, the config file will **not** be reset to the default config on a [`ConfigError::HashMismatch`] error.
///
/// # Errors
///
/// This function will return an error if the config, cache or local data directory could not be found or created, or if something went wrong while deserializing the config.
///
/// If the flag `reset_conf_on_err` is set to `false` and the deserialization fails, an error will be returned. If it is set to `true` the config file will be reset to the default config.
///
/// If the file being read is less than 16 bytes, an error will be returned. It assumes that the first 16 bytes are the hash, even without verifying it, as this could lead to corrupted data being loaded more often.
///
/// # Example
///
/// ```
/// use binconf::ConfigLocation::{Cache, Config, LocalData, Cwd};
/// use binconf::{Encode, Decode};
///
/// #[derive(Default, PartialEq, Debug, Encode, Decode)]
/// struct TestConfig {
///    test: String,
///    test_vec: Vec<u8>,
/// }
///
///let config = binconf::load_bin_skip_check::<TestConfig>("test-binconf-read-bin", None, Config, false).unwrap();
///
/// assert_eq!(config, TestConfig::default());
/// ```
pub fn load_bin_skip_check<T>(
    app_name: impl AsRef<str>,
    config_name: Option<&str>,
    location: impl AsRef<ConfigLocation>,
    reset_conf_on_err: bool,
) -> Result<T, ConfigError>
where
    T: Default + Encode,
    for<'de> T: Decode<'de>,
{
    load_bin_internal(
        app_name.as_ref(),
        config_name,
        location.as_ref(),
        reset_conf_on_err,
        true,
    )
}

fn load_bin_internal<T>(
    app_name: &str,
    config_name: Option<&str>,
    location: &ConfigLocation,
    reset_conf_on_err: bool,
    skip_hash_check: bool,
) -> Result<T, ConfigError>
where
    T: Default + Encode,
    for<'de> T: Decode<'de>,
{
    let config_file_path =
        crate::config_location(app_name, config_name, ConfigType::Bin.as_str(), location)?;

    let save_default_conf = || {
        let default_config = T::default();
        let mut file = std::io::BufWriter::new(std::fs::File::create(&config_file_path)?);

        let full_data = prepare_serialized_data(&default_config);
        file.write_all(&full_data)?;

        Ok(default_config)
    };

    if !config_file_path.try_exists()? {
        return save_default_conf();
    }

    let file = std::fs::File::open(&config_file_path)?;
    let mut reader = std::io::BufReader::new(file);

    let mut data = Vec::new();
    reader.read_to_end(&mut data)?;

    // If the file is empty, or smaller than 16 bytes, we can't have a `xxh3_128` hash
    if data.len() < HASH_BYTE_LENGTH {
        if reset_conf_on_err {
            return save_default_conf();
        }
        return Err(ConfigError::CorruptedHashSector);
    }

    if !skip_hash_check {
        let (binary_hash_from_file, binary_hash_from_data) = get_hash_from_file_and_data(&data);

        if binary_hash_from_file != binary_hash_from_data {
            if reset_conf_on_err {
                return save_default_conf();
            }
            return Err(ConfigError::HashMismatch);
        }
    }

    // The first 16 bytes are the `xxh3_128` hash, the rest is the serialized data
    let binary_data_without_hash = &data[HASH_BYTE_LENGTH..];
    let config: T = match bitcode::decode(binary_data_without_hash) {
        Ok(config) => config,
        Err(err) => {
            if reset_conf_on_err {
                save_default_conf()?
            } else {
                return Err(ConfigError::Bitcode(err));
            }
        }
    };

    Ok(config)
}

/// Stores a config file in the config, cache, cwd, or local data directory of the current user. In `binary` format.
///
/// It will store a config file, serializing it with the `bincode` crate.
///
/// # Errors
///
/// This function will return an error if the config, cache or local data directory could not be found or created, or if something went wrong while serializing the config.
///
/// # Example
///
/// ```
/// use binconf::ConfigLocation::{Cache, Config, LocalData, Cwd};
/// use binconf::{Encode, Decode};
///
/// #[derive(Default, PartialEq, Debug, Encode, Decode)]
/// struct TestConfig {
///   test: String,
///   test_vec: Vec<u8>,
/// }
///
/// let test_config = TestConfig {
///  test: String::from("test-bin"),
///  test_vec: vec![1, 2, 3, 4, 5],
/// };
///
/// binconf::store_bin("test-binconf-store-bin", None, Config, &test_config).unwrap();
///
/// let config = binconf::load_bin::<TestConfig>("test-binconf-store-bin", None, Config, false).unwrap();
/// assert_eq!(config, test_config);
/// ```
pub fn store_bin<T>(
    app_name: impl AsRef<str>,
    config_name: Option<&str>,
    location: impl AsRef<ConfigLocation>,
    data: &T,
) -> Result<(), ConfigError>
where
    T: Encode,
{
    let config_file_path = crate::config_location(
        app_name.as_ref(),
        config_name.as_ref().map(AsRef::as_ref),
        ConfigType::Bin.as_str(),
        location.as_ref(),
    )?;

    let mut file = std::io::BufWriter::new(std::fs::File::create(config_file_path)?);
    let full_data = prepare_serialized_data(data);

    file.write_all(&full_data[..])?;

    Ok(())
}

/// Returns the `xxh3_128` hash of the file and the `xxh3_128` hash of the data.
///
/// The first element of the tuple is the `xxh3_128` hash of the file, the second element is the `xxh3_128` hash of the data.
///
/// If the data is corrupted, the `xxh3_128` hash of the file and the `xxh3_128` hash of the data will not match.
fn get_hash_from_file_and_data(data: &[u8]) -> (&[u8], Vec<u8>) {
    // The first 64 bits (16 bytes) of the data will be the xxh3_128 hash of the data.
    let binary_hash_from_file = &data[..HASH_BYTE_LENGTH];

    // The rest of the data will be the serialized data.
    let binary_data_without_hash = &data[HASH_BYTE_LENGTH..];

    let binary_hash_from_data = &xxh3_128(binary_data_without_hash).to_le_bytes()[..];

    // The `xxh3_128` hash should be 64 bits (16 bytes) long. If it's not, something went wrong.
    // This prevents a vec allocation with incorrect size.
    assert!(binary_hash_from_data.len() == HASH_BYTE_LENGTH);

    (binary_hash_from_file, binary_hash_from_data.to_vec())
}

/// Prepares the data to be stored in a file.
///
/// It will calculate the `xxh3_128` hash of the data and prepend it to the data.
///
/// Returns the binary data with the hash prepended.
///
/// The first `64 bits (16 bytes)` of the data will be the `xxh3_128` hash of the data, the rest of the data will be the serialized data.
fn prepare_serialized_data<T>(data: &T) -> Vec<u8>
where
    T: bitcode::Encode,
{
    // Create a buffer with 16 bytes zeroed out, and append the serialized data to it.
    let mut full_data = [vec![0; HASH_BYTE_LENGTH], bitcode::encode(data)].concat();
    // Calculate the `xxh3_128` hash of the serialized data.

    let hash = &xxh3_128(&full_data[HASH_BYTE_LENGTH..]).to_le_bytes()[..];

    // Prepend the `xxh3_128` hash to the binary data. If the hash length is not 16 bytes, this will panic. This should never happen as the `xxh3_128` hash is always 16 bytes.
    // This function will panic if the two slices have different lengths.
    full_data[..HASH_BYTE_LENGTH].clone_from_slice(hash);

    full_data
}

#[cfg(test)]
mod tests {
    use std::io::Seek;

    use super::*;

    use crate::get_configuration_path;

    use ConfigLocation::{Cache, Config, Cwd, LocalData};

    #[derive(Default, PartialEq, Debug, Clone, Encode, Decode)]
    struct TestConfig {
        test: String,
        test_vec: Vec<u8>,
    }

    #[derive(Default, Clone, Debug, Decode, Encode)]
    struct TestConfig2 {
        strings: String,
        vecs: Vec<u8>,
        num_1: i32,
        num_2: i32,
    }

    #[test]
    fn read_default_config_bin() {
        let config = load_bin::<String>(
            "test-binconf-read_default_config-string-bin",
            None,
            Config,
            false,
        )
        .unwrap();
        assert_eq!(config, String::from(""));

        let test_config = TestConfig {
            test: String::from("test"),
            test_vec: vec![1, 2, 3, 4, 5],
        };

        let config: TestConfig = load_bin(
            "test-binconf-read_default_config-struct-bin",
            None,
            Config,
            false,
        )
        .unwrap();
        assert_eq!(config, TestConfig::default());

        store_bin(
            "test-binconf-read_default_config-struct-bin",
            None::<&str>,
            Config,
            &test_config,
        )
        .unwrap();
        let config: TestConfig = load_bin(
            "test-binconf-read_default_config-struct-bin",
            None,
            Config,
            false,
        )
        .unwrap();
        assert_eq!(config, test_config);
    }

    #[test]
    fn config_with_name_bin() {
        let config = load_bin::<String>(
            "test-binconf-config_with_name-string-bin",
            Some("test-config.bin"),
            Config,
            false,
        )
        .unwrap();
        assert_eq!(config, String::from(""));

        let test_config = TestConfig {
            test: String::from("test"),
            test_vec: vec![1, 2, 3, 4, 5],
        };

        let config: TestConfig = load_bin(
            "test-binconf-config_with_name-struct-bin",
            Some("test-config.bin"),
            Config,
            false,
        )
        .unwrap();
        assert_eq!(config, TestConfig::default());

        store_bin(
            "test-binconf-config_with_name-struct-bin",
            Some("test-config.bin"),
            Config,
            &test_config,
        )
        .unwrap();
        let config: TestConfig = load_bin(
            "test-binconf-config_with_name-struct-bin",
            Some("test-config.bin"),
            Config,
            false,
        )
        .unwrap();
        assert_eq!(config, test_config);
    }

    #[test]
    fn returns_error_on_invalid_config_bin() {
        let data = TestConfig {
            test: String::from("test"),
            test_vec: vec![1, 2],
        };

        store_bin(
            "test-binconf-returns_error_on_invalid_config-bin",
            None,
            Config,
            &data,
        )
        .unwrap();
        let config = load_bin::<TestConfig2>(
            "test-binconf-returns_error_on_invalid_config-bin",
            None,
            Config,
            false,
        );

        assert!(config.is_err());
    }

    #[test]
    fn save_config_user_config_bin() {
        let data = TestConfig {
            test: String::from("test"),
            test_vec: vec![1, 2, 3, 4, 5],
        };

        store_bin(
            "test-binconf-save_config_user_config-bin",
            None,
            Config,
            &data,
        )
        .unwrap();
        let config: TestConfig = load_bin(
            "test-binconf-save_config_user_config-bin",
            None,
            Config,
            false,
        )
        .unwrap();
        assert_eq!(config, data);
    }

    #[test]
    fn save_config_user_cache_bin() {
        let data = TestConfig {
            test: String::from("test"),
            test_vec: vec![1, 2, 3, 4, 5],
        };

        store_bin(
            "test-binconf-save_config_user_cache-bin",
            None,
            Cache,
            &data,
        )
        .unwrap();
        let config: TestConfig = load_bin(
            "test-binconf-save_config_user_cache-bin",
            None,
            Cache,
            false,
        )
        .unwrap();
        assert_eq!(config, data);
    }

    #[test]
    fn save_config_user_local_data_bin() {
        let data = TestConfig {
            test: String::from("test"),
            test_vec: vec![1, 2, 3, 4, 5],
        };

        store_bin(
            "test-binconf-save_config_user_local_data-bin",
            None,
            LocalData,
            &data,
        )
        .unwrap();
        let config: TestConfig = load_bin(
            "test-binconf-save_config_user_local_data-bin",
            None,
            LocalData,
            false,
        )
        .unwrap();
        assert_eq!(config, data);
    }

    #[test]
    fn save_config_user_cwd_bin() {
        let data = TestConfig {
            test: String::from("test"),
            test_vec: vec![1, 2, 3, 4, 5],
        };

        store_bin("test-binconf-save_config_user_cwd-bin", None, Cwd, &data).unwrap();
        let config: TestConfig =
            load_bin("test-binconf-save_config_user_cwd-bin", None, Cwd, false).unwrap();
        assert_eq!(config, data);
    }

    #[test]
    fn load_config_fallback() {
        let data = String::from("test of corrupted data");

        store_bin("test-binconf-load_config_fallback-bin", None, Config, &data).unwrap();

        assert_eq!(
            load_bin::<String>("test-binconf-load_config_fallback-bin", None, Config, false)
                .unwrap(),
            data
        );

        // Corrupt data
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .read(true)
            .open(
                get_configuration_path(
                    "test-binconf-load_config_fallback-bin",
                    None,
                    ConfigType::Bin,
                    Config,
                )
                .unwrap(),
            )
            .unwrap();

        let mut new_data = Vec::new();
        file.read_to_end(&mut new_data).unwrap();

        if let Some(last) = new_data.last_mut() {
            // Change last byte to char `o`
            *last = 0x6F;
        }

        file.seek(std::io::SeekFrom::Start(0)).unwrap();
        file.write_all(&new_data[..]).unwrap();

        // Read corrupted data without fallback (should fail)
        assert!(
            load_bin::<String>("test-binconf-load_config_fallback-bin", None, Config, false)
                .is_err()
        );

        // Read corrupted data with fallback (should succeed)
        let corrupted_data = load_bin_skip_check::<String>(
            "test-binconf-load_config_fallback-bin",
            None,
            Config,
            true,
        )
        .unwrap();

        assert_eq!(corrupted_data, "test of corrupted dato");
    }
}