text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `src/value.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>value.rs.html -- source</title>

    <link rel="stylesheet" type="text/css" href="../../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../../main.css">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

   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
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412

//! Hjson Value
//!
//! This module is centered around the `Value` type, which can represent all possible Hjson values.
//!
//! # Example of use:
//!
//! ```rust</span>
<span class='doccomment'>//! extern crate serde_hjson;</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//! use serde_hjson::Value;</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//! fn main() {</span>
<span class='doccomment'>//!     let s = "{x: 1.0, y: 2.0}";</span>
<span class='doccomment'>//!     let value: Value = serde_hjson::from_str(s).unwrap();</span>
<span class='doccomment'>//! }</span>
<span class='doccomment'>//! ```
//!
//! It is also possible to deserialize from a `Value` type:
//!
//! ```rust</span>
<span class='doccomment'>//! extern crate serde_hjson;</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//! use serde_hjson::{Value, Map};</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//! fn main() {</span>
<span class='doccomment'>//!     let mut map = Map::new();</span>
<span class='doccomment'>//!     map.insert(String::from("x"), Value::F64(1.0));</span>
<span class='doccomment'>//!     map.insert(String::from("y"), Value::F64(2.0));</span>
<span class='doccomment'>//!     let value = Value::Object(map);</span>
<span class='doccomment'>//!</span>
<span class='doccomment'>//!     let map: Map<String, f64> = serde_hjson::from_value(value).unwrap();</span>
<span class='doccomment'>//! }</span>
<span class='doccomment'>//! ```

#[cfg(not(feature = "preserve_order"))]
use std::collections::{BTreeMap, btree_map};

#[cfg(feature = "preserve_order")]
use linked_hash_map::{self, LinkedHashMap};

use std::fmt;
use std::io;
use std::str;
use std::vec;

use num_traits::NumCast;

use serde::de;
use serde::ser;

use error::{Error, ErrorCode};

/// Represents a key/value type.
#[cfg(not(feature = "preserve_order"))]
pub type Map<K, V> = BTreeMap<K, V>;
/// Represents a key/value type.
#[cfg(feature = "preserve_order")]
pub type Map<K, V> = LinkedHashMap<K, V>;

/// Represents the `IntoIter` type.
#[cfg(not(feature = "preserve_order"))]
pub type MapIntoIter<K, V> = btree_map::IntoIter<K, V>;
/// Represents the IntoIter type.
#[cfg(feature = "preserve_order")]
pub type MapIntoIter<K, V> = linked_hash_map::IntoIter<K, V>;

#[cfg(not(feature = "preserve_order"))]
type MapVisitor<K, T> = de::impls::BTreeMapVisitor<K, T>;
#[cfg(feature = "preserve_order")]
type MapVisitor<K, T> = linked_hash_map::serde::LinkedHashMapVisitor<K, T>;

/// Represents a Hjson/JSON value
#[derive(Clone, PartialEq)]
pub enum Value {
    /// Represents a JSON null value
    Null,

    /// Represents a JSON Boolean
    Bool(bool),

    /// Represents a JSON signed integer
    I64(i64),

    /// Represents a JSON unsigned integer
    U64(u64),

    /// Represents a JSON floating point number
    F64(f64),

    /// Represents a JSON string
    String(String),

    /// Represents a JSON array
    Array(Vec<Value>),

    /// Represents a JSON object
    Object(Map<String, Value>),
}

impl Value {
    /// If the `Value` is an Object, returns the value associated with the provided key.
    /// Otherwise, returns None.
    pub fn find<'a>(&'a self, key: &str) -> Option<&'a Value> {
        match *self {
            Value::Object(ref map) => map.get(key),
            _ => None,
        }
    }

    /// Attempts to get a nested Value Object for each key in `keys`.
    /// If any key is found not to exist, find_path will return None.
    /// Otherwise, it will return the `Value` associated with the final key.
    pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Value> {
        let mut target = self;
        for key in keys {
            match target.find(key) {
                Some(t) => {
                    target = t;
                }
                None => return None,
            }
        }
        Some(target)
    }

    /// Looks up a value by a JSON Pointer.
    ///
    /// JSON Pointer defines a string syntax for identifying a specific value
    /// within a JavaScript Object Notation (JSON) document.
    ///
    /// A Pointer is a Unicode string with the reference tokens separated by `/`.
    /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
    /// addressed value is returned and if there is no such value `None` is
    /// returned.
    ///
    /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
    pub fn pointer<'a>(&'a self, pointer: &str) -> Option<&'a Value> {
        fn parse_index(s: &str) -> Option<usize> {
            if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
                return None;
            }
            s.parse().ok()
        }
        if pointer == "" {
            return Some(self);
        }
        if !pointer.starts_with('/') {
            return None;
        }
        let mut target = self;
        for escaped_token in pointer.split('/').skip(1) {
            let token = escaped_token.replace("~1", "/").replace("~0", "~");
            let target_opt = match *target {
                Value::Object(ref map) => map.get(&token[..]),
                Value::Array(ref list) => {
                    parse_index(&token[..]).and_then(|x| list.get(x))
                }
                _ => return None,
            };
            if let Some(t) = target_opt {
                target = t;
            } else {
                return None;
            }
        }
        Some(target)
    }

    /// If the `Value` is an Object, performs a depth-first search until
    /// a value associated with the provided key is found. If no value is found
    /// or the `Value` is not an Object, returns None.
    pub fn search<'a>(&'a self, key: &str) -> Option<&'a Value> {
        match *self {
            Value::Object(ref map) => {
                match map.get(key) {
                    Some(json_value) => Some(json_value),
                    None => {
                        for (_, v) in map.iter() {
                            match v.search(key) {
                                x if x.is_some() => return x,
                                _ => (),
                            }
                        }
                        None
                    }
                }
            }
            _ => None,
        }
    }

    /// Returns true if the `Value` is an Object. Returns false otherwise.
    pub fn is_object(&self) -> bool {
        self.as_object().is_some()
    }

    /// If the `Value` is an Object, returns the associated Map.
    /// Returns None otherwise.
    pub fn as_object(&self) -> Option<&Map<String, Value>> {
        match *self {
            Value::Object(ref map) => Some(map),
            _ => None,
        }
    }

    /// If the `Value` is an Object, returns the associated mutable Map.
    /// Returns None otherwise.
    pub fn as_object_mut(&mut self) -> Option<&mut Map<String, Value>> {
        match *self {
            Value::Object(ref mut map) => Some(map),
            _ => None,
        }
    }

    /// Returns true if the `Value` is an Array. Returns false otherwise.
    pub fn is_array(&self) -> bool {
        self.as_array().is_some()
    }

    /// If the `Value` is an Array, returns the associated vector.
    /// Returns None otherwise.
    pub fn as_array(&self) -> Option<&Vec<Value>> {
        match *self {
            Value::Array(ref array) => Some(&*array),
            _ => None,
        }
    }

    /// If the `Value` is an Array, returns the associated mutable vector.
    /// Returns None otherwise.
    pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
        match *self {
            Value::Array(ref mut list) => Some(list),
            _ => None,
        }
    }

    /// Returns true if the `Value` is a String. Returns false otherwise.
    pub fn is_string(&self) -> bool {
        self.as_str().is_some()
    }

    /// If the `Value` is a String, returns the associated str.
    /// Returns None otherwise.
    pub fn as_str(&self) -> Option<&str> {
        match *self {
            Value::String(ref s) => Some(s),
            _ => None,
        }
    }

    /// Returns true if the `Value` is a Number. Returns false otherwise.
    pub fn is_number(&self) -> bool {
        match *self {
            Value::I64(_) | Value::U64(_) | Value::F64(_) => true,
            _ => false,
        }
    }

    /// Returns true if the `Value` is a i64. Returns false otherwise.
    pub fn is_i64(&self) -> bool {
        match *self {
            Value::I64(_) => true,
            _ => false,
        }
    }

    /// Returns true if the `Value` is a u64. Returns false otherwise.
    pub fn is_u64(&self) -> bool {
        match *self {
            Value::U64(_) => true,
            _ => false,
        }
    }

    /// Returns true if the `Value` is a f64. Returns false otherwise.
    pub fn is_f64(&self) -> bool {
        match *self {
            Value::F64(_) => true,
            _ => false,
        }
    }

    /// If the `Value` is a number, return or cast it to a i64.
    /// Returns None otherwise.
    pub fn as_i64(&self) -> Option<i64> {
        match *self {
            Value::I64(n) => Some(n),
            Value::U64(n) => NumCast::from(n),
            _ => None,
        }
    }

    /// If the `Value` is a number, return or cast it to a u64.
    /// Returns None otherwise.
    pub fn as_u64(&self) -> Option<u64> {
        match *self {
            Value::I64(n) => NumCast::from(n),
            Value::U64(n) => Some(n),
            _ => None,
        }
    }

    /// If the `Value` is a number, return or cast it to a f64.
    /// Returns None otherwise.
    pub fn as_f64(&self) -> Option<f64> {
        match *self {
            Value::I64(n) => NumCast::from(n),
            Value::U64(n) => NumCast::from(n),
            Value::F64(n) => Some(n),
            _ => None,
        }
    }

    /// Returns true if the `Value` is a Boolean. Returns false otherwise.
    pub fn is_boolean(&self) -> bool {
        self.as_bool().is_some()
    }

    /// If the `Value` is a Boolean, returns the associated bool.
    /// Returns None otherwise.
    pub fn as_bool(&self) -> Option<bool> {
        match *self {
            Value::Bool(b) => Some(b),
            _ => None,
        }
    }

    /// Returns true if the `Value` is a Null. Returns false otherwise.
    pub fn is_null(&self) -> bool {
        self.as_null().is_some()
    }

    /// If the `Value` is a Null, returns ().
    /// Returns None otherwise.
    pub fn as_null(&self) -> Option<()> {
        match *self {
            Value::Null => Some(()),
            _ => None,
        }
    }
}

impl ser::Serialize for Value {
    #[inline]
    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
        where S: ser::Serializer,
    {
        match *self {
            Value::Null => serializer.serialize_unit(),
            Value::Bool(v) => serializer.serialize_bool(v),
            Value::I64(v) => serializer.serialize_i64(v),
            Value::U64(v) => serializer.serialize_u64(v),
            Value::F64(v) => serializer.serialize_f64(v),
            Value::String(ref v) => serializer.serialize_str(v),
            Value::Array(ref v) => v.serialize(serializer),
            Value::Object(ref v) => v.serialize(serializer),
        }
    }
}

impl de::Deserialize for Value {
    #[inline]
    fn deserialize<D>(deserializer: &mut D) -> Result<Value, D::Error>
        where D: de::Deserializer,
    {
        struct ValueVisitor;

        impl de::Visitor for ValueVisitor {
            type Value = Value;

            #[inline]
            fn visit_bool<E>(&mut self, value: bool) -> Result<Value, E> {
                Ok(Value::Bool(value))
            }

            #[inline]
            fn visit_i64<E>(&mut self, value: i64) -> Result<Value, E> {
                if value < 0 {
                    Ok(Value::I64(value))
                } else {
                    Ok(Value::U64(value as u64))
                }
            }

            #[inline]
            fn visit_u64<E>(&mut self, value: u64) -> Result<Value, E> {
                Ok(Value::U64(value))
            }

            #[inline]
            fn visit_f64<E>(&mut self, value: f64) -> Result<Value, E> {
                Ok(Value::F64(value))
            }

            #[inline]
            fn visit_str<E>(&mut self, value: &str) -> Result<Value, E>
                where E: de::Error,
            {
                self.visit_string(String::from(value))
            }

            #[inline]
            fn visit_string<E>(&mut self, value: String) -> Result<Value, E> {
                Ok(Value::String(value))
            }

            #[inline]
            fn visit_none<E>(&mut self) -> Result<Value, E> {
                Ok(Value::Null)
            }

            #[inline]
            fn visit_some<D>(
                &mut self,
                deserializer: &mut D
            ) -> Result<Value, D::Error>
                where D: de::Deserializer,
            {
                de::Deserialize::deserialize(deserializer)
            }

            #[inline]
            fn visit_unit<E>(&mut self) -> Result<Value, E> {
                Ok(Value::Null)
            }

            #[inline]
            fn visit_seq<V>(&mut self, visitor: V) -> Result<Value, V::Error>
                where V: de::SeqVisitor,
            {
                let values = try!(de::impls::VecVisitor::new()
                    .visit_seq(visitor));
                Ok(Value::Array(values))
            }

            #[inline]
            fn visit_map<V>(&mut self, visitor: V) -> Result<Value, V::Error>
                where V: de::MapVisitor,
            {
                let values = try!(MapVisitor::new().visit_map(visitor));
                Ok(Value::Object(values))
            }
        }

        deserializer.deserialize(ValueVisitor)
    }
}

struct WriterFormatter<'a, 'b: 'a> {
    inner: &'a mut fmt::Formatter<'b>,
}

impl<'a, 'b> io::Write for WriterFormatter<'a, 'b> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        fn io_error<E>(_: E) -> io::Error {
            // Value does not matter because fmt::Debug and fmt::Display impls
            // below just map it to fmt::Error
            io::Error::new(io::ErrorKind::Other, "fmt error")
        }
        let s = try!(str::from_utf8(buf).map_err(io_error));
        try!(self.inner.write_str(s).map_err(io_error));
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

impl fmt::Debug for Value {
    /// Serializes a Hjson value into a string
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut wr = WriterFormatter {
            inner: f,
        };
        super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error)
    }
}

impl fmt::Display for Value {
    /// Serializes a Hjson value into a string
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut wr = WriterFormatter {
            inner: f,
        };
        super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error)
    }
}

impl str::FromStr for Value {
    type Err = Error;
    fn from_str(s: &str) -> Result<Value, Error> {
        super::de::from_str(s)
    }
}

/// Create a `serde::Serializer` that serializes a `Serialize`e into a `Value`.
pub struct Serializer {
    value: Value,
}

impl Serializer {
    /// Construct a new `Serializer`.
    pub fn new() -> Serializer {
        Serializer {
            value: Value::Null,
        }
    }

    /// Unwrap the `Serializer` and return the `Value`.
    pub fn unwrap(self) -> Value {
        self.value
    }
}

impl Default for Serializer {
    fn default() -> Self {
        Serializer::new()
    }
}

#[doc(hidden)]
pub struct TupleVariantState {
    name: String,
    vec: Vec<Value>,
}

#[doc(hidden)]
pub struct StructVariantState {
    name: String,
    map: Map<String, Value>,
}

#[doc(hidden)]
pub struct MapState {
    map: Map<String, Value>,
    next_key: Option<String>,
}

impl ser::Serializer for Serializer {
    type Error = Error;

    type SeqState = Vec<Value>;
    type TupleState = Vec<Value>;
    type TupleStructState = Vec<Value>;
    type TupleVariantState = TupleVariantState;
    type MapState = MapState;
    type StructState = MapState;
    type StructVariantState = StructVariantState;

    #[inline]
    fn serialize_bool(&mut self, value: bool) -> Result<(), Error> {
        self.value = Value::Bool(value);
        Ok(())
    }

    #[inline]
    fn serialize_isize(&mut self, value: isize) -> Result<(), Error> {
        self.serialize_i64(value as i64)
    }

    #[inline]
    fn serialize_i8(&mut self, value: i8) -> Result<(), Error> {
        self.serialize_i64(value as i64)
    }

    #[inline]
    fn serialize_i16(&mut self, value: i16) -> Result<(), Error> {
        self.serialize_i64(value as i64)
    }

    #[inline]
    fn serialize_i32(&mut self, value: i32) -> Result<(), Error> {
        self.serialize_i64(value as i64)
    }

    fn serialize_i64(&mut self, value: i64) -> Result<(), Error> {
        if value < 0 {
            self.value = Value::I64(value);
        } else {
            self.value = Value::U64(value as u64);
        }
        Ok(())
    }

    #[inline]
    fn serialize_usize(&mut self, value: usize) -> Result<(), Error> {
        self.serialize_u64(value as u64)
    }

    #[inline]
    fn serialize_u8(&mut self, value: u8) -> Result<(), Error> {
        self.serialize_u64(value as u64)
    }

    #[inline]
    fn serialize_u16(&mut self, value: u16) -> Result<(), Error> {
        self.serialize_u64(value as u64)
    }

    #[inline]
    fn serialize_u32(&mut self, value: u32) -> Result<(), Error> {
        self.serialize_u64(value as u64)
    }

    #[inline]
    fn serialize_u64(&mut self, value: u64) -> Result<(), Error> {
        self.value = Value::U64(value);
        Ok(())
    }

    #[inline]
    fn serialize_f32(&mut self, value: f32) -> Result<(), Error> {
        self.serialize_f64(value as f64)
    }

    #[inline]
    fn serialize_f64(&mut self, value: f64) -> Result<(), Error> {
        self.value = Value::F64(value);
        Ok(())
    }

    #[inline]
    fn serialize_char(&mut self, value: char) -> Result<(), Error> {
        let mut s = String::new();
        s.push(value);
        self.serialize_str(&s)
    }

    #[inline]
    fn serialize_str(&mut self, value: &str) -> Result<(), Error> {
        self.value = Value::String(String::from(value));
        Ok(())
    }

    fn serialize_bytes(&mut self, value: &[u8]) -> Result<(), Error> {
        let mut state = try!(self.serialize_seq(Some(value.len())));
        for byte in value {
            try!(self.serialize_seq_elt(&mut state, byte));
        }
        self.serialize_seq_end(state)
    }

    #[inline]
    fn serialize_unit(&mut self) -> Result<(), Error> {
        Ok(())
    }

    #[inline]
    fn serialize_unit_struct(
        &mut self,
        _name: &'static str
    ) -> Result<(), Error> {
        self.serialize_unit()
    }

    #[inline]
    fn serialize_unit_variant(
        &mut self,
        _name: &'static str,
        _variant_index: usize,
        variant: &'static str
    ) -> Result<(), Error> {
        self.serialize_str(variant)
    }

    #[inline]
    fn serialize_newtype_struct<T>(
        &mut self,
        _name: &'static str,
        value: T
    ) -> Result<(), Error>
        where T: ser::Serialize,
    {
        value.serialize(self)
    }

    fn serialize_newtype_variant<T>(
        &mut self,
        _name: &'static str,
        _variant_index: usize,
        variant: &'static str,
        value: T
    ) -> Result<(), Error>
        where T: ser::Serialize,
    {
        let mut values = Map::new();
        values.insert(String::from(variant), to_value(&value));
        self.value = Value::Object(values);
        Ok(())
    }

    #[inline]
    fn serialize_none(&mut self) -> Result<(), Error> {
        self.serialize_unit()
    }

    #[inline]
    fn serialize_some<V>(&mut self, value: V) -> Result<(), Error>
        where V: ser::Serialize,
    {
        value.serialize(self)
    }

    fn serialize_seq(
        &mut self,
        len: Option<usize>
    ) -> Result<Vec<Value>, Error> {
        Ok(Vec::with_capacity(len.unwrap_or(0)))
    }

    fn serialize_seq_elt<T: ser::Serialize>(
        &mut self,
        state: &mut Vec<Value>,
        value: T
    ) -> Result<(), Error>
        where T: ser::Serialize,
    {
        state.push(to_value(&value));
        Ok(())
    }

    fn serialize_seq_end(&mut self, state: Vec<Value>) -> Result<(), Error> {
        self.value = Value::Array(state);
        Ok(())
    }

    fn serialize_seq_fixed_size(
        &mut self,
        size: usize
    ) -> Result<Vec<Value>, Error> {
        self.serialize_seq(Some(size))
    }

    fn serialize_tuple(&mut self, len: usize) -> Result<Vec<Value>, Error> {
        self.serialize_seq(Some(len))
    }

    fn serialize_tuple_elt<T: ser::Serialize>(
        &mut self,
        state: &mut Vec<Value>,
        value: T
    ) -> Result<(), Error> {
        self.serialize_seq_elt(state, value)
    }

    fn serialize_tuple_end(&mut self, state: Vec<Value>) -> Result<(), Error> {
        self.serialize_seq_end(state)
    }

    fn serialize_tuple_struct(
        &mut self,
        _name: &'static str,
        len: usize
    ) -> Result<Vec<Value>, Error> {
        self.serialize_seq(Some(len))
    }

    fn serialize_tuple_struct_elt<T: ser::Serialize>(
        &mut self,
        state: &mut Vec<Value>,
        value: T
    ) -> Result<(), Error> {
        self.serialize_seq_elt(state, value)
    }

    fn serialize_tuple_struct_end(
        &mut self,
        state: Vec<Value>
    ) -> Result<(), Error> {
        self.serialize_seq_end(state)
    }

    fn serialize_tuple_variant(
        &mut self,
        _name: &'static str,
        _variant_index: usize,
        variant: &'static str,
        len: usize
    ) -> Result<TupleVariantState, Error> {
        Ok(TupleVariantState {
            name: String::from(variant),
            vec: Vec::with_capacity(len),
        })
    }

    fn serialize_tuple_variant_elt<T: ser::Serialize>(
        &mut self,
        state: &mut TupleVariantState,
        value: T
    ) -> Result<(), Error> {
        state.vec.push(to_value(&value));
        Ok(())
    }

    fn serialize_tuple_variant_end(
        &mut self,
        state: TupleVariantState
    ) -> Result<(), Error> {
        let mut object = Map::new();

        object.insert(state.name, Value::Array(state.vec));

        self.value = Value::Object(object);
        Ok(())
    }

    fn serialize_map(
        &mut self,
        _len: Option<usize>
    ) -> Result<MapState, Error> {
        Ok(MapState {
            map: Map::new(),
            next_key: None,
        })
    }

    fn serialize_map_key<T: ser::Serialize>(
        &mut self,
        state: &mut MapState,
        key: T,
    ) -> Result<(), Error> {
        match to_value(&key) {
            Value::String(s) => state.next_key = Some(s),
            _ => return Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)),
        };
        Ok(())
    }

    fn serialize_map_value<T: ser::Serialize>(
        &mut self,
        state: &mut MapState,
        value: T,
    ) -> Result<(), Error> {
        match state.next_key.take() {
            Some(key) => state.map.insert(key, to_value(&value)),
            None => {
                return Err(Error::Syntax(ErrorCode::Custom("serialize_map_value without \
                                                            matching serialize_map_key".to_owned()),
                                         0, 0));
            }
        };
        Ok(())
    }

    fn serialize_map_end(
        &mut self,
        state: MapState,
    ) -> Result<(), Error> {
        self.value = Value::Object(state.map);
        Ok(())
    }

    fn serialize_struct(
        &mut self,
        _name: &'static str,
        len: usize
    ) -> Result<MapState, Error> {
        self.serialize_map(Some(len))
    }

    fn serialize_struct_elt<V: ser::Serialize>(
        &mut self,
        state: &mut MapState,
        key: &'static str,
        value: V
    ) -> Result<(), Error> {
        try!(self.serialize_map_key(state, key));
        self.serialize_map_value(state, value)
    }

    fn serialize_struct_end(
        &mut self,
        state: MapState
    ) -> Result<(), Error> {
        self.serialize_map_end(state)
    }

    fn serialize_struct_variant(
        &mut self,
        _name: &'static str,
        _variant_index: usize,
        variant: &'static str,
        _len: usize
    ) -> Result<StructVariantState, Error> {
        Ok(StructVariantState {
            name: String::from(variant),
            map: Map::new(),
        })
    }

    fn serialize_struct_variant_elt<V: ser::Serialize>(
        &mut self,
        state: &mut StructVariantState,
        key: &'static str,
        value: V
    ) -> Result<(), Error> {
        state.map.insert(String::from(key), to_value(&value));
        Ok(())
    }

    fn serialize_struct_variant_end(
        &mut self,
        state: StructVariantState
    ) -> Result<(), Error> {
        let mut object = Map::new();

        object.insert(state.name, Value::Object(state.map));

        self.value = Value::Object(object);
        Ok(())
    }
}

/// Creates a `serde::Deserializer` from a `Value` object.
pub struct Deserializer {
    value: Option<Value>,
}

impl Deserializer {
    /// Creates a new deserializer instance for deserializing the specified Hjson value.
    pub fn new(value: Value) -> Deserializer {
        Deserializer {
            value: Some(value),
        }
    }
}

impl de::Deserializer for Deserializer {
    type Error = Error;

    #[inline]
    fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
        where V: de::Visitor,
    {
        let value = match self.value.take() {
            Some(value) => value,
            None => {
                return Err(de::Error::end_of_stream());
            }
        };

        match value {
            Value::Null => visitor.visit_unit(),
            Value::Bool(v) => visitor.visit_bool(v),
            Value::I64(v) => visitor.visit_i64(v),
            Value::U64(v) => visitor.visit_u64(v),
            Value::F64(v) => visitor.visit_f64(v),
            Value::String(v) => visitor.visit_string(v),
            Value::Array(v) => {
                let len = v.len();
                visitor.visit_seq(SeqDeserializer {
                    de: self,
                    iter: v.into_iter(),
                    len: len,
                })
            }
            Value::Object(v) => {
                let len = v.len();
                visitor.visit_map(MapDeserializer {
                    de: self,
                    iter: v.into_iter(),
                    value: None,
                    len: len,
                })
            }
        }
    }

    #[inline]
    fn deserialize_option<V>(
        &mut self,
        mut visitor: V
    ) -> Result<V::Value, Error>
        where V: de::Visitor,
    {
        match self.value {
            Some(Value::Null) => visitor.visit_none(),
            Some(_) => visitor.visit_some(self),
            None => Err(de::Error::end_of_stream()),
        }
    }

    #[inline]
    fn deserialize_enum<V>(
        &mut self,
        _name: &str,
        _variants: &'static [&'static str],
        mut visitor: V
    ) -> Result<V::Value, Error>
        where V: de::EnumVisitor,
    {
        let (variant, value) = match self.value.take() {
            Some(Value::Object(value)) => {
                let mut iter = value.into_iter();
                let (variant, value) = match iter.next() {
                    Some(v) => v,
                    None => {
                        return Err(de::Error::invalid_type(de::Type::VariantName));
                    }
                };
                // enums are encoded in json as maps with a single key:value pair
                if iter.next().is_some() {
                    return Err(de::Error::invalid_type(de::Type::Map));
                }
                (variant, Some(value))
            }
            Some(Value::String(variant)) => (variant, None),
            Some(_) => {
                return Err(de::Error::invalid_type(de::Type::Enum));
            }
            None => {
                return Err(de::Error::end_of_stream());
            }
        };

        visitor.visit(VariantDeserializer {
            de: self,
            val: value,
            variant: Some(Value::String(variant)),
        })
    }

    #[inline]
    fn deserialize_newtype_struct<V>(
        &mut self,
        _name: &'static str,
        mut visitor: V
    ) -> Result<V::Value, Self::Error>
        where V: de::Visitor,
    {
        visitor.visit_newtype_struct(self)
    }

    forward_to_deserialize!{
        deserialize_bool();
        deserialize_usize();
        deserialize_u8();
        deserialize_u16();
        deserialize_u32();
        deserialize_u64();
        deserialize_isize();
        deserialize_i8();
        deserialize_i16();
        deserialize_i32();
        deserialize_i64();
        deserialize_f32();
        deserialize_f64();
        deserialize_char();
        deserialize_str();
        deserialize_string();
        deserialize_unit();
        deserialize_seq();
        deserialize_seq_fixed_size(len: usize);
        deserialize_bytes();
        deserialize_map();
        deserialize_unit_struct(name: &'static str);
        deserialize_tuple_struct(name: &'static str, len: usize);
        deserialize_struct(name: &'static str, fields: &'static [&'static str]);
        deserialize_struct_field();
        deserialize_tuple(len: usize);
        deserialize_ignored_any();
    }
}

struct VariantDeserializer<'a> {
    de: &'a mut Deserializer,
    val: Option<Value>,
    variant: Option<Value>,
}

impl<'a> de::VariantVisitor for VariantDeserializer<'a> {
    type Error = Error;

    fn visit_variant<V>(&mut self) -> Result<V, Error>
        where V: de::Deserialize,
    {
        let variant = self.variant.take().expect("variant is missing");
        de::Deserialize::deserialize(&mut Deserializer::new(variant))
    }

    fn visit_unit(&mut self) -> Result<(), Error> {
        match self.val.take() {
            Some(val) => {
                de::Deserialize::deserialize(&mut Deserializer::new(val))
            }
            None => Ok(()),
        }
    }

    fn visit_newtype<T>(&mut self) -> Result<T, Error>
        where T: de::Deserialize,
    {
        let val = self.val.take().expect("val is missing");
        de::Deserialize::deserialize(&mut Deserializer::new(val))
    }

    fn visit_tuple<V>(
        &mut self,
        _len: usize,
        visitor: V
    ) -> Result<V::Value, Error>
        where V: de::Visitor,
    {
        let val = self.val.take().expect("val is missing");
        if let Value::Array(fields) = val {
            de::Deserializer::deserialize(&mut SeqDeserializer {
                                              de: self.de,
                                              len: fields.len(),
                                              iter: fields.into_iter(),
                                          },
                                          visitor)
        } else {
            Err(de::Error::invalid_type(de::Type::Tuple))
        }
    }

    fn visit_struct<V>(
        &mut self,
        _fields: &'static [&'static str],
        visitor: V
    ) -> Result<V::Value, Error>
        where V: de::Visitor,
    {
        let val = self.val.take().expect("val is missing");
        if let Value::Object(fields) = val {
            de::Deserializer::deserialize(&mut MapDeserializer {
                                              de: self.de,
                                              len: fields.len(),
                                              iter: fields.into_iter(),
                                              value: None,
                                          },
                                          visitor)
        } else {
            Err(de::Error::invalid_type(de::Type::Struct))
        }
    }
}

struct SeqDeserializer<'a> {
    de: &'a mut Deserializer,
    iter: vec::IntoIter<Value>,
    len: usize,
}

impl<'a> de::Deserializer for SeqDeserializer<'a> {
    type Error = Error;

    #[inline]
    fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
        where V: de::Visitor,
    {
        if self.len == 0 {
            visitor.visit_unit()
        } else {
            visitor.visit_seq(self)
        }
    }

    forward_to_deserialize!{
        deserialize_bool();
        deserialize_usize();
        deserialize_u8();
        deserialize_u16();
        deserialize_u32();
        deserialize_u64();
        deserialize_isize();
        deserialize_i8();
        deserialize_i16();
        deserialize_i32();
        deserialize_i64();
        deserialize_f32();
        deserialize_f64();
        deserialize_char();
        deserialize_str();
        deserialize_string();
        deserialize_unit();
        deserialize_option();
        deserialize_seq();
        deserialize_seq_fixed_size(len: usize);
        deserialize_bytes();
        deserialize_map();
        deserialize_unit_struct(name: &'static str);
        deserialize_newtype_struct(name: &'static str);
        deserialize_tuple_struct(name: &'static str, len: usize);
        deserialize_struct(name: &'static str, fields: &'static [&'static str]);
        deserialize_struct_field();
        deserialize_tuple(len: usize);
        deserialize_enum(name: &'static str, variants: &'static [&'static str]);
        deserialize_ignored_any();
    }
}

impl<'a> de::SeqVisitor for SeqDeserializer<'a> {
    type Error = Error;

    fn visit<T>(&mut self) -> Result<Option<T>, Error>
        where T: de::Deserialize,
    {
        match self.iter.next() {
            Some(value) => {
                self.len -= 1;
                self.de.value = Some(value);
                Ok(Some(try!(de::Deserialize::deserialize(self.de))))
            }
            None => Ok(None),
        }
    }

    fn end(&mut self) -> Result<(), Error> {
        if self.len == 0 {
            Ok(())
        } else {
            Err(de::Error::invalid_length(self.len))
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.len, Some(self.len))
    }
}

struct MapDeserializer<'a> {
    de: &'a mut Deserializer,
    iter: MapIntoIter<String, Value>,
    value: Option<Value>,
    len: usize,
}

impl<'a> de::MapVisitor for MapDeserializer<'a> {
    type Error = Error;

    fn visit_key<T>(&mut self) -> Result<Option<T>, Error>
        where T: de::Deserialize,
    {
        match self.iter.next() {
            Some((key, value)) => {
                self.len -= 1;
                self.value = Some(value);
                self.de.value = Some(Value::String(key));
                Ok(Some(try!(de::Deserialize::deserialize(self.de))))
            }
            None => Ok(None),
        }
    }

    fn visit_value<T>(&mut self) -> Result<T, Error>
        where T: de::Deserialize,
    {
        let value = self.value.take().expect("value is missing");
        self.de.value = Some(value);
        Ok(try!(de::Deserialize::deserialize(self.de)))
    }

    fn end(&mut self) -> Result<(), Error> {
        if self.len == 0 {
            Ok(())
        } else {
            Err(de::Error::invalid_length(self.len))
        }
    }

    fn missing_field<V>(&mut self, field: &'static str) -> Result<V, Error>
        where V: de::Deserialize,
    {
        struct MissingFieldDeserializer(&'static str);

        impl de::Deserializer for MissingFieldDeserializer {
            type Error = de::value::Error;

            fn deserialize<V>(
                &mut self,
                _visitor: V
            ) -> Result<V::Value, Self::Error>
                where V: de::Visitor,
            {
                let &mut MissingFieldDeserializer(field) = self;
                Err(de::value::Error::MissingField(field))
            }

            fn deserialize_option<V>(
                &mut self,
                mut visitor: V
            ) -> Result<V::Value, Self::Error>
                where V: de::Visitor,
            {
                visitor.visit_none()
            }

            forward_to_deserialize!{
                deserialize_bool();
                deserialize_usize();
                deserialize_u8();
                deserialize_u16();
                deserialize_u32();
                deserialize_u64();
                deserialize_isize();
                deserialize_i8();
                deserialize_i16();
                deserialize_i32();
                deserialize_i64();
                deserialize_f32();
                deserialize_f64();
                deserialize_char();
                deserialize_str();
                deserialize_string();
                deserialize_unit();
                deserialize_seq();
                deserialize_seq_fixed_size(len: usize);
                deserialize_bytes();
                deserialize_map();
                deserialize_unit_struct(name: &'static str);
                deserialize_newtype_struct(name: &'static str);
                deserialize_tuple_struct(name: &'static str, len: usize);
                deserialize_struct(name: &'static str, fields: &'static [&'static str]);
                deserialize_struct_field();
                deserialize_tuple(len: usize);
                deserialize_enum(name: &'static str, variants: &'static [&'static str]);
                deserialize_ignored_any();
            }
        }

        let mut de = MissingFieldDeserializer(field);
        Ok(try!(de::Deserialize::deserialize(&mut de)))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.len, Some(self.len))
    }
}

impl<'a> de::Deserializer for MapDeserializer<'a> {
    type Error = Error;

    #[inline]
    fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
        where V: de::Visitor,
    {
        visitor.visit_map(self)
    }

    forward_to_deserialize!{
        deserialize_bool();
        deserialize_usize();
        deserialize_u8();
        deserialize_u16();
        deserialize_u32();
        deserialize_u64();
        deserialize_isize();
        deserialize_i8();
        deserialize_i16();
        deserialize_i32();
        deserialize_i64();
        deserialize_f32();
        deserialize_f64();
        deserialize_char();
        deserialize_str();
        deserialize_string();
        deserialize_unit();
        deserialize_option();
        deserialize_seq();
        deserialize_seq_fixed_size(len: usize);
        deserialize_bytes();
        deserialize_map();
        deserialize_unit_struct(name: &'static str);
        deserialize_newtype_struct(name: &'static str);
        deserialize_tuple_struct(name: &'static str, len: usize);
        deserialize_struct(name: &'static str, fields: &'static [&'static str]);
        deserialize_struct_field();
        deserialize_tuple(len: usize);
        deserialize_enum(name: &'static str, variants: &'static [&'static str]);
        deserialize_ignored_any();
    }
}

/// Shortcut function to encode a `T` into a Hjson `Value`
///
/// ```rust</span>
<span class='doccomment'>/// use serde_hjson::to_value;</span>
<span class='doccomment'>/// let val = to_value("foo");</span>
<span class='doccomment'>/// assert_eq!(val.as_str(), Some("foo"))</span>
<span class='doccomment'>/// ```
pub fn to_value<T: ?Sized>(value: &T) -> Value
    where T: ser::Serialize,
{
    let mut ser = Serializer::new();
    value.serialize(&mut ser).expect("failed to serialize");
    ser.unwrap()
}

/// Shortcut function to decode a Hjson `Value` into a `T`
pub fn from_value<T>(value: Value) -> Result<T, Error>
    where T: de::Deserialize,
{
    let mut de = Deserializer::new(value);
    de::Deserialize::deserialize(&mut de)
}

/// A trait for converting values to Hjson
pub trait ToJson {
    /// Converts the value of `self` to an instance of Hjson
    fn to_json(&self) -> Value;
}

impl<T: ?Sized> ToJson for T
    where T: ser::Serialize,
{
    fn to_json(&self) -> Value {
        to_value(&self)
    }
}

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
module Azure::NetApp::Mgmt::V2020_06_01
  #
  # Microsoft NetApp Azure Resource Provider specification
  #
  class NetAppResource
    include MsRestAzure

    #
    # Creates and initializes a new instance of the NetAppResource class.
    # @param client service class for accessing basic functionality.
    #
    def initialize(client)
      @client = client
    end

    # @return [AzureNetAppFilesManagementClient] reference to the AzureNetAppFilesManagementClient
    attr_reader :client

    #
    # Check resource name availability
    #
    # Check if a resource name is available.
    #
    # @param location [String] The location
    # @param name [String] Resource name to verify.
    # @param type [CheckNameResourceTypes] Resource type used for verification.
    # Possible values include: 'Microsoft.NetApp/netAppAccounts',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots'
    # @param resource_group [String] Resource group name.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [CheckAvailabilityResponse] operation results.
    #
    def check_name_availability(location, name, type, resource_group, custom_headers:nil)
      response = check_name_availability_async(location, name, type, resource_group, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Check resource name availability
    #
    # Check if a resource name is available.
    #
    # @param location [String] The location
    # @param name [String] Resource name to verify.
    # @param type [CheckNameResourceTypes] Resource type used for verification.
    # Possible values include: 'Microsoft.NetApp/netAppAccounts',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots'
    # @param resource_group [String] Resource group name.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def check_name_availability_with_http_info(location, name, type, resource_group, custom_headers:nil)
      check_name_availability_async(location, name, type, resource_group, custom_headers:custom_headers).value!
    end

    #
    # Check resource name availability
    #
    # Check if a resource name is available.
    #
    # @param location [String] The location
    # @param name [String] Resource name to verify.
    # @param type [CheckNameResourceTypes] Resource type used for verification.
    # Possible values include: 'Microsoft.NetApp/netAppAccounts',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots'
    # @param resource_group [String] Resource group name.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def check_name_availability_async(location, name, type, resource_group, custom_headers:nil)
      fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
      fail ArgumentError, 'location is nil' if location.nil?
      fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
      fail ArgumentError, 'name is nil' if name.nil?
      fail ArgumentError, 'type is nil' if type.nil?
      fail ArgumentError, 'resource_group is nil' if resource_group.nil?

      body = ResourceNameAvailabilityRequest.new
      unless name.nil? && type.nil? && resource_group.nil?
        body.name = name
        body.type = type
        body.resource_group = resource_group
      end

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?

      # Serialize Request
      request_mapper = Azure::NetApp::Mgmt::V2020_06_01::Models::ResourceNameAvailabilityRequest.mapper()
      request_content = @client.serialize(request_mapper,  body)
      request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil

      path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.NetApp/locations/{location}/checkNameAvailability'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'subscriptionId' => @client.subscription_id,'location' => location},
          query_params: {'api-version' => @client.api_version},
          body: request_content,
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:post, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::NetApp::Mgmt::V2020_06_01::Models::CheckAvailabilityResponse.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Check file path availability
    #
    # Check if a file path is available.
    #
    # @param location [String] The location
    # @param name [String] Resource name to verify.
    # @param type [CheckNameResourceTypes] Resource type used for verification.
    # Possible values include: 'Microsoft.NetApp/netAppAccounts',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots'
    # @param resource_group [String] Resource group name.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [CheckAvailabilityResponse] operation results.
    #
    def check_file_path_availability(location, name, type, resource_group, custom_headers:nil)
      response = check_file_path_availability_async(location, name, type, resource_group, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Check file path availability
    #
    # Check if a file path is available.
    #
    # @param location [String] The location
    # @param name [String] Resource name to verify.
    # @param type [CheckNameResourceTypes] Resource type used for verification.
    # Possible values include: 'Microsoft.NetApp/netAppAccounts',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots'
    # @param resource_group [String] Resource group name.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def check_file_path_availability_with_http_info(location, name, type, resource_group, custom_headers:nil)
      check_file_path_availability_async(location, name, type, resource_group, custom_headers:custom_headers).value!
    end

    #
    # Check file path availability
    #
    # Check if a file path is available.
    #
    # @param location [String] The location
    # @param name [String] Resource name to verify.
    # @param type [CheckNameResourceTypes] Resource type used for verification.
    # Possible values include: 'Microsoft.NetApp/netAppAccounts',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots'
    # @param resource_group [String] Resource group name.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def check_file_path_availability_async(location, name, type, resource_group, custom_headers:nil)
      fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
      fail ArgumentError, 'location is nil' if location.nil?
      fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
      fail ArgumentError, 'name is nil' if name.nil?
      fail ArgumentError, 'type is nil' if type.nil?
      fail ArgumentError, 'resource_group is nil' if resource_group.nil?

      body = ResourceNameAvailabilityRequest.new
      unless name.nil? && type.nil? && resource_group.nil?
        body.name = name
        body.type = type
        body.resource_group = resource_group
      end

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?

      # Serialize Request
      request_mapper = Azure::NetApp::Mgmt::V2020_06_01::Models::ResourceNameAvailabilityRequest.mapper()
      request_content = @client.serialize(request_mapper,  body)
      request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil

      path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.NetApp/locations/{location}/checkFilePathAvailability'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'subscriptionId' => @client.subscription_id,'location' => location},
          query_params: {'api-version' => @client.api_version},
          body: request_content,
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:post, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::NetApp::Mgmt::V2020_06_01::Models::CheckAvailabilityResponse.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Check quota availability
    #
    # Check if a quota is available.
    #
    # @param location [String] The location
    # @param name [String] Name of the resource to verify.
    # @param type [CheckQuotaNameResourceTypes] Resource type used for
    # verification. Possible values include: 'Microsoft.NetApp/netAppAccounts',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots'
    # @param resource_group [String] Resource group name.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [CheckAvailabilityResponse] operation results.
    #
    def check_quota_availability(location, name, type, resource_group, custom_headers:nil)
      response = check_quota_availability_async(location, name, type, resource_group, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Check quota availability
    #
    # Check if a quota is available.
    #
    # @param location [String] The location
    # @param name [String] Name of the resource to verify.
    # @param type [CheckQuotaNameResourceTypes] Resource type used for
    # verification. Possible values include: 'Microsoft.NetApp/netAppAccounts',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots'
    # @param resource_group [String] Resource group name.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def check_quota_availability_with_http_info(location, name, type, resource_group, custom_headers:nil)
      check_quota_availability_async(location, name, type, resource_group, custom_headers:custom_headers).value!
    end

    #
    # Check quota availability
    #
    # Check if a quota is available.
    #
    # @param location [String] The location
    # @param name [String] Name of the resource to verify.
    # @param type [CheckQuotaNameResourceTypes] Resource type used for
    # verification. Possible values include: 'Microsoft.NetApp/netAppAccounts',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes',
    # 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots'
    # @param resource_group [String] Resource group name.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def check_quota_availability_async(location, name, type, resource_group, custom_headers:nil)
      fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
      fail ArgumentError, 'location is nil' if location.nil?
      fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
      fail ArgumentError, 'name is nil' if name.nil?
      fail ArgumentError, 'type is nil' if type.nil?
      fail ArgumentError, 'resource_group is nil' if resource_group.nil?

      body = QuotaAvailabilityRequest.new
      unless name.nil? && type.nil? && resource_group.nil?
        body.name = name
        body.type = type
        body.resource_group = resource_group
      end

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?

      # Serialize Request
      request_mapper = Azure::NetApp::Mgmt::V2020_06_01::Models::QuotaAvailabilityRequest.mapper()
      request_content = @client.serialize(request_mapper,  body)
      request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil

      path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.NetApp/locations/{location}/checkQuotaAvailability'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'subscriptionId' => @client.subscription_id,'location' => location},
          query_params: {'api-version' => @client.api_version},
          body: request_content,
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:post, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::NetApp::Mgmt::V2020_06_01::Models::CheckAvailabilityResponse.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
-------------------------------------------------------------------------------
-- <copyright company="Sherlock">
--     Copyright 2013 Sherlock. Licensed under the Apache License, Version 2.0.
-- </copyright>
-------------------------------------------------------------------------------

CREATE PROCEDURE [Environments].[UpdateHypervMachine]
    @machineId NVARCHAR(50),
    @name NVARCHAR(50),
    @description NVARCHAR(MAX),
    @networkName NVARCHAR(50),
    @macAddress NVARCHAR(50),
    @isAvailableForTesting BIT,
    @isActive BIT,
    @operatingSystemId INT,
    @hostId NVARCHAR(50),
    @image NVARCHAR(50),
    @snapshotToReturnTo NVARCHAR(MAX)
AS
    IF NOT EXISTS (
        SELECT *
        FROM [Environments].[HypervMachine]
        WHERE [pk_HypervMachineId] = @machineId)
    BEGIN
        RAISERROR
            (
                N'An entry for a machine with ID %s does not exist.',
                11,
                1,
                @machineId
            )
        RETURN
    END

    DECLARE @isPhysicalMachine INT
    EXEC [Environments].[IsPhysicalMachine] @hostId, @isPhysicalMachine OUTPUT
    IF @isPhysicalMachine = 0
    BEGIN
        RAISERROR
            (
                N'The machine with ID %s is not a physical machine and thus cannot be a host machine.',
                11,
                1,
                @hostId
            )
        RETURN
    END

    BEGIN TRANSACTION

        UPDATE [Environments].[Machine]
        SET
            [Name] = @name,
            [Description] = @description,
            [NetworkName] = @networkName,
            [MacAddress] = @macAddress,
            [IsAvailableForTesting] = @isAvailableForTesting,
            [IsActive] = @isActive,
            [fk_OperatingSystem] = @operatingSystemId
        WHERE [pk_MachineId] = @machineId

        UPDATE [Environments].[HypervMachine]
        SET
            [Image] = @image,
            [SnapshotToReturnTo] = @snapshotToReturnTo,
            [fk_HostId] = @hostId
        WHERE [pk_HypervMachineId] = @machineId

        IF @@ERROR <> 0
        BEGIN
            ROLLBACK

            RAISERROR
                (
                    'Failed to update machine with ID %s.',
                    11,
                    1,
                    @machineId
                )
            RETURN
        END

    COMMIT
RETURN 0


text:
require './spec/spec_helper'

RSpec.describe Saper::Actions::ConvertToJSON do

  let :subject do
    Saper::Actions::ConvertToJSON.new
  end

  context ".type" do
    it "returns convert_to_json" do
      expect(described_class.type).to eq 'convert_to_json'
    end
  end

  context ".accepts?(:atom)" do
    it "returns false" do
      expect(described_class.accepts?(:atom)).to be false
    end
  end

  context ".accepts?(:document)" do
    it "returns true" do
      expect(described_class.accepts?(:document)).to be true
    end
  end

  context ".accepts?(:html)" do
    it "returns false" do
      expect(described_class.accepts?(:html)).to be false
    end
  end

  context ".accepts?(:json)" do
    it "returns false" do
      expect(described_class.accepts?(:json)).to be false
    end
  end

  context ".accepts?(:markdown)" do
    it "returns false" do
      expect(described_class.accepts?(:markdown)).to be false
    end
  end

  context ".accepts?(:nothing)" do
    it "returns false" do
      expect(described_class.accepts?(:nothing)).to be false
    end
  end

  context ".accepts?(:text)" do
    it "returns true " do
      expect(described_class.accepts?(:text)).to be true
    end
  end

  context ".accepts?(:time)" do
    it "returns false" do
      expect(described_class.accepts?(:time)).to be false
    end
  end

  context ".accepts?(:url)" do
    it "returns false" do
      expect(described_class.accepts?(:url)).to be false
    end
  end

  context ".accepts?(:xml)" do
    it "returns false" do
      expect(described_class.accepts?(:xml)).to be false
    end
  end

  context ".output_for(:atom)" do
    it "returns :nothing" do
      expect(described_class.output_for(:atom)).to be :nothing
    end
  end

  context ".output_for(:document)" do
    it "returns :json" do
      expect(described_class.output_for(:document)).to be :json
    end
  end

  context ".output_for(:html)" do
    it "returns :nothing" do
      expect(described_class.output_for(:html)).to be :nothing
    end
  end

  context ".output_for(:json)" do
    it "returns :nothing" do
      expect(described_class.output_for(:json)).to be :nothing
    end
  end

  context ".output_for(:markdown)" do
    it "returns :nothing" do
      expect(described_class.output_for(:markdown)).to be :nothing
    end
  end

  context ".output_for(:text)" do
    it "returns :text" do
      expect(described_class.output_for(:text)).to be :json
    end
  end

  context ".output_for(:time)" do
    it "returns :nothing" do
      expect(described_class.output_for(:time)).to be :nothing
    end
  end

  context ".output_for(:url)" do
    it "returns :nothing" do
      expect(described_class.output_for(:url)).to be :nothing
    end
  end

  context ".output_for(:xml)" do
    it "returns :nothing" do
      expect(described_class.output_for(:xml)).to be :nothing
    end
  end

  context ".returns_multiple_items?" do
    it "returns false" do
      expect(described_class.returns_multiple_items?).to be false
    end
  end

  context "#run(nil)" do
    it "raises InvalidInput" do
      expect { subject.run(nil) }.to raise_error Saper::Errors::InvalidInput
    end
  end

  context "#run(Numeric)" do
    it "raises InvalidInput" do
      expect { subject.run(2) }.to raise_error Saper::Errors::InvalidInput
    end
  end

  context "#run(invalid String)" do
    it "raises InvalidOutput" do
      expect { subject.run('not json') }.to raise_error Saper::Errors::InvalidOutput
    end
  end

  context "#run(valid String)" do
    it "returns JSON instance" do
      expect(subject.run('{"test":"ok"}')).to be_a Saper::Items::JSON
    end
  end

  context "#run(valid Text)" do
    it "returns JSON instance" do
      expect(subject.run(Saper::Items::Text.new('{"test":"ok"}'))).to be_a Saper::Items::JSON
    end
  end

end


text:
package com.intellij.ui.tabs.impl;

import com.intellij.ide.DataManager;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.advanced.AdvancedSettings;
import com.intellij.openapi.ui.JBPopupMenu;
import com.intellij.openapi.ui.popup.util.PopupUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.*;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.panels.Wrapper;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.ui.tabs.JBTabsEx;
import com.intellij.ui.tabs.TabInfo;
import com.intellij.ui.tabs.UiDecorator;
import com.intellij.ui.tabs.impl.themes.TabTheme;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ui.*;
import com.intellij.util.ui.accessibility.ScreenReader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.util.List;

public class TabLabel extends JPanel implements Accessible {
  private static final Logger LOG = Logger.getInstance(TabLabel.class);

  // If this System property is set to true 'close' button would be shown on the left of text (it's on the right by default)
  protected final SimpleColoredComponent myLabel;

  private final LayeredIcon myIcon;
  private Icon myOverlayedIcon;

  private final TabInfo myInfo;
  protected ActionPanel myActionPanel;
  private boolean myCentered;

  private final Wrapper myLabelPlaceholder = new Wrapper(false);
  protected final JBTabsImpl myTabs;

  public TabLabel(JBTabsImpl tabs, final TabInfo info) {
    super(false);

    myTabs = tabs;
    myInfo = info;

    myLabel = createLabel(tabs);

    // Allow focus so that user can TAB into the selected TabLabel and then
    // navigate through the other tabs using the LEFT/RIGHT keys.
    setFocusable(ScreenReader.isActive());
    setOpaque(false);
    setLayout(new MyTabLabelLayout());

    myLabelPlaceholder.setOpaque(false);
    myLabelPlaceholder.setFocusable(false);
    myLabel.setFocusable(false);
    add(myLabelPlaceholder, BorderLayout.CENTER);

    setAlignmentToCenter(true);

    myIcon = new LayeredIcon(2);

    addMouseListener(new MouseAdapter() {
      @Override
      public void mousePressed(final MouseEvent e) {
        if (UIUtil.isCloseClick(e, MouseEvent.MOUSE_PRESSED)) return;
        if (JBTabsImpl.isSelectionClick(e, false) && myInfo.isEnabled()) {
          final TabInfo selectedInfo = myTabs.getSelectedInfo();
          if (selectedInfo != myInfo) {
            myInfo.setPreviousSelection(selectedInfo);
          }
          Component c = SwingUtilities.getDeepestComponentAt(e.getComponent(), e.getX(), e.getY());
          if (c instanceof InplaceButton) return;
          myTabs.select(info, true);
          ObjectUtils.consumeIfNotNull(PopupUtil.getPopupContainerFor(TabLabel.this), popup -> {
            if (ClientProperty.isTrue(popup.getContent(), MorePopupAware.class)) {
              popup.cancel();
            }
          });
        }
        else {
          handlePopup(e);
        }
      }

      @Override
      public void mouseClicked(final MouseEvent e) {
        handlePopup(e);
      }

      @Override
      public void mouseReleased(final MouseEvent e) {
        myInfo.setPreviousSelection(null);
        handlePopup(e);
      }

      @Override
      public void mouseEntered(MouseEvent e) {
        setHovered(true);
      }

      @Override
      public void mouseExited(MouseEvent e) {
        setHovered(false);
      }
    });

    if (isFocusable()) {
      // Navigate to the previous/next tab when LEFT/RIGHT is pressed.
      addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
          if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            int index = myTabs.getIndexOf(myInfo);
            if (index >= 0) {
              e.consume();
              // Select the previous tab, then set the focus its TabLabel.
              TabInfo previous = myTabs.findEnabledBackward(index, true);
              if (previous != null) {
                myTabs.select(previous, false).doWhenDone(() -> myTabs.getSelectedLabel().requestFocusInWindow());
              }
            }
          }
          else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            int index = myTabs.getIndexOf(myInfo);
            if (index >= 0) {
              e.consume();
              // Select the previous tab, then set the focus its TabLabel.
              TabInfo next = myTabs.findEnabledForward(index, true);
              if (next != null) {
                // Select the next tab, then set the focus its TabLabel.
                myTabs.select(next, false).doWhenDone(() -> myTabs.getSelectedLabel().requestFocusInWindow());
              }
            }
          }
        }
      });

      // Repaint when we gain/lost focus so that the focus cue is displayed.
      addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {
          repaint();
        }

        @Override
        public void focusLost(FocusEvent e) {
          repaint();
        }
      });
    }
  }

  private void setHovered(boolean value) {
    if (isHovered() == value) return;
    if (value) {
      myTabs.setHovered(this);
    }
    else {
      myTabs.unHover(this);
    }
  }

  public boolean isHovered() {
    return myTabs.isHoveredTab(this);
  }

  @Override
  public boolean isFocusable() {
    // We don't want the focus unless we are the selected tab.
    if (myTabs.getSelectedLabel() != this) {
      return false;
    }

    return super.isFocusable();
  }

  private SimpleColoredComponent createLabel(final JBTabsImpl tabs) {
    SimpleColoredComponent label = new SimpleColoredComponent() {
      @Override
      public Font getFont() {
        Font font = super.getFont();

        return (isFontSet() || !myTabs.useSmallLabels()) ? font :
               RelativeFont.NORMAL.fromResource("EditorTabs.fontSizeOffset", -2, JBUIScale.scale(11f)).derive(StartupUiUtil.getLabelFont());
      }

      @Override
      protected Color getActiveTextColor(Color attributesColor) {
        TabPainterAdapter painterAdapter = myTabs.getTabPainterAdapter();
        TabTheme theme = painterAdapter.getTabTheme();
        return myTabs.getSelectedInfo() == myInfo && (UIUtil.getLabelForeground().equals(attributesColor) || attributesColor == null)
               ? myTabs.isActiveTabs(myInfo)
                 ? theme.getUnderlinedTabForeground()
                 : theme.getUnderlinedTabInactiveForeground()
               : super.getActiveTextColor(attributesColor);
      }
    };
    label.setOpaque(false);
    label.setBorder(null);
    label.setIconTextGap(
      tabs.isEditorTabs() ? (!UISettings.getShadowInstance().getHideTabsIfNeeded() ? 4 : 2) + 1 : new JLabel().getIconTextGap());
    label.setIconOpaque(false);
    label.setIpad(JBInsets.emptyInsets());

    return label;
  }

  public boolean isPinned() {
    return myInfo != null && myInfo.isPinned();
  }

  @Override
  public Dimension getPreferredSize() {
    Dimension size = getNotStrictPreferredSize();
    if (isPinned()) {
      size.width = Math.min(TabLayout.getMaxPinnedTabWidth(), size.width);
    }
    return size;
  }

  public Dimension getNotStrictPreferredSize() {
    return super.getPreferredSize();
  }

  @Override
  public Insets getInsets() {
    Insets insets = super.getInsets();
    if (myTabs.isEditorTabs() && (UISettings.getShadowInstance().getShowCloseButton() || myInfo.isPinned()) && hasIcons()) {
      if (UISettings.getShadowInstance().getCloseTabButtonOnTheRight()) {
        insets.right -= JBUIScale.scale(4);
      }
      else {
        insets.left -= JBUIScale.scale(4);
      }
    }
    return insets;
  }

  public void setAlignmentToCenter(boolean toCenter) {
    if (myCentered == toCenter && getLabelComponent().getParent() != null) return;

    setPlaceholderContent(toCenter, getLabelComponent());
  }

  protected void setPlaceholderContent(boolean toCenter, JComponent component) {
    myLabelPlaceholder.removeAll();

    JComponent content = toCenter ? new Centerizer(component, Centerizer.TYPE.BOTH) : new Centerizer(component, Centerizer.TYPE.VERTICAL);
    myLabelPlaceholder.setContent(content);

    myCentered = toCenter;
  }

  public void paintOffscreen(Graphics g) {
    synchronized (getTreeLock()) {
      validateTree();
    }
    doPaint(g);
  }

  @Override
  public void paint(final Graphics g) {
    if (myTabs.isDropTarget(myInfo)) {
      if (myTabs.getDropSide() == -1) {
        g.setColor(JBUI.CurrentTheme.DragAndDrop.Area.BACKGROUND);
        g.fillRect(0, 0, getWidth(), getHeight());
      }
      return;
    }
    doPaint(g);
  }

  private void doPaint(final Graphics g) {
    super.paint(g);
  }

  public boolean isLastPinned() {
    if (myInfo.isPinned() && AdvancedSettings.getBoolean("editor.keep.pinned.tabs.on.left")) {
      @NotNull List<TabInfo> tabs = myTabs.getTabs();
      for (int i = 0; i < tabs.size(); i++) {
        TabInfo info = tabs.get(i);
        if (info == myInfo && i < tabs.size() - 1) {
          return !tabs.get(i + 1).isPinned();
        }
      }
    }
    return false;
  }

  public boolean isNextToLastPinned() {
    if (!myInfo.isPinned() && AdvancedSettings.getBoolean("editor.keep.pinned.tabs.on.left")) {
      @NotNull List<TabInfo> tabs = myTabs.getVisibleInfos();
      boolean wasPinned = false;
      for (TabInfo info : tabs) {
        if (wasPinned && info == myInfo) return true;
        wasPinned = info.isPinned();
      }
    }
    return false;
  }

  private void handlePopup(final MouseEvent e) {
    if (e.getClickCount() != 1 || !e.isPopupTrigger() || PopupUtil.getPopupContainerFor(this) != null) return;

    if (e.getX() < 0 || e.getX() >= e.getComponent().getWidth() || e.getY() < 0 || e.getY() >= e.getComponent().getHeight()) return;

    String place = myTabs.getPopupPlace();
    place = place != null ? place : ActionPlaces.UNKNOWN;
    myTabs.myPopupInfo = myInfo;

    final DefaultActionGroup toShow = new DefaultActionGroup();
    if (myTabs.getPopupGroup() != null) {
      toShow.addAll(myTabs.getPopupGroup());
      toShow.addSeparator();
    }

    JBTabsImpl tabs =
      (JBTabsImpl)JBTabsEx.NAVIGATION_ACTIONS_KEY.getData(DataManager.getInstance().getDataContext(e.getComponent(), e.getX(), e.getY()));
    if (tabs == myTabs && myTabs.myAddNavigationGroup) {
      toShow.addAll(myTabs.myNavigationActions);
    }

    if (toShow.getChildrenCount() == 0) return;

    myTabs.myActivePopup = ActionManager.getInstance().createActionPopupMenu(place, toShow).getComponent();
    myTabs.myActivePopup.addPopupMenuListener(myTabs.myPopupListener);

    myTabs.myActivePopup.addPopupMenuListener(myTabs);
    JBPopupMenu.showByEvent(e, myTabs.myActivePopup);
  }

  public void setText(final SimpleColoredText text) {
    myLabel.change(() -> {
      myLabel.clear();
      myLabel.setIcon(hasIcons() ? myIcon : null);

      if (text != null) {
        text.appendToComponent(myLabel);
      }
    }, false);

    invalidateIfNeeded();
  }

  private void invalidateIfNeeded() {
    if (getLabelComponent().getRootPane() == null) return;

    Dimension d = getLabelComponent().getSize();
    Dimension pref = getLabelComponent().getPreferredSize();
    if (d != null && d.equals(pref)) {
      return;
    }

    getLabelComponent().invalidate();

    if (myActionPanel != null) {
      myActionPanel.invalidate();
    }

    myTabs.revalidateAndRepaint(false);
  }

  public void setIcon(final Icon icon) {
    setIcon(icon, 0);
  }

  private boolean hasIcons() {
    LayeredIcon layeredIcon = getLayeredIcon();
    boolean hasIcons = false;
    Icon[] layers = layeredIcon.getAllLayers();
    for (Icon layer1 : layers) {
      if (layer1 != null) {
        hasIcons = true;
        break;
      }
    }

    return hasIcons;
  }

  private void setIcon(@Nullable final Icon icon, int layer) {
    LayeredIcon layeredIcon = getLayeredIcon();
    layeredIcon.setIcon(icon, layer);
    if (hasIcons()) {
      myLabel.setIcon(layeredIcon);
    }
    else {
      myLabel.setIcon(null);
    }

    invalidateIfNeeded();
  }

  private LayeredIcon getLayeredIcon() {
    return myIcon;
  }

  public TabInfo getInfo() {
    return myInfo;
  }

  public void apply(UiDecorator.UiDecoration decoration) {
    if (decoration == null) {
      return;
    }

    if (decoration.getLabelFont() != null) {
      setFont(decoration.getLabelFont());
      getLabelComponent().setFont(decoration.getLabelFont());
    }

    Insets insets = decoration.getLabelInsets();
    if (insets != null) {
      Insets current = JBTabsImpl.ourDefaultDecorator.getDecoration().getLabelInsets();
      if (current != null) {
        setBorder(
          new EmptyBorder(getValue(current.top, insets.top), getValue(current.left, insets.left), getValue(current.bottom, insets.bottom),
                          getValue(current.right, insets.right)));
      }
    }
  }

  private static int getValue(int currentValue, int newValue) {
    return newValue != -1 ? newValue : currentValue;
  }

  public void setTabActions(ActionGroup group) {
    removeOldActionPanel();

    if (group == null) return;

    myActionPanel = new ActionPanel(myTabs, myInfo, e -> processMouseEvent(SwingUtilities.convertMouseEvent(e.getComponent(), e, this)),
                                    value -> setHovered(value));
    boolean buttonsOnTheRight = UISettings.getShadowInstance().getCloseTabButtonOnTheRight();
    Border border = buttonsOnTheRight ? JBUI.Borders.empty(1, ExperimentalUI.isNewUI() ? 3 : 0, 1, 0)
                                      : JBUI.Borders.empty(1, 0, 1, 3);
    myActionPanel.setBorder(border);
    toggleShowActions(false);

    add(myActionPanel, buttonsOnTheRight ? BorderLayout.EAST : BorderLayout.WEST);

    myTabs.revalidateAndRepaint(false);
  }

  private void removeOldActionPanel() {
    if (myActionPanel != null) {
      myActionPanel.getParent().remove(myActionPanel);
      myActionPanel = null;
    }
  }

  public boolean updateTabActions() {
    return myActionPanel != null && myActionPanel.update();
  }

  private void setAttractionIcon(@Nullable Icon icon) {
    if (myIcon.getIcon(0) == null) {
      setIcon(null, 1);
      myOverlayedIcon = icon;
    }
    else {
      setIcon(icon, 1);
      myOverlayedIcon = null;
    }
  }

  public boolean repaintAttraction() {
    if (!myTabs.myAttractions.contains(myInfo)) {
      if (getLayeredIcon().isLayerEnabled(1)) {
        getLayeredIcon().setLayerEnabled(1, false);
        setAttractionIcon(null);
        invalidateIfNeeded();
        return true;
      }
      return false;
    }

    boolean needsUpdate = false;

    if (getLayeredIcon().getIcon(1) != myInfo.getAlertIcon()) {
      setAttractionIcon(myInfo.getAlertIcon());
      needsUpdate = true;
    }

    int maxInitialBlinkCount = 5;
    int maxRefireBlinkCount = maxInitialBlinkCount + 2;
    if (myInfo.getBlinkCount() < maxInitialBlinkCount && myInfo.isAlertRequested()) {
      getLayeredIcon().setLayerEnabled(1, !getLayeredIcon().isLayerEnabled(1));
      if (myInfo.getBlinkCount() == 0) {
        needsUpdate = true;
      }
      myInfo.setBlinkCount(myInfo.getBlinkCount() + 1);

      if (myInfo.getBlinkCount() == maxInitialBlinkCount) {
        myInfo.resetAlertRequest();
      }

      repaint();
    }
    else {
      if (myInfo.getBlinkCount() < maxRefireBlinkCount && myInfo.isAlertRequested()) {
        getLayeredIcon().setLayerEnabled(1, !getLayeredIcon().isLayerEnabled(1));
        myInfo.setBlinkCount(myInfo.getBlinkCount() + 1);

        if (myInfo.getBlinkCount() == maxRefireBlinkCount) {
          myInfo.setBlinkCount(maxInitialBlinkCount);
          myInfo.resetAlertRequest();
        }

        repaint();
      }
      else {
        needsUpdate = !getLayeredIcon().isLayerEnabled(1);
        getLayeredIcon().setLayerEnabled(1, true);
      }
    }

    invalidateIfNeeded();

    return needsUpdate;
  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    paintBackground(g);
  }

  private void paintBackground(Graphics g) {
    TabPainterAdapter painterAdapter = myTabs.getTabPainterAdapter();
    painterAdapter.paintBackground(this, g, myTabs);
  }

  @Override
  protected void paintChildren(final Graphics g) {
    super.paintChildren(g);

    if (getLabelComponent().getParent() == null) {
      return;
    }

    final Rectangle textBounds = SwingUtilities.convertRectangle(getLabelComponent().getParent(), getLabelComponent().getBounds(), this);
    // Paint border around label if we got the focus
    if (isFocusOwner()) {
      g.setColor(UIUtil.getTreeSelectionBorderColor());
      UIUtil.drawDottedRectangle(g, textBounds.x, textBounds.y, textBounds.x + textBounds.width - 1, textBounds.y + textBounds.height - 1);
    }

    if (myOverlayedIcon == null) {
      return;
    }

    if (getLayeredIcon().isLayerEnabled(1)) {

      final int top = (getSize().height - myOverlayedIcon.getIconHeight()) / 2;

      myOverlayedIcon.paintIcon(this, g, textBounds.x - myOverlayedIcon.getIconWidth() / 2, top);
    }
  }

  public void setTabActionsAutoHide(final boolean autoHide) {
    if (myActionPanel == null || myActionPanel.isAutoHide() == autoHide) {
      return;
    }

    myActionPanel.setAutoHide(autoHide);
  }

  public void toggleShowActions(boolean show) {
    if (myActionPanel != null) {
      myActionPanel.toggleShowActions(show);
    }
  }

  void updateActionLabelPosition() {
    if (myActionPanel != null) {
      if (!myActionPanel.isVisible()) {
        remove(myActionPanel);
      }
      else {
        add(myActionPanel, UISettings.getShadowInstance().getCloseTabButtonOnTheRight() ? BorderLayout.EAST : BorderLayout.WEST);
      }
    }
  }

  @Override
  public String toString() {
    return myInfo.getText();
  }

  public void setTabEnabled(boolean enabled) {
    getLabelComponent().setEnabled(enabled);
  }

  public JComponent getLabelComponent() {
    return myLabel;
  }

  @Override
  public String getToolTipText(MouseEvent event) {
    Point pointInLabel = new RelativePoint(event).getPoint(myLabel);
    Icon icon = myLabel.getIcon();
    int iconWidth = (icon != null ? icon.getIconWidth() : JBUI.scale(16));
    if ((myLabel.getVisibleRect().width >= iconWidth * 2 || !UISettings.getInstance().getShowTabsTooltips())
        && myLabel.findFragmentAt(pointInLabel.x) == SimpleColoredComponent.FRAGMENT_ICON) {
      String toolTip = myIcon.getToolTip(false);
      if (toolTip != null) {
        return StringUtil.capitalize(toolTip);
      }
    }
    return super.getToolTipText(event);
  }

  @Override
  public AccessibleContext getAccessibleContext() {
    if (accessibleContext == null) {
      accessibleContext = new AccessibleTabLabel();
    }
    return accessibleContext;
  }

  protected class AccessibleTabLabel extends AccessibleJPanel {
    @Override
    public String getAccessibleName() {
      String name = super.getAccessibleName();
      if (name == null && myLabel != null) {
        name = myLabel.getAccessibleContext().getAccessibleName();
      }
      return name;
    }

    @Override
    public String getAccessibleDescription() {
      String description = super.getAccessibleDescription();
      if (description == null && myLabel != null) {
        description = myLabel.getAccessibleContext().getAccessibleDescription();
      }
      return description;
    }

    @Override
    public AccessibleRole getAccessibleRole() {
      return AccessibleRole.PAGE_TAB;
    }
  }

  private class MyTabLabelLayout extends BorderLayout {

    @Override
    public void addLayoutComponent(Component comp, Object constraints) {
      checkConstraints(constraints);
      super.addLayoutComponent(comp, constraints);
    }

    private void checkConstraints(Object constraints) {
      if (NORTH.equals(constraints) || SOUTH.equals(constraints)) {
        LOG.warn(new IllegalArgumentException("constraints=" + constraints));
      }
    }

    @Override
    public void layoutContainer(Container parent) {
      synchronized (parent.getTreeLock()) {
        boolean success = doCustomLayout(parent);
        if (!success) {
          super.layoutContainer(parent);
        }
      }
    }

    private boolean doCustomLayout(Container parent) {
      int tabPlacement = UISettings.getInstance().getEditorTabPlacement();
      if (!myInfo.isPinned() && myTabs != null && myTabs.ignoreTabLabelLimitedWidthWhenPaint() &&
          (tabPlacement == SwingConstants.TOP || tabPlacement == SwingConstants.BOTTOM) &&
          parent.getWidth() < parent.getPreferredSize().width) {
        int spaceTop = parent.getInsets().top;
        int spaceLeft = parent.getInsets().left;
        int spaceBottom = parent.getHeight() - parent.getInsets().bottom;
        int spaceHeight = spaceBottom - spaceTop;

        int xOffset = spaceLeft;

        xOffset = layoutComponent(xOffset, getLayoutComponent(WEST), spaceTop, spaceHeight);
        xOffset = layoutComponent(xOffset, getLayoutComponent(CENTER), spaceTop, spaceHeight);
        layoutComponent(xOffset, getLayoutComponent(EAST), spaceTop, spaceHeight);

        return true;
      }
      return false;
    }

    private int layoutComponent(int xOffset, Component component, int spaceTop, int spaceHeight) {
      if (component != null) {
        int prefWestWidth = component.getPreferredSize().width;
        setBoundsWithVAlign(component, xOffset, prefWestWidth, spaceTop, spaceHeight);
        xOffset += prefWestWidth + getHgap();
      }
      return xOffset;
    }

    private void setBoundsWithVAlign(Component component, int left, int width, int spaceTop, int spaceHeight) {
      if (component == null) return;

      int height = component.getPreferredSize().height;
      int top = spaceTop + (spaceHeight - height) / 2;
      component.setBounds(left, top, width, height);
    }
  }
}


text:
Annict::Application.config.session_store :active_record_store,
  expire_after: 10.days,
  domain: :all


text:
<os-head-bar
    [nav]="false"
    [goBack]="true"
    [editMode]="isEditing"
    [hasMainButton]="canManage()"
    [mainButtonIcon]="'edit'"
    [mainActionTooltip]="'Edit' | translate"
    (cancelEditEvent)="isEditing = !isEditing"
    (mainEvent)="isEditing = !isEditing"
    (saveEvent)="saveChanges()"
>

{{ 'Legal notice' | translate }}

</os-head-bar>

<os-legal-notice-content
    [canBeEdited]="true"
    [isEditing]="isEditing"
    (update)="legalNotice = $event"
></os-legal-notice-content>

<mat-card class="os-card">

        <button type="button" mat-button (click)="resetCache()">
            {{ 'Reset cache' | translate }}
        </button>

        <button type="button" mat-button (click)="checkForUpdate()">
            {{ 'Check for updates' | translate }}
        </button>

        <button type="button" mat-button (click)="showDevTools=!showDevTools">
            {{ 'Show devtools' | translate }}
        </button>

    <mat-card class="os-card" *ngIf="showDevTools">

            <button type="button" mat-button (click)="printDS()">
                Print DS
            </button>

            <button type="button" mat-button (click)="getThisComponent()">
                Get this component
            </button>

    </mat-card>
</mat-card>

<mat-card class="os-card spacer-bottom-60" *osPerms="'users.can_manage'">

{{ 'Statistics' | translate }}

{{ 'Active users' | translate }}

        <os-count-users></os-count-users>

{{ 'Requests to speak' | translate }}

        <os-user-statistics></os-user-statistics>

</mat-card>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/2NMCT1-Van.Wambeke.Matthieu-opdracht1-dec.iml" filepath="$PROJECT_DIR$/.idea/2NMCT1-Van.Wambeke.Matthieu-opdracht1-dec.iml" />
    </modules>
  </component>
</project>


text:
@interface FilterConditionView : UIView

@end