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
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
use core::nonzero::NonZero;

use std::fmt::{self, Debug, Formatter};
use std::{io, mem};
use std::sync::Arc;

use raw::{Allocator, RawIobuf, write_failed};
use intlike::IntLike;
use iobuf::Iobuf;

/// Read-Only Iobuf
///
/// An `Iobuf` that cannot write into the buffer, but all read-only operations
/// are supported. It is possible to get a `RWIobuf` by performing a `deep_clone`
/// of the Iobuf, but this is extremely inefficient.
///
/// If your function only needs to do read-only operations on an Iobuf, consider
/// taking a generic `Iobuf` trait instead. That way, it can be used with either
/// a ROIobuf or a RWIobuf, generically.
pub struct ROIobuf<'a> {
  raw: RawIobuf<'a>,
}

#[test]
fn check_sane_roiobuf_size() {
  assert_eq!(mem::size_of::<ROIobuf>(), mem::size_of::<*mut u8>() + 16);
}

impl<'a> Clone for ROIobuf<'a> {
  #[inline(always)]
  fn clone(&self) -> Self {
    ROIobuf {
      raw: unsafe { self.raw.clone_nonatomic() },
    }
  }

  #[inline(always)]
  fn clone_from(&mut self, source: &Self) {
    unsafe { self.raw.clone_from_nonatomic(&source.raw) }
  }
}

impl<'a> Drop for ROIobuf<'a> {
  #[inline(always)]
  fn drop(&mut self) { unsafe { self.raw.drop_nonatomic() } }
}

/// Read-Write Iobuf
///
/// An `Iobuf` which can read and write into a buffer.
///
/// Iobufs may be `cloned` cheaply. When cloned, the data itself is shared and
/// refcounted, and a new copy of the limits and window is made. This can be
/// used to construct multiple views into the same buffer.
///
/// `poke` and `fill` write a value at a position relative to the start of
/// the window. Only `fill` advances the window by the amount written.
/// They are meant to be used with `try!`.
///
/// A suffix `_be` means the data will be read big-endian. A suffix `_le` means
/// the data will be read little-endian.
///
/// The `unsafe_` prefix means the function omits bounds checks. Misuse can
/// easily cause security issues. Be careful!
pub struct RWIobuf<'a> {
  raw: RawIobuf<'a>,
}

#[test]
fn check_sane_rwiobuf_size() {
  assert_eq!(mem::size_of::<RWIobuf>(), mem::size_of::<*mut u8>() + 16);
}

impl<'a> Clone for RWIobuf<'a> {
  #[inline(always)]
  fn clone(&self) -> Self {
    RWIobuf {
      raw: unsafe { self.raw.clone_nonatomic() },
    }
  }

  #[inline(always)]
  fn clone_from(&mut self, source: &Self) {
    unsafe { self.raw.clone_from_nonatomic(&source.raw) }
  }
}

impl<'a> Drop for RWIobuf<'a> {
  #[inline(always)]
  fn drop(&mut self) { unsafe { self.raw.drop_nonatomic() } }
}

impl<'a> io::Write for RWIobuf<'a> {
  #[inline]
  fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
    match self.fill(buf) {
      Ok(())  => Ok(buf.len()),
      Err(()) => write_failed(),
    }
  }

  #[inline(always)]
  fn flush(&mut self) -> io::Result<()> { Ok(()) }
}

/// Atomic Read-Only Iobuf
///
/// An `ROIobuf` which is safe to `Send` across tasks and `Share` with other tasks.
/// This atomically refcounts the buffer, which has a greater cost on `.clone()`,
/// but provides more flexibility to multithreaded consumers.
///
/// To create an `AROIobuf`, create a normal `Iobuf` and call `.atomic_read_only()`.
///
/// Below is an example of fill an Iobuf in one thread with the numbers 0x00 to
/// 0xFF, and consuming/validating these numbers in parallel in 4 other threads:
///
/// ```rust
/// #![feature(std_misc)]
/// use iobuf::{RWIobuf, AROIobuf, Iobuf};
/// use std::thread;
///
/// // Write the bytes 0x00 - 0xFF into an Iobuf.
/// fn fill(buf: &mut RWIobuf<'static>) -> Result<(), ()> {
///   for i in 0x00u32 .. 0x100 {
///     try!(buf.fill_be(i as u8));
///   }
///
///   Ok(())
/// }
///
/// // Validates the contents of buf are `idx`, `idx+1`, `idx+2`, ...
/// // until the buffer is exhausted.
/// fn check(buf: &mut AROIobuf, mut idx: u32) -> Result<(), ()> {
///   loop {
///     let b: u8 =
///       match buf.consume_be::<u8>() {
///         Err(()) => return Ok(()),
///         Ok(b) => b
///       };
///
///     if b as u32 == idx {
///       idx += 1;
///     } else {
///       return Err(())
///     }
///   }
/// }
///
/// let mut source_b = RWIobuf::new(256);
/// assert_eq!(fill(&mut source_b), Ok(()));
///
/// // Reset the Iobuf for reading.
/// source_b.flip_lo();
///
/// // We can still clone this buffer. It will be non-atomically refcounted for
/// // now.
/// {
///   let _ = source_b.clone();
/// }
///
/// // Now prepare it for sending to our 4 subtasks.
/// let shared_b: AROIobuf = source_b.atomic_read_only().ok().unwrap();
///
/// let mut tasks = vec!();
///
/// for i in 0..4 {
///   // This clone modifies the AROIobuf's atomic refcount.
///   let mut b = shared_b.clone();
///   tasks.push(thread::spawn(move || {
///     let start = i*0x40;
///     assert_eq!(b.advance(start), Ok(()));
///     assert_eq!(b.resize(0x40), Ok(()));
///     assert_eq!(check(&mut b, start), Ok(()));
///     assert!(b.is_empty());
///
///     // This clone will atomically modify refcounts.
///     {
///       let _ = b.clone();
///     }
///   }));
/// }
///
/// for mut t in tasks.into_iter() {
///   t.join();
/// }
/// ```
pub struct AROIobuf {
  raw: RawIobuf<'static>,
}

unsafe impl Send for AROIobuf {}
unsafe impl Sync for AROIobuf {}

impl Clone for AROIobuf {
  #[inline(always)]
  fn clone(&self) -> Self { AROIobuf { raw: unsafe { self.raw.clone_atomic() } } }

  #[inline(always)]
  fn clone_from(&mut self, source: &Self) { unsafe { self.raw.clone_from_atomic(&source.raw) } }
}

impl Drop for AROIobuf {
  #[inline(always)]
  fn drop(&mut self) { unsafe { self.raw.drop_atomic() } }
}

/// A unique, immutable Iobuf.
///
/// If the refcount on an Iobuf is `1`, it can be made unique with `.unique()`.
/// This will allow sending across channels, and later conversion back to a
/// normal refcounted (atomically or non) Iobuf with zero overhead.
pub struct UniqueIobuf {
  raw: RawIobuf<'static>,
}

unsafe impl Send for UniqueIobuf {}
unsafe impl Sync for UniqueIobuf {}

impl UniqueIobuf {
  /// Safely converts a `UniqueIobuf` into a `ROIobuf`.
  #[inline(always)]
  pub fn read_only(self) -> ROIobuf<'static> {
    unsafe { mem::transmute(self) }
  }

  /// Safely converts a `UniqueIobuf` into a `RWIobuf`.
  #[inline(always)]
  pub fn read_write(self) -> RWIobuf<'static> {
    unsafe { mem::transmute(self) }
  }

  /// Safely converts a `UniqueIobuf` into a `AROIobuf`.
  #[inline(always)]
  pub fn atomic_read_only(self) -> AROIobuf {
    unsafe { mem::transmute(self) }
  }
}

impl Drop for UniqueIobuf {
  #[inline(always)]
  fn drop(&mut self) { unsafe { self.raw.drop_nonatomic() } }
}

impl<'a> ROIobuf<'a> {
  /// Constructs a trivially empty Iobuf, limits and window are 0, and there's
  /// an empty backing buffer. This will not allocate.
  ///
  /// ```rust
  /// use iobuf::{ROIobuf,Iobuf};
  ///
  /// let mut b = ROIobuf::empty();
  ///
  /// assert_eq!(b.cap(), 0);
  /// assert_eq!(b.len(), 0);
  /// ```
  #[inline(always)]
  pub fn empty() -> ROIobuf<'static> {
    ROIobuf { raw: RawIobuf::empty() }
  }

  /// Constructs an Iobuf with the same contents as a string. The limits and
  /// window will be initially set to cover the whole string.
  ///
  /// No copying or allocating will be done by this function.
  ///
  /// ```rust
  /// use iobuf::{ROIobuf,Iobuf};
  ///
  /// let mut b = ROIobuf::from_str("hello");
  ///
  /// assert_eq!(b.cap(), 5);
  /// assert_eq!(b.len(), 5);
  /// unsafe { assert_eq!(b.as_window_slice(), b"hello"); }
  /// unsafe { assert_eq!(b.as_limit_slice(), b"hello"); }
  /// ```
  #[inline(always)]
  pub fn from_str(s: &'a str) -> Self {
    ROIobuf { raw: RawIobuf::from_str(s) }
  }

  /// Copies a `str` into a read-only Iobuf. The contents of the `str` will be
  /// copied, so prefer to use the other constructors whenever possible.
  ///
  /// ```rust
  /// use iobuf::{ROIobuf,Iobuf};
  ///
  /// let mut b = ROIobuf::from_str_copy("hello");
  ///
  /// assert_eq!(b.cap(), 5);
  /// assert_eq!(b.len(), 5);
  /// unsafe { assert_eq!(b.as_window_slice(), b"hello"); }
  /// unsafe { assert_eq!(b.as_limit_slice(), b"hello"); }
  /// ```
  #[inline(always)]
  pub fn from_str_copy(s: &str) -> Self {
    ROIobuf { raw: RawIobuf::from_str_copy(s) }
  }

  /// Copies a `str` into a read-only Iobuf, whose memory comes from the given
  /// allocator.
  #[inline(always)]
  pub fn from_str_copy_with_allocator(s: &str, allocator: Arc<Box<Allocator>>) -> ROIobuf<'static> {
    ROIobuf { raw: RawIobuf::from_str_copy_with_allocator(s, allocator) }
  }

  /// Copies the contents of a slice into a read-only Iobuf. The contents of the
  /// slice will be copied, so prefer to use the other constructors whenever
  /// possible.
  ///
  /// ```rust
  /// use iobuf::{ROIobuf,Iobuf};
  ///
  /// let mut v = vec!(1u8, 2, 3, 4, 5, 6);
  /// v[1] = 20;
  ///
  /// let mut b = ROIobuf::from_slice_copy(&v[..]);
  ///
  /// let expected = [ 1,20,3,4,5,6 ];
  /// unsafe { assert_eq!(b.as_window_slice(), &expected[..]); }
  /// ```
  #[inline(always)]
  pub fn from_slice_copy(s: &[u8]) -> ROIobuf<'static> {
    ROIobuf { raw: RawIobuf::from_slice_copy(s) }
  }

  /// Copies a byte vector into a new read-only Iobuf, whose memory comes from
  /// the given allocator.
  #[inline(always)]
  pub fn from_slice_copy_with_allocator(s: &[u8], allocator: Arc<Box<Allocator>>) -> ROIobuf<'static> {
    ROIobuf { raw: RawIobuf::from_slice_copy_with_allocator(s, allocator) }
  }

  /// Constructs an Iobuf from a slice. The Iobuf will not copy the slice
  /// contents, and therefore their lifetimes will be linked.
  ///
  /// ```rust
  /// use iobuf::{ROIobuf,Iobuf};
  ///
  /// let s = [1,2,3,4];
  ///
  /// let mut b = ROIobuf::from_slice(&s[..]);
  ///
  /// assert_eq!(b.advance(1), Ok(()));
  ///
  /// assert_eq!(s[1], 2); // we can still use the slice!
  /// assert_eq!(b.peek_be(1), Ok(0x0304u16)); // ...and the Iobuf!
  /// ```
  #[inline(always)]
  pub fn from_slice(s: &'a [u8]) -> Self {
    ROIobuf { raw: RawIobuf::from_slice(s) }
  }
}

impl<'a> RWIobuf<'a> {
  /// Constructs a trivially empty Iobuf, limits and window are 0, and there's
  /// an empty backing buffer. This will not allocate.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let mut b = RWIobuf::empty();
  ///
  /// assert_eq!(b.len(), 0);
  /// assert_eq!(b.cap(), 0);
  /// ```
  #[inline(always)]
  pub fn empty() -> RWIobuf<'static> {
    RWIobuf { raw: RawIobuf::empty() }
  }

  /// Constructs a new Iobuf with a buffer of size `len`, undefined contents,
  /// and the limits and window set to the full size of the buffer.
  ///
  /// The maximum length of an Iobuf is approximately 2 GB.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let mut b = RWIobuf::new(10);
  ///
  /// assert_eq!(b.len(), 10);
  /// assert_eq!(b.cap(), 10);
  /// ```
  #[inline(always)]
  pub fn new(len: usize) -> RWIobuf<'static> {
    RWIobuf { raw: RawIobuf::new(len) }
  }

  /// Constructs a new Iobuf with a buffer of size `len`, undefined contents,
  /// and the limits and window set to the full range of the buffer. The memory
  /// will be allocated out of the given allocator, instead of the global heap.
  ///
  /// The maximum length of an Iobuf is approximately 2 GB.
  #[inline(always)]
  pub fn new_with_allocator(len: usize, allocator: Arc<Box<Allocator>>) -> RWIobuf<'static> {
    RWIobuf { raw: RawIobuf::new_with_allocator(len, allocator) }
  }

  /// Copies a `str` into a writeable Iobuf. The contents of the `str` will be
  /// copied, so prefer to use the non-copying constructors whenever possible.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let mut b = RWIobuf::from_str_copy("hello");
  ///
  /// assert_eq!(b.poke_be(1, b'4'), Ok(()));
  ///
  /// assert_eq!(b.len(), 5);
  /// assert_eq!(b.cap(), 5);
  /// unsafe { assert_eq!(b.as_window_slice(), b"h4llo"); }
  /// unsafe { assert_eq!(b.as_limit_slice(), b"h4llo"); }
  /// ```
  #[inline(always)]
  pub fn from_str_copy(s: &str) -> RWIobuf<'static> {
    RWIobuf { raw: RawIobuf::from_str_copy(s) }
  }

  /// Copies a `str` into a writeable Iobuf, whose memory comes from the given
  /// allocator.
  #[inline(always)]
  pub fn from_str_copy_with_allocator(s: &str, allocator: Arc<Box<Allocator>>) -> RWIobuf<'static> {
    RWIobuf { raw: RawIobuf::from_str_copy_with_allocator(s, allocator) }
  }

  /// Constructs an Iobuf from a slice. The Iobuf will not copy the slice
  /// contents, and therefore their lifetimes will be linked.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let mut s = [1,2,3,4];
  ///
  /// {
  ///   let mut b = RWIobuf::from_slice(&mut s[..]);
  ///
  ///   assert_eq!(b.advance(1), Ok(()));
  ///   assert_eq!(b.peek_be(1), Ok(0x0304u16)); // ...and the Iobuf!
  ///   assert_eq!(b.poke_be(1, 100u8), Ok(()));
  /// }
  ///
  /// // We can still use the slice, but only because of the braces above.
  /// assert_eq!(s[2], 100);
  /// ```
  #[inline(always)]
  pub fn from_slice(s: &'a mut [u8]) -> Self {
    RWIobuf { raw: RawIobuf::from_slice(s) }
  }

  /// Copies a byte vector into a new, writeable Iobuf. The contents of the
  /// slice will be copied, so prefer to use the other constructors whenever
  /// possible.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let mut v = vec!(1u8, 2, 3, 4, 5, 6, 10);
  /// v[1] = 20;
  ///
  /// let mut b = RWIobuf::from_slice_copy(&v[..]);
  ///
  /// let expected = [ 1,20,3,4,5,6,10 ];
  /// unsafe { assert_eq!(b.as_window_slice(), expected); }
  /// ```
  #[inline(always)]
  pub fn from_slice_copy(s: &[u8]) -> RWIobuf<'static> {
    RWIobuf { raw: RawIobuf::from_slice_copy(s) }
  }

  /// Copies a byte vector into a new writeable Iobuf, whose memory comes from
  /// the given allocator.
  #[inline(always)]
  pub fn from_slice_copy_with_allocator(s: &[u8], allocator: Arc<Box<Allocator>>) -> RWIobuf<'static> {
    RWIobuf { raw: RawIobuf::from_slice_copy_with_allocator(s, allocator) }
  }

  /// Reads the data in the window as a mutable slice. Note that since `&mut`
  /// in rust really means `&unique`, this function lies. There can exist
  /// multiple slices of the same data. Therefore, this function is unsafe.
  ///
  /// It may only be used safely if you ensure that the data in the iobuf never
  /// interacts with the slice, as they point to the same data. `peek`ing or
  /// `poke`ing the slice returned from this function is a big no-no.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf, Iobuf};
  ///
  /// let mut s = [1,2,3];
  ///
  /// {
  ///   let mut b = RWIobuf::from_slice(&mut s[..]);
  ///
  ///   assert_eq!(b.advance(1), Ok(()));
  ///   unsafe { b.as_mut_window_slice()[1] = 30; }
  /// }
  ///
  /// let expected = [ 1,2,30 ];
  /// assert_eq!(s, &expected[..]);
  /// ```
  #[inline(always)]
  pub unsafe fn as_mut_window_slice<'b>(&'b self) -> &'b mut [u8] {
    self.raw.as_mut_window_slice()
  }

  /// Reads the data in the window as a mutable slice. Note that since `&mut`
  /// in rust really means `&unique`, this function lies. There can exist
  /// multiple slices of the same data. Therefore, this function is unsafe.
  ///
  /// It may only be used safely if you ensure that the data in the iobuf never
  /// interacts with the slice, as they point to the same data. `peek`ing or
  /// `poke`ing the slice returned from this function is a big no-no.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf, Iobuf};
  ///
  /// let mut s = [1,2,3];
  ///
  /// {
  ///   let mut b = RWIobuf::from_slice(&mut s[..]);
  ///
  ///   assert_eq!(b.advance(1), Ok(()));
  ///   unsafe { b.as_mut_limit_slice()[1] = 20; }
  /// }
  ///
  /// assert_eq!(s, &[1,20,3][..]);
  /// ```
  #[inline(always)]
  pub unsafe fn as_mut_limit_slice<'b>(&'b self) -> &'b mut [u8] {
    self.raw.as_mut_limit_slice()
  }

  /// Gets a read-only copy of this Iobuf. This is a very cheap operation, as
  /// the backing buffers are shared. This can be useful for interfacing with
  /// code that only accepts read-only Iobufs.
  ///
  /// In general, ROIobuf should never be used as a function parameter. If
  /// read-only acceess is all that is required, take a generic `<T: Iobuf>`.
  ///
  /// ```rust
  /// use iobuf::{ROIobuf,RWIobuf,Iobuf};
  ///
  /// let mut s = [1,2,3,4];
  ///
  /// let rwb: RWIobuf = RWIobuf::from_slice(&mut s[..]);
  ///
  /// // write some data into rwb.
  ///
  /// let rb: ROIobuf = rwb.read_only();
  ///
  /// // now do read-only ops.
  /// assert_eq!(rb.len(), 4);
  /// ```
  #[inline(always)]
  pub fn read_only(&self) -> ROIobuf<'a> {
    ROIobuf { raw: unsafe { self.raw.clone_nonatomic() } }
  }

  /// Copies data from the window to the lower limit fo the iobuf and sets the
  /// window to range from the end of the copied data to the upper limit. This
  /// is typically called after a series of `Consume`s to save unread data and
  /// prepare for the next series of `Fill`s and `flip_lo`s.
  ///
  /// ```rust
  /// use std::result::Result::{self,Ok};
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// // A header, saying how many shorts will follow. Unfortunately, our buffer
  /// // isn't big enough for all the shorts! Assume the rest will be sent in a
  /// // later packet.
  /// let mut s = [ 0x02, 0x11, 0x22, 0x33 ];
  /// let mut b = RWIobuf::from_slice(&mut s[..]);
  ///
  /// #[derive(Eq, PartialEq, Debug)]
  /// enum ParseState {
  ///   NeedMore(u16), // sum so far
  ///   Done(u16),     // final sum
  /// };
  ///
  /// // Returns a pair of the sum of shorts seen so far, and `true` if we're
  /// // finally done parsing. The sum will be partial if parsing is incomplete.
  /// fn parse(b: &mut RWIobuf) -> Result<ParseState, ()> {
  ///   let len: u8 = try!(b.consume_be());
  ///   let mut sum = 0u16;
  ///
  ///   for _ in (0u8 .. len) {
  ///     unsafe {
  ///       if b.len() < 2 {
  ///         b.compact();
  ///         return Ok(ParseState::NeedMore(sum));
  ///       }
  ///       sum += b.unsafe_consume_be::<u16>();
  ///     }
  ///   }
  ///
  ///   Ok(ParseState::Done(sum))
  /// }
  ///
  /// assert_eq!(parse(&mut b), Ok(ParseState::NeedMore(0x1122)));
  /// assert_eq!(b.len(), 3);
  /// assert_eq!(b.cap(), 4);
  /// assert_eq!(b.peek_be(0), Ok(0x11u8));
  /// ```
  #[inline(always)]
  pub fn compact(&mut self) { self.raw.compact() }

  /// Writes the bytes at a given offset from the beginning of the window, into
  /// the supplied buffer. Either the entire buffer is copied, or an error is
  /// returned because bytes outside of the window would be written.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let data = [ 1,2,3,4 ];
  ///
  /// let mut b = RWIobuf::new(10);
  ///
  /// assert_eq!(b.poke(0, &data[..]), Ok(()));
  /// assert_eq!(b.poke(3, &data[..]), Ok(()));
  /// assert_eq!(b.resize(7), Ok(()));
  /// assert_eq!(b.poke(4, &data[..]), Err(())); // no partial write, just failure
  ///
  /// let expected = [ 1,2,3,1,2,3,4 ];
  /// unsafe { assert_eq!(b.as_window_slice(), expected); }
  /// ```
  #[inline(always)]
  pub fn poke(&self, pos: u32, src: &[u8]) -> Result<(), ()> { self.raw.poke(pos, src) }

  /// Writes a big-endian primitive at a given offset from the beginning of the
  /// window.
  ///
  /// An error is returned if bytes outside of the window would be accessed.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let mut b = RWIobuf::new(10);
  ///
  /// assert_eq!(b.poke_be(0, 0x0304u16), Ok(()));
  /// assert_eq!(b.poke_be(1, 0x0505u16), Ok(()));
  /// assert_eq!(b.poke_be(3, 0x06070809u32), Ok(()));
  ///
  /// assert_eq!(b.resize(7), Ok(()));
  ///
  /// let expected = [ 3,5,5,6,7,8,9 ];
  /// unsafe { assert_eq!(b.as_window_slice(), expected); }
  /// ```
  #[inline(always)]
  pub fn poke_be<T: IntLike>(&self, pos: u32, t: T) -> Result<(), ()> { self.raw.poke_be(pos, t) }

  /// Writes a little-endian primitive at a given offset from the beginning of
  /// the window.
  ///
  /// An error is returned if bytes outside of the window would be accessed.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let mut b = RWIobuf::new(10);
  ///
  /// assert_eq!(b.poke_le(0, 0x0304u16), Ok(()));
  /// assert_eq!(b.poke_le(1, 0x0505u16), Ok(()));
  /// assert_eq!(b.poke_le(3, 0x06070809u32), Ok(()));
  ///
  /// assert_eq!(b.resize(7), Ok(()));
  ///
  /// unsafe { assert_eq!(b.as_window_slice(), [ 4, 5, 5, 9, 8, 7, 6 ]); }
  /// ```
  #[inline(always)]
  pub fn poke_le<T: IntLike>(&self, pos: u32, t: T) -> Result<(), ()> { self.raw.poke_le(pos, t) }

  /// Writes bytes from the supplied buffer, starting from the front of the
  /// window. Either the entire buffer is copied, or an error is returned
  /// because bytes outside the window were requested.
  ///
  /// After the bytes have been written, the window will be moved to no longer
  /// include then.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let data = [ 1, 2, 3, 4 ];
  ///
  /// let mut b = RWIobuf::new(10);
  ///
  /// assert_eq!(b.fill(&data[..]), Ok(()));
  /// assert_eq!(b.fill(&data[..]), Ok(()));
  /// assert_eq!(b.fill(&data[..]), Err(()));
  ///
  /// b.flip_lo();
  ///
  /// unsafe { assert_eq!(b.as_window_slice(), &[ 1,2,3,4,1,2,3,4 ][..]); }
  /// ```
  #[inline(always)]
  pub fn fill(&mut self, src: &[u8]) -> Result<(), ()> { self.raw.fill(src) }

  /// Writes a big-endian primitive into the beginning of the window.
  ///
  /// After the primitive has been written, the window will be moved such that
  /// it is no longer included.
  ///
  /// An error is returned if bytes outside of the window were requested.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let mut b = RWIobuf::new(10);
  ///
  /// assert_eq!(b.fill_be(0x12345678u32), Ok(()));
  /// assert_eq!(b.fill_be(0x11223344u32), Ok(()));
  /// assert_eq!(b.fill_be(0x54321123u32), Err(()));
  /// assert_eq!(b.fill_be(0x8877u16), Ok(()));
  ///
  /// b.flip_lo();
  ///
  /// unsafe { assert_eq!(b.as_window_slice(), [ 0x12, 0x34, 0x56, 0x78
  ///                                          , 0x11, 0x22, 0x33, 0x44
  ///                                          , 0x88, 0x77 ]); }
  /// ```
  #[inline(always)]
  pub fn fill_be<T: IntLike>(&mut self, t: T) -> Result<(), ()> { self.raw.fill_be(t) }

  /// Writes a little-endian primitive into the beginning of the window.
  ///
  /// After the primitive has been written, the window will be moved such that
  /// it is no longer included.
  ///
  /// An error is returned if bytes outside of the window were requested.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let mut b = RWIobuf::new(10);
  ///
  /// assert_eq!(b.fill_le(0x12345678u32), Ok(()));
  /// assert_eq!(b.fill_le(0x11223344u32), Ok(()));
  /// assert_eq!(b.fill_le(0x54321123u32), Err(()));
  /// assert_eq!(b.fill_le(0x8877u16), Ok(()));
  ///
  /// b.flip_lo();
  ///
  /// unsafe { assert_eq!(b.as_window_slice(), [ 0x78, 0x56, 0x34, 0x12
  ///                                          , 0x44, 0x33, 0x22, 0x11
  ///                                          , 0x77, 0x88 ]); }
  /// ```
  #[inline(always)]
  pub fn fill_le<T: IntLike>(&mut self, t: T) -> Result<(), ()> { self.raw.fill_le(t) }

  /// Writes the bytes at a given offset from the beginning of the window, into
  /// the supplied buffer. It is undefined behavior to write outside the iobuf
  /// window.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let data = [ 1,2,3,4 ];
  ///
  /// let mut b = RWIobuf::new(10);
  ///
  /// unsafe {
  ///   b.check_range_fail(1, 7);
  ///
  ///   b.unsafe_advance(1);
  ///   b.narrow();
  ///
  ///   b.unsafe_poke(0, &data);
  ///   b.unsafe_poke(3, &data);
  ///   b.unsafe_advance(7);
  /// }
  ///
  /// b.flip_lo();
  ///
  /// unsafe { assert_eq!(b.as_window_slice(), [ 1,2,3,1,2,3,4 ]); }
  /// ```
  #[inline(always)]
  pub unsafe fn unsafe_poke(&self, pos: u32, src: &[u8]) { self.raw.unsafe_poke(pos, src) }

  /// Writes a big-endian primitive at a given offset from the beginning of the
  /// window. It is undefined behavior to write outside the iobuf window.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let mut b = RWIobuf::new(10);
  ///
  /// unsafe {
  ///   b.check_range_fail(0, 7);
  ///
  ///   b.unsafe_poke_be(0, 0x0304u16);
  ///   b.unsafe_poke_be(1, 0x0505u16);
  ///   b.unsafe_poke_be(3, 0x06070809u32);
  /// }
  ///
  /// assert_eq!(b.resize(7), Ok(()));
  ///
  /// unsafe { assert_eq!(b.as_window_slice(), [ 3, 5, 5, 6, 7, 8, 9 ]); }
  /// ```
  #[inline(always)]
  pub unsafe fn unsafe_poke_be<T: IntLike>(&self, pos: u32, t: T) { self.raw.unsafe_poke_be(pos, t) }

  /// Writes a little-endian primitive at a given offset from the beginning of
  /// the window. It is undefined behavior to write outside the iobuf window.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let mut b = RWIobuf::new(10);
  ///
  /// unsafe {
  ///   b.check_range_fail(0, 7);
  ///
  ///   b.unsafe_poke_le(0, 0x0304u16);
  ///   b.unsafe_poke_le(1, 0x0505u16);
  ///   b.unsafe_poke_le(3, 0x06070809u32);
  /// }
  ///
  /// assert_eq!(b.resize(7), Ok(()));
  ///
  /// unsafe { assert_eq!(b.as_window_slice(), [ 4, 5, 5, 9, 8, 7, 6 ]); }
  /// ```
  #[inline(always)]
  pub unsafe fn unsafe_poke_le<T: IntLike>(&self, pos: u32, t: T) { self.raw.unsafe_poke_le(pos, t) }

  /// Writes bytes from the supplied buffer, starting from the front of the
  /// window. It is undefined behavior to write outside the iobuf window.
  ///
  /// After the bytes have been written, the window will be moved to no longer
  /// include then.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let data = [ 1, 2, 3, 4 ];
  ///
  /// let mut b = RWIobuf::new(10);
  ///
  /// unsafe {
  ///   b.check_range_fail(0, 8);
  ///
  ///   b.unsafe_fill(&data[..]);
  ///   b.unsafe_fill(&data[..]);
  /// }
  ///
  /// b.flip_lo();
  ///
  /// unsafe { assert_eq!(b.as_window_slice(), [ 1,2,3,4,1,2,3,4 ]); }
  /// ```
  #[inline(always)]
  pub unsafe fn unsafe_fill(&mut self, src: &[u8]) { self.raw.unsafe_fill(src) }

  /// Writes a big-endian primitive into the beginning of the window. It is
  /// undefined behavior to write outside the iobuf window.
  ///
  /// After the primitive has been written, the window will be moved such that
  /// it is no longer included.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let mut b = RWIobuf::new(10);
  ///
  /// unsafe {
  ///   b.check_range_fail(0, 10);
  ///
  ///   b.unsafe_fill_be(0x12345678u32);
  ///   b.unsafe_fill_be(0x11223344u32);
  ///   // b.unsafe_fill_be(0x54321123u32); DO NOT DO THIS. Undefined behavior.
  ///   b.unsafe_fill_be(0x8877u16);
  /// }
  ///
  /// b.flip_lo();
  ///
  /// unsafe { assert_eq!(b.as_window_slice(), [ 0x12, 0x34, 0x56, 0x78
  ///                                          , 0x11, 0x22, 0x33, 0x44
  ///                                          , 0x88, 0x77 ]); }
  /// ```
  #[inline(always)]
  pub unsafe fn unsafe_fill_be<T: IntLike>(&mut self, t: T) { self.raw.unsafe_fill_be(t) }

  /// Writes a little-endian primitive into the beginning of the window. It is
  /// undefined behavior to write outside the iobuf window.
  ///
  /// After the primitive has been written, the window will be moved such that
  /// it is no longer included.
  ///
  /// ```rust
  /// use iobuf::{RWIobuf,Iobuf};
  ///
  /// let mut b = RWIobuf::new(10);
  ///
  /// unsafe {
  ///   b.check_range_fail(0, 10);
  ///
  ///   b.unsafe_fill_le(0x12345678u32);
  ///   b.unsafe_fill_le(0x11223344u32);
  ///   // b.unsafe_fill_le(0x54321123u32); DO NOT DO THIS. Undefined behavior.
  ///   b.unsafe_fill_le(0x8877u16);
  /// }
  ///
  /// b.flip_lo();
  ///
  /// unsafe { assert_eq!(b.as_window_slice(), [ 0x78, 0x56, 0x34, 0x12
  ///                                          , 0x44, 0x33, 0x22, 0x11
  ///                                          , 0x77, 0x88 ]); }
  /// ```
  #[inline(always)]
  pub unsafe fn unsafe_fill_le<T: IntLike>(&mut self, t: T) { self.raw.unsafe_fill_le(t) }
}

impl AROIobuf {
  /// Stops atomically reference counting a unique buffer. This method returns
  /// `Ok` if the `AROIobuf` is the last of its kind, and `Err` if it's not.
  ///
  /// ```rust
  /// use iobuf::{AROIobuf, ROIobuf, Iobuf};
  ///
  /// let buf: ROIobuf<'static> = ROIobuf::from_str_copy("hello, world!");
  /// let a_buf: AROIobuf = buf.atomic_read_only().ok().unwrap();
  /// unsafe { assert_eq!(a_buf.as_window_slice(), b"hello, world!"); }
  ///
  /// let buf: ROIobuf<'static> = a_buf.read_only().ok().unwrap();
  ///
  /// // TA-DA!
  /// unsafe { assert_eq!(buf.as_window_slice(), b"hello, world!"); }
  /// ```
  #[inline(always)]
  pub fn read_only(self) -> Result<ROIobuf<'static>, AROIobuf> {
    unsafe {
      if self.raw.is_unique_atomic() {
        Ok(mem::transmute(self))
      } else {
        Err(self)
      }
    }
  }

  /// Stops atomically reference counting a unique buffer. This method returns
  /// `Ok` if the `AROIobuf` is the last of its kind, and `Err` if it's not.
  ///
  /// ```rust
  /// use iobuf::{AROIobuf, ROIobuf, RWIobuf, Iobuf};
  ///
  /// let buf: ROIobuf<'static> = ROIobuf::from_str_copy("hello, world!");
  /// let a_buf: AROIobuf = buf.atomic_read_only().ok().unwrap();
  /// unsafe { assert_eq!(a_buf.as_window_slice(), b"hello, world!"); }
  ///
  /// let buf: RWIobuf<'static> = a_buf.read_write().ok().unwrap();
  ///
  /// // TA-DA!
  /// unsafe { assert_eq!(buf.as_window_slice(), b"hello, world!"); }
  /// ```
  #[inline(always)]
  pub fn read_write(self) -> Result<RWIobuf<'static>, AROIobuf> {
    unsafe {
      if self.raw.is_unique_atomic() {
        Ok(mem::transmute(self))
      } else {
        Err(self)
      }
    }
  }
}

impl<'a> Iobuf for ROIobuf<'a> {
  #[inline(always)]
  fn deep_clone(&self) -> RWIobuf<'static> { RWIobuf { raw: self.raw.deep_clone() } }

  #[inline(always)]
  fn deep_clone_with_allocator(&self, allocator: Arc<Box<Allocator>>) -> RWIobuf<'static> {
    RWIobuf { raw: self.raw.deep_clone_with_allocator(allocator) }
  }

  #[inline(always)]
  fn unique(self) -> Result<UniqueIobuf, Self> {
    unsafe {
      if self.raw.is_unique_nonatomic() {
        Ok(mem::transmute(self))
      } else {
        Err(self)
      }
    }
  }

  #[inline(always)]
  fn atomic_read_only(self) -> Result<AROIobuf, Self> {
    unsafe {
      if self.raw.is_unique_nonatomic() {
        Ok(mem::transmute(self))
      } else {
        Err(self)
      }
    }
  }

  #[inline(always)]
  fn len(&self) -> u32 { self.raw.len() }

  #[inline(always)]
  fn cap(&self) -> u32 { self.raw.cap() }

  #[inline(always)]
  fn is_empty(&self) -> bool { self.raw.is_empty() }

  #[inline(always)]
  unsafe fn as_window_slice<'b>(&'b self) -> &'b [u8] { self.raw.as_window_slice() }

  #[inline(always)]
  unsafe fn as_limit_slice<'b>(&'b self) -> &'b [u8] { self.raw.as_limit_slice() }

  #[inline(always)]
  fn sub_window(&mut self, pos: u32, len: u32) -> Result<(), ()> { self.raw.sub_window(pos, len) }

  #[inline(always)]
  fn sub_window_from(&mut self, pos: u32) -> Result<(), ()> { self.raw.sub_window_from(pos) }

  #[inline(always)]
  fn sub_window_to(&mut self, len: u32) -> Result<(), ()> { self.raw.sub_window_to(len) }

  #[inline(always)]
  unsafe fn unsafe_sub_window(&mut self, pos: u32, len: u32) { self.raw.unsafe_sub_window(pos, len) }

  #[inline(always)]
  unsafe fn unsafe_sub_window_from(&mut self, pos: u32) { self.raw.unsafe_sub_window_from(pos) }

  #[inline(always)]
  unsafe fn unsafe_sub_window_to(&mut self, len: u32) { self.raw.unsafe_sub_window_to(len) }

  #[inline(always)]
  fn sub(&mut self, pos: u32, len: u32) -> Result<(), ()> { self.raw.sub(pos, len) }

  #[inline(always)]
  fn sub_from(&mut self, pos: u32) -> Result<(), ()> { self.raw.sub_from(pos) }

  #[inline(always)]
  fn sub_to(&mut self, len: u32) -> Result<(), ()> { self.raw.sub_to(len) }

  #[inline(always)]
  unsafe fn unsafe_sub(&mut self, pos: u32, len: u32) { self.raw.unsafe_sub(pos, len) }

  #[inline(always)]
  unsafe fn unsafe_sub_from(&mut self, pos: u32) { self.raw.unsafe_sub_from(pos) }

  #[inline(always)]
  unsafe fn unsafe_sub_to(&mut self, len: u32) { self.raw.unsafe_sub_to(len) }

  #[inline(always)]
  fn set_limits_and_window(&mut self, limits: (u32, u32), window: (u32, u32)) -> Result<(), ()> { self.raw.set_limits_and_window(limits, window) }

  #[inline(always)]
  fn narrow(&mut self) { self.raw.narrow() }

  #[inline(always)]
  fn advance(&mut self, len: u32) -> Result<(), ()> { self.raw.advance(len) }

  #[inline(always)]
  unsafe fn unsafe_advance(&mut self, len: u32) { self.raw.unsafe_advance(len) }

  #[inline(always)]
  fn extend(&mut self, len: u32) -> Result<(), ()> { self.raw.extend(len) }

  #[inline(always)]
  unsafe fn unsafe_extend(&mut self, len: u32) { self.raw.unsafe_extend(len) }

  #[inline(always)]
  fn is_extended_by<Buf: Iobuf>(&self, other: &Buf) -> bool { unsafe { self.raw.is_extended_by(other.as_raw()) } }

  #[inline(always)]
  fn extend_with<Buf: Iobuf>(&mut self, other: &Buf) -> Result<(), ()> { unsafe { self.raw.extend_with(other.as_raw()) } }

  #[inline(always)]
  fn resize(&mut self, len: u32) -> Result<(), ()> { self.raw.resize(len) }

  #[inline(always)]
  unsafe fn unsafe_resize(&mut self, len: u32) { self.raw.unsafe_resize(len) }

  #[inline(always)]
  fn split_at(&self, pos: u32) -> Result<(Self, Self), ()> {
    self.raw.split_at_nonatomic(pos).map(|(a, b)| (ROIobuf { raw: a }, ROIobuf { raw: b }))
  }

  #[inline(always)]
  unsafe fn unsafe_split_at(&self, pos: u32) -> (Self, Self) {
    let (a, b) = self.raw.unsafe_split_at_nonatomic(pos);
    (ROIobuf { raw: a }, ROIobuf { raw: b })
  }

  #[inline(always)]
  fn split_start_at(&mut self, pos: u32) -> Result<Self, ()> {
    self.raw.split_start_at_nonatomic(pos).map(|b| ROIobuf { raw: b })
  }

  #[inline(always)]
  unsafe fn unsafe_split_start_at(&mut self, pos: u32) -> Self {
    ROIobuf { raw: self.raw.unsafe_split_start_at_nonatomic(pos) }
  }

  #[inline(always)]
  fn rewind(&mut self) { self.raw.rewind() }

  #[inline(always)]
  fn reset(&mut self) { self.raw.reset() }

  #[inline(always)]
  fn flip_lo(&mut self) { self.raw.flip_lo() }

  #[inline(always)]
  fn flip_hi(&mut self) { self.raw.flip_hi() }

  #[inline(always)]
  fn lo_space(&self) -> u32 { self.raw.lo_space() }

  #[inline(always)]
  fn hi_space(&self) -> u32 { self.raw.hi_space() }

  #[inline(always)]
  fn peek(&self, pos: u32, dst: &mut [u8]) -> Result<(), ()> { self.raw.peek(pos, dst) }
  #[inline(always)]
  fn peek_be<T: IntLike>(&self, pos: u32) -> Result<T, ()> { self.raw.peek_be(pos) }
  #[inline(always)]
  fn peek_le<T: IntLike>(&self, pos: u32) -> Result<T, ()> { self.raw.peek_le(pos) }

  #[inline(always)]
  fn consume(&mut self, dst: &mut [u8]) -> Result<(), ()> { self.raw.consume(dst) }
  #[inline(always)]
  fn consume_be<T: IntLike>(&mut self) -> Result<T, ()> { self.raw.consume_be::<T>() }
  #[inline(always)]
  fn consume_le<T: IntLike>(&mut self) -> Result<T, ()> { self.raw.consume_le::<T>() }

  #[inline(always)]
  fn check_range(&self, pos: u32, len: u32) -> Result<(), ()> { self.raw.check_range_u32(pos, len) }

  #[inline(always)]
  fn check_range_usize(&self, pos: u32, len: usize) -> Result<(), ()> { self.raw.check_range_usize(pos, len) }

  #[inline(always)]
  fn check_range_fail(&self, pos: u32, len: u32) { self.raw.check_range_u32_fail(pos, len) }

  #[inline(always)]
  fn check_range_usize_fail(&self, pos: u32, len: usize) { self.raw.check_range_usize_fail(pos, len) }

  #[inline(always)]
  unsafe fn unsafe_peek(&self, pos: u32, dst: &mut [u8]) { self.raw.unsafe_peek(pos, dst) }
  #[inline(always)]
  unsafe fn unsafe_peek_be<T: IntLike>(&self, pos: u32) -> T { self.raw.unsafe_peek_be(pos) }
  #[inline(always)]
  unsafe fn unsafe_peek_le<T: IntLike>(&self, pos: u32) -> T { self.raw.unsafe_peek_le(pos) }

  #[inline(always)]
  unsafe fn unsafe_consume(&mut self, dst: &mut [u8]) { self.raw.unsafe_consume(dst) }
  #[inline(always)]
  unsafe fn unsafe_consume_be<T: IntLike>(&mut self) -> T { self.raw.unsafe_consume_be::<T>() }
  #[inline(always)]
  unsafe fn unsafe_consume_le<T: IntLike>(&mut self) -> T { self.raw.unsafe_consume_le::<T>() }

  #[inline(always)]
  unsafe fn as_raw<'b>(&'b self) -> &'b RawIobuf<'b> { mem::transmute(&self.raw) }

  #[inline(always)]
  fn invariant(&self) -> Result<(), Box<String>> { self.raw.invariant() }

  #[inline(always)]
  fn ptr(&self) -> NonZero<*mut u8> { self.raw.ptr() }
  #[inline(always)]
  fn is_owned(&self) -> bool { self.raw.is_owned() }
  #[inline(always)]
  fn lo_min(&self) -> u32 { self.raw.lo_min() }
  #[inline(always)]
  fn lo(&self) -> u32 { self.raw.lo() }
  #[inline(always)]
  fn hi(&self) -> u32 { self.raw.hi() }
  #[inline(always)]
  fn hi_max(&self) -> u32 { self.raw.hi_max() }
}

impl Iobuf for AROIobuf {
  #[inline(always)]
  fn deep_clone(&self) -> RWIobuf<'static> {
    RWIobuf { raw: self.raw.deep_clone() }
  }

  #[inline(always)]
  fn deep_clone_with_allocator(&self, allocator: Arc<Box<Allocator>>) -> RWIobuf<'static> {
    RWIobuf { raw: self.raw.deep_clone_with_allocator(allocator) }
  }

  #[inline(always)]
  fn unique(self) -> Result<UniqueIobuf, AROIobuf> {
    unsafe {
      if self.raw.is_unique_atomic() {
        Ok(mem::transmute(self))
      } else {
        Err(self)
      }
    }
  }

  #[inline(always)]
  fn atomic_read_only(self) -> Result<AROIobuf, AROIobuf> {
    Ok(self)
  }

  #[inline(always)]
  fn len(&self) -> u32 { self.raw.len() }

  #[inline(always)]
  fn cap(&self) -> u32 { self.raw.cap() }

  #[inline(always)]
  fn is_empty(&self) -> bool { self.raw.is_empty() }

  #[inline(always)]
  unsafe fn as_window_slice<'b>(&'b self) -> &'b [u8] { self.raw.as_window_slice() }

  #[inline(always)]
  unsafe fn as_limit_slice<'b>(&'b self) -> &'b [u8] { self.raw.as_limit_slice() }

  #[inline(always)]
  fn sub_window(&mut self, pos: u32, len: u32) -> Result<(), ()> { self.raw.sub_window(pos, len) }

  #[inline(always)]
  fn sub_window_from(&mut self, pos: u32) -> Result<(), ()> { self.raw.sub_window_from(pos) }

  #[inline(always)]
  fn sub_window_to(&mut self, len: u32) -> Result<(), ()> { self.raw.sub_window_to(len) }

  #[inline(always)]
  unsafe fn unsafe_sub_window(&mut self, pos: u32, len: u32) { self.raw.unsafe_sub_window(pos, len) }

  #[inline(always)]
  unsafe fn unsafe_sub_window_from(&mut self, pos: u32) { self.raw.unsafe_sub_window_from(pos) }

  #[inline(always)]
  unsafe fn unsafe_sub_window_to(&mut self, len: u32) { self.raw.unsafe_sub_window_to(len) }

  #[inline(always)]
  fn sub(&mut self, pos: u32, len: u32) -> Result<(), ()> { self.raw.sub(pos, len) }

  #[inline(always)]
  fn sub_from(&mut self, pos: u32) -> Result<(), ()> { self.raw.sub_from(pos) }

  #[inline(always)]
  fn sub_to(&mut self, len: u32) -> Result<(), ()> { self.raw.sub_to(len) }

  #[inline(always)]
  unsafe fn unsafe_sub(&mut self, pos: u32, len: u32) { self.raw.unsafe_sub(pos, len) }

  #[inline(always)]
  unsafe fn unsafe_sub_from(&mut self, pos: u32) { self.raw.unsafe_sub_from(pos) }

  #[inline(always)]
  unsafe fn unsafe_sub_to(&mut self, len: u32) { self.raw.unsafe_sub_to(len) }

  #[inline(always)]
  fn set_limits_and_window(&mut self, limits: (u32, u32), window: (u32, u32)) -> Result<(), ()> { self.raw.set_limits_and_window(limits, window) }

  #[inline(always)]
  fn narrow(&mut self) { self.raw.narrow() }

  #[inline(always)]
  fn advance(&mut self, len: u32) -> Result<(), ()> { self.raw.advance(len) }

  #[inline(always)]
  unsafe fn unsafe_advance(&mut self, len: u32) { self.raw.unsafe_advance(len) }

  #[inline(always)]
  fn extend(&mut self, len: u32) -> Result<(), ()> { self.raw.extend(len) }

  #[inline(always)]
  unsafe fn unsafe_extend(&mut self, len: u32) { self.raw.unsafe_extend(len) }

  #[inline(always)]
  fn is_extended_by<Buf: Iobuf>(&self, other: &Buf) -> bool { unsafe { self.raw.is_extended_by(other.as_raw()) } }

  #[inline(always)]
  fn extend_with<Buf: Iobuf>(&mut self, other: &Buf) -> Result<(), ()> { unsafe { self.raw.extend_with(other.as_raw()) } }

  #[inline(always)]
  fn resize(&mut self, len: u32) -> Result<(), ()> { self.raw.resize(len) }

  #[inline(always)]
  unsafe fn unsafe_resize(&mut self, len: u32) { self.raw.unsafe_resize(len) }

  #[inline(always)]
  fn split_at(&self, pos: u32) -> Result<(Self, Self), ()> {
    self.raw.split_at_atomic(pos).map(
      |(a, b)| (AROIobuf { raw: a },
                AROIobuf { raw: b }))
  }

  #[inline(always)]
  unsafe fn unsafe_split_at(&self, pos: u32) -> (Self, Self) {
    let (a, b) = self.raw.unsafe_split_at_atomic(pos);
    (AROIobuf { raw: a },
     AROIobuf { raw: b })
  }

  #[inline(always)]
  fn split_start_at(&mut self, pos: u32) -> Result<Self, ()> {
    self.raw.split_start_at_atomic(pos).map(
      |b| AROIobuf { raw: b })
  }

  #[inline(always)]
  unsafe fn unsafe_split_start_at(&mut self, pos: u32) -> Self {
    AROIobuf { raw: self.raw.unsafe_split_start_at_atomic(pos) }
  }

  #[inline(always)]
  fn rewind(&mut self) { self.raw.rewind() }

  #[inline(always)]
  fn reset(&mut self) { self.raw.reset() }

  #[inline(always)]
  fn flip_lo(&mut self) { self.raw.flip_lo() }

  #[inline(always)]
  fn flip_hi(&mut self) { self.raw.flip_hi() }

  #[inline(always)]
  fn lo_space(&self) -> u32 { self.raw.lo_space() }

  #[inline(always)]
  fn hi_space(&self) -> u32 { self.raw.hi_space() }

  #[inline(always)]
  fn peek(&self, pos: u32, dst: &mut [u8]) -> Result<(), ()> { self.raw.peek(pos, dst) }
  #[inline(always)]
  fn peek_be<T: IntLike>(&self, pos: u32) -> Result<T, ()> { self.raw.peek_be(pos) }
  #[inline(always)]
  fn peek_le<T: IntLike>(&self, pos: u32) -> Result<T, ()> { self.raw.peek_le(pos) }

  #[inline(always)]
  fn consume(&mut self, dst: &mut [u8]) -> Result<(), ()> { self.raw.consume(dst) }
  #[inline(always)]
  fn consume_be<T: IntLike>(&mut self) -> Result<T, ()> { self.raw.consume_be::<T>() }
  #[inline(always)]
  fn consume_le<T: IntLike>(&mut self) -> Result<T, ()> { self.raw.consume_le::<T>() }

  #[inline(always)]
  fn check_range(&self, pos: u32, len: u32) -> Result<(), ()> { self.raw.check_range_u32(pos, len) }

  #[inline(always)]
  fn check_range_usize(&self, pos: u32, len: usize) -> Result<(), ()> { self.raw.check_range_usize(pos, len) }

  #[inline(always)]
  fn check_range_fail(&self, pos: u32, len: u32) { self.raw.check_range_u32_fail(pos, len) }

  #[inline(always)]
  fn check_range_usize_fail(&self, pos: u32, len: usize) { self.raw.check_range_usize_fail(pos, len) }

  #[inline(always)]
  unsafe fn unsafe_peek(&self, pos: u32, dst: &mut [u8]) { self.raw.unsafe_peek(pos, dst) }
  #[inline(always)]
  unsafe fn unsafe_peek_be<T: IntLike>(&self, pos: u32) -> T { self.raw.unsafe_peek_be(pos) }
  #[inline(always)]
  unsafe fn unsafe_peek_le<T: IntLike>(&self, pos: u32) -> T { self.raw.unsafe_peek_le(pos) }

  #[inline(always)]
  unsafe fn unsafe_consume(&mut self, dst: &mut [u8]) { self.raw.unsafe_consume(dst) }
  #[inline(always)]
  unsafe fn unsafe_consume_be<T: IntLike>(&mut self) -> T { self.raw.unsafe_consume_be::<T>() }
  #[inline(always)]
  unsafe fn unsafe_consume_le<T: IntLike>(&mut self) -> T { self.raw.unsafe_consume_le::<T>() }

  #[inline(always)]
  unsafe fn as_raw<'b>(&'b self) -> &'b RawIobuf<'b> { mem::transmute(&self.raw) }

  #[inline(always)]
  fn invariant(&self) -> Result<(), Box<String>> { self.raw.invariant() }

  #[inline(always)]
  fn ptr(&self) -> NonZero<*mut u8> { self.raw.ptr() }
  #[inline(always)]
  fn is_owned(&self) -> bool { self.raw.is_owned() }
  #[inline(always)]
  fn lo_min(&self) -> u32 { self.raw.lo_min() }
  #[inline(always)]
  fn lo(&self) -> u32 { self.raw.lo() }
  #[inline(always)]
  fn hi(&self) -> u32 { self.raw.hi() }
  #[inline(always)]
  fn hi_max(&self) -> u32 { self.raw.hi_max() }
}

impl<'a> Iobuf for RWIobuf<'a> {
  #[inline(always)]
  fn deep_clone(&self) -> RWIobuf<'static> { RWIobuf { raw: self.raw.deep_clone() } }

  #[inline(always)]
  fn deep_clone_with_allocator(&self, allocator: Arc<Box<Allocator>>) -> RWIobuf<'static> {
    RWIobuf { raw: self.raw.deep_clone_with_allocator(allocator) }
  }

  #[inline(always)]
  fn unique(self) -> Result<UniqueIobuf, Self> {
    unsafe {
      if self.raw.is_unique_atomic() {
        Ok(mem::transmute(self))
      } else {
        Err(self)
      }
    }
  }

  #[inline(always)]
  fn atomic_read_only(self) -> Result<AROIobuf, Self> {
    unsafe {
      if self.raw.is_unique_nonatomic() {
        Ok(mem::transmute(self))
      } else {
        Err(self)
      }
    }
  }

  #[inline(always)]
  fn len(&self) -> u32 { self.raw.len() }

  #[inline(always)]
  fn cap(&self) -> u32 { self.raw.cap() }

  #[inline(always)]
  fn is_empty(&self) -> bool { self.raw.is_empty() }

  #[inline(always)]
  unsafe fn as_window_slice<'b>(&'b self) -> &'b [u8] { self.raw.as_window_slice() }

  #[inline(always)]
  unsafe fn as_limit_slice<'b>(&'b self) -> &'b [u8] { self.raw.as_limit_slice() }

  #[inline(always)]
  fn sub_window(&mut self, pos: u32, len: u32) -> Result<(), ()> { self.raw.sub_window(pos, len) }

  #[inline(always)]
  fn sub_window_from(&mut self, pos: u32) -> Result<(), ()> { self.raw.sub_window_from(pos) }

  #[inline(always)]
  fn sub_window_to(&mut self, len: u32) -> Result<(), ()> { self.raw.sub_window_to(len) }

  #[inline(always)]
  unsafe fn unsafe_sub_window(&mut self, pos: u32, len: u32) { self.raw.unsafe_sub_window(pos, len) }

  #[inline(always)]
  unsafe fn unsafe_sub_window_from(&mut self, pos: u32) { self.raw.unsafe_sub_window_from(pos) }

  #[inline(always)]
  unsafe fn unsafe_sub_window_to(&mut self, len: u32) { self.raw.unsafe_sub_window_to(len) }

  #[inline(always)]
  fn sub(&mut self, pos: u32, len: u32) -> Result<(), ()> { self.raw.sub(pos, len) }

  #[inline(always)]
  fn sub_from(&mut self, pos: u32) -> Result<(), ()> { self.raw.sub_from(pos) }

  #[inline(always)]
  fn sub_to(&mut self, len: u32) -> Result<(), ()> { self.raw.sub_to(len) }

  #[inline(always)]
  unsafe fn unsafe_sub(&mut self, pos: u32, len: u32) { self.raw.unsafe_sub(pos, len) }

  #[inline(always)]
  unsafe fn unsafe_sub_from(&mut self, pos: u32) { self.raw.unsafe_sub_from(pos) }

  #[inline(always)]
  unsafe fn unsafe_sub_to(&mut self, len: u32) { self.raw.unsafe_sub_to(len) }

  #[inline(always)]
  fn set_limits_and_window(&mut self, limits: (u32, u32), window: (u32, u32)) -> Result<(), ()> { self.raw.set_limits_and_window(limits, window) }

  #[inline(always)]
  fn narrow(&mut self) { self.raw.narrow() }

  #[inline(always)]
  fn advance(&mut self, len: u32) -> Result<(), ()> { self.raw.advance(len) }

  #[inline(always)]
  unsafe fn unsafe_advance(&mut self, len: u32) { self.raw.unsafe_advance(len) }

  #[inline(always)]
  fn extend(&mut self, len: u32) -> Result<(), ()> { self.raw.extend(len) }

  #[inline(always)]
  unsafe fn unsafe_extend(&mut self, len: u32) { self.raw.unsafe_extend(len) }

  #[inline(always)]
  fn is_extended_by<Buf: Iobuf>(&self, other: &Buf) -> bool { unsafe { self.raw.is_extended_by(other.as_raw()) } }

  #[inline(always)]
  fn extend_with<Buf: Iobuf>(&mut self, other: &Buf) -> Result<(), ()> { unsafe { self.raw.extend_with(other.as_raw()) } }

  #[inline(always)]
  fn resize(&mut self, len: u32) -> Result<(), ()> { self.raw.resize(len) }

  #[inline(always)]
  unsafe fn unsafe_resize(&mut self, len: u32) { self.raw.unsafe_resize(len) }

  #[inline(always)]
  fn split_at(&self, pos: u32) -> Result<(Self, Self), ()> {
    self.raw.split_at_nonatomic(pos).map(|(a, b)| (RWIobuf { raw: a }, RWIobuf { raw: b }))
  }

  #[inline(always)]
  unsafe fn unsafe_split_at(&self, pos: u32) -> (Self, Self) {
    let (a, b) = self.raw.unsafe_split_at_nonatomic(pos);
    (RWIobuf { raw: a }, RWIobuf { raw: b })
  }

  #[inline(always)]
  fn split_start_at(&mut self, pos: u32) -> Result<Self, ()> {
    self.raw.split_start_at_nonatomic(pos).map(|b| RWIobuf { raw: b })
  }

  #[inline(always)]
  unsafe fn unsafe_split_start_at(&mut self, pos: u32) -> Self {
    RWIobuf { raw: self.raw.unsafe_split_start_at_nonatomic(pos) }
  }

  #[inline(always)]
  fn rewind(&mut self) { self.raw.rewind() }

  #[inline(always)]
  fn reset(&mut self) { self.raw.reset() }

  #[inline(always)]
  fn flip_lo(&mut self) { self.raw.flip_lo() }

  #[inline(always)]
  fn flip_hi(&mut self) { self.raw.flip_hi() }

  #[inline(always)]
  fn lo_space(&self) -> u32 { self.raw.lo_space() }

  #[inline(always)]
  fn hi_space(&self) -> u32 { self.raw.hi_space() }

  #[inline(always)]
  fn peek(&self, pos: u32, dst: &mut [u8]) -> Result<(), ()> { self.raw.peek(pos, dst) }
  #[inline(always)]
  fn peek_be<T: IntLike>(&self, pos: u32) -> Result<T, ()> { self.raw.peek_be(pos) }
  #[inline(always)]
  fn peek_le<T: IntLike>(&self, pos: u32) -> Result<T, ()> { self.raw.peek_le(pos) }

  #[inline(always)]
  fn consume(&mut self, dst: &mut [u8]) -> Result<(), ()> { self.raw.consume(dst) }
  #[inline(always)]
  fn consume_be<T: IntLike>(&mut self) -> Result<T, ()> { self.raw.consume_be::<T>() }
  #[inline(always)]
  fn consume_le<T: IntLike>(&mut self) -> Result<T, ()> { self.raw.consume_le::<T>() }

  #[inline(always)]
  fn check_range(&self, pos: u32, len: u32) -> Result<(), ()> { self.raw.check_range_u32(pos, len) }

  #[inline(always)]
  fn check_range_usize(&self, pos: u32, len: usize) -> Result<(), ()> { self.raw.check_range_usize(pos, len) }

  #[inline(always)]
  fn check_range_fail(&self, pos: u32, len: u32) { self.raw.check_range_u32_fail(pos, len) }

  #[inline(always)]
  fn check_range_usize_fail(&self, pos: u32, len: usize) { self.raw.check_range_usize_fail(pos, len) }

  #[inline(always)]
  unsafe fn unsafe_peek(&self, pos: u32, dst: &mut [u8]) { self.raw.unsafe_peek(pos, dst) }
  #[inline(always)]
  unsafe fn unsafe_peek_be<T: IntLike>(&self, pos: u32) -> T { self.raw.unsafe_peek_be(pos) }
  #[inline(always)]
  unsafe fn unsafe_peek_le<T: IntLike>(&self, pos: u32) -> T { self.raw.unsafe_peek_le(pos) }

  #[inline(always)]
  unsafe fn unsafe_consume(&mut self, dst: &mut [u8]) { self.raw.unsafe_consume(dst) }
  #[inline(always)]
  unsafe fn unsafe_consume_be<T: IntLike>(&mut self) -> T { self.raw.unsafe_consume_be::<T>() }
  #[inline(always)]
  unsafe fn unsafe_consume_le<T: IntLike>(&mut self) -> T { self.raw.unsafe_consume_le::<T>() }

  #[inline(always)]
  unsafe fn as_raw<'b>(&'b self) -> &'b RawIobuf<'b> { mem::transmute(&self.raw) }

  #[inline(always)]
  fn invariant(&self) -> Result<(), Box<String>> { self.raw.invariant() }

  #[inline(always)]
  fn ptr(&self) -> NonZero<*mut u8> { self.raw.ptr() }
  #[inline(always)]
  fn is_owned(&self) -> bool { self.raw.is_owned() }
  #[inline(always)]
  fn lo_min(&self) -> u32 { self.raw.lo_min() }
  #[inline(always)]
  fn lo(&self) -> u32 { self.raw.lo() }
  #[inline(always)]
  fn hi(&self) -> u32 { self.raw.hi() }
  #[inline(always)]
  fn hi_max(&self) -> u32 { self.raw.hi_max() }
}

impl<'a> Debug for ROIobuf<'a> {
  #[inline]
  fn fmt(&self, f: &mut Formatter) -> fmt::Result {
    self.raw.show(f, "read-only")
  }
}

impl<'a> Debug for RWIobuf<'a> {
  #[inline]
  fn fmt(&self, f: &mut Formatter) -> fmt::Result {
    self.raw.show(f, "read-write")
  }
}

impl Debug for AROIobuf {
  #[inline]
  fn fmt(&self, f: &mut Formatter) -> fmt::Result {
    self.raw.show(f, "atomic read-only")
  }
}

impl Debug for UniqueIobuf {
  #[inline]
  fn fmt(&self, f: &mut Formatter) -> fmt::Result {
    self.raw.show(f, "unique")
  }
}

#[cfg(never)]
mod test {
  use impls::AROIobuf;
  use iobuf::Iobuf;

  use quickcheck::{quickcheck, Arbitrary, Gen, Shrinker};

    impl Arbitrary for AROIobuf {
      fn arbitrary<G: Gen>(g: &mut G) -> AROIobuf {
        let data: Vec<u8> = Arbitrary::arbitrary(g);

        assert!(data.len() < u32::MAX as usize);

        let (a, b, c, d): (u32, u32, u32, u32) = Arbitrary::arbitrary(g);

        let hi_max = a % (data.len() as u32 + 1);
        let hi     = b % (hi_max + 1);
        let lo     = c % (hi + 1);
        let lo_min = d % (lo + 1);

        let mut buf = ROIobuf::from_slice_copy(&data[..]);
        buf.set_limits_and_window((lo_min, hi_max), (lo, hi)).unwrap();

        buf.atomic_read_only().unwrap()
      }

      fn shrink(&self) -> Box<Shrinker<AROIobuf>+'static> {
        let mut v: Vec<AROIobuf> = vec!();

        // explore every possible subset of limits and bounds
        for hi_max in range(0, self.raw.hi_max()) {
          for hi in range(0, min(hi_max, self.raw.hi())) {
            for lo in range(self.raw.lo() + 1, hi + 1) {
              for lo_min in range(self.raw.lo_min() + 1, lo + 1) {
                let mut new_buf: AROIobuf = (*self).clone();
                new_buf.set_limits_and_window((lo_min, hi_max), (lo, hi)).unwrap();
                v.push(new_buf);
              }
            }
          }
        }

        box v.into_iter()
      }
    }


  #[test]
  fn prop_valid_hi() {
    fn test_hi(v: AROIobuf) -> bool {
         v.hi() <= v.hi_max()
    }
    quickcheck(test_hi as fn(AROIobuf) -> bool)
  }

  #[test]
  fn prop_valid_bounds() {
    fn test_bounds(v: AROIobuf) -> bool {
      v.lo() <= v.hi()
    }
    quickcheck(test_bounds as fn(AROIobuf) -> bool)
  }

  #[test]
  fn prop_valid_lo() {
    fn test_lo(v: AROIobuf) -> bool {
      v.lo_min() <= v.lo()
    }
    quickcheck(test_lo as fn(AROIobuf) -> bool)
  }
}