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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use internal::stringpool::StringRef;
use internal::value::{Value, ValueRef};
use std::{fmt, i16, i32};
use std::io::{self, Read, Write};
use std::str;

// ========================================================================= //

// Constants for the _Columns table's Type column bitfield:
const COL_FIELD_SIZE_MASK: i32 = 0xff;
const COL_LOCALIZABLE_BIT: i32 = 0x200;
const COL_STRING_BIT: i32 = 0x800;
const COL_NULLABLE_BIT: i32 = 0x1000;
const COL_PRIMARY_KEY_BIT: i32 = 0x2000;
// I haven't yet been able to find any clear documentation on what these two
// bits in the column type bitfield do, so both the constant names and the way
// this library handles them are laregly speculative right now:
const COL_VALID_BIT: i32 = 0x100;
const COL_NONBINARY_BIT: i32 = 0x400;

// ========================================================================= //

/// A database column data type.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ColumnType {
    /// A 16-bit integer.
    Int16,
    /// A 32-bit integer.
    Int32,
    /// A string, with the specified maximum length (or zero for no max).
    Str(usize),
}

impl ColumnType {
    fn from_bitfield(type_bits: i32) -> io::Result<ColumnType> {
        let field_size = (type_bits & COL_FIELD_SIZE_MASK) as usize;
        if (type_bits & COL_STRING_BIT) != 0 {
            Ok(ColumnType::Str(field_size))
        } else if field_size == 2 {
            Ok(ColumnType::Int16)
        } else if field_size == 4 {
            Ok(ColumnType::Int32)
        } else {
            invalid_data!("Invalid field size for integer column ({})",
                          field_size);
        }
    }

    fn bitfield(&self) -> i32 {
        match *self {
            ColumnType::Int16 => 0x2,
            ColumnType::Int32 => 0x4,
            ColumnType::Str(max_len) => COL_STRING_BIT | (max_len as i32),
        }
    }

    pub(crate) fn read_value<R: Read>(&self, reader: &mut R,
                                      long_string_refs: bool)
                                      -> io::Result<ValueRef> {
        match *self {
            ColumnType::Int16 => {
                match reader.read_i16::<LittleEndian>()? {
                    0 => Ok(ValueRef::Null),
                    number => Ok(ValueRef::Int((number ^ -0x8000) as i32)),
                }
            }
            ColumnType::Int32 => {
                match reader.read_i32::<LittleEndian>()? {
                    0 => Ok(ValueRef::Null),
                    number => Ok(ValueRef::Int(number ^ -0x8000_0000)),
                }
            }
            ColumnType::Str(_) => {
                match StringRef::read(reader, long_string_refs)? {
                    Some(string_ref) => Ok(ValueRef::Str(string_ref)),
                    None => Ok(ValueRef::Null),
                }
            }
        }
    }

    pub(crate) fn write_value<W: Write>(&self, writer: &mut W,
                                        value_ref: ValueRef,
                                        long_string_refs: bool)
                                        -> io::Result<()> {
        match *self {
            ColumnType::Int16 => {
                match value_ref {
                    ValueRef::Null => writer.write_i16::<LittleEndian>(0)?,
                    ValueRef::Int(number) => {
                        let number = (number as i16) ^ -0x8000;
                        writer.write_i16::<LittleEndian>(number)?
                    }
                    ValueRef::Str(_) => {
                        invalid_input!("Cannot write {:?} to {} column",
                                       value_ref,
                                       self)
                    }
                }
            }
            ColumnType::Int32 => {
                match value_ref {
                    ValueRef::Null => writer.write_i32::<LittleEndian>(0)?,
                    ValueRef::Int(number) => {
                        let number = number ^ -0x8000_0000;
                        writer.write_i32::<LittleEndian>(number)?
                    }
                    ValueRef::Str(_) => {
                        invalid_input!("Cannot write {:?} to {} column",
                                       value_ref,
                                       self)
                    }
                }
            }
            ColumnType::Str(_) => {
                let string_ref = match value_ref {
                    ValueRef::Null => None,
                    ValueRef::Int(_) => {
                        invalid_input!("Cannot write {:?} to {} column",
                                       value_ref,
                                       self)
                    }
                    ValueRef::Str(string_ref) => Some(string_ref),
                };
                StringRef::write(writer, string_ref, long_string_refs)?;
            }
        }
        Ok(())
    }

    pub(crate) fn width(&self, long_string_refs: bool) -> u64 {
        match *self {
            ColumnType::Int16 => 2,
            ColumnType::Int32 => 4,
            ColumnType::Str(_) => if long_string_refs { 3 } else { 2 },
        }
    }
}

impl fmt::Display for ColumnType {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            ColumnType::Int16 => formatter.write_str("SMALLINT"),
            ColumnType::Int32 => formatter.write_str("INTEGER"),
            ColumnType::Str(max_len) => {
                formatter.write_str("VARCHAR(")?;
                max_len.fmt(formatter)?;
                formatter.write_str(")")?;
                Ok(())
            }
        }
    }
}

// ========================================================================= //

/// Indicates the format of a string-typed database column.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ColumnCategory {
    /// An unrestricted text string.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(msi::ColumnCategory::Text.validate("Hello, World!"));
    /// ```
    Text,
    /// A text string containing no lowercase letters.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(msi::ColumnCategory::UpperCase.validate("HELLO, WORLD!"));
    /// assert!(!msi::ColumnCategory::UpperCase.validate("Hello, World!"));
    /// ```
    UpperCase,
    /// A text string containing no uppercase letters.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(msi::ColumnCategory::LowerCase.validate("hello, world!"));
    /// assert!(!msi::ColumnCategory::LowerCase.validate("Hello, World!"));
    /// ```
    LowerCase,
    /// A signed 16-bit integer.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(msi::ColumnCategory::Integer.validate("32767"));
    /// assert!(msi::ColumnCategory::Integer.validate("-47"));
    /// assert!(!msi::ColumnCategory::Integer.validate("40000"));
    /// ```
    Integer,
    /// A signed 32-bit integer.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(msi::ColumnCategory::DoubleInteger.validate("2147483647"));
    /// assert!(msi::ColumnCategory::DoubleInteger.validate("-99999"));
    /// assert!(!msi::ColumnCategory::DoubleInteger.validate("3000000000"));
    /// ```
    DoubleInteger,
    /// A string identifier (such as a table or column name).  May only contain
    /// alphanumerics, underscores, and periods, and must start with a letter
    /// or underscore.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(msi::ColumnCategory::Identifier.validate("HelloWorld"));
    /// assert!(msi::ColumnCategory::Identifier.validate("_99.Bottles"));
    /// assert!(!msi::ColumnCategory::Identifier.validate("3.14159"));
    /// ```
    Identifier,
    /// A string that is either an identifier (see above), or a reference to an
    /// environment variable (which consists of a `%` character followed by an
    /// identifier).
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(msi::ColumnCategory::Property.validate("HelloWorld"));
    /// assert!(msi::ColumnCategory::Property.validate("%HelloWorld"));
    /// assert!(!msi::ColumnCategory::Property.validate("Hello%World"));
    /// ```
    Property,
    /// The name of a file or directory.
    Filename,
    /// A filename that can contain shell glob wildcards.
    WildCardFilename,
    /// A string containing an absolute filepath.
    Path,
    /// A string containing a semicolon-separated list of absolute filepaths.
    Paths,
    /// A string containing an absolute or relative filepath.
    AnyPath,
    /// A string containing either a filename or an identifier.
    DefaultDir,
    /// A string containing a registry path.
    RegPath,
    /// A string containing special formatting escapes, such as environment
    /// variables.
    Formatted,
    /// Unknown.
    KeyFormatted,
    /// Like `Formatted`, but allows additional escapes.
    Template,
    /// A string represeting a boolean predicate.
    Condition,
    /// A hyphenated, uppercase GUID string, enclosed in curly braces.
    Guid,
    /// A string containing a version number.  The string must consist of at
    /// most four period-separated numbers, with each number being at most
    /// 65535.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(msi::ColumnCategory::Version.validate("1"));
    /// assert!(msi::ColumnCategory::Version.validate("1.22"));
    /// assert!(msi::ColumnCategory::Version.validate("1.22.3"));
    /// assert!(msi::ColumnCategory::Version.validate("1.22.3.444"));
    /// assert!(!msi::ColumnCategory::Version.validate("1.99999"));
    /// assert!(!msi::ColumnCategory::Version.validate(".12"));
    /// assert!(!msi::ColumnCategory::Version.validate("1.2.3.4.5"));
    /// ```
    Version,
    /// A string containing a comma-separated list of deciaml language ID
    /// numbers.
    Language,
    /// A string that refers to a binary data stream.
    Binary,
    /// A string that refers to a custom source.
    CustomSource,
    /// A string that refers to a cabinet.
    Cabinet,
    /// A string that refers to a shortcut.
    Shortcut,
    /// A string containing a URL.
    Url,
}

impl ColumnCategory {
    pub(crate) fn all() -> Vec<ColumnCategory> {
        vec![
            ColumnCategory::Text,
            ColumnCategory::UpperCase,
            ColumnCategory::LowerCase,
            ColumnCategory::Integer,
            ColumnCategory::DoubleInteger,
            ColumnCategory::Identifier,
            ColumnCategory::Property,
            ColumnCategory::Filename,
            ColumnCategory::WildCardFilename,
            ColumnCategory::Path,
            ColumnCategory::Paths,
            ColumnCategory::AnyPath,
            ColumnCategory::DefaultDir,
            ColumnCategory::RegPath,
            ColumnCategory::Formatted,
            ColumnCategory::KeyFormatted,
            ColumnCategory::Template,
            ColumnCategory::Condition,
            ColumnCategory::Guid,
            ColumnCategory::Version,
            ColumnCategory::Language,
            ColumnCategory::Binary,
            ColumnCategory::CustomSource,
            ColumnCategory::Cabinet,
            ColumnCategory::Shortcut,
            ColumnCategory::Url,
        ]
    }

    pub(crate) fn as_str(&self) -> &'static str {
        match *self {
            ColumnCategory::AnyPath => "AnyPath",
            ColumnCategory::Binary => "Binary",
            ColumnCategory::Cabinet => "Cabinet",
            ColumnCategory::Condition => "Condition",
            ColumnCategory::CustomSource => "CustomSource",
            ColumnCategory::DefaultDir => "DefaultDir",
            ColumnCategory::DoubleInteger => "DoubleInteger",
            ColumnCategory::Filename => "Filename",
            ColumnCategory::Formatted => "Formatted",
            ColumnCategory::Guid => "GUID",
            ColumnCategory::Identifier => "Identifier",
            ColumnCategory::Integer => "Integer",
            ColumnCategory::KeyFormatted => "KeyFormatted",
            ColumnCategory::Language => "Language",
            ColumnCategory::LowerCase => "LowerCase",
            ColumnCategory::Path => "Path",
            ColumnCategory::Paths => "Paths",
            ColumnCategory::Property => "Property",
            ColumnCategory::RegPath => "RegPath",
            ColumnCategory::Shortcut => "Shortcut",
            ColumnCategory::Template => "Template",
            ColumnCategory::Text => "Text",
            ColumnCategory::UpperCase => "UpperCase",
            ColumnCategory::Url => "URL",
            ColumnCategory::Version => "Version",
            ColumnCategory::WildCardFilename => "WildCardFilename",
        }
    }

    /// Returns true if the given string is valid to store in a database column
    /// with this category.
    pub fn validate(&self, string: &str) -> bool {
        match *self {
            ColumnCategory::Text => true,
            ColumnCategory::UpperCase => {
                !string.chars().any(|chr| chr >= 'a' && chr <= 'z')
            }
            ColumnCategory::LowerCase => {
                !string.chars().any(|chr| chr >= 'A' && chr <= 'Z')
            }
            ColumnCategory::Integer => string.parse::<i16>().is_ok(),
            ColumnCategory::DoubleInteger => string.parse::<i32>().is_ok(),
            ColumnCategory::Identifier => {
                string.starts_with(|chr| {
                                       chr >= 'A' && chr <= 'Z' ||
                                           chr >= 'a' && chr <= 'z' ||
                                           chr == '_'
                                   }) &&
                    !string.contains(|chr| {
                                         !(chr >= 'A' && chr <= 'Z' ||
                                               chr >= 'a' && chr <= 'z' ||
                                               chr >= '0' && chr <= '9' ||
                                               chr == '_' ||
                                               chr == '.')
                                     })
            }
            ColumnCategory::Property => {
                let substr = if string.starts_with('%') {
                    &string[1..]
                } else {
                    string
                };
                ColumnCategory::Identifier.validate(substr)
            }
            ColumnCategory::Version => {
                let mut parts = string.split('.');
                parts.clone().count() <= 4 &&
                    parts.all(|part| part.parse::<u16>().is_ok())
            }
            // TODO: Validate other categories.
            _ => true,
        }
    }
}

impl fmt::Display for ColumnCategory {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        self.as_str().fmt(formatter)
    }
}

impl str::FromStr for ColumnCategory {
    type Err = io::Error;

    fn from_str(string: &str) -> io::Result<ColumnCategory> {
        match string {
            "AnyPath" => Ok(ColumnCategory::AnyPath),
            "Binary" => Ok(ColumnCategory::Binary),
            "Cabinet" => Ok(ColumnCategory::Cabinet),
            "Condition" => Ok(ColumnCategory::Condition),
            "CustomSource" => Ok(ColumnCategory::CustomSource),
            "DefaultDir" => Ok(ColumnCategory::DefaultDir),
            "DoubleInteger" => Ok(ColumnCategory::DoubleInteger),
            "Filename" => Ok(ColumnCategory::Filename),
            "Formatted" => Ok(ColumnCategory::Formatted),
            "GUID" => Ok(ColumnCategory::Guid),
            "Guid" => Ok(ColumnCategory::Guid),
            "Identifier" => Ok(ColumnCategory::Identifier),
            "Integer" => Ok(ColumnCategory::Integer),
            "KeyFormatted" => Ok(ColumnCategory::KeyFormatted),
            "Language" => Ok(ColumnCategory::Language),
            "LowerCase" => Ok(ColumnCategory::LowerCase),
            "Path" => Ok(ColumnCategory::Path),
            "Paths" => Ok(ColumnCategory::Paths),
            "Property" => Ok(ColumnCategory::Property),
            "RegPath" => Ok(ColumnCategory::RegPath),
            "Shortcut" => Ok(ColumnCategory::Shortcut),
            "Template" => Ok(ColumnCategory::Template),
            "Text" => Ok(ColumnCategory::Text),
            "UpperCase" => Ok(ColumnCategory::UpperCase),
            "URL" => Ok(ColumnCategory::Url),
            "Url" => Ok(ColumnCategory::Url),
            "Version" => Ok(ColumnCategory::Version),
            "WildCardFilename" => Ok(ColumnCategory::WildCardFilename),
            _ => invalid_data!("Invalid category: {:?}", string),
        }
    }
}

// ========================================================================= //

/// A database column.
#[derive(Clone)]
pub struct Column {
    name: String,
    coltype: ColumnType,
    is_localizable: bool,
    is_nullable: bool,
    is_primary_key: bool,
    value_range: Option<(i32, i32)>,
    foreign_key: Option<(String, i32)>,
    category: Option<ColumnCategory>,
    enum_values: Vec<String>,
}

impl Column {
    /// Begins building a new column with the given name.
    ///
    /// # Examples
    ///
    /// ```
    /// let column = msi::Column::build("Foo").nullable().int16();
    /// assert_eq!(column.name(), "Foo");
    /// assert!(column.is_nullable());
    /// assert_eq!(column.coltype(), msi::ColumnType::Int16);
    /// ```
    pub fn build(name: &str) -> ColumnBuilder {
        ColumnBuilder::new(name.to_string())
    }

    pub(crate) fn with_name_prefix(&self, prefix: &str) -> Column {
        Column {
            name: format!("{}.{}", prefix, self.name),
            coltype: self.coltype,
            is_localizable: self.is_localizable,
            is_nullable: self.is_nullable,
            is_primary_key: self.is_primary_key,
            value_range: self.value_range,
            foreign_key: self.foreign_key.clone(),
            category: self.category,
            enum_values: self.enum_values.clone(),
        }
    }

    pub(crate) fn but_nullable(mut self) -> Column {
        self.is_nullable = true;
        self
    }

    pub(crate) fn bitfield(&self) -> i32 {
        let mut bits = self.coltype.bitfield() | COL_VALID_BIT;
        if self.is_localizable {
            bits |= COL_LOCALIZABLE_BIT;
        }
        if self.is_nullable {
            bits |= COL_NULLABLE_BIT;
        }
        let nonbinary = match self.coltype {
            ColumnType::Int16 => true,
            ColumnType::Int32 => false,
            ColumnType::Str(0) => {
                self.category != Some(ColumnCategory::Binary)
            }
            ColumnType::Str(_) => true,
        };
        if nonbinary {
            bits |= COL_NONBINARY_BIT;
        }
        if self.is_primary_key {
            bits |= COL_PRIMARY_KEY_BIT;
        }
        bits
    }

    /// Returns true if the given string is a valid column name.
    pub(crate) fn is_valid_name(name: &str) -> bool {
        ColumnCategory::Identifier.validate(name)
    }

    /// Returns the name of the column.
    pub fn name(&self) -> &str { &self.name }

    /// Returns the type of data stored in the column.
    pub fn coltype(&self) -> ColumnType { self.coltype }

    /// Returns true if values in this column can be localized.
    pub fn is_localizable(&self) -> bool { self.is_localizable }

    /// Returns true if values in this column can be null.
    pub fn is_nullable(&self) -> bool { self.is_nullable }

    /// Returns true if this is primary key column.
    pub fn is_primary_key(&self) -> bool { self.is_primary_key }

    /// Returns the (min, max) integer value range for this column, if any.
    pub fn value_range(&self) -> Option<(i32, i32)> { self.value_range }

    pub(crate) fn foreign_key(&self) -> Option<(&str, i32)> {
        self.foreign_key
            .as_ref()
            .map(|&(ref name, index)| (name.as_str(), index))
    }

    /// Returns the string value category for this column, if any.
    pub fn category(&self) -> Option<ColumnCategory> { self.category }

    /// Returns the list of valid enum values for this column, if any.
    pub fn enum_values(&self) -> Option<&[String]> {
        if self.enum_values.is_empty() {
            None
        } else {
            Some(&self.enum_values)
        }
    }

    /// Returns true if the given value is valid for this column.
    pub fn is_valid_value(&self, value: &Value) -> bool {
        match *value {
            Value::Null => self.is_nullable,
            Value::Int(number) => {
                if let Some((min, max)) = self.value_range {
                    if number < min || number > max {
                        return false;
                    }
                }
                match self.coltype {
                    ColumnType::Int16 => {
                        number > (i16::MIN as i32) &&
                            number <= (i16::MAX as i32)
                    }
                    ColumnType::Int32 => number > i32::MIN,
                    ColumnType::Str(_) => false,
                }
            }
            Value::Str(ref string) => {
                match self.coltype {
                    ColumnType::Int16 |
                    ColumnType::Int32 => false,
                    ColumnType::Str(max_len) => {
                        if let Some(category) = self.category {
                            if !category.validate(&string) {
                                return false;
                            }
                        }
                        if !self.enum_values.is_empty() &&
                            !self.enum_values.contains(string)
                        {
                            return false;
                        }
                        max_len == 0 || string.chars().count() <= max_len
                    }
                }
            }
        }
    }
}

// ========================================================================= //

/// A factory for configuring a new database column.
pub struct ColumnBuilder {
    name: String,
    is_localizable: bool,
    is_nullable: bool,
    is_primary_key: bool,
    value_range: Option<(i32, i32)>,
    foreign_key: Option<(String, i32)>,
    category: Option<ColumnCategory>,
    enum_values: Vec<String>,
}

impl ColumnBuilder {
    fn new(name: String) -> ColumnBuilder {
        ColumnBuilder {
            name: name,
            is_localizable: false,
            is_nullable: false,
            is_primary_key: false,
            value_range: None,
            foreign_key: None,
            category: None,
            enum_values: Vec::new(),
        }
    }

    /// Makes the column be localizable.
    pub fn localizable(mut self) -> ColumnBuilder {
        self.is_localizable = true;
        self
    }

    /// Makes the column allow null values.
    pub fn nullable(mut self) -> ColumnBuilder {
        self.is_nullable = true;
        self
    }

    /// Makes the column be a primary key column.
    pub fn primary_key(mut self) -> ColumnBuilder {
        self.is_primary_key = true;
        self
    }

    /// Makes the column only permit values in the given range.
    pub fn range(mut self, min: i32, max: i32) -> ColumnBuilder {
        self.value_range = Some((min, max));
        self
    }

    /// Makes the column refer to a key column in another table.
    pub fn foreign_key(mut self, table_name: &str, column_index: i32)
                       -> ColumnBuilder {
        self.foreign_key = Some((table_name.to_string(), column_index));
        self
    }

    /// For string columns, makes the column use the specified data format.
    pub fn category(mut self, category: ColumnCategory) -> ColumnBuilder {
        self.category = Some(category);
        self
    }

    /// Makes the column only permit the given values.
    pub fn enum_values(mut self, values: &[&str]) -> ColumnBuilder {
        self.enum_values = values.iter().map(|val| val.to_string()).collect();
        self
    }

    /// Builds a column that stores a 16-bit integer.
    pub fn int16(self) -> Column { self.with_type(ColumnType::Int16) }

    /// Builds a column that stores a 32-bit integer.
    pub fn int32(self) -> Column { self.with_type(ColumnType::Int32) }

    /// Builds a column that stores a string.
    pub fn string(self, max_len: usize) -> Column {
        self.with_type(ColumnType::Str(max_len))
    }

    /// Builds a column that stores an identifier string.  This is equivalent
    /// to `self.category(ColumnCategory::Identifier).string(max_len)`.
    pub fn id_string(self, max_len: usize) -> Column {
        self.category(ColumnCategory::Identifier).string(max_len)
    }

    /// Builds a column that stores a text string.  This is equivalent to
    /// `self.category(ColumnCategory::Text).string(max_len)`.
    pub fn text_string(self, max_len: usize) -> Column {
        self.category(ColumnCategory::Text).string(max_len)
    }

    /// Builds a column that refers to a binary data stream.  This sets the
    /// category to `ColumnCategory::Binary` in addition to setting the column
    /// type.
    pub fn binary(self) -> Column {
        self.category(ColumnCategory::Binary).string(0)
    }

    fn with_type(self, coltype: ColumnType) -> Column {
        Column {
            name: self.name,
            coltype: coltype,
            is_localizable: self.is_localizable,
            is_nullable: self.is_nullable,
            is_primary_key: self.is_primary_key,
            value_range: self.value_range,
            foreign_key: self.foreign_key,
            category: self.category,
            enum_values: self.enum_values,
        }
    }

    pub(crate) fn with_bitfield(self, type_bits: i32) -> io::Result<Column> {
        let is_nullable = (type_bits & COL_NULLABLE_BIT) != 0;
        Ok(Column {
               name: self.name,
               coltype: ColumnType::from_bitfield(type_bits)?,
               is_localizable: (type_bits & COL_LOCALIZABLE_BIT) != 0,
               is_nullable: is_nullable || self.is_nullable,
               is_primary_key: (type_bits & COL_PRIMARY_KEY_BIT) != 0,
               value_range: self.value_range,
               foreign_key: self.foreign_key,
               category: self.category,
               enum_values: self.enum_values,
           })
    }
}

// ========================================================================= //

#[cfg(test)]
mod tests {
    use super::{Column, ColumnCategory, ColumnType};
    use internal::codepage::CodePage;
    use internal::stringpool::StringPool;
    use internal::value::{Value, ValueRef};

    #[test]
    fn category_string_round_trip() {
        for category in ColumnCategory::all() {
            assert_eq!(category
                           .to_string()
                           .parse::<ColumnCategory>()
                           .unwrap(),
                       category);
        }
    }

    #[test]
    fn valid_column_name() {
        assert!(Column::is_valid_name("fooBar"));
        assert!(Column::is_valid_name("_Whatever"));
        assert!(Column::is_valid_name("Catch22"));
        assert!(Column::is_valid_name("Foo.Bar"));

        assert!(!Column::is_valid_name(""));
        assert!(!Column::is_valid_name("99Bottles"));
    }

    #[test]
    fn read_column_value() {
        let mut input: &[u8] = b"\x00\x00";
        assert_eq!(ColumnType::Int16.read_value(&mut input, false).unwrap(),
                   ValueRef::Null);

        let mut input: &[u8] = b"\x23\x81";
        assert_eq!(ColumnType::Int16.read_value(&mut input, false).unwrap(),
                   ValueRef::Int(0x123));

        let mut input: &[u8] = b"\xff\x7f";
        assert_eq!(ColumnType::Int16.read_value(&mut input, false).unwrap(),
                   ValueRef::Int(-1));

        let mut input: &[u8] = b"\x00\x00\x00\x00";
        assert_eq!(ColumnType::Int32.read_value(&mut input, false).unwrap(),
                   ValueRef::Null);

        let mut input: &[u8] = b"\x67\x45\x23\x81";
        assert_eq!(ColumnType::Int32.read_value(&mut input, false).unwrap(),
                   ValueRef::Int(0x1234567));

        let mut input: &[u8] = b"\xff\xff\xff\x7f";
        assert_eq!(ColumnType::Int32.read_value(&mut input, false).unwrap(),
                   ValueRef::Int(-1));

        let mut string_pool = StringPool::new(CodePage::default());
        let string_ref = string_pool.incref("Hello, world!".to_string());
        assert_eq!(string_ref.number(), 1);

        let mut input: &[u8] = b"\x00\x00";
        assert_eq!(ColumnType::Str(24).read_value(&mut input, false).unwrap(),
                   ValueRef::Null);

        let mut input: &[u8] = b"\x01\x00";
        assert_eq!(ColumnType::Str(24).read_value(&mut input, false).unwrap(),
                   ValueRef::Str(string_ref));

        let mut input: &[u8] = b"\x00\x00\x00";
        assert_eq!(ColumnType::Str(24).read_value(&mut input, true).unwrap(),
                   ValueRef::Null);

        let mut input: &[u8] = b"\x01\x00\x00";
        assert_eq!(ColumnType::Str(24).read_value(&mut input, true).unwrap(),
                   ValueRef::Str(string_ref));
    }

    #[test]
    fn write_column_value() {
        let mut output = Vec::<u8>::new();
        let value_ref = ValueRef::Null;
        ColumnType::Int16.write_value(&mut output, value_ref, false).unwrap();
        assert_eq!(&output as &[u8], b"\x00\x00");

        let mut output = Vec::<u8>::new();
        let value_ref = ValueRef::Int(0x123);
        ColumnType::Int16.write_value(&mut output, value_ref, false).unwrap();
        assert_eq!(&output as &[u8], b"\x23\x81");

        let mut output = Vec::<u8>::new();
        let value_ref = ValueRef::Int(-1);
        ColumnType::Int16.write_value(&mut output, value_ref, false).unwrap();
        assert_eq!(&output as &[u8], b"\xff\x7f");

        let mut output = Vec::<u8>::new();
        let value_ref = ValueRef::Null;
        ColumnType::Int32.write_value(&mut output, value_ref, false).unwrap();
        assert_eq!(&output as &[u8], b"\x00\x00\x00\x00");

        let mut output = Vec::<u8>::new();
        let value_ref = ValueRef::Int(0x1234567);
        ColumnType::Int32.write_value(&mut output, value_ref, false).unwrap();
        assert_eq!(&output as &[u8], b"\x67\x45\x23\x81");

        let mut output = Vec::<u8>::new();
        let value_ref = ValueRef::Int(-1);
        ColumnType::Int32.write_value(&mut output, value_ref, false).unwrap();
        assert_eq!(&output as &[u8], b"\xff\xff\xff\x7f");

        let mut string_pool = StringPool::new(CodePage::default());
        let string_ref = string_pool.incref("Hello, world!".to_string());
        assert_eq!(string_ref.number(), 1);

        let mut output = Vec::<u8>::new();
        let value_ref = ValueRef::Null;
        ColumnType::Str(9).write_value(&mut output, value_ref, false).unwrap();
        assert_eq!(&output as &[u8], b"\x00\x00");

        let mut output = Vec::<u8>::new();
        let value_ref = ValueRef::Str(string_ref);
        ColumnType::Str(9).write_value(&mut output, value_ref, false).unwrap();
        assert_eq!(&output as &[u8], b"\x01\x00");

        let mut output = Vec::<u8>::new();
        let value_ref = ValueRef::Null;
        ColumnType::Str(9).write_value(&mut output, value_ref, true).unwrap();
        assert_eq!(&output as &[u8], b"\x00\x00\x00");

        let mut output = Vec::<u8>::new();
        let value_ref = ValueRef::Str(string_ref);
        ColumnType::Str(9).write_value(&mut output, value_ref, true).unwrap();
        assert_eq!(&output as &[u8], b"\x01\x00\x00");
    }

    #[test]
    fn valid_column_value() {
        let column = Column::build("Foo").nullable().int16();
        assert!(column.is_valid_value(&Value::Null));
        assert!(column.is_valid_value(&Value::Int(0x7fff)));
        assert!(!column.is_valid_value(&Value::Int(0x8000)));
        assert!(column.is_valid_value(&Value::Int(-0x7fff)));
        assert!(!column.is_valid_value(&Value::Int(-0x8000)));
        assert!(!column.is_valid_value(&Value::Str("1234".to_string())));

        let column = Column::build("Bar").int32();
        assert!(!column.is_valid_value(&Value::Null));
        assert!(column.is_valid_value(&Value::Int(0x7fff_ffff)));
        assert!(column.is_valid_value(&Value::Int(-0x7fff_ffff)));
        assert!(!column.is_valid_value(&Value::Int(-0x8000_0000)));
        assert!(!column.is_valid_value(&Value::Str("1234".to_string())));

        let column = Column::build("Bar").range(1, 32).int32();
        assert!(!column.is_valid_value(&Value::Int(0)));
        assert!(column.is_valid_value(&Value::Int(1)));
        assert!(column.is_valid_value(&Value::Int(7)));
        assert!(column.is_valid_value(&Value::Int(32)));
        assert!(!column.is_valid_value(&Value::Int(33)));

        let column = Column::build("Baz").string(8);
        assert!(!column.is_valid_value(&Value::Null));
        assert!(!column.is_valid_value(&Value::Int(0)));
        assert!(column.is_valid_value(&Value::Str("".to_string())));
        assert!(column.is_valid_value(&Value::Str("1234".to_string())));
        assert!(column.is_valid_value(&Value::Str("12345678".to_string())));
        assert!(!column.is_valid_value(&Value::Str("123456789".to_string())));

        let column = Column::build("Quux").string(0);
        assert!(column.is_valid_value(&Value::Str("".to_string())));
        assert!(column.is_valid_value(&Value::Str("123456789".to_string())));

        let column = Column::build("Foo").id_string(0);
        assert!(column.is_valid_value(&Value::Str("FooBar".to_string())));
        assert!(!column.is_valid_value(&Value::Str("".to_string())));
        assert!(!column.is_valid_value(&Value::Str("1234".to_string())));

        let column = Column::build("Bar").enum_values(&["Y", "N"]).string(1);
        assert!(column.is_valid_value(&Value::Str("Y".to_string())));
        assert!(column.is_valid_value(&Value::Str("N".to_string())));
        assert!(!column.is_valid_value(&Value::Str("X".to_string())));
    }
}

// ========================================================================= //