serini 0.3.0

A serde-based INI file parser for Rust
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! # serini
//!
//! A serde-based INI file parser that supports serialization and deserialization of Rust structs.
//!
//! ## Features
//!
//! - **Serialize Rust structs to INI format** - Nested structs become sections
//! - **Deserialize INI files to Rust structs** - Type-safe parsing with automatic type conversion
//! - **Option handling** - [`None`][Option] values are serialized as commented lines
//! - **Escape sequences** - Properly handles special characters in values
//! - **Section support** - Nested structs are automatically converted to INI sections
//! - **Type safety** - Leverages serde's type system for safe conversions
//!
//! ## Quick Start
//!
//! Add this to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! serde = { version = "1.0", features = ["derive"] }
//! serini = "0.1"
//! ```
//!
//! ## Basic Example
//!
//! ```rust
//! use serde::{Deserialize, Serialize};
//! use serini::{from_str, to_string};
//!
//! #[derive(Debug, Serialize, Deserialize, PartialEq)]
//! struct Config {
//!     name: String,
//!     port: u16,
//!     #[serde(skip_serializing_if = "Option::is_none")]
//!     debug: Option<usize>,
//!     database: Database,
//! }
//!
//! #[derive(Debug, Serialize, Deserialize, PartialEq)]
//! struct Database {
//!     host: String,
//!     port: u16,
//!     username: String,
//!     password: Option<String>,
//! }
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let config = Config {
//!         name: "My Application".to_string(),
//!         port: 8080,
//!         debug: None,
//!         database: Database {
//!             host: "localhost".to_string(),
//!             port: 5432,
//!             username: "admin".to_string(),
//!             password: None,
//!         },
//!     };
//!
//!     // Serialize to INI
//!     let ini_string = to_string(&config)?;
//!     println!("{}", ini_string);
//!     // Output:
//!     // name = My Application
//!     // port = 8080
//!     //
//!     // [database]
//!     // host = localhost
//!     // port = 5432
//!     // username = admin
//!     // ; password =
//!
//!     // Deserialize from INI
//!     let parsed: Config = from_str(&ini_string)?;
//!     assert_eq!(config, parsed);
//!
//!     Ok(())
//! }
//! ```
//!
//! ## Section Handling
//!
//! Nested structs automatically become INI sections:
//!
//! ```rust
//! use serde::{Deserialize, Serialize};
//! use serini::to_string;
//!
//! #[derive(Serialize, Deserialize)]
//! struct ServerConfig {
//!     general: General,
//!     http: HttpConfig,
//!     database: DatabaseConfig,
//! }
//!
//! #[derive(Serialize, Deserialize)]
//! struct General {
//!     name: String,
//!     debug: bool,
//! }
//!
//! #[derive(Serialize, Deserialize)]
//! struct HttpConfig {
//!     host: String,
//!     port: u16,
//!     timeout: u64,
//! }
//!
//! #[derive(Serialize, Deserialize)]
//! struct DatabaseConfig {
//!     url: String,
//!     max_connections: u32,
//! }
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let config = ServerConfig {
//!     general: General {
//!         name: "MyServer".to_string(),
//!         debug: false,
//!     },
//!     http: HttpConfig {
//!         host: "0.0.0.0".to_string(),
//!         port: 8080,
//!         timeout: 30,
//!     },
//!     database: DatabaseConfig {
//!         url: "postgres://localhost/mydb".to_string(),
//!         max_connections: 100,
//!     },
//! };
//!
//! let ini = to_string(&config)?;
//! # Ok(())
//! # }
//! ```
//!
//! Produces:
//!
//! ```ini
//! [general]
//! name = MyServer
//! debug = false
//!
//! [http]
//! host = 0.0.0.0
//! port = 8080
//! timeout = 30
//!
//! [database]
//! url = postgres://localhost/mydb
//! max_connections = 100
//! ```
//!
//! ## Option Handling
//!
//! `Option<T>` fields are handled specially:
//! - `Some(value)` is serialized normally
//! - `None` is serialized as a commented line
//!
//! ```rust
//! use serde::{Deserialize, Serialize};
//! use serini::to_string;
//!
//! #[derive(Serialize, Deserialize)]
//! struct User {
//!     username: String,
//!     email: Option<String>,
//!     age: Option<u32>,
//! }
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let user = User {
//!     username: "alice".to_string(),
//!     email: Some("alice@example.com".to_string()),
//!     age: None,
//! };
//!
//! let ini = to_string(&user)?;
//! # Ok(())
//! # }
//! ```
//!
//! Produces:
//!
//! ```ini
//! username = alice
//! email = alice@example.com
//! ; age =
//! ```
//!
//! ## Escape Sequences
//!
//! Special characters in values are automatically escaped:
//!
//! | Character | Escaped |
//! |-----------|---------|
//! | `\` | `\\` |
//! | `\n` | `\n` |
//! | `\r` | `\r` |
//! | `\t` | `\t` |
//! | `"` | `\"` |
//! | `;` | `\;` |
//! | `#` | `\#` |
//!
//! ```rust
//! use serde::{Deserialize, Serialize};
//! use serini::{from_str, to_string};
//!
//! #[derive(Serialize, Deserialize, Debug, PartialEq)]
//! struct Message {
//!     text: String,
//!     note: String,
//! }
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let msg = Message {
//!     text: "Hello\nWorld!".to_string(),
//!     note: "This has \"quotes\" and a ; semicolon".to_string(),
//! };
//!
//! let ini = to_string(&msg)?;
//! // text = Hello\nWorld!
//! // note = This has \"quotes\" and a \; semicolon
//!
//! let parsed: Message = from_str(&ini)?;
//! assert_eq!(msg, parsed);
//! # Ok(())
//! # }
//! ```
//!
//! ## Supported Types
//!
//! The following types are supported for serialization and deserialization:
//!
//! - **Integers**: `i8`, `i16`, `i32`, `i64`, `u8`, `u16`, `u32`, `u64`
//! - **Floats**: `f32`, `f64`
//! - **Boolean**: `bool` (serialized as `true`/`false`)
//! - **String**: `String`, `&str`
//! - **Option**: `Option<T>` where `T` is a supported type
//! - **Structs**: Custom structs with named fields
//!
//! ## Limitations
//!
//! The following serde types are **not** supported:
//!
//! - Sequences (Vec, arrays, etc.)
//! - Tuples and tuple structs
//! - Enums with variants
//! - Maps (HashMap, BTreeMap, etc.)
//! - Unit structs
//!
//! Attempting to serialize or deserialize these types will result in an error.
//!
//! ## Error Handling
//!
//! This crate uses an`Error` type using [thiserror] to provide granular error variants:
//!
//! ```rust
//! use serde::{Deserialize, Serialize};
//! use serini::{from_str, Error};
//!
//! #[derive(Deserialize)]
//! struct Config {
//!     port: u16,
//! }
//!
//! # fn main() {
//! let ini = "port = not_a_number";
//!
//! match from_str::<Config>(ini) {
//!     Ok(_) => println!("Parsed successfully"),
//!     Err(Error::InvalidValue { typ, value }) => {
//!         println!("Invalid {} value: {}", typ, value);
//!     }
//!     Err(e) => println!("Error: {}", e),
//! }
//! # }
//! ```
//!
//! ## API Reference
//!
//! ### Functions
//!
//! #### [`to_string`]
//!
//! Serializes a value to an INI string.
//!
//! #### [`from_str`]
//!
//! Deserializes an INI string to a value.
//!
//! ## Advanced Example
//!
//! Here's a complete example showing various features:
//!
//! ```rust
//! use serde::{Deserialize, Serialize};
//! use serini::{from_str, to_string};
//!
//! #[derive(Debug, Serialize, Deserialize, PartialEq)]
//! struct AppConfig {
//!     #[serde(rename = "app-name")]
//!     app_name: String,
//!     version: String,
//!     debug_mode: bool,
//!     max_connections: u32,
//!     timeout_seconds: Option<u64>,
//!     
//!     server: ServerSettings,
//!     database: DatabaseSettings,
//!     cache: Option<CacheSettings>,
//! }
//!
//! #[derive(Debug, Serialize, Deserialize, PartialEq)]
//! struct ServerSettings {
//!     host: String,
//!     port: u16,
//!     #[serde(rename = "use-tls")]
//!     use_tls: bool,
//!     certificate_path: Option<String>,
//! }
//!
//! #[derive(Debug, Serialize, Deserialize, PartialEq)]
//! struct DatabaseSettings {
//!     #[serde(rename = "connection-string")]
//!     connection_string: String,
//!     pool_size: u32,
//!     timeout: u32,
//! }
//!
//! #[derive(Debug, Serialize, Deserialize, PartialEq)]
//! struct CacheSettings {
//!     backend: String,
//!     ttl_seconds: u64,
//!     max_entries: u64,
//! }
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create a configuration
//! let config = AppConfig {
//!     app_name: "MyApp".to_string(),
//!     version: "1.0.0".to_string(),
//!     debug_mode: false,
//!     max_connections: 100,
//!     timeout_seconds: Some(30),
//!     
//!     server: ServerSettings {
//!         host: "0.0.0.0".to_string(),
//!         port: 8443,
//!         use_tls: true,
//!         certificate_path: Some("/etc/ssl/cert.pem".to_string()),
//!     },
//!     
//!     database: DatabaseSettings {
//!         connection_string: "postgres://user:pass@localhost/mydb".to_string(),
//!         pool_size: 20,
//!         timeout: 5,
//!     },
//!     
//!     cache: None,
//! };
//!
//! // Serialize to INI
//! let ini_string = to_string(&config)?;
//! println!("Generated INI:\n{}", ini_string);
//!
//! // Parse it back
//! let parsed: AppConfig = from_str(&ini_string)?;
//! assert_eq!(config, parsed);
//!
//! // Example INI file that could be parsed
//! let ini_file = r#"
//! app-name = MyApp
//! version = 1.0.0
//! debug_mode = false
//! max_connections = 100
//! timeout_seconds = 30
//!
//! [server]
//! host = 0.0.0.0
//! port = 8443
//! use-tls = true
//! certificate_path = /etc/ssl/cert.pem
//!
//! [database]
//! connection-string = postgres://user:pass@localhost/mydb
//! pool_size = 20
//! timeout = 5
//!
//! ; cache =
//! "#;
//!
//! let from_file: AppConfig = from_str(ini_file)?;
//! assert_eq!(config, from_file);
//! # Ok(())
//! # }
//! ```
//!
//! ## License
//!
//! This project is licensed under the MIT License - see the LICENSE file for details.

pub mod de;
pub mod error;
pub mod ser;

pub use de::from_str;
pub use error::Error;
pub use ser::to_string;

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    mod nested {
        use super::*;

        #[derive(Debug, Serialize, Deserialize, PartialEq)]
        struct Config {
            name: String,
            port: u16,
            enabled: bool,
            description: Option<String>,
            database: Database,
            cache: Cache,
        }

        #[derive(Debug, Serialize, Deserialize, PartialEq)]
        struct Database {
            host: String,
            port: u16,
            username: String,
            password: Option<String>,
        }

        #[derive(Debug, Serialize, Deserialize, PartialEq)]
        struct Cache {
            ttl: i32,
            max_size: Option<u64>,
        }

        #[test]
        fn test_serialize() {
            let config = Config {
                name: "My App".to_string(),
                port: 8080,
                enabled: true,
                description: Some("A test application".to_string()),
                database: Database {
                    host: "localhost".to_string(),
                    port: 5432,
                    username: "admin".to_string(),
                    password: None,
                },
                cache: Cache {
                    ttl: 300,
                    max_size: Some(1000000),
                },
            };

            let ini_str = to_string(&config).unwrap();
            println!("{}", ini_str);

            // Root level fields
            assert!(ini_str.contains("name = My App"));
            assert!(ini_str.contains("port = 8080"));
            assert!(ini_str.contains("enabled = true"));
            assert!(ini_str.contains("description = A test application"));

            // Database section
            assert!(ini_str.contains("[database]"));
            assert!(ini_str.contains("host = localhost"));
            assert!(ini_str.contains("; password ="));

            // Cache section
            assert!(ini_str.contains("[cache]"));
            assert!(ini_str.contains("ttl = 300"));
            assert!(ini_str.contains("max_size = 1000000"));

            // Verify proper structure
            let lines: Vec<&str> = ini_str.lines().collect();
            let db_idx = lines.iter().position(|&l| l == "[database]").unwrap();
            let cache_idx = lines.iter().position(|&l| l == "[cache]").unwrap();
            assert!(db_idx > 0); // Database section comes after root fields
            assert!(cache_idx > db_idx); // Cache section comes after database
        }

        #[test]
        fn test_serialize_skip_none() {
            #[derive(Debug, Serialize)]
            struct Config {
                #[serde(skip_serializing_if = "Option::is_none")]
                is_hidden: Option<bool>,
                is_none: Option<bool>,
                #[serde(skip_serializing_if = "Option::is_none")]
                is_some: Option<bool>,
            }

            let config = Config {
                is_hidden: None,
                is_none: None,
                is_some: Some(true),
            };

            let ini = to_string(&config).unwrap();
            let mut lines = ini.lines();

            assert_eq!(lines.next(), Some("; is_none = "));
            assert_eq!(lines.next(), Some("is_some = true"));
            assert!(lines.next().is_none());
        }

        #[test]
        fn test_deserialize_nested() {
            let ini_str = r#"
    name = My App
    port = 8080
    enabled = true
    description = A test application
    
    [database]
    host = localhost
    port = 5432
    username = admin
    
    [cache]
    ttl = 300
    max_size = 1000000
    "#;

            let config: Config = from_str(ini_str).unwrap();

            assert_eq!(config.name, "My App");
            assert_eq!(config.port, 8080);
            assert!(config.enabled);
            assert_eq!(config.description, Some("A test application".to_string()));
            assert_eq!(config.database.host, "localhost");
            assert_eq!(config.database.port, 5432);
            assert_eq!(config.database.username, "admin");
            assert_eq!(config.database.password, None);
            assert_eq!(config.cache.ttl, 300);
            assert_eq!(config.cache.max_size, Some(1000000));
        }
    }

    mod boxed {
        use super::*;

        #[derive(Debug, Serialize, Deserialize, PartialEq)]
        struct Config {
            speed: f32,
            anime: Option<Box<Config>>,
            movie: Option<Box<Config>>,
        }

        #[test]
        fn test_serialize_boxed() {
            let config = Config {
                speed: 1.0,
                anime: Some(Box::new(Config {
                    speed: 1.5,
                    anime: None,
                    movie: None,
                })),
                movie: Some(Box::new(Config {
                    speed: 2.0,
                    anime: None,
                    movie: None,
                })),
            };

            let ini_str = to_string(&config).unwrap();
            println!("{}", ini_str);

            // Root level fields
            assert!(ini_str.contains("speed = 1"));
            assert!(ini_str.contains("[anime]"));
            assert!(ini_str.contains("[movie]"));

            // Verify proper structure
            let lines: Vec<&str> = ini_str.lines().collect();
            let anime_idx = lines.iter().position(|&l| l == "[anime]").unwrap();
            let movie_idx = lines.iter().position(|&l| l == "[movie]").unwrap();
            assert!(anime_idx > 0); // anime section comes after root fields
            assert!(movie_idx > anime_idx); // movie section comes after anime
            assert_eq!("speed = 1.5", lines[anime_idx + 1]);
            assert_eq!("speed = 2", lines[movie_idx + 1]);
        }

        #[test]
        fn test_deserialize_boxed() {
            let ini_str = r#"
    speed = 1
    
    [anime]
    speed = 1.5
    
    [movie]
    speed = 2
    "#;

            let config: Config = from_str(ini_str).unwrap();
            let anime = config.anime.unwrap();
            let movie = config.movie.unwrap();

            assert_eq!(config.speed, 1.0);
            assert_eq!(anime.speed, 1.5);
            assert_eq!(movie.speed, 2.0);
            assert!(anime.anime.is_none());
            assert!(anime.movie.is_none());
            assert!(movie.anime.is_none());
            assert!(movie.movie.is_none());
        }
    }

    #[test]
    fn test_escaping() {
        #[derive(Debug, Serialize, Deserialize, PartialEq)]
        struct EscapeTest {
            multiline: String,
            special_chars: String,
        }

        let test = EscapeTest {
            multiline: "Line 1\nLine 2\tTabbed".to_string(),
            special_chars: "Value with \"quotes\" and ; semicolon # hash".to_string(),
        };

        let ini_str = to_string(&test).unwrap();
        assert!(ini_str.contains(r"Line 1\nLine 2\tTabbed"));
        assert!(ini_str.contains(r#"Value with \"quotes\" and \; semicolon \# hash"#));

        let deserialized: EscapeTest = from_str(&ini_str).unwrap();
        assert_eq!(test, deserialized);
    }

    #[test]
    fn roundtrip_backslashes() {
        #[derive(Debug, Serialize, Deserialize, PartialEq)]
        struct RoundtripTest {
            bs_bs: String,
            bs_n: String,
            bs_r: String,
            bs_t: String,
            bs_dquot: String,
            bs_semi: String,
            bs_octo: String,
        }

        let bs_bs = r#"\\"#;
        let bs_n = r#"\n"#;
        let bs_r = r#"\r"#;
        let bs_t = r#"\t"#;
        let bs_dquot = r#"\""#;
        let bs_semi = r#"\;"#;
        let bs_octo = r#"\#"#;

        let test = RoundtripTest {
            bs_bs: bs_bs.to_string(),
            bs_n: bs_n.to_string(),
            bs_r: bs_r.to_string(),
            bs_t: bs_t.to_string(),
            bs_dquot: bs_dquot.to_string(),
            bs_semi: bs_semi.to_string(),
            bs_octo: bs_octo.to_string(),
        };

        let ini_str = to_string(&test).unwrap();
        let deserialized: RoundtripTest = from_str(&ini_str).unwrap();
        assert_eq!(test, deserialized)
    }
}