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
use crate::stringifier::Stringifier;
use crate::toml::auto_correct::AutoCorrect;
use crate::{ArrayOfTable, Level, Log, Opt, Table, NEW_LINE};

/// Kind of table.  
/// テーブルの種類。  
#[derive(Clone)]
pub enum KindOfTable {
    /// Sub table.  
    /// ただのサブ・テーブル。
    Table(Table),
    /// Array of table.  
    /// テーブルの配列。
    ArrayOfTable(ArrayOfTable),
}

#[derive(Clone)]
pub struct InternalTable {
    /// Base name.
    /// `B` in `[A.B]`.
    /// `a=1&b=2` in `["a=1&b=2"]`.
    pub base_name: String,
    /// Clone table.
    pub table: KindOfTable,
}
impl InternalTable {
    pub fn from_table(table: &Table) -> Self {
        InternalTable {
            base_name: table.base_name.to_string(),
            table: KindOfTable::Table(table.clone()),
        }
    }
    pub fn from_sub_table(name: &str, sub_table: &Table) -> Self {
        InternalTable {
            base_name: name.to_string(),
            table: KindOfTable::Table(sub_table.clone()),
        }
    }
    pub fn from_aot(name: &str, aot: &ArrayOfTable) -> Self {
        InternalTable {
            base_name: name.to_string(),
            table: KindOfTable::ArrayOfTable(aot.clone()),
        }
    }
    /// Example: `Info = "Message"`.
    pub fn create_log_level_kv_pair(table: &Table) -> String {
        let message = if table.message_trailing_newline {
            // There is a trailing newline.
            format!("{}{}", table.message, NEW_LINE)
        } else {
            table.message.to_string()
        };
        format!(
            "{} = {}
",
            table.level,
            Stringifier::format_str_value(&message)
        )
    }
    pub fn stringify(&self) -> String {
        let toml = &mut String::new();
        let indent_spaces = &mut String::new();
        // Write as TOML.
        // Recursive.
        InternalTable::stringify_sub_table(
            toml,
            indent_spaces,
            None,
            match &self.table {
                KindOfTable::Table(table) => Some(InternalTable::create_log_level_kv_pair(&table)),
                KindOfTable::ArrayOfTable(_) => None,
            },
            &self,
        );
        // End of recursive.
        // New line.
        toml.push_str(
            "
",
        );
        toml.to_string()
    }

    pub fn stringify_sub_table(
        toml: &mut String,
        indent_spaces: &mut String,
        parent: Option<&str>,
        log_level_kv_pair: Option<String>,
        i_table: &InternalTable,
    ) {
        // Table name.
        let path = &format!(
            "{}{}",
            if let Some(parent) = parent {
                format!("{}.", parent).to_string()
            } else {
                "".to_string()
            },
            i_table.base_name
        );
        // Table or Array of table.
        match &i_table.table {
            KindOfTable::Table(k_table) => {
                toml.push_str(&indent_spaces);
                toml.push_str(&format!(
                    "[{}]
",
                    path
                ));
                // Log level message.
                if let Some(log_level_kv_pair) = log_level_kv_pair {
                    toml.push_str(&log_level_kv_pair);
                }
                // Sorted map.
                if let Some(sorted_map) = &k_table.sorted_map {
                    for (k2, formatted_v) in sorted_map {
                        toml.push_str(&indent_spaces);
                        toml.push_str(&format!(
                            "{} = {}
",
                            k2, formatted_v
                        ));
                    }
                }
                // Sub tables.
                if let Some(sub_tables) = &k_table.sub_tables {
                    indent_spaces.push_str("  ");
                    for (_k1, sub_i_table) in sub_tables {
                        InternalTable::stringify_sub_table(
                            toml,
                            indent_spaces,
                            Some(path),
                            None,
                            sub_i_table,
                        );
                    }
                    indent_spaces.pop();
                    indent_spaces.pop();
                }
            }
            KindOfTable::ArrayOfTable(k_aot) => {
                for (i, sibling_table) in k_aot.tables.iter().enumerate() {
                    // Table header.
                    toml.push_str(&indent_spaces);
                    toml.push_str(&format!(
                        "[[{}]]
",
                        path
                    ));
                    // Sorted map.
                    if let Some(sorted_map) = &sibling_table.sorted_map {
                        for (k2, formatted_v) in sorted_map {
                            toml.push_str(&indent_spaces);
                            toml.push_str(&format!(
                                "{} = {}
",
                                k2, formatted_v
                            ));
                        }
                    }
                    // Sub tables.
                    if let Some(sub_tables) = &sibling_table.sub_tables {
                        indent_spaces.push_str("  ");
                        for (_k1, sub_i_table) in sub_tables {
                            InternalTable::stringify_sub_table(
                                toml,
                                indent_spaces,
                                Some(&format!("{}.{}", path, i)),
                                None,
                                sub_i_table,
                            );
                        }
                        indent_spaces.pop();
                        indent_spaces.pop();
                    }
                }
            }
        }
    }
}

impl Default for ArrayOfTable {
    fn default() -> Self {
        ArrayOfTable { tables: Vec::new() }
    }
}
impl ArrayOfTable {
    /// Push a table.  
    /// テーブルを追加します。
    pub fn table(&mut self, table: &Table) -> &mut Self {
        self.tables.push(table.clone());
        self
    }
}

impl Default for Table {
    fn default() -> Self {
        Table {
            // The base name is added when writing the log.
            // ログを書くときにベース名が付きます。
            base_name: "".to_string(),
            level: Level::Trace,
            message: "".to_string(),
            message_trailing_newline: false,
            sorted_map: None,
            sub_tables: None,
        }
    }
}
impl Table {
    /*
    pub fn convert_multi_byte_string(value: &str) -> String {
        let bytes: &[u8] = value.as_bytes();
        // convert bytes => str
        // let res = bytes.iter().map(|&s| s as char).collect::<String>();
        let converted: String = if let Ok(converted) = String::from_utf8(bytes.to_vec()) {
            converted
        } else {
            value.to_string()
        };
        println!(
            "Value=|{}|{}| Converted=|{}|{}|",
            value,
            value.len(),
            converted,
            converted.len()
        );
        converted
    }
    */
    /// Insert boolean value.  
    /// 真理値を挿入します。  
    ///
    /// # Arguments
    ///
    /// * `key` - A key.  
    ///             キー。  
    /// * `value` - A value.  
    ///             値。  
    ///
    /// # Returns
    ///
    /// Table.  
    /// テーブル。  
    pub fn bool<'a>(&'a mut self, key: &'a str, value: bool) -> &'a mut Self {
        let mut old = None;
        self.get_sorted_map(|sorted_map| {
            old = sorted_map.insert(
                AutoCorrect::correct_key(key),
                // Message.
                value.to_string(),
            );
        });

        if let Some(old) = old {
            Table::print_already_use(key, &old, &value.to_string());
        }

        self
    }
    /// Insert character value.  
    /// 文字を挿入します。  
    ///
    /// # Arguments
    ///
    /// * `key` - A key.  
    ///             キー。  
    /// * `value` - A value.  
    ///             値。  
    ///
    /// # Returns
    ///
    /// Table.  
    /// テーブル。  
    pub fn char<'a>(&'a mut self, key: &'a str, value: char) -> &'a mut Self {
        let mut old = None;
        self.get_sorted_map(|sorted_map| {
            old = sorted_map.insert(
                // Log detail level.
                AutoCorrect::correct_key(key),
                // Message.
                Stringifier::format_str_value(&value.to_string()).to_string(),
            );
        });

        if let Some(old) = old {
            Table::print_already_use(key, &old, &value.to_string());
        }

        self
    }
    /// Insert float value.  
    /// 浮動小数点数を挿入します。  
    ///
    /// # Arguments
    ///
    /// * `key` - A key.  
    ///             キー。  
    /// * `value` - A value.  
    ///             値。  
    ///
    /// # Returns
    ///
    /// Table.  
    /// テーブル。  
    pub fn float<'a>(&'a mut self, key: &'a str, value: f64) -> &'a mut Self {
        let mut old = None;
        self.get_sorted_map(|sorted_map| {
            old = sorted_map.insert(
                // Log detail level.
                AutoCorrect::correct_key(key),
                // Message.
                value.to_string(),
            );
        });

        if let Some(old) = old {
            Table::print_already_use(key, &old, &value.to_string());
        }

        self
    }
    /// Insert integer value.  
    /// 符号付き整数を挿入します。  
    ///
    /// # Arguments
    ///
    /// * `key` - A key.  
    ///             キー。  
    /// * `value` - A value.  
    ///             値。  
    ///
    /// # Returns
    ///
    /// Table.  
    /// テーブル。  
    pub fn int<'a>(&'a mut self, key: &'a str, value: i128) -> &'a mut Self {
        let mut old = None;
        self.get_sorted_map(|sorted_map| {
            old = sorted_map.insert(
                // Log detail level.
                AutoCorrect::correct_key(key),
                // Message.
                value.to_string(),
            );
        });

        if let Some(old) = old {
            Table::print_already_use(key, &old, &value.to_string());
        }

        self
    }
    /// Insert pointer size integer value.  
    /// 符号付きポインター・サイズ整数を挿入します。  
    ///
    /// # Arguments
    ///
    /// * `key` - A key.  
    ///             キー。  
    /// * `value` - A value.  
    ///             値。  
    ///
    /// # Returns
    ///
    /// Table.  
    /// テーブル。  
    pub fn isize<'a>(&'a mut self, key: &'a str, value: isize) -> &'a mut Self {
        let mut old = None;
        self.get_sorted_map(|sorted_map| {
            old = sorted_map.insert(
                // Log detail level.
                AutoCorrect::correct_key(key),
                // Message.
                value.to_string(),
            );
        });

        if let Some(old) = old {
            Table::print_already_use(key, &old, &value.to_string());
        }

        self
    }
    /// Insert literal string value. Do not put in quotes.  
    /// リテラル文字列を挿入します。引用符で挟みません。  
    ///
    /// # Arguments
    ///
    /// * `key` - A key.  
    ///             キー。  
    /// * `value` - A value.  
    ///             値。  
    ///
    /// # Returns
    ///
    /// Table.  
    /// テーブル。  
    pub fn literal<'a>(&'a mut self, key: &'a str, value: &str) -> &'a mut Self {
        let mut old = None;
        self.get_sorted_map(|sorted_map| {
            old = sorted_map.insert(
                // Log detail level.
                AutoCorrect::correct_key(key),
                // Message.
                value.to_string(),
            );
        });

        if let Some(old) = old {
            Table::print_already_use(key, &old, &value.to_string());
        }

        self
    }
    /// Insert string value.  
    /// 文字列を挿入します。  
    ///
    /// # Arguments
    ///
    /// * `key` - A key.  
    ///             キー。  
    /// * `value` - A value.  
    ///             値。  
    ///
    /// # Returns
    ///
    /// Table.  
    /// テーブル。  
    pub fn str<'a>(&'a mut self, key: &'a str, value: &str) -> &'a mut Self {
        let mut old = None;
        self.get_sorted_map(|sorted_map| {
            old = sorted_map.insert(
                // Log detail level.
                AutoCorrect::correct_key(key),
                // Message.
                Stringifier::format_str_value(value).to_string(),
            );
        });

        if let Some(old) = old {
            Table::print_already_use(key, &old, &value.to_string());
        }

        self
    }
    /// Insert table recursively.  
    /// テーブルを再帰的に挿入します。  
    ///
    /// # Arguments
    ///
    /// * `base_name` - Sub table name.  
    ///                 サブ・テーブル名。  
    /// * `table` - Sub table.  
    ///             サブ・テーブル。  
    ///
    /// # Returns
    ///
    /// Main table.  
    /// メインの方のテーブル。  
    pub fn sub_t<'a>(&'a mut self, base_name: &str, sub_table: &Table) -> &'a mut Self {
        let mut old = None;
        self.get_sub_tables(|sub_i_tables| {
            old = sub_i_tables.insert(
                // Base name.
                AutoCorrect::correct_key(base_name),
                // Message.
                InternalTable::from_sub_table(&AutoCorrect::correct_key(base_name), &sub_table),
            );
        });

        if let Some(_) = old {
            Table::print_already_use(
                &AutoCorrect::correct_key(base_name),
                &"...Omitted...",
                &"...Omitted...",
            );
        }

        self
    }
    /// Insert array of table recursively.  
    /// テーブルの配列を再帰的に挿入します。  
    ///
    /// # Arguments
    ///
    /// * `base_name` - Array of table name.  
    ///                 テーブルの配列名。  
    /// * `table` - Array of table.  
    ///             テーブルの配列。  
    ///
    /// # Returns
    ///
    /// Main table.  
    /// メインの方のテーブル。  
    pub fn sub_aot<'a>(&'a mut self, base_name: &str, aot: &ArrayOfTable) -> &'a mut Self {
        let mut old = None;
        self.get_sub_tables(|sub_i_tables| {
            old = sub_i_tables.insert(
                // Base name.
                AutoCorrect::correct_key(base_name),
                // Message.
                InternalTable::from_aot(&AutoCorrect::correct_key(base_name), &aot),
            );
        });

        if let Some(_) = old {
            Table::print_already_use(
                &AutoCorrect::correct_key(base_name),
                &"...Omitted...",
                &"...Omitted...",
            );
        }

        self
    }
    /// Insert unsigned integer value.  
    /// 符号無し整数を挿入します。  
    ///
    /// # Arguments
    ///
    /// * `key` - A key.  
    ///             キー。  
    /// * `value` - A value.  
    ///             値。  
    ///
    /// # Returns
    ///
    /// Table.  
    /// テーブル。  
    pub fn uint<'a>(&'a mut self, key: &'a str, value: u128) -> &'a mut Self {
        let mut old = None;
        self.get_sorted_map(|sorted_map| {
            old = sorted_map.insert(
                // Log detail level.
                AutoCorrect::correct_key(key),
                // Message.
                value.to_string(),
            );
        });

        if let Some(old) = old {
            Table::print_already_use(key, &old, &value.to_string());
        }

        self
    }
    /// Insert unsigned pointer size integer value.  
    /// 符号無しポインター・サイズ整数を挿入します。  
    ///
    /// # Arguments
    ///
    /// * `key` - A key.  
    ///             キー。  
    /// * `value` - A value.  
    ///             値。  
    ///
    /// # Returns
    ///
    /// Table.  
    /// テーブル。  
    pub fn usize<'a>(&'a mut self, key: &'a str, value: usize) -> &'a mut Self {
        let mut old = None;
        self.get_sorted_map(|sorted_map| {
            old = sorted_map.insert(
                // Log detail level.
                AutoCorrect::correct_key(key),
                // Message.
                value.to_string(),
            );
        });

        if let Some(old) = old {
            Table::print_already_use(key, &old, &value.to_string());
        }

        self
    }
    /// Key duplicate message.
    /// キーの重複メッセージ。
    fn print_already_use(key: &str, old: &str, value: &str) {
        if let Ok(opt) = Log::get_opt() {
            match opt {
                Opt::BeginnersSupport | Opt::Development => {
                    println!(
                        "casual_logger   | |{}| is already use. |{}| is is overwritten by |{}|.",
                        key, old, value
                    );
                }
                _ => {} // Ignored it.
            }
        }
    }
}