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
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
//
// Copyright (c) 2016 KAMADA Ken'ichi.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
//

use std::fmt;

use value;
use value::Value;
use util::{atou16, isupper};

/// A tag of a TIFF field.
///
/// Some well-known tags are provided as associated constants of
/// this type.  The constant names follow the Exif specification
/// but not the Rust naming conventions.
//
// This is not an enum to keep safety and API stability, while
// supporting unknown tag numbers.  This comment is based on the
// behavior of Rust 1.12.
// Storing unknown values in a repr(u16) enum is unsafe.  The compiler
// assumes that there is no undefined discriminant even with a C-like
// enum, so the exhaustiveness check of a match expression will break.
// Storing unknown values in a special variant such as Unknown(u16)
// tends to break backward compatibility.  When Tag::VariantFoo is
// defined in a new version of the library, the old codes using
// Tag::Unknown(Foo's tag number) will break.
//
// Use of constants is restricted in patterns.  As of Rust 1.12,
// PartialEq and Eq need to be _automatically derived_ for Tag to
// emulate structural equivalency.
// <https://github.com/rust-lang/rfcs/pull/1445>
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Tag(pub Context, pub u16);

impl Tag {
    /// Returns the context of the tag.
    #[inline]
    pub fn context(self) -> Context {
        self.0
    }

    /// Returns the tag number.
    #[inline]
    pub fn number(self) -> u16 {
        self.1
    }

    /// Returns the description of the tag.
    #[inline]
    pub fn description(&self) -> Option<&str> {
        get_tag_info(*self).map(|ti| ti.desc)
    }

    /// Returns the default value of the tag.  `None` is returned if
    /// it is not defined in the standard or it depends on the context.
    #[inline]
    pub fn default_value(&self) -> Option<Value> {
        get_tag_info(*self).and_then(|ti| (&ti.default).into())
    }
}

impl fmt::Display for Tag {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match get_tag_info(*self) {
            Some(ti) => f.pad(ti.name),
            None => f.pad(&format!("{:?}", self)),
        }
    }
}

/// An enum that indicates how a tag number is interpreted.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Context {
    /// TIFF attributes defined in the TIFF Rev. 6.0 specification.
    Tiff,	// 0th/1st IFD
    /// Exif attributes.
    Exif,	// 0th/1st IFD -- Exif IFD
    /// GPS attributes.
    Gps,	// 0th/1st IFD -- GPS IFD
    /// Interoperability attributes.
    Interop,	// 0th/1st IFD -- Exif IFD -- Interoperability IFD
}

macro_rules! generate_well_known_tag_constants {
    (
        $( |$ctx:path| $(
            // Copy the doc attribute to the actual definition.
            $( #[$attr:meta] )*
            ($name:ident, $num:expr, $defval:expr, $dispval:ident, $desc:expr)
        ),+, )+
    ) => (
        /// A module that contains Exif tag constants.
        ///
        /// Compatibility warning: Exif tag constants in this module will be
        /// converted to associated constants of `Tag` when the feature is
        /// stabilized.
        ///
        /// It is not recommended to import the constants directly into
        /// your namespace; import the module and use with the module name
        /// like `tag::DateTime`.  The constant names follow the Exif
        /// specification but not the Rust naming conventions, and a user
        /// of the constants will get the non_upper_case_globals warning
        /// if a bare constant is used in a match arm.
        // This is discussed in
        // <https://github.com/rust-lang/rust/issues/25207>.
        pub mod constants {
            use super::{Context, Tag};
            $($(
                $( #[$attr] )*
                #[allow(non_upper_case_globals)]
                #[deprecated(since = "0.3.0", note = "use `Tag::TagName` instead of `tag::TagName`")]
                pub const $name: Tag = Tag($ctx, $num);
            )+)+
        }

        impl Tag {
            $($(
                $( #[$attr] )*
                #[allow(non_upper_case_globals)]
                pub const $name: Tag = Tag($ctx, $num);
            )+)+
        }

        // Use a separate module to avoid name conflicts between
        // const Tag and static TagInfo.
        mod tag_info {
            use std::fmt;
            use value::Value;
            use value::DefaultValue;

            pub struct TagInfo {
                pub name: &'static str,
                pub desc: &'static str,
                pub default: DefaultValue,
                pub dispval: fn(&mut fmt::Write, &Value) -> fmt::Result,
            }

            $($(
                #[allow(non_upper_case_globals)]
                pub static $name: TagInfo = TagInfo {
                    name: stringify!($name),
                    desc: $desc,
                    default: $defval,
                    dispval: super::$dispval,
                };
            )+)+
        }

        fn get_tag_info(tag: Tag) -> Option<&'static tag_info::TagInfo> {
            match tag {
                $($(
                    Tag::$name => Some(&tag_info::$name),
                )+)+
                _ => None,
            }
        }
    )
}

// Tag constant names do not follow the Rust naming conventions but
// the Exif field names: camel cases and all-capital acronyms.
generate_well_known_tag_constants!(
    // Exif-specific IFDs [EXIF23 4.6.3].
    |Context::Tiff|

    /// A pointer to the Exif IFD.  This is used for the internal structure
    /// of Exif data and will not be returned to the user.
    (ExifIFDPointer, 0x8769, DefaultValue::None, d_default,
     "Exif IFD pointer"),
    /// A pointer to the GPS IFD.  This is used for the internal structure
    /// of Exif data and will not be returned to the user.
    (GPSInfoIFDPointer, 0x8825, DefaultValue::None, d_default,
     "GPS Info IFD pointer"),

    |Context::Exif|

    /// A pointer to the interoperability IFD.  This is used for the internal
    /// structure of Exif data and will not be returned to the user.
    (InteropIFDPointer, 0xa005, DefaultValue::None, d_default,
     "Interoperability IFD pointer"),

    // TIFF primary and thumbnail attributes [EXIF23 4.6.4 Table 4,
    // 4.6.8 Table 17, and 4.6.8 Table 21].
    |Context::Tiff|

    (ImageWidth, 0x100, DefaultValue::None, d_default,
     "Image width"),
    (ImageLength, 0x101, DefaultValue::None, d_default,
     "Image height"),
    (BitsPerSample, 0x102, DefaultValue::Short(&[8, 8, 8]), d_default,
     "Number of bits per component"),
    (Compression, 0x103, DefaultValue::None, d_compression,
     "Compression scheme"),
    (PhotometricInterpretation, 0x106, DefaultValue::None, d_photointp,
     "Pixel composition"),
    (ImageDescription, 0x10e, DefaultValue::None, d_default,
     "Image title"),
    (Make, 0x10f, DefaultValue::None, d_default,
     "Manufacturer of image input equipment"),
    (Model, 0x110, DefaultValue::None, d_default,
     "Model of image input equipment"),
    (StripOffsets, 0x111, DefaultValue::None, d_default,
     "Image data location"),
    (Orientation, 0x112, DefaultValue::Short(&[1]), d_orientation,
     "Orientation of image"),
    (SamplesPerPixel, 0x115, DefaultValue::Short(&[3]), d_default,
     "Number of components"),
    (RowsPerStrip, 0x116, DefaultValue::None, d_default,
     "Number of rows per strip"),
    (StripByteCounts, 0x117, DefaultValue::None, d_default,
     "Bytes per compressed strip"),
    (XResolution, 0x11a, DefaultValue::Rational(&[(72, 1)]), d_decimal,
     "Image resolution in width direction"),
    (YResolution, 0x11b, DefaultValue::Rational(&[(72, 1)]), d_decimal,
     "Image resolution in height direction"),
    (PlanarConfiguration, 0x11c, DefaultValue::Short(&[1]), d_planarcfg,
     "Image data arrangement"),
    (ResolutionUnit, 0x128, DefaultValue::Short(&[2]), d_resunit,
     "Unit of X and Y resolution"),
    (TransferFunction, 0x12d, DefaultValue::None, d_default,
     "Transfer function"),
    (Software, 0x131, DefaultValue::None, d_default,
     "Software used"),
    (DateTime, 0x132, DefaultValue::None, d_datetime,
     "File change date and time"),
    (Artist, 0x13b, DefaultValue::None, d_default,
     "Person who created the image"),
    (WhitePoint, 0x13e, DefaultValue::None, d_decimal,
     "White point chromaticity"),
    (PrimaryChromaticities, 0x13f, DefaultValue::None, d_decimal,
     "Chromaticities of primaries"),
    // Not referenced in Exif.
    (TileOffsets, 0x144, DefaultValue::None, d_default,
     "Tiled image data location"),
    // Not referenced in Exif.
    (TileByteCounts, 0x145, DefaultValue::None, d_default,
     "Bytes per compressed tile"),
    (JPEGInterchangeFormat, 0x201, DefaultValue::None, d_default,
     "Offset to JPEG SOI"),
    (JPEGInterchangeFormatLength, 0x202, DefaultValue::None, d_default,
     "Bytes of JPEG data"),
    (YCbCrCoefficients, 0x211, DefaultValue::Unspecified, d_decimal,
     "Color space transformation matrix coefficients"),
    (YCbCrSubSampling, 0x212, DefaultValue::None, d_ycbcrsubsamp,
     "Subsampling ratio of Y to C"),
    (YCbCrPositioning, 0x213, DefaultValue::Short(&[1]), d_ycbcrpos,
     "Y and C positioning"),
    (ReferenceBlackWhite, 0x214, DefaultValue::ContextDependent, d_decimal,
     "Pair of black and white reference values"),
    (Copyright, 0x8298, DefaultValue::None, d_default,
     "Copyright holder"),

    // Exif IFD attributes [EXIF23 4.6.5 Table 7 and 4.6.8 Table 18].
    |Context::Exif|

    (ExposureTime, 0x829a, DefaultValue::None, d_exptime,
     "Exposure time"),
    (FNumber, 0x829d, DefaultValue::None, d_fnumber,
     "F number"),
    (ExposureProgram, 0x8822, DefaultValue::None, d_expprog,
     "Exposure program"),
    (SpectralSensitivity, 0x8824, DefaultValue::None, d_default,
     "Spectral sensitivity"),
    (PhotographicSensitivity, 0x8827, DefaultValue::None, d_default,
     "Photographic sensitivity"),
    (OECF, 0x8828, DefaultValue::None, d_default,
     "Optoelectric conversion factor"),
    (SensitivityType, 0x8830, DefaultValue::None, d_sensitivitytype,
     "Sensitivity type"),
    (StandardOutputSensitivity, 0x8831, DefaultValue::None, d_default,
     "Standard output sensitivity"),
    (RecommendedExposureIndex, 0x8832, DefaultValue::None, d_default,
     "Recommended exposure index"),
    (ISOSpeed, 0x8833, DefaultValue::None, d_default,
     "ISO speed"),
    (ISOSpeedLatitudeyyy, 0x8834, DefaultValue::None, d_default,
     "ISO speed latitude yyy"),
    (ISOSpeedLatitudezzz, 0x8835, DefaultValue::None, d_default,
     "ISO speed latitude zzz"),
    // The absence of this field means non-conformance to Exif, so the default
    // value specified in the standard (e.g., "0231") should not apply.
    (ExifVersion, 0x9000, DefaultValue::None, d_exifver,
     "Exif version"),
    (DateTimeOriginal, 0x9003, DefaultValue::None, d_datetime,
     "Date and time of original data generation"),
    (DateTimeDigitized, 0x9004, DefaultValue::None, d_datetime,
     "Date and time of digital data generation"),
    (OffsetTime, 0x9010, DefaultValue::None, d_default,
     "Offset data of DateTime"),
    (OffsetTimeOriginal, 0x9011, DefaultValue::None, d_default,
     "Offset data of DateTimeOriginal"),
    (OffsetTimeDigitized, 0x9012, DefaultValue::None, d_default,
     "Offset data of DateTimeDigitized"),
    (ComponentsConfiguration, 0x9101, DefaultValue::ContextDependent, d_cpntcfg,
     "Meaning of each component"),
    (CompressedBitsPerPixel, 0x9102, DefaultValue::None, d_decimal,
     "Image compression mode"),
    (ShutterSpeedValue, 0x9201, DefaultValue::None, d_decimal,
     "Shutter speed"),
    (ApertureValue, 0x9202, DefaultValue::None, d_decimal,
     "Aperture"),
    (BrightnessValue, 0x9203, DefaultValue::None, d_decimal,
     "Brightness"),
    (ExposureBiasValue, 0x9204, DefaultValue::None, d_decimal,
     "Exposure bias"),
    (MaxApertureValue, 0x9205, DefaultValue::None, d_decimal,
     "Maximum lens aperture"),
    (SubjectDistance, 0x9206, DefaultValue::None, d_subjdist,
     "Subject distance"),
    (MeteringMode, 0x9207, DefaultValue::Short(&[0]), d_metering,
     "Metering mode"),
    (LightSource, 0x9208, DefaultValue::Short(&[0]), d_lightsrc,
     "Light source"),
    (Flash, 0x9209, DefaultValue::Unspecified, d_flash,
     "Flash"),
    (FocalLength, 0x920a, DefaultValue::None, d_decimal,
     "Lens focal length"),
    (SubjectArea, 0x9214, DefaultValue::None, d_subjarea,
     "Subject area"),
    (MakerNote, 0x927c, DefaultValue::None, d_default,
     "Manufacturer notes"),
    (UserComment, 0x9286, DefaultValue::None, d_default,
     "User comments"),
    (SubSecTime, 0x9290, DefaultValue::None, d_default,
     "DateTime subseconds"),
    (SubSecTimeOriginal, 0x9291, DefaultValue::None, d_default,
     "DateTimeOriginal subseconds"),
    (SubSecTimeDigitized, 0x9292, DefaultValue::None, d_default,
     "DateTimeDigitized subseconds"),
    (Temperature, 0x9400, DefaultValue::None, d_optdecimal,
     "Temperature"),
    (Humidity, 0x9401, DefaultValue::None, d_optdecimal,
     "Humidity"),
    (Pressure, 0x9402, DefaultValue::None, d_optdecimal,
     "Pressure"),
    (WaterDepth, 0x9403, DefaultValue::None, d_optdecimal,
     "Water depth"),
    (Acceleration, 0x9404, DefaultValue::None, d_optdecimal,
     "Acceleration"),
    (CameraElevationAngle, 0x9405, DefaultValue::None, d_optdecimal,
     "Camera elevation angle"),
    (FlashpixVersion, 0xa000, DefaultValue::Undefined(b"0100"), d_exifver,
     "Supported Flashpix version"),
    (ColorSpace, 0xa001, DefaultValue::Unspecified, d_cspace,
     "Color space information"),
    (PixelXDimension, 0xa002, DefaultValue::None, d_default,
     "Valid image width"),
    (PixelYDimension, 0xa003, DefaultValue::Unspecified, d_default,
     "Valid image height"),
    (RelatedSoundFile, 0xa004, DefaultValue::None, d_default,
     "Related audio file"),
    (FlashEnergy, 0xa20b, DefaultValue::None, d_decimal,
     "Flash energy"),
    (SpatialFrequencyResponse, 0xa20c, DefaultValue::None, d_default,
     "Spatial frequency response"),
    (FocalPlaneXResolution, 0xa20e, DefaultValue::None, d_decimal,
     "Focal plane X resolution"),
    (FocalPlaneYResolution, 0xa20f, DefaultValue::None, d_decimal,
     "Focal plane Y resolution"),
    (FocalPlaneResolutionUnit, 0xa210, DefaultValue::Short(&[2]), d_resunit,
     "Focal plane resolution unit"),
    (SubjectLocation, 0xa214, DefaultValue::None, d_subjarea,
     "Subject location"),
    (ExposureIndex, 0xa215, DefaultValue::None, d_decimal,
     "Exposure index"),
    (SensingMethod, 0xa217, DefaultValue::None, d_sensingmethod,
     "Sensing method"),
    (FileSource, 0xa300, DefaultValue::Undefined(&[3]), d_filesrc,
     "File source"),
    (SceneType, 0xa301, DefaultValue::Undefined(&[1]), d_scenetype,
     "Scene type"),
    (CFAPattern, 0xa302, DefaultValue::None, d_default,
     "CFA pattern"),
    (CustomRendered, 0xa401, DefaultValue::Short(&[0]), d_customrendered,
     "Custom image processing"),
    (ExposureMode, 0xa402, DefaultValue::None, d_expmode,
     "Exposure mode"),
    (WhiteBalance, 0xa403, DefaultValue::None, d_whitebalance,
     "White balance"),
    (DigitalZoomRatio, 0xa404, DefaultValue::None, d_dzoomratio,
     "Digital zoom ratio"),
    (FocalLengthIn35mmFilm, 0xa405, DefaultValue::None, d_focallen35,
     "Focal length in 35 mm film"),
    (SceneCaptureType, 0xa406, DefaultValue::Short(&[0]), d_scenecaptype,
     "Scene capture type"),
    (GainControl, 0xa407, DefaultValue::None, d_gainctrl,
     "Gain control"),
    (Contrast, 0xa408, DefaultValue::Short(&[0]), d_contrast,
     "Contrast"),
    (Saturation, 0xa409, DefaultValue::Short(&[0]), d_saturation,
     "Saturation"),
    (Sharpness, 0xa40a, DefaultValue::Short(&[0]), d_sharpness,
     "Sharpness"),
    (DeviceSettingDescription, 0xa40b, DefaultValue::None, d_default,
     "Device settings description"),
    (SubjectDistanceRange, 0xa40c, DefaultValue::None, d_subjdistrange,
     "Subject distance range"),
    (ImageUniqueID, 0xa420, DefaultValue::None, d_default,
     "Unique image ID"),
    (CameraOwnerName, 0xa430, DefaultValue::None, d_default,
     "Camera owner name"),
    (BodySerialNumber, 0xa431, DefaultValue::None, d_default,
     "Body serial number"),
    (LensSpecification, 0xa432, DefaultValue::None, d_lensspec,
     "Lens specification"),
    (LensMake, 0xa433, DefaultValue::None, d_default,
     "Lens make"),
    (LensModel, 0xa434, DefaultValue::None, d_default,
     "Lens model"),
    (LensSerialNumber, 0xa435, DefaultValue::None, d_default,
     "Lens serial number"),
    (Gamma, 0xa500, DefaultValue::None, d_decimal,
     "Gamma"),

    // GPS attributes [EXIF23 4.6.6 Table 15 and 4.6.8 Table 19].
    |Context::Gps|

    // Depends on the Exif version.
    (GPSVersionID, 0x0, DefaultValue::ContextDependent, d_gpsver,
     "GPS tag version"),
    (GPSLatitudeRef, 0x1, DefaultValue::None, d_gpslatlongref,
     "North or south latitude"),
    (GPSLatitude, 0x2, DefaultValue::None, d_gpsdms,
     "Latitude"),
    (GPSLongitudeRef, 0x3, DefaultValue::None, d_gpslatlongref,
     "East or West Longitude"),
    (GPSLongitude, 0x4, DefaultValue::None, d_gpsdms,
     "Longitude"),
    (GPSAltitudeRef, 0x5, DefaultValue::Byte(&[0]), d_gpsaltref,
     "Altitude reference"),
    (GPSAltitude, 0x6, DefaultValue::None, d_decimal,
     "Altitude"),
    (GPSTimeStamp, 0x7, DefaultValue::None, d_gpstimestamp,
     "GPS time (atomic clock)"),
    (GPSSatellites, 0x8, DefaultValue::None, d_default,
     "GPS satellites used for measurement"),
    (GPSStatus, 0x9, DefaultValue::None, d_gpsstatus,
     "GPS receiver status"),
    (GPSMeasureMode, 0xa, DefaultValue::None, d_gpsmeasuremode,
     "GPS measurement mode"),
    (GPSDOP, 0xb, DefaultValue::None, d_decimal,
     "Measurement precision"),
    (GPSSpeedRef, 0xc, DefaultValue::Ascii(&[b"K"]), d_gpsspeedref,
     "Speed unit"),
    (GPSSpeed, 0xd, DefaultValue::None, d_decimal,
     "Speed of GPS receiver"),
    (GPSTrackRef, 0xe, DefaultValue::Ascii(&[b"T"]), d_gpsdirref,
     "Reference for direction of movement"),
    (GPSTrack, 0xf, DefaultValue::None, d_decimal,
     "Direction of movement"),
    (GPSImgDirectionRef, 0x10, DefaultValue::Ascii(&[b"T"]), d_gpsdirref,
     "Reference for direction of image"),
    (GPSImgDirection, 0x11, DefaultValue::None, d_decimal,
     "Direction of image"),
    (GPSMapDatum, 0x12, DefaultValue::None, d_default,
     "Geodetic survey data used"),
    (GPSDestLatitudeRef, 0x13, DefaultValue::None, d_gpslatlongref,
     "Reference for latitude of destination"),
    (GPSDestLatitude, 0x14, DefaultValue::None, d_gpsdms,
     "Latitude of destination"),
    (GPSDestLongitudeRef, 0x15, DefaultValue::None, d_gpslatlongref,
     "Reference for longitude of destination"),
    (GPSDestLongitude, 0x16, DefaultValue::None, d_gpsdms,
     "Longitude of destination"),
    (GPSDestBearingRef, 0x17, DefaultValue::Ascii(&[b"T"]), d_gpsdirref,
     "Reference for bearing of destination"),
    (GPSDestBearing, 0x18, DefaultValue::None, d_decimal,
     "Bearing of destination"),
    (GPSDestDistanceRef, 0x19, DefaultValue::Ascii(&[b"K"]), d_gpsdistref,
     "Reference for distance to destination"),
    (GPSDestDistance, 0x1a, DefaultValue::None, d_decimal,
     "Distance to destination"),
    (GPSProcessingMethod, 0x1b, DefaultValue::None, d_ascii_in_undef,
     "Name of GPS processing method"),
    (GPSAreaInformation, 0x1c, DefaultValue::None, d_default,
     "Name of GPS area"),
    (GPSDateStamp, 0x1d, DefaultValue::None, d_gpsdatestamp,
     "GPS date"),
    (GPSDifferential, 0x1e, DefaultValue::None, d_gpsdifferential,
     "GPS differential correction"),
    (GPSHPositioningError, 0x1f, DefaultValue::None, d_decimal,
     "Horizontal positioning error"),

    // Interoperability attributes [EXIF23 4.6.7 Table 16 and 4.6.8 Table 20].
    |Context::Interop|

    (InteroperabilityIndex, 0x1, DefaultValue::None, d_default,
     "Interoperability identification"),
);

// For Value::display_as().
pub fn display_value_as<'a>(value: &'a Value, tag: Tag) -> value::Display<'a> {
    match get_tag_info(tag) {
        Some(ti) => value::Display { fmt: ti.dispval, value: value },
        None => value::Display { fmt: d_default, value: value },
    }
}

// Compression (TIFF 0x103)
fn d_compression(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(1) => "uncompressed",
        Some(2) => "Modified Huffman",
        Some(6) => "JPEG",
        Some(32773) => "PackBits",
        _ => return d_unknown(w, value, "unknown compression "),
    };
    w.write_str(s)
}

// PhotometricInterpretation (TIFF 0x106)
fn d_photointp(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(0) => "white is zero",
        Some(1) => "black is zero",
        Some(2) => "RGB",
        Some(3) => "palette color",
        Some(4) => "transparency mask",
        Some(6) => "YCbCr",
        _ => return d_unknown(w, value, "unknown photometric interpretation "),
    };
    w.write_str(s)
}

// Orientation (TIFF 0x112)
fn d_orientation(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(1) => "row 0 at top and column 0 at left",
        Some(2) => "row 0 at top and column 0 at right",
        Some(3) => "row 0 at bottom and column 0 at right",
        Some(4) => "row 0 at bottom and column 0 at left",
        Some(5) => "row 0 at left and column 0 at top",
        Some(6) => "row 0 at right and column 0 at top",
        Some(7) => "row 0 at right and column 0 at bottom",
        Some(8) => "row 0 at left and column 0 at bottom",
        _ => return d_unknown(w, value, "unknown orientation "),
    };
    w.write_str(s)
}

// PlanarConfiguration (TIFF 0x11c)
fn d_planarcfg(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(1) => "chunky",
        Some(2) => "planar",
        _ => return d_unknown(w, value, "unknown planar configuration "),
    };
    w.write_str(s)
}

// ResolutionUnit (TIFF 0x128)
fn d_resunit(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(1) => "no absolute unit",
        Some(2) => "pixels per inch",
        Some(3) => "pixels per centimeter",
        _ => return d_unknown(w, value, "unknown unit "),
    };
    w.write_str(s)
}

// DateTime (TIFF 0x132), DateTimeOriginal (Exif 0x9003), and
// DateTimeDigitized (Exif 0x9004)
fn d_datetime(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    if let Value::Ascii(ref v) = *value {
        if let Some(dt) = v.first() {
            if let Ok(dt) = ::tiff::DateTime::from_ascii(dt) {
                return write!(w, "{}", dt)
            }
        }
    }
    d_default(w, value)
}

// YCbCrSubSampling (TIFF 0x212)
fn d_ycbcrsubsamp(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let horiz = value.get_uint(0).unwrap_or(0);
    let vert = value.get_uint(1).unwrap_or(0);
    let s = match (horiz, vert) {
        (1, 1) => "full horizontally, full vertically (4:4:4)",
        (1, 2) => "full horizontally, half vertically",
        (1, 4) => "full horizontally, quarter vertically",
        (2, 1) => "half horizontally, full vertically (4:2:2)",
        (2, 2) => "half horizontally, half vertically (4:2:0)",
        (2, 4) => "half horizontally, quarter vertically",
        (4, 1) => "quarter horizontally, full vertically (4:1:1)",
        (4, 2) => "quarter horizontally, half vertically",
        (4, 4) => "quarter horizontally, quarter vertically",
        _ => return d_default(w, value),
    };
    w.write_str(s)
}

// YCbCrPositioning (TIFF 0x213)
fn d_ycbcrpos(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(1) => "centered",
        Some(2) => "co-sited",
        _ => return d_unknown(w, value, "unknown YCbCr positioning "),
    };
    w.write_str(s)
}

// ExposureTime (Exif 0x829a)
fn d_exptime(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    if let Value::Rational(ref v) = *value {
        if let Some(et) = v.first() {
            if et.num >= et.denom {
                return write!(w, "{}", et.to_f64());
            } else if et.num != 0 {
                return write!(w, "1/{}", et.denom as f64 / et.num as f64);
            }
        }
    }
    d_default(w, value)
}

// FNumber (Exif 0x829d)
fn d_fnumber(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    try!(w.write_str("f/"));
    d_decimal(w, value)
}

// ExposureProgram (Exif 0x8822)
fn d_expprog(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(1) => "manual",
        Some(2) => "normal program",
        Some(3) => "aperture priority",
        Some(4) => "shutter priority",
        Some(5) => "creative program",
        Some(6) => "action program",
        Some(7) => "portrait mode",
        Some(8) => "landscape mode",
        _ => return d_unknown(w, value, "unknown exposure program "),
    };
    w.write_str(s)
}

// SensitivityType (Exif 0x8830)
fn d_sensitivitytype(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(1) => "SOS",
        Some(2) => "REI",
        Some(3) => "ISO speed",
        Some(4) => "SOS/REI",
        Some(5) => "SOS/ISO speed",
        Some(6) => "REI/ISO speed",
        Some(7) => "SOS/REI/ISO speed",
        _ => return d_unknown(w, value, "unknown sensitivity type "),
    };
    w.write_str(s)
}

// ExifVersion (Exif 0x9000), FlashpixVersion (Exif 0xa000)
fn d_exifver(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    if let Value::Undefined(u, _) = *value {
        if u.len() == 4 {
            if let Ok(major) = atou16(&u[0..2]) {
                if let Ok(minor) = atou16(&u[2..4]) {
                    if minor % 10 == 0 {
                        return write!(w, "{}.{}", major, minor / 10);
                    } else {
                        return write!(w, "{}.{:02}", major, minor);
                    }
                }
            }
        }
    }
    d_default(w, value)
}

// ComponentsConfiguration (Exif 0x9101)
fn d_cpntcfg(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    if let Value::Undefined(u, _) = *value {
        for &x in u {
            try!(match x {
                0 => w.write_char('_'),
                1 => w.write_char('Y'),
                2 => w.write_str("Cb"),
                3 => w.write_str("Cr"),
                4 => w.write_char('R'),
                5 => w.write_char('G'),
                6 => w.write_char('B'),
                _ => w.write_char('?'),
            });
        }
        return Ok(());
    }
    d_default(w, value)
}

// SubjectDistance (Exif 0x9206)
fn d_subjdist(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    if let Value::Rational(ref v) = *value {
        if let Some(dist) = v.first() {
            if dist.num == 0 {
                return w.write_str("unknown");
            } else if dist.num == 0xffffffff {
                return w.write_str("infinity");
            }
        }
    }
    d_decimal(w, value)
}

// MeteringMode (Exif 0x9207)
fn d_metering(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(1) => "average",
        Some(2) => "center-weighted average",
        Some(3) => "spot",
        Some(4) => "multi-spot",
        Some(5) => "pattern",
        Some(6) => "partial",
        Some(255) => "other",
        _ => return d_unknown(w, value, "unknown metering mode "),
    };
    w.write_str(s)
}

// LightSource (Exif 0x9208)
fn d_lightsrc(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(1) => "daylight",
        Some(2) => "fluorescent",
        Some(3) => "tungsten",
        Some(4) => "flash",
        Some(9) => "fine weather",
        Some(10) => "cloudy weather",
        Some(11) => "shade",
        Some(12) => "daylight fluorescent (D 5700-7100K)",
        Some(13) => "day white fluorescent (N 4600-5500K)",
        Some(14) => "cool white fluorescent (W 3800-4500K)",
        Some(15) => "white fluorescent (WW 3250-3800K)",
        Some(16) => "warm white fluorescent (L 2600-3250K)",
        Some(17) => "standard light A",
        Some(18) => "standard light B",
        Some(19) => "standard light C",
        Some(20) => "D55",
        Some(21) => "D65",
        Some(22) => "D75",
        Some(23) => "D50",
        Some(24) => "ISO studio tungsten",
        Some(255) => "other",
        _ => return d_unknown(w, value, "unknown light source "),
    };
    w.write_str(s)
}

// Flash (Exif 0x9209)
fn d_flash(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    const FIRED: &'static [&'static str] = &["not fired", "fired"];
    const RETURN: &'static [&'static str] = &[
        ", no return light detection function",
        ", reserved return light",
        ", return light not detected",
        ", return light detected",
    ];
    const AUTO: &'static [&'static str] = &[
        ", unknown auto mode", ", forced", ", suppressed", ", auto"];
    const FUNCTION: &'static [&'static str] = &["", ", no function present"];
    const RED_EYE: &'static [&'static str] = &["", ", red-eye reduction"];

    if let Some(v) = value.get_uint(0) {
        write!(w, "{}{}{}{}{}{}",
               FIRED[v as usize & 1],
               RETURN[v as usize >> 1 & 3],
               AUTO[v as usize >> 3 & 3],
               FUNCTION[v as usize >> 5 & 1],
               RED_EYE[v as usize >> 6 & 1],
               if v >> 7 != 0 { ", unknown MSB bits" } else { "" })
    } else {
        d_default(w, value)
    }
}

// SubjectArea (Exif 0x9214), SubjectLocation (Exif 0xa214)
// Only (x, y) case is valid for SubjectLocation.
fn d_subjarea(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    if let Some(x) = value.get_uint(0) {
        if let Some(y) = value.get_uint(1) {
            if let Some(d) = value.get_uint(2) {
                if let Some(h) = value.get_uint(3) {
                    return write!(w, "rectangle (x={}, y={}, w={}, h={})",
                                  x, y, d, h);
                }
                return write!(w, "circle (x={}, y={}, d={})", x, y, d);
            }
            return write!(w, "point (x={}, y={})", x, y);
        }
    }
    d_default(w, value)
}

// Rational/SRational with 0xffffffff being unknown.
// Temperature (Exif 0x9400), Humidity (Exif 0x9401),
// Pressure (Exif 0x9402), WaterDepth (Exif 0x9403),
// Acceleration (Exif 0x9404), CameraElevationAngle (Exif 0x9405)
fn d_optdecimal(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    match *value {
        Value::Rational(ref v) if v.len() > 0 =>
            if v[0].denom != 0xffffffff {
                write!(w, "{}", v[0].to_f64())
            } else {
                w.write_str("unknown")
            },
        Value::SRational(ref v) if v.len() > 0 =>
            if v[0].denom != -1 {
                write!(w, "{}", v[0].to_f64())
            } else {
                w.write_str("unknown")
            },
        _ => d_decimal(w, value),
    }
}

// ColorSpace (Exif 0xa001)
fn d_cspace(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(1) => "sRGB",
        Some(0xffff) => "uncalibrated",
        _ => return d_unknown(w, value, "unknown color space "),
    };
    w.write_str(s)
}

// SensingMethod (Exif 0xa217)
fn d_sensingmethod(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(1) => "not defined",
        Some(2) => "one-chip color area sensor",
        Some(3) => "two-chip color area sensor",
        Some(4) => "three-chip color area sensor",
        Some(5) => "color sequential area sensor",
        Some(7) => "trilinear sensor",
        Some(8) => "color sequential linear sensor",
        _ => return d_unknown(w, value, "unknown sensing method "),
    };
    w.write_str(s)
}

// FileSource (Exif 0xa300)
fn d_filesrc(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match match *value {
        Value::Undefined(s, _) => s.first().map(|&x| x),
        _ => None,
    } {
        Some(0) => "others",
        Some(1) => "transparency scanner",
        Some(2) => "reflective scanner",
        Some(3) => "DSC",
        _ => return d_unknown(w, value, "unknown file source "),
    };
    w.write_str(s)
}

// SceneType (Exif 0xa301)
fn d_scenetype(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match match *value {
        Value::Undefined(s, _) => s.first().map(|&x| x),
        _ => None,
    } {
        Some(1) => "directly photographed image",
        _ => return d_unknown(w, value, "unknown scene type "),
    };
    w.write_str(s)
}

// CustomRendered (Exif 0xa401)
fn d_customrendered(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(0) => "normal process",
        Some(1) => "custom process",
        _ => return d_unknown(w, value, "unknown custom rendered "),
    };
    w.write_str(s)
}

// ExposureMode (Exif 0xa402)
fn d_expmode(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(0) => "auto exposure",
        Some(1) => "manual exposure",
        Some(2) => "auto bracket",
        _ => return d_unknown(w, value, "unknown exposure mode "),
    };
    w.write_str(s)
}

// WhiteBalance (Exif 0xa403)
fn d_whitebalance(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(0) => "auto white balance",
        Some(1) => "manual white balance",
        _ => return d_unknown(w, value, "unknown white balance mode "),
    };
    w.write_str(s)
}

// DigitalZoomRatio (Exif 0xa404)
fn d_dzoomratio(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    if let Value::Rational(ref v) = *value {
        if v.len() > 0 && v[0].num == 0 {
            return w.write_str("unused");
        }
    }
    d_decimal(w, value)
}

// FocalLengthIn35mmFilm (Exif 0xa405)
fn d_focallen35(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    match value.get_uint(0) {
        Some(0) => w.write_str("unknown"),
        _ => d_default(w, value),
    }
}

// SceneCaptureType (Exif 0xa406)
fn d_scenecaptype(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(0) => "standard",
        Some(1) => "landscape",
        Some(2) => "portrait",
        Some(3) => "night scene",
        _ => return d_unknown(w, value, "unknown scene capture type "),
    };
    w.write_str(s)
}

// GainControl (Exif 0xa407)
fn d_gainctrl(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(0) => "none",
        Some(1) => "low gain up",
        Some(2) => "high gain up",
        Some(3) => "low gain down",
        Some(4) => "high gain down",
        _ => return d_unknown(w, value, "unknown gain control "),
    };
    w.write_str(s)
}

// Contrast (Exif 0xa408)
fn d_contrast(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(0) => "normal",
        Some(1) => "soft",
        Some(2) => "hard",
        _ => return d_unknown(w, value, "unknown contrast processing "),
    };
    w.write_str(s)
}

// Saturation (Exif 0xa409)
fn d_saturation(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(0) => "normal",
        Some(1) => "low saturation",
        Some(2) => "high saturation",
        _ => return d_unknown(w, value, "unknown saturation processing "),
    };
    w.write_str(s)
}

// Sharpness (Exif 0xa40a)
fn d_sharpness(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(0) => "normal",
        Some(1) => "soft",
        Some(2) => "hard",
        _ => return d_unknown(w, value, "unknown sharpness processing "),
    };
    w.write_str(s)
}

// SubjectDistanceRange (Exif 0xa40c)
fn d_subjdistrange(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(1) => "macro",
        Some(2) => "close view",
        Some(3) => "distant view",
        _ => return d_unknown(w, value, "unknown subject distance range "),
    };
    w.write_str(s)
}

// LensSpecification (Exif 0xa432)
fn d_lensspec(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    match *value {
        Value::Rational(ref v) if v.len() >= 4 =>
            // There are several notations: "F1.4" in Japan, "f/1.4"
            // in the U.S., and so on.
            write!(w, "{}-{} mm, f/{}-{}",
                   v[0].to_f64(), v[1].to_f64(),
                   v[2].to_f64(), v[3].to_f64()),
        _ => d_default(w, value),
    }
}

// GPSVersionID (Exif/GPS 0x0)
fn d_gpsver(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    match *value {
        Value::Byte(ref v) if v.len() >= 4 =>
            write!(w, "{}.{}.{}.{}", v[0], v[1], v[2], v[3]),
        _ => d_default(w, value),
    }
}

// GPSLatitudeRef (Exif/GPS 0x1), GPSLongitudeRef (Exif/GPS 0x3)
// GPSDestLatitudeRef (Exif/GPS 0x13), GPSDestLongitudeRef (Exif/GPS 0x15)
fn d_gpslatlongref(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    match *value {
        Value::Ascii(ref v) if (v.len() == 1 && v[0].len() == 1 &&
                                isupper(v[0][0])) =>
            w.write_char(v[0][0] as char),
        _ => d_default(w, value),
    }
}

// GPSLatitude (Exif/GPS 0x2), GPSLongitude (Exif 0x4),
// GPSDestLatitude (Exif/GPS 0x14), GPSDestLongitude (Exif 0x16)
fn d_gpsdms(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    match *value {
        Value::Rational(ref v) if v.len() >= 3 =>
            write!(w, "{} deg {} min {} sec",
                   v[0].to_f64(), v[1].to_f64(), v[2].to_f64()),
        _ => d_default(w, value),
    }
}

// GPSAltitudeRef (Exif/GPS 0x5)
fn d_gpsaltref(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(0) => "above sea level",
        Some(1) => "below sea level",
        _ => return d_unknown(w, value, "unknown GPS altitude ref "),
    };
    w.write_str(s)
}

// GPSTimeStamp (Exif/GPS 0x7)
fn d_gpstimestamp(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    match *value {
        Value::Rational(ref v) if v.len() >= 3 => {
            let (h, m, s) = (v[0].to_f64(), v[1].to_f64(), v[2].to_f64());
            write!(w, "{}{}:{}{}:{}{}",
                   if h < 10.0 { "0" } else { "" }, h,
                   if m < 10.0 { "0" } else { "" }, m,
                   if s < 10.0 { "0" } else { "" }, s)
        },
        _ => d_default(w, value),
    }
}

// GPSStatus (Exif/GPS 0x9)
fn d_gpsstatus(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match match *value {
        Value::Ascii(ref v) => v.first().map(|&x| x),
        _ => None,
    } {
        Some(b"A") => "measurement in progress",
        Some(b"V") => "measurement interrupted",
        _ => return d_unknown(w, value, "unknown GPS status "),
    };
    w.write_str(s)
}

// GPSMeasure (Exif/GPS 0xa)
fn d_gpsmeasuremode(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match match *value {
        Value::Ascii(ref v) => v.first().map(|&x| x),
        _ => None,
    } {
        Some(b"2") => "2-dimensional measurement",
        Some(b"3") => "3-dimensional measurement",
        _ => return d_unknown(w, value, "unknown GPS measurement mode "),
    };
    w.write_str(s)
}

// GPSSpeedRef (Exif/GPS 0xc)
fn d_gpsspeedref(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match match *value {
        Value::Ascii(ref v) => v.first().map(|&x| x),
        _ => None,
    } {
        Some(b"K") => "km/h",
        Some(b"M") => "mph",
        Some(b"N") => "knots",
        _ => return d_unknown(w, value, "unknown GPS speed ref "),
    };
    w.write_str(s)
}

// GPSTrackRef (Exif/GPS 0xe), GPSImgDirectionRef (Exif/GPS 0x10),
// GPSDestBearingRef (Exif/GPS 0x17)
fn d_gpsdirref(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match match *value {
        Value::Ascii(ref v) => v.first().map(|&x| x),
        _ => None,
    } {
        Some(b"T") => "true direction",
        Some(b"M") => "magnetic direction",
        _ => return d_unknown(w, value, "unknown GPS direction ref "),
    };
    w.write_str(s)
}

// GPSDestDistanceRef (Exif/GPS 0x19)
fn d_gpsdistref(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match match *value {
        Value::Ascii(ref v) => v.first().map(|&x| x),
        _ => None,
    } {
        Some(b"K") => "km",
        Some(b"M") => "miles",
        Some(b"N") => "nautical miles",
        _ => return d_unknown(w, value, "unknown GPS distance ref "),
    };
    w.write_str(s)
}

// GPSDateStamp (Exif/GPS 0x1d)
fn d_gpsdatestamp(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    if let Value::Ascii(ref v) = *value {
        if let Some(data) = v.first() {
            if data.len() >= 10 && data[4] == b':' && data[7] == b':' {
                if let Ok(year) = atou16(&data[0..4]) {
                    if let Ok(month) = atou16(&data[5..7]) {
                        if let Ok(day) = atou16(&data[8..10]) {
                            return write!(w, "{:04}-{:02}-{:02}",
                                          year, month, day)
                        }
                    }
                }
            }
        }
    }
    d_default(w, value)
}

// GPSDifferential (Exif/GPS 0x1e)
fn d_gpsdifferential(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    let s = match value.get_uint(0) {
        Some(0) => "no differential correction",
        Some(1) => "differential correction applied",
        _ => return d_unknown(w, value, "unknown GPS differential correction "),
    };
    w.write_str(s)
}

fn d_ascii_in_undef(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    match *value {
        Value::Undefined(s, _) => d_sub_ascii(w, s),
        _ => d_default(w, value),
    }
}

fn d_decimal(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    match *value {
        Value::Rational(ref v) => d_sub_comma_f64(w, v),
        Value::SRational(ref v) => d_sub_comma_f64(w, v),
        _ => d_default(w, value),
    }
}

#[inline(never)]
fn d_unknown(w: &mut fmt::Write, value: &Value, prefix: &str) -> fmt::Result {
    try!(w.write_str(prefix));
    d_default(w, value)
}

fn d_default(w: &mut fmt::Write, value: &Value) -> fmt::Result {
    match *value {
        Value::Byte(ref v) => d_sub_comma(w, v),
        Value::Ascii(ref v) => {
            let mut first = true;
            for x in v {
                if !first {
                    try!(w.write_str(", "));
                }
                first = false;
                try!(d_sub_ascii(w, x));
            }
            Ok(())
        },
        Value::Short(ref v) => d_sub_comma(w, v),
        Value::Long(ref v) => d_sub_comma(w, v),
        Value::Rational(ref v) => d_sub_comma(w, v),
        Value::SByte(ref v) => d_sub_comma(w, v),
        Value::Undefined(ref s, _) => d_sub_hex(w, s),
        Value::SShort(ref v) => d_sub_comma(w, v),
        Value::SLong(ref v) => d_sub_comma(w, v),
        Value::SRational(ref v) => d_sub_comma(w, v),
        Value::Float(ref v) => d_sub_comma(w, v),
        Value::Double(ref v) => d_sub_comma(w, v),
        Value::Unknown(t, c, o) =>
            write!(w, "unknown value (type={}, count={}, offset={:#x})",
                   t, c, o),
    }
}

fn d_sub_comma<T>(w: &mut fmt::Write, slice: &[T])
                  -> fmt::Result where T: fmt::Display {
    let mut first = true;
    for x in slice {
        try!(match first {
            true => write!(w, "{}", x),
            false => write!(w, ", {}", x),
        });
        first = false;
    }
    Ok(())
}

fn d_sub_comma_f64<T>(w: &mut fmt::Write, slice: &[T])
                      -> fmt::Result where T: Copy + Into<f64> {
    let mut first = true;
    for &x in slice {
        let x: f64 = x.into();
        try!(match first {
            true => write!(w, "{}", x),
            false => write!(w, ", {}", x),
        });
        first = false;
    }
    Ok(())
}

fn d_sub_hex(w: &mut fmt::Write, bytes: &[u8]) -> fmt::Result {
    try!(w.write_str("0x"));
    for x in bytes {
        try!(write!(w, "{:02x}", x));
    }
    Ok(())
}

fn d_sub_ascii(w: &mut fmt::Write, bytes: &[u8]) -> fmt::Result {
    try!(w.write_char('"'));
    for &c in bytes {
        match c {
            b'\\' | b'"' => {
                try!(w.write_char('\\'));
                try!(w.write_char(c as char));
            },
            0x20...0x7e => try!(w.write_char(c as char)),
            _ => try!(write!(w, "\\x{:02x}", c)),
        }
    }
    w.write_char('"')
}

#[cfg(test)]
mod tests {
    use value::Rational;
    use super::*;

    // This test checks if Tag constants can be used in patterns.
    #[test]
    fn tag_constant_in_pattern() {
        // Destructuring, which will always work.
        match Tag(Context::Tiff, 0x132) {
            Tag(Context::Tiff, 0x132) => {},
            _ => panic!("failed to match Tag"),
        }
        // Matching against a constant.  Test if this compiles.
        match Tag(Context::Tiff, 0x132) {
            Tag::DateTime => {},
            _ => panic!("failed to match Tag"),
        }
    }

    #[test]
    fn default_value() {
        assert_pat!(Tag::DateTime.default_value(), None);
        match Tag::BitsPerSample.default_value() {
            Some(Value::Short(v)) => assert_eq!(v, &[8, 8, 8]),
            _ => panic!(),
        }
        match Tag::XResolution.default_value() {
            Some(Value::Rational(v)) => {
                assert_eq!(v.len(), 1);
                assert_eq!(v[0].num, 72);
                assert_eq!(v[0].denom, 1);
            },
            _ => panic!(),
        }
        match Tag::FileSource.default_value() {
            Some(Value::Undefined(v, _)) => assert_eq!(v, &[3]),
            _ => panic!(),
        }
        match Tag::GPSAltitudeRef.default_value() {
            Some(Value::Byte(v)) => assert_eq!(v, &[0]),
            _ => panic!(),
        }
        match Tag::GPSSpeedRef.default_value() {
            Some(Value::Ascii(v)) => assert_eq!(v, &[b"K"]),
            _ => panic!(),
        }
    }

    #[test]
    fn tag_fmt_display() {
        let tag1 = Tag(Context::Tiff, 0x132);
        assert_eq!(format!("{:15}", tag1), "DateTime       ");
        assert_eq!(format!("{:>15}", tag1), "       DateTime");
        assert_eq!(format!("{:5.6}", tag1), "DateTi");
        let tag2 = Tag(Context::Exif, 0);
        assert_eq!(format!("{:15}", tag2), "Tag(Exif, 0)   ");
        assert_eq!(format!("{:>15}", tag2), "   Tag(Exif, 0)");
        assert_eq!(format!("{:5.6}", tag2), "Tag(Ex");
    }

    #[test]
    fn disp_val_sub() {
        let mut buf = String::new();
        d_sub_comma(&mut buf, &[0u16, 1, 2]).unwrap();
        assert_eq!(buf, "0, 1, 2");

        let mut buf = String::new();
        d_sub_comma(&mut buf, &[Rational { num: 3, denom: 5 }]).unwrap();
        assert_eq!(buf, "3/5");

        let mut buf = String::new();
        d_sub_comma_f64(&mut buf, &[Rational { num: 1, denom: 2 }]).unwrap();
        assert_eq!(buf, "0.5");

        let mut buf = String::new();
        d_sub_hex(&mut buf, b"abc\x00\xff").unwrap();
        assert_eq!(buf, "0x61626300ff");

        let mut buf = String::new();
        d_sub_ascii(&mut buf, b"a \"\\b\"\n").unwrap();
        assert_eq!(buf, r#""a \"\\b\"\x0a""#);
    }
}