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
//! Flatbuffer Builder.
//!
//! Builder is a state machine for creating FlatBuffer objects.
//! Use a Builder to construct object(s) starting from leaf nodes.
use byteorder::{ByteOrder, LittleEndian};

use types::*;
use table::Table;

/// Builder provides functions to build Flatbuffer data.
///
/// A Builder constructs byte buffers in a last-first manner for simplicity and
/// performance.
#[derive(Debug, Clone)]
pub struct Builder {
    // Where the FlatBuffer is constructed.
    bytes: Vec<u8>,
    // Minimum alignment encountered so far.
    min_align: usize,
    // Starting offset of the current struct/table.
    object_start: UOffsetT,
    // Whether we are currently serializing a table.
    nested: bool,
    // Whether the buffer is finished.
    finished: bool,
    // The vtable for the current table.
    vtable: Vec<UOffsetT>,
    // The number of vtable slots required by the current object.
    vtable_in_use: usize,
    // Offsets of other Vtables in the buffer.
    vtables: Vec<UOffsetT>,
    // Unused space in the buffer. Size from beggining of buffer to first vtable
    space: usize,
    // Number of elements in the current vector
    vector_len: usize,
}

impl Builder {
    /// Start a new FlatBuffer `Builder` backed by a buffer with an
    /// initial capacity of `size`.
    pub fn with_capacity(size: usize) -> Self {
        let mut bytes = Vec::with_capacity(size);
        unsafe { bytes.set_len(size) };
        Builder {
            bytes: bytes,
            min_align: 1,
            object_start: 0,
            nested: false,
            finished: false,
            vtable_in_use: 0,
            vtable: Vec::with_capacity(16),
            vtables: Vec::with_capacity(16),
            space: size,
            vector_len: 0,
        }
    }

    /// Start encoding a new object in the buffer.
    pub fn start_object(&mut self, num_fields: usize) {
        self.assert_not_nested();
        self.nested = true;
        self.finished = false;
        self.vtable.clear();
        self.vtable.resize(num_fields, 0);
        self.vtable_in_use = num_fields;
        self.object_start = self.offset();
        self.min_align = 1;
    }

    /// finish off writing the object that is under construction.
    ///
    /// Returns the offset of the object in the inside the buffer.
    pub fn end_object(&mut self) -> UOffsetT {
        self.assert_nested();
        self.nested = false;
        self.write_vtable()
    }

    /// Read a completed object at offset.
    ///
    /// The offset is the `UOffsetT` returned by `end_object`.
    pub fn read_object(&self, offset: UOffsetT) -> Table {
        Table::with_pos(&self.bytes, self.bytes.len() - offset as usize)
    }

    /// Read a completed object at offset.
    ///
    /// The offset is the `UOffsetT` returned by `end_table`.
    pub fn read_table(&self, offset: UOffsetT) -> Table {
        Table::from_offset(&self.bytes, self.bytes.len() - offset as usize)
    }

    /// Initializes bookkeeping for writing a new vector.
    pub fn start_vector(&mut self, elem_size: usize, num_elems: usize, alignment: usize) {
        self.assert_not_nested();
        self.nested = true;
        self.finished = false;
        self.vector_len = num_elems;
        self.prep(UOFFSETT_SIZE, elem_size * num_elems);
        self.prep(alignment, elem_size * num_elems);
    }

    /// finish off writing the current vector.
    pub fn end_vector(&mut self) -> UOffsetT {
        self.assert_nested();

        let len = self.vector_len;
        self.put_u32(len as u32);

        self.nested = false;
        self.offset() as UOffsetT
    }

    /// Create a string in the buffer from an already encoded UTF-8 `String`.
    pub fn create_string(&mut self, value: &str) -> UOffsetT {
        let len = value.len();
        self.add_u8(0);
        self.start_vector(1, len, 1);
        self.space -= len;
        for (i, c) in value.bytes().enumerate() {
            let pos = self.space + i;
            self.place_u8(pos, c);
        }
        self.end_vector()
    }

    /// Create a vector in the buffer from an already encoded
    /// byte vector.
    pub fn create_vector(&mut self, value: &[u8]) -> UOffsetT {
        let len = value.len();
        self.start_vector(1, len, 0);
        self.space -= len;
        for (i, c) in value.iter().enumerate() {
            let pos = self.space + i;
            self.place_u8(pos, *c);
        }
        self.end_vector()
    }

    /// Create a vector of `UOffsetT` in the buffer.
    /// This function will encode the values to `LittleEndian`.
    pub fn create_uoffset_vector(&mut self, value: &[UOffsetT]) -> UOffsetT {
        let len = value.len();
        self.start_vector(UOFFSETT_SIZE, len, 0);
        self.space -= len;
        for (i, c) in value.iter().enumerate() {
            let pos = self.space + i;
            self.place_u32(pos, *c);
        }
        self.end_vector()
    }

    /// Finalize a table, pointing to the given `root_table`.
    pub fn finish_table(&mut self, root_table: UOffsetT) -> UOffsetT {
        self.assert_not_nested();
        let align = self.min_align;
        self.prep(align, UOFFSETT_SIZE);
        self.add_uoffset(root_table);
        self.finished = true;
        self.offset()
    }

    /// Get a reference to the underlying buffer.
    /// Buffer starts from the first byte of useful data
    /// i.e. `&[pos..]`.
    pub fn get_bytes(&self) -> &[u8] {
        let pos = self.pos();
        &self.bytes[pos..]
    }
    
    /// Returns the current buffer and replaces it with
    /// a `new_buffer`.
    ///
    /// Thie function facilitates some reuse of the `Builder` object.
    /// Use `into()` if the `Builder` is no longer required.
    pub fn swap_out(&mut self, mut new_buffer: Vec<u8>) -> Vec<u8> {
        use std::mem;
        mem::swap(&mut self.bytes, &mut new_buffer);
        self.reset();
        new_buffer
    }

    /// Resets the builder.
    ///
    /// Clears the buffer without resizing. This allows for reuse
    /// without allocating new memeory.
    pub fn reset(&mut self) {
        self.min_align = 1;
        self.object_start = 0;
        self.nested = false;
        self.finished = false;
        self.vtable_in_use = 0;
        unsafe {
            self.vtable.set_len(0);
            self.vtables.set_len(0);
        }
        self.space = self.bytes.capacity();
        self.vector_len = 0;
    }

    /// Returns the length of the buffer.
    pub fn len(&self) -> usize {
        self.bytes.len()
    }

    /// Offset relative to the end of the buffer.
    #[inline(always)]
    pub fn offset(&self) -> UOffsetT {
        (self.bytes.len() - self.space) as UOffsetT
    }
    
    /// Returns the offset relative to the beggining
    /// of the buffer.
    pub fn pos(&self) -> usize {
        self.space
    }

    /// prepare to write an element of `size` after `additional_bytes`
    /// have been written.
    pub fn prep(&mut self, size: usize, additional_bytes: usize) {
        if size > self.min_align {
            self.min_align = size
        }
        let align_size = self.offset() as usize + additional_bytes + 1; 
        let align_size = ((align_size ^ 1)) & (size - 1);
        while self.space <= align_size + size + additional_bytes {
            self.grow();
        }
        self.pad(align_size)
    }

    /// pad places zeros at the current offset.
    pub fn pad(&mut self, n: usize) {
        for _ in 0..n {
            self.space -= 1;
            let pos = self.space;
            self.place_u8(pos, 0)
        }
    }
}

impl Builder {
    /// Add a `bool` to the buffer, backwards from the current location.
    /// Doesn't align nor check for space.
    pub fn put_bool(&mut self, boolean: bool) {
        self.space -= 1;
        let head = self.space;
        self.bytes[head] = if boolean {
            1
        } else {
            0
        };
    }

    /// Add a `byte` to the buffer, backwards from the current location.
    /// Doesn't align nor check for space.
    pub fn put_u8(&mut self, byte: u8) {
        self.space -= 1;
        let head = self.space;
        self.bytes[head] = byte;
    }

    /// Add a `value` of type `i8` to the buffer, backwards from the current
    /// location. Doesn't align nor check for space.
    pub fn put_i8(&mut self, value: i8) {
        self.put_u8(value as u8)
    }

    /// Add a `value` of type `u16` to the buffer, backwards from the current
    /// location. Doesn't align nor check for space.
    pub fn put_u16(&mut self, value: u16) {
        self.space -= 2;
        let head = self.space;
        LittleEndian::write_u16(&mut self.bytes[head..head + 2], value);
    }

    /// Add a `value` of type `i16` to the buffer, backwards from the current
    /// location. Doesn't align nor check for space.
    pub fn put_i16(&mut self, value: i16) {
        self.put_u16(value as u16)
    }

    /// Add a `value` of type `u32` to the buffer, backwards from the current
    /// location. Doesn't align nor check for space.
    pub fn put_u32(&mut self, value: u32) {
        self.space -= 4;
        let head = self.space;
        LittleEndian::write_u32(&mut self.bytes[head..head + 4], value);
    }

    /// Add a `value` of type `i32` to the buffer, backwards from the current
    /// location. Doesn't align nor check for space.
    pub fn put_i32(&mut self, value: i32) {
        self.put_u32(value as u32)
    }

    /// Add a `value` of type `u64` to the buffer, backwards from the current
    /// location. Doesn't align nor check for space.
    pub fn put_u64(&mut self, value: u64) {
        self.space -= 8;
        let head = self.space;
        LittleEndian::write_u64(&mut self.bytes[head..head + 8], value);

    }

    /// Add a `value` of type `i64` to the buffer, backwards from the current
    /// location. Doesn't align nor check for space.
    pub fn put_i64(&mut self, value: i64) {
        self.put_u64(value as u64)
    }

    /// Add a `value` of type `f32` to the buffer, backwards from the current
    /// location. Doesn't align nor check for space.
    pub fn put_f32(&mut self, value: f32) {
        self.space -= 4;
        let head = self.space;
        LittleEndian::write_f32(&mut self.bytes[head..head + 4], value);
    }

    /// Add a `value` of type `f64` to the buffer, backwards from the current
    /// location. Doesn't align nor check for space.
    pub fn put_f64(&mut self, value: f64) {
        self.space -= 8;
        let head = self.space;
        LittleEndian::write_f64(&mut self.bytes[head..head + 8], value);
    }

    /// Add a `value` of type `UOffsetT` to the buffer, backwards from the
    /// current location. Doesn't align nor check for space.
    pub fn put_uoffset(&mut self, value: UOffsetT) {
        self.space -= 4;
        let head = self.space;
        LittleEndian::write_u32(&mut self.bytes[head..head + 4], value);
    }

    /// Add a `bool` to the buffer, properly aligned, and grows the
    /// buffer (if necessary).
    pub fn add_bool(&mut self, value: bool) {
        self.prep(1, 0);
        self.put_bool(value);
    }

    /// Add a value of type `u8` to the buffer, properly aligned, and grows the
    /// buffer (if necessary).
    pub fn add_u8(&mut self, value: u8) {
        self.prep(1, 0);
        self.put_u8(value);
    }

    /// Add a value of type `i8` to the buffer, properly aligned, and grows the
    /// buffer (if necessary).
    pub fn add_i8(&mut self, value: i8) {
        self.add_u8(value as u8);
    }

    /// Add a value of type `u16` to the buffer, properly aligned, and grows the
    /// buffer (if necessary).
    pub fn add_u16(&mut self, value: u16) {
        self.prep(2, 0);
        self.put_u16(value);
    }

    /// Add a value of type `i16` to the buffer, properly aligned, and grows the
    /// buffer (if necessary).
    pub fn add_i16(&mut self, value: i16) {
        self.add_u16(value as u16);
    }

    /// Add a value of type `u32` to the buffer, properly aligned, and grows the
    /// buffer (if necessary).
    pub fn add_u32(&mut self, value: u32) {
        self.prep(4, 0);
        self.put_u32(value);
    }

    /// Add a value of type `i32` to the buffer, properly aligned, and grows the
    /// buffer (if necessary).
    pub fn add_i32(&mut self, value: i32) {
        self.add_u32(value as u32);
    }

    /// Add a value of type `u64` to the buffer, properly aligned, and grows the
    /// buffer (if necessary).
    pub fn add_u64(&mut self, value: u64) {
        self.prep(8, 0);
        self.put_u64(value);
    }

    /// Add a value of type `i64` to the buffer, properly aligned, and grows the
    /// buffer (if necessary).
    pub fn add_i64(&mut self, value: i64) {
        self.add_u64(value as u64);
    }

    /// Add a value of type `f32` to the buffer, properly aligned, and grows the
    /// buffer (if necessary).
    pub fn add_f32(&mut self, value: f32) {
        self.prep(4, 0);
        self.put_f32(value);
    }

    /// Add a value of type `f64` to the buffer, properly aligned, and grows the
    /// buffer (if necessary).
    pub fn add_f64(&mut self, value: f64) {
        self.prep(8, 0);
        self.put_f64(value);
    }

    /// Add a value of type `f64` to the buffer, properly aligned, and grows the
    /// buffer (if necessary).
    /// prepends an UOffsetT, relative to where it will be written.
    pub fn add_uoffset(&mut self, value: UOffsetT) {
        self.prep(UOFFSETT_SIZE, 0);
		assert!(value <= self.offset() as UOffsetT, "unreachable: off <= boffset();");
        let relative = self.offset() as u32 - value as u32 + UOFFSETT_SIZE as u32;
        self.put_uoffset(relative);
    }

    /// Slot sets the vtable key `voffset` to the current location in the buffer.
    pub fn slot(&mut self, slot: usize) {
        self.vtable[slot] = self.offset() as UOffsetT;
    }

    /// Add a `bool` onto the object at vtable slot `o`. If value `x` equals
    /// default `d`, then the slot will be set to zero and no other data
    /// will be written.
    pub fn add_slot_bool(&mut self, o: usize, value: bool, d: bool) {
        if value != d {
            self.add_bool(value);
            self.slot(o)
        }
    }

    /// Add a value of type `u8` onto the object at vtable slot `o`. If value
    /// `x` equals default `d`, then the slot will be set to zero and no other
    /// data will be written.
    pub fn add_slot_u8(&mut self, o: usize, value: u8, d: u8) {
        if value != d {
            self.add_u8(value);
            self.slot(o)
        }
    }

    /// Add a value of type `i8` onto the object at vtable slot `o`. If value
    /// `x` equals default `d`, then the slot will be set to zero and no other
    /// data will be written.
    pub fn add_slot_i8(&mut self, o: usize, value: i8, d: i8) {
        self.add_slot_u8(o, value as u8, d as u8);
    }

    /// Add a value of type `u16` onto the object at vtable slot `o`. If value
    /// `x` equals default `d`, then the slot will be set to zero and no other
    /// data will be written.
    pub fn add_slot_u16(&mut self, o: usize, value: u16, d: u16) {
        if value != d {
            self.add_u16(value);
            self.slot(o)
        }
    }

    /// Add a value of type `i16` onto the object at vtable slot `o`. If value
    /// `x` equals default `d`, then the slot will be set to zero and no other
    /// data will be written.
    pub fn add_slot_i16(&mut self, o: usize, value: i16, d: i16) {
        self.add_slot_u16(o, value as u16, d as u16);
    }

    /// Add a value of type `u32` onto the object at vtable slot `o`. If value
    /// `x` equals default `d`, then the slot will be set to zero and no other
    /// data will be written.
    pub fn add_slot_u32(&mut self, o: usize, value: u32, d: u32) {
        if value != d {
            self.add_u32(value);
            self.slot(o)
        }
    }

    /// Add a value of type `i32` onto the object at vtable slot `o`. If value
    /// `x` equals default `d`, then the slot will be set to zero and no other
    /// data will be written.
    pub fn add_slot_i32(&mut self, o: usize, value: i32, d: i32) {
        self.add_slot_u32(o, value as u32, d as u32);
    }

    /// Add a value of type `u64` onto the object at vtable slot `o`. If value
    /// `x` equals default `d`, then the slot will be set to zero and no other
    /// data will be written.
    pub fn add_slot_u64(&mut self, o: usize, value: u64, d: u64) {
        if value != d {
            self.add_u64(value);
            self.slot(o)
        }
    }

    /// Add a value of type `i64` onto the object at vtable slot `o`. If value
    /// `x` equals default `d`, then the slot will be set to zero and no other
    /// data will be written.
    pub fn add_slot_i64(&mut self, o: usize, value: i64, d: i64) {
        self.add_slot_u64(o, value as u64, d as u64);
    }

    /// Add a value of type `f32` onto the object at vtable slot `o`. If value
    /// `x` equals default `d`, then the slot will be set to zero and no other
    /// data will be written.
    pub fn add_slot_f32(&mut self, o: usize, value: f32, d: f32) {
        if value != d {
            self.add_f32(value);
            self.slot(o)
        }
    }

    /// Add a value of type `f64` onto the object at vtable slot `o`. If value
    /// `x` equals default `d`, then the slot will be set to zero and no other
    /// data will be written.
    pub fn add_slot_f64(&mut self, o: usize, value: f64, d: f64) {
        if value != d {
            self.add_f64(value);
            self.slot(o)
        }
    }

    /// Add a value of type `UOffsetT` onto the object at vtable slot `o`. If
    /// value `x` equals default `d`, then the slot will be set to zero and no
    /// other data will be written.
    ///
    /// prepends an UOffsetT, relative to where it will be written.
    pub fn add_slot_uoffset(&mut self, o: usize, value: UOffsetT, d: UOffsetT) {
        if value != d {
            self.add_uoffset(value);
            self.slot(o)
        }
    }

    /// PrependStructSlot prepends a struct onto the object at vtable slot `o`.
    /// Structs are stored inline, so nothing additional is being added.
    /// In generated code, `d` is always 0.
    pub fn add_slot_struct(&mut self, o: usize, value: UOffsetT, d: UOffsetT) {
        if value != d {
            self.assert_nested();
		    assert!(value == self.offset() as u32, "Inline data write outside of object");
		    self.slot(o)
        }
    }

    /// Place a `u8` at `pos` relative to the beginning
    /// of the underlaying buffer.
    pub fn place_u8(&mut self, pos: usize, value: u8) {
        self.bytes[pos] = value;
    }

    /// Place a `u32` with `LittleEndian` encoding at `pos`
    /// relative to the beginning of the underlaying buffer.
    pub fn place_u32(&mut self, pos: usize, value: u32) {
        LittleEndian::write_u32(&mut self.bytes[pos..pos + 4], value);
    }

    /// Place a `i32` with `LittleEndian` encoding at `pos`
    /// relative to the beginning of the underlaying buffer.
    pub fn place_i32(&mut self, pos: usize, value: i32) {
        LittleEndian::write_i32(&mut self.bytes[pos..pos + 4], value);
    }

    /// Place a `u64` with `LittleEndian` encoding at `pos`
    /// relative to the beginning of the underlaying buffer.
    pub fn place_u64(&mut self, pos: usize, value: u64) {
        LittleEndian::write_u64(&mut self.bytes[pos..pos + 8], value);
    }

    /// Check to assert `finish` has not been called.
    pub fn assert_not_finished(&self) {
        assert!(!self.finished,
                "FlatBuffers: root table is not finished.");
    }

    /// Check to assert `start_object` has not been called.
    pub fn assert_not_nested(&self) {
        assert!(!self.nested,
                "FlatBuffers: object serialization must not be nested.");
    }
    
    /// Check to assert `start_object` has been called.
    pub fn assert_nested(&self) {
        assert!(self.nested,
                "FlatBuffers: struct must be serialized inline.");
    }

    /// Helper method to read a VOffsetT at `pos` relative to the
    /// beginning of the underlying buffer - this may not be the start
    /// of any useful data. Use with `offset()` to get the `UOffsetT`
    /// of useful data.
    pub fn get_u16(&self, pos: usize) -> VOffsetT {
        LittleEndian::read_u16(&self.bytes[pos..pos + 2])
    }

    /// Helper method to read a UOffsetT at `pos` relative to the
    /// beginning of the underlying buffer - this may not be the start
    /// of any useful data. Use with `offset()` to get the `UOffsetT`
    /// of useful data.
    pub fn get_32(&self, pos: usize) -> UOffsetT {
        LittleEndian::read_u32(&self.bytes[pos..pos + 4])
    }

    /// Doubles the size of the buffer.
    ///
    /// Copies the old data towards the end of the new buffer (since we build
    /// the buffer backwards).
    /// Max buffer size is 2 Gigabytes - otherwise u16 index values might
    /// be invalid.
    pub fn grow(&mut self) {
        let old_capacity = if self.bytes.capacity() == 0 {
            1
        } else {
            self.bytes.capacity()
        };
        let size_test = old_capacity & 0xC0000000;
        assert!(size_test == 0,
                "FlatBuffers: cannot grow buffer beyond 2 gigabytes.");
        let new_capacity = old_capacity << 1;
        let mut nbytes = Vec::with_capacity(new_capacity);
        for _ in 0..old_capacity {
            nbytes.push(0)
        }
        self.space = new_capacity - self.offset() as usize;
        nbytes.extend_from_slice(&self.bytes);
        unsafe { nbytes.set_len(new_capacity) };
        self.bytes = nbytes;
    }

    // WriteVtable serializes the vtable for the current object.
    //
    // Before writing out the vtable, this checks pre-existing vtables for
    // equality to this one. If an equal vtable is found, point the object to
    // the existing vtable and return.
    //
    // Because vtable values are sensitive to alignment of object data, not all
    // logically-equal vtables will be deduplicated.
    fn write_vtable(&mut self) -> UOffsetT {
        self.add_uoffset(0);
        let vtableloc = self.offset() as usize;
        // Write out the current vtable.
        for i in (0..self.vtable_in_use).rev() {
            // Offset relative to the start of the table.
            let offset = if self.vtable[i] != 0 {
                vtableloc - self.vtable[i] as usize
            } else {
                0
            };
            self.add_u16(offset as u16);
        }
        // write the metadata
        let total_obj_size = vtableloc - self.object_start as usize;
        let vtable_size = (self.vtable_in_use + VTABLE_METADATA_FIEDS) * VOFFSETT_SIZE;
        self.add_u16(total_obj_size as u16);
        self.add_u16(vtable_size as u16);
        // check for identical vtable
        let mut existing_vt = 0;
        let mut this_vt = self.space;
        'outer: for (i, vt_offset) in self.vtables.iter().rev().enumerate() {
            let vt_start = self.bytes.len() - *vt_offset as usize;
            let vt_len = self.get_u16(vt_start);
            if vt_len != self.get_u16(this_vt) {
                continue;
            }
            let vt_end = vt_start + vt_len as usize;
            let vt_bytes = &self.bytes[vt_start + VTABLE_METADATA_SIZE..vt_end];
            for (j, chunk) in vt_bytes.chunks(VOFFSETT_SIZE).enumerate() {
                let this_start = this_vt + VTABLE_METADATA_SIZE + (j * VOFFSETT_SIZE) as usize;
                let this_end = this_start + VOFFSETT_SIZE;
                let this_chunk = &self.bytes[this_start..this_end];
                if chunk != this_chunk {
                    continue 'outer;
                }
            }
            existing_vt = self.vtables[i] as usize;
            break 'outer;
        }

        if existing_vt != 0 {
            // found a match
            self.space = self.bytes.capacity() - vtableloc;
            let pos = self.space;
            self.place_i32(pos, (existing_vt as i32 - vtableloc as i32));
        } else {
            // no match
            this_vt = self.offset() as usize;
            self.vtables.push(this_vt as u32);
            let capacity = self.bytes.capacity();
            self.place_i32(capacity - vtableloc, (this_vt - vtableloc) as i32);
        }
        self.vtable.clear();
        vtableloc as UOffsetT
    }
}

impl Default for Builder {
    fn default() -> Builder {
        Builder::with_capacity(1024)
    }
}

impl Into<Vec<u8>> for Builder {
    fn into(self) -> Vec<u8> {
        self.bytes
    }
}

#[cfg(test)]
mod test {
    use super::Builder;
    use types::*;
    use table::Table;

    #[test]
    fn grow_buffer() {
        let mut b = Builder::with_capacity(0);
        b.grow();
        assert_eq!(b.space, 2);
        assert_eq!(b.offset(), 0);
        assert_eq!(b.len(), 2);

        let mut b = Builder::with_capacity(1);
        b.grow();
        assert_eq!(b.space, 2);
        assert_eq!(b.offset(), 0);
        assert_eq!(b.len(), 2);

        let mut b = Builder::with_capacity(2);
        b.grow();
        assert_eq!(b.space, 4);
        assert_eq!(b.offset(), 0);
        assert_eq!(b.len(), 4);
    }

    #[test]
    fn grow_buffer2() {
        let mut builder = Builder::with_capacity(2);
        builder.add_u8(4);
        builder.add_u8(2);
        let old_capacity = builder.bytes.capacity();
        builder.grow();
        // capacity doubled
        assert_eq!(builder.bytes.capacity(), old_capacity * 2);
        assert_eq!(builder.bytes.len(), old_capacity * 2);
        // bytes moved to end of new buffer
        assert_eq!(builder.bytes[(old_capacity * 2) - 2], 2u8);
        assert_eq!(builder.bytes[(old_capacity * 2) - 1], 4u8);
    }

    #[test]
    fn check_bytes() {
        fn check(b: &Builder, i: u8, want: &[u8]) {
            let got = &b.bytes;
            assert!(got.ends_with(want),
                    "case {}: want\n{:?}\nbut got\n{:?}\n",
                    i,
                    want,
                    got)
        };
        let mut b = Builder::with_capacity(0);
        check(&b, 1, &[]);

        b.add_bool(true);
        check(&b, 2, &[1]);
        b.add_i8(-127);
        check(&b, 3, &[129, 1]);
        b.add_u8(255);
        check(&b, 4, &[255, 129, 1]);
        b.add_i16(-32222);
        check(&b, 5, &[0x22, 0x82, 0, 255, 129, 1]); // first pad
        b.add_u16(0xFEEE);
        check(&b, 6, &[0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1]); // no pad this time
        b.add_i32(-53687092);
        check(&b,
              7,
              &[204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1]);
        b.add_u32(0x98765432);
        check(&b,
              8,
              &[0x32, 0x54, 0x76, 0x98, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129,
                1]);

        b = Builder::with_capacity(0);
        b.add_u64(0x1122334455667788);
        check(&b, 9, &[0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11]);

        // test 2: 1xbyte vector
        b = Builder::with_capacity(0);
        check(&b, 10, &[]);
        b.start_vector(1, 1, 1);
        check(&b, 11, &[0, 0, 0]); // align to 4bytes
        b.add_u8(1);
        check(&b, 12, &[1, 0, 0, 0]);
        b.end_vector();
        check(&b, 13, &[1, 0, 0, 0, 1, 0, 0, 0]); // padding

        // test 3: 2xbyte vector
        b = Builder::with_capacity(0);
        b.start_vector(1, 2, 1);
        check(&b, 14, &[0,0]); // align to 4bytes
        b.add_u8(1);
        check(&b, 15, &[1,0,0]);
        b.add_u8(2);
        check(&b, 16, &[2,1,0,0]);
        b.end_vector();
        check(&b, 17, &[2, 0, 0, 0, 2, 1, 0, 0]); // padding

        // test 3b: 11xbyte vector matches builder size
        b = Builder::with_capacity(12);
        b.start_vector(1, 8, 1);
        check(&b, 18, &[]);
        for i in 0..11 {
            b.add_u8(i);
        }
        b.end_vector();
        // says size is 8 not 11 
        check(&b, 19, &[8, 0, 0, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);

        // test 4: 1xuint16 vector
        b = Builder::with_capacity(0);
        b.start_vector(2, 1, 1);
        check(&b, 20, &[0,0]); // align to 4bytes
        b.add_u16(1);
        check(&b, 21, &[1,0,0,0]); 
        b.end_vector();
        check(&b, 22, &[1,0,0,0,1,0,0,0]);  // padding

        // test 5: 2xuint16 vector
        b = Builder::with_capacity(0);
        b.start_vector(2, 2, 1);
        check(&b, 23, &[]); // align to 4bytes
        b.add_u16(0xABCD);
        check(&b, 24, &[0xCD, 0xAB]);
        b.add_u16(0xDCBA);
        check(&b, 25, &[0xBA, 0xDC,0xCD, 0xAB]);
        b.end_vector();
        check(&b, 25, &[2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB]);

        // create string
        b = Builder::with_capacity(0);
        b.create_string("foo");
        check(&b, 26, &[3, 0, 0, 0, 102, 111, 111, 0]); // 0-terminated, no pad
        b.create_string("moop");
        check(&b, 27, &[4, 0, 0, 0, 109, 111, 111, 112, 0, 0, 0, 0, // 0-terminated, 3-byte pad
                        3, 0, 0, 0, 102, 111, 111, 0]);

        // test 7: empty vtable
        b = Builder::with_capacity(0);
        b.start_object(0);
        check(&b, 28, &[]);
        b.end_object();
        check(&b, 29, &[4, 0, 4, 0, 4, 0, 0, 0]);

        // test 8: vtable with one true bool
        b = Builder::with_capacity(0);
        b.start_object(1);
        check(&b, 30, &[]);
        b.add_slot_bool(0, true, false);
        let obj = b.end_object();
        check(&b, 31, &[
            6, 0, // vtable bytes
            8, 0, // length of object including vtable offset
            7, 0, // start of bool value
            6, 0, 0, 0, // offset for start of vtable (int32)
            0, 0, 0, // padded to 4 bytes
            1, // bool value
        ]);
        {
            let read_obj = b.read_object(obj);
            let o = read_obj.field_offset(4);
            let got = read_obj.get_bool(o);
            assert!(got == true, "Failed to read back last object - got {:?} expected true", got);
            let got = read_obj.get_u8(o);
            assert!(got == 1, "Failed to read back last object. wrong value expected 1 got {}", got);
        }
        

        // test 9: vtable with one default bool
        b = Builder::with_capacity(0);
        b.start_object(1);
        check(&b, 32, &[]);
        b.add_slot_bool(0, false, false);
        b.end_object();
        check(&b, 33, &[
            6, 0, // vtable bytes
            4, 0, // end of object from here
            0, 0, // entry 1 is zero
            6, 0, 0, 0, // offset for start of vtable (int32)
        ]);

        // test 10: vtable with one int16
        b = Builder::with_capacity(0);
        b.start_object(1);
        b.add_slot_i16(0, 0x789A, 0);
        b.end_object();
        check(&b, 34, &[
            6, 0, // vtable bytes
            8, 0, // end of object from here
            6, 0, // offset to value
            6, 0, 0, 0, // offset for start of vtable (int32)
            0, 0, // padding to 4 bytes
            0x9A, 0x78,
        ]);

        // test 11: vtable with two int16
        b = Builder::with_capacity(0);
        b.start_object(2);
        b.add_slot_i16(0, 0x3456, 0);
        b.add_slot_i16(1, 0x789A, 0);
        b.end_object();
        check(&b, 35, &[
            8, 0, // vtable bytes
            8, 0, // end of object from here
            6, 0, // offset to value 0
            4, 0, // offset to value 1
            8, 0, 0, 0, // offset for start of vtable (int32)
            0x9A, 0x78, // value 1
            0x56, 0x34, // value 0
        ]);

        // test 12a: vtable with int16 and bool
        b = Builder::with_capacity(0);
        b.start_object(2);
        b.add_slot_i16(0, 0x3456, 0);
        b.add_slot_bool(1, true, false);
        b.end_object();
        check(&b, 36, &[
            8, 0, // vtable bytes
            8, 0, // end of object from here
            6, 0, // offset to value 0
            5, 0, // offset to value 1
            8, 0, 0, 0, // offset for start of vtable (int32)
            0,          // padding
            1,          // value 1
            0x56, 0x34, // value 0
        ]);

        // test 12b: vtable with empty vector
        b = Builder::with_capacity(0);
        b.start_vector(1, 0, 1);
        let vecend = b.end_vector();
        b.start_object(1);
        b.add_slot_uoffset(0, vecend, 0);
        b.end_object();
        check(&b, 37, &[
            6, 0, // vtable bytes
            8, 0,
            4, 0, // offset to vector offset
            6, 0, 0, 0, // offset for start of vtable (int32)
            4, 0, 0, 0,
            0, 0, 0, 0, // length of vector (not in struct)
        ]);

        // test 12c: vtable with empty vector of byte and some scalars
        b = Builder::with_capacity(0);
        b.start_vector(1, 0, 1);
        let vecend = b.end_vector();
        b.start_object(2);
        b.add_slot_i16(0, 55, 0);
        b.add_slot_uoffset(1, vecend, 0);
        b.end_object();
        check(&b, 38, &[
            8, 0, // vtable bytes
            12, 0,
            10, 0, // offset to value 0
            4, 0, // offset to vector offset
            8, 0, 0, 0, // vtable loc
            8, 0, 0, 0, // value 1
            0, 0, 55, 0, // value 0    
            0, 0, 0, 0, // length of vector (not in struct)
        ]);
        {
            let buffer = b.get_bytes();
            assert_eq!(buffer, &[
                8, 0, // vtable bytes
                12, 0,
                10, 0, // offset to value 0
                4, 0, // offset to vector offset
                8, 0, 0, 0, // vtable loc
                8, 0, 0, 0, // value 1
                0, 0, 55, 0, // value 0    
                0, 0, 0, 0, // length of vector (not in struct)
            ]);
        }

        // test 13: vtable with 1 int16 and 2-vector of int16
        b = Builder::with_capacity(0);
        b.start_vector(2, 2, 1);
        b.add_i16(0x1234);
        b.add_i16(0x5678);
        let vecend = b.end_vector();
        b.start_object(2);
        b.add_slot_uoffset(1, vecend, 0);
        b.add_slot_i16(0, 55, 0);
        b.end_object();
        check(&b, 39, &[
                8, 0, // vtable bytes
                12, 0, // length of object
                6, 0, // start of value 0 from end of vtable
                8, 0, // start of value 1 from end of buffer
                8, 0, 0, 0, // offset for start of vtable (int32)
                0, 0, // padding
                55, 0, // value 0
                4, 0, 0, 0, // vector position from here
                2, 0, 0, 0, // length of vector (uint32)
                0x78, 0x56, // vector value 1
                0x34, 0x12, // vector value 0
        ]);

        // test 14: vtable with 1 struct of 1 int8, 1 int16, 1 int32
        b = Builder::with_capacity(0);
        b.start_object(1);
        b.prep(4+4+4, 0);
        b.add_i8(55);
        b.pad(3);
        b.add_i16(0x1234);
        b.pad(2);
        b.add_i32(0x12345678);
        let struct_start = b.offset();
        b.add_slot_struct(0, struct_start as u32, 0);
        b.end_object();
        check(&b, 40, &[
                6, 0, // vtable bytes
                16, 0, // end of object from here
                4, 0, // start of struct from here
                6, 0, 0, 0, // offset for start of vtable (int32)
                0x78, 0x56, 0x34, 0x12, // value 2
                0, 0, // padding
                0x34, 0x12, // value 1
                0, 0, 0, // padding
                55, // value 0
        ]);

       // test 15: vtable with 1 vector of 2 struct of 2 int8
        b = Builder::with_capacity(0);
        b.start_vector(1*2, 2, 1);
        b.add_i8(33);
        b.add_i8(44);
        b.add_i8(55);
        b.add_i8(66);
        let vecend = b.end_vector();
        b.start_object(1);
        b.add_slot_uoffset(0, vecend, 0);
        b.end_object();
        check(&b, 41, &[
                6, 0, // vtable bytes
                8, 0,
                4, 0, // offset of vector offset
                6, 0, 0, 0, // offset for start of vtable (int32)
                4, 0, 0, 0, // vector start offset

                2, 0, 0, 0, // vector length
                66, // vector value 1,1
                55, // vector value 1,0
                44, // vector value 0,1
                33, // vector value 0,0
        ]);

        // test 16: table with some elements
        b = Builder::with_capacity(0);
        b.start_object(2);
        b.add_slot_i8(0, 33, 0);
        b.add_slot_i16(1, 66, 0);
        let off = b.end_object();
        b.finish_table(off);

        check(&b, 42, &[
                12, 0, 0, 0, // root of table: points to vtable offset

                8, 0, // vtable bytes
                8, 0, // end of object from here
                7, 0, // start of value 0
                4, 0, // start of value 1

                8, 0, 0, 0, // offset for start of vtable (int32)

                66, 0, // value 1
                0,  // padding
                33, // value 0
        ]);

          // test 17: one unfinished table and one finished table
        b = Builder::with_capacity(0);
        b.start_object(2);
        b.add_slot_i8(0, 33, 0);
        b.add_slot_i8(1, 44, 0);
        let obj1 = b.end_object();
        let table1 = b.finish_table(obj1);

        b.start_object(3);
        b.add_slot_i8(0, 55, 0);
        b.add_slot_i8(1, 66, 0);
        b.add_slot_i8(2, 77, 0);
        let obj2 = b.end_object();
        let table2 = b.finish_table(obj2);

        check(&b, 43, &[
                16, 0, 0, 0, // root of table: points to object
                0, 0, // padding

                10, 0, // vtable bytes
                8, 0, // size of object
                7, 0, // start of value 0
                6, 0, // start of value 1
                5, 0, // start of value 2
                10, 0, 0, 0, // offset for start of vtable (int32)
                0,  // padding
                77, // value 2
                66, // value 1
                55, // value 0

                12, 0, 0, 0, // root of table: points to object

                8, 0, // vtable bytes
                8, 0, // size of object
                7, 0, // start of value 0
                6, 0, // start of value 1
                8, 0, 0, 0, // offset for start of vtable (int32)
                0, 0, // padding
                44, // value 1
                33, // value 0
        ]);
        assert!(b.offset() as usize + b.pos() == b.len());
        {
            let read_obj = b.read_object(obj1);
            let o = read_obj.field_offset(4);
            let got = read_obj.get_u8(o);
            assert!(got == 33, "Failed to read back last object - got {:?} expected 33", got);
            let read_table = b.read_table(table1);
            let o = read_table.field_offset(6);
            let got = read_table.get_u8(o);
            assert!(got == 44, "Failed to read back last object - got {:?} expected 44", got);

            let read_obj = b.read_object(obj2);
            let o = read_obj.field_offset(4);
            let got = read_obj.get_u8(o);
            assert!(got == 55, "Failed to read back last object - got {:?} expected 55", got);
            let read_table = b.read_table(table2);
            let o = read_table.field_offset(6);
            let got = read_table.get_u8(o);
            assert!(got == 66, "Failed to read back last object - got {:?} expected 66", got);
            let o = read_table.field_offset(8);
            let got = read_table.get_u8(o);
            assert!(got == 77, "Failed to read back last object - got {:?} expected 77", got);
        }


        // test 18: a bunch of bools
        b = Builder::with_capacity(0);
        b.start_object(8);
        b.add_slot_bool(0, true, false);
        b.add_slot_bool(1, true, false);
        b.add_slot_bool(2, true, false);
        b.add_slot_bool(3, true, false);
        b.add_slot_bool(4, true, false);
        b.add_slot_bool(5, true, false);
        b.add_slot_bool(6, true, false);
        b.add_slot_bool(7, true, false);
        let off = b.end_object();
        b.finish_table(off);

        check(&b, 44, &[
                24, 0, 0, 0, // root of table: points to vtable offset

                20, 0, // vtable bytes
                12, 0, // size of object
                11, 0, // start of value 0
                10, 0, // start of value 1
                9, 0, // start of value 2
                8, 0, // start of value 3
                7, 0, // start of value 4
                6, 0, // start of value 5
                5, 0, // start of value 6
                4, 0, // start of value 7
                20, 0, 0, 0, // vtable offset

                1, // value 7
                1, // value 6
                1, // value 5
                1, // value 4
                1, // value 3
                1, // value 2
                1, // value 1
                1, // value 0
        ]);


        // test 19: three bools
        b = Builder::with_capacity(0);
        b.start_object(3);
        b.add_slot_bool(0, true, false);
        b.add_slot_bool(1, true, false);
        b.add_slot_bool(2, true, false);
        let off = b.end_object();
        b.finish_table(off);

        check(&b, 45, &[
                16, 0, 0, 0, // root of table: points to vtable offset

                0, 0, // padding

                10, 0, // vtable bytes
                8, 0, // size of object
                7, 0, // start of value 0
                6, 0, // start of value 1
                5, 0, // start of value 2
                10, 0, 0, 0, // vtable offset from here

                0, // padding
                1, // value 2
                1, // value 1
                1, // value 0
        ]);

        // test 20: some floats
        b = Builder::with_capacity(0);
        b.start_object(1);
        b.add_slot_f32(0, 1.0, 0.0);
        b.end_object();

        check(&b, 46, &[
                6, 0, // vtable bytes
                8, 0, // size of object
                4, 0, // start of value 0
                6, 0, 0, 0, // vtable offset

                0, 0, 128, 63, // value 0
        ]);
    }

    #[test]
    fn duplicate_vtable() {
        let mut b = Builder::with_capacity(0);
        
	    b.start_object(4);
	    b.add_slot_u8(0, 0, 0);
	    b.add_slot_u8(1, 11, 0);
	    b.add_slot_u8(2, 22, 0);
	    b.add_slot_i16(3, 33, 0);
	    let obj0 = b.end_object();
        
	    b.start_object(4);
	    b.add_slot_u8(0, 0, 0);
	    b.add_slot_u8(1, 44, 0);
	    b.add_slot_u8(2, 55, 0);
	    b.add_slot_i16(3, 66, 0);
	    let obj1 = b.end_object();

	    b.start_object(4);
	    b.add_slot_u8(0, 0, 0);
	    b.add_slot_u8(1, 77, 0);
	    b.add_slot_u8(2, 88, 0);
	    b.add_slot_i16(3, 99, 0);
	    let obj2 = b.end_object();

        let got = b.get_bytes();

        let want: &[u8] = &[
		    240, 255, 255, 255, // == -12. offset to dedupped vtable.
		    99, 0,
		    88,
		    77,
		    248, 255, 255, 255, // == -8. offset to dedupped vtable.
		    66, 0,
		    55,
		    44,
		    12, 0,
		    8, 0,
		    0, 0,
		    7, 0,
		    6, 0,
		    4, 0,
		    12, 0, 0, 0,
		    33, 0,
		    22,
		    11,
	    ];
        assert!(got == want, "testVtableDeduplication want:\n{} {:?}\nbut got:\n{} {:?}\n",
			    want.len(), want, got.len(), got);

        let len = got.len();
        let table0 = Table::with_pos(got, len - obj0 as usize);
        let table1 = Table::with_pos(got, len - obj1 as usize);
        let table2 = Table::with_pos(got, len - obj2 as usize);
        fn test_table(tab: &Table, a: VOffsetT, b: u8, c: u8, d: u8) {
            let got = tab.read_voffset_slot(0, 0); 
            if 12 != got {
			    panic!("failed 0, 0: {}", got)
		    }
		    // object size
            let got = tab.read_voffset_slot(2, 0);
		    if  8 != got {
			    panic!("failed 2, 0: {}", got)
		    }
		    // default value
            let got = tab.read_voffset_slot(4, 0);
		    if  a != got {
			    panic!("failed 4, 0: {}", got)
		    }
            let got = tab.get_slot_u8(6, 0);
		    if  b != got as u8 {
			    panic!("failed 6, 0: {}", got)
		    }
            let val = tab.get_slot_u8(8, 0);
		    if  c != val as u8 {
			    panic!("failed 8, 0: {}", got)
		    }
            let got = tab.get_slot_u8(10, 0); 
		    if d != got as u8 {
			    panic!("failed 10, 0: {}", got)
		    }

        }
        test_table(&table0, 0, 11, 22, 33);
	    test_table(&table1, 0, 44, 55, 66);
	    test_table(&table2, 0, 77, 88, 99);

    }
}