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
// vim: tw=80
//! POSIX Asynchronous I/O
//!
//! The POSIX AIO interface is used for asynchronous I/O on files and disk-like
//! devices.  It supports [`read`](struct.AioCb.html#method.read),
//! [`write`](struct.AioCb.html#method.write), and
//! [`fsync`](struct.AioCb.html#method.fsync) operations.  Completion
//! notifications can optionally be delivered via
//! [signals](../signal/enum.SigevNotify.html#variant.SigevSignal), via the
//! [`aio_suspend`](fn.aio_suspend.html) function, or via polling.  Some
//! platforms support other completion
//! notifications, such as
//! [kevent](../signal/enum.SigevNotify.html#variant.SigevKevent).
//!
//! Multiple operations may be submitted in a batch with
//! [`lio_listio`](fn.lio_listio.html), though the standard does not guarantee
//! that they will be executed atomically.
//!
//! Outstanding operations may be cancelled with
//! [`cancel`](struct.AioCb.html#method.cancel) or
//! [`aio_cancel_all`](fn.aio_cancel_all.html), though the operating system may
//! not support this for all filesystems and devices.

// TODO: is there any way to make constructors that don't require using the
// heap?  Anything that could return a pinned stack variable?
// The only way i can see is for the constructor to return a plain AioCb.  The
// caller can then pin it like
// let a = AioCb::from_fool
// let pinned = Pin::new(&a)
// and use it with any method taking pinned types.  But there are two problems:
// 1) Nothing prevents the caller from calling aio_read on one pinned pointer,
//    dropping it, moving the aiocb, createing a new pinned pointer, and calling
//    aio_error on that.
// 2) It's more typing for almost all consumers, who will box the aiocb anyway.
use {Error, Result};
use errno::Errno;
use std::os::unix::io::RawFd;
use libc::{c_void, off_t, size_t};
use libc;
use std::borrow::{Borrow, BorrowMut};
use std::fmt;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::mem;
use std::pin::Pin;
use std::ptr::{null, null_mut};
use sys::signal::*;
use std::thread;
use sys::time::TimeSpec;

libc_enum! {
    /// Mode for `AioCb::fsync`.  Controls whether only data or both data and
    /// metadata are synced.
    #[repr(i32)]
    pub enum AioFsyncMode {
        /// do it like `fsync`
        O_SYNC,
        /// on supported operating systems only, do it like `fdatasync`
        #[cfg(any(target_os = "ios",
                  target_os = "linux",
                  target_os = "macos",
                  target_os = "netbsd",
                  target_os = "openbsd"))]
        O_DSYNC
    }
}

libc_enum! {
    /// When used with [`lio_listio`](fn.lio_listio.html), determines whether a
    /// given `aiocb` should be used for a read operation, a write operation, or
    /// ignored.  Has no effect for any other aio functions.
    #[repr(i32)]
    pub enum LioOpcode {
        LIO_NOP,
        LIO_WRITE,
        LIO_READ,
    }
}

libc_enum! {
    /// Mode for [`lio_listio`](fn.lio_listio.html)
    #[repr(i32)]
    pub enum LioMode {
        /// Requests that [`lio_listio`](fn.lio_listio.html) block until all
        /// requested operations have been completed
        LIO_WAIT,
        /// Requests that [`lio_listio`](fn.lio_listio.html) return immediately
        LIO_NOWAIT,
    }
}

/// Return values for [`AioCb::cancel`](struct.AioCb.html#method.cancel) and
/// [`aio_cancel_all`](fn.aio_cancel_all.html)
#[repr(i32)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum AioCancelStat {
    /// All outstanding requests were canceled
    AioCanceled = libc::AIO_CANCELED,
    /// Some requests were not canceled.  Their status should be checked with
    /// `AioCb::error`
    AioNotCanceled = libc::AIO_NOTCANCELED,
    /// All of the requests have already finished
    AioAllDone = libc::AIO_ALLDONE,
}

/// Owns (uniquely or shared) a memory buffer to keep it from `Drop`ing while
/// the kernel has a pointer to it.
pub enum Buffer<'a> {
    /// No buffer to own.
    ///
    /// Used for operations like `aio_fsync` that have no data, or for unsafe
    /// operations that work with raw pointers.
    None,
    /// Keeps a reference to a slice
    Phantom(PhantomData<&'a mut [u8]>),
    /// Generic thing that keeps a buffer from dropping
    BoxedSlice(Box<dyn Borrow<[u8]>>),
    /// Generic thing that keeps a mutable buffer from dropping
    BoxedMutSlice(Box<dyn BorrowMut<[u8]>>),
}

impl<'a> Debug for Buffer<'a> {
    // Note: someday it may be possible to Derive Debug for a trait object, but
    // not today.
    // https://github.com/rust-lang/rust/issues/1563
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Buffer::None => write!(fmt, "None"),
            Buffer::Phantom(p) => p.fmt(fmt),
            Buffer::BoxedSlice(ref bs) => {
                let borrowed : &dyn Borrow<[u8]> = bs.borrow();
                write!(fmt, "BoxedSlice({:?})",
                    borrowed as *const dyn Borrow<[u8]>)
            },
            Buffer::BoxedMutSlice(ref bms) => {
                let borrowed : &dyn BorrowMut<[u8]> = bms.borrow();
                write!(fmt, "BoxedMutSlice({:?})",
                    borrowed as *const dyn BorrowMut<[u8]>)
            }
        }
    }
}

/// AIO Control Block.
///
/// The basic tructure used by all aio functions.  Each `AioCb` represents one
/// I/O request.
pub struct AioCb<'a> {
    // TODO: try using pin-project! to mark the aiocb field as structurally
    // pinned, but not other fields.
    aiocb: libc::aiocb,
    /// Tracks whether the buffer pointed to by `libc::aiocb.aio_buf` is mutable
    mutable: bool,
    /// Could this `AioCb` potentially have any in-kernel state?
    in_progress: bool,
    /// Optionally keeps a reference to the data.
    ///
    /// Used to keep buffers from `Drop`'ing, and may be returned once the
    /// `AioCb` is completed by [`buffer`](#method.buffer).
    buffer: Buffer<'a>,
    _pin: std::marker::PhantomPinned
}

impl<'a> AioCb<'a> {
    /// Remove the inner `Buffer` and return it
    ///
    /// It is an error to call this method while the `AioCb` is still in
    /// progress.
    pub fn buffer(&mut self) -> Buffer<'a> {
        assert!(!self.in_progress);
        let mut x = Buffer::None;
        mem::swap(&mut self.buffer, &mut x);
        x
    }

    /// Remove the inner boxed slice, if any, and return it.
    ///
    /// The returned value will be the argument that was passed to
    /// `from_boxed_slice` when this `AioCb` was created.
    ///
    /// It is an error to call this method while the `AioCb` is still in
    /// progress.
    pub fn boxed_slice(&mut self) -> Option<Box<dyn Borrow<[u8]>>> {
        assert!(!self.in_progress, "Can't remove the buffer from an AioCb that's still in-progress.  Did you forget to call aio_return?");
        if let Buffer::BoxedSlice(_) = self.buffer {
            let mut oldbuffer = Buffer::None;
            mem::swap(&mut self.buffer, &mut oldbuffer);
            if let Buffer::BoxedSlice(inner) = oldbuffer {
                Some(inner)
            } else {
                unreachable!();
            }
        } else {
            None
        }
    }

    /// Remove the inner boxed mutable slice, if any, and return it.
    ///
    /// The returned value will be the argument that was passed to
    /// `from_boxed_mut_slice` when this `AioCb` was created.
    ///
    /// It is an error to call this method while the `AioCb` is still in
    /// progress.
    pub fn boxed_mut_slice(self: &mut Pin<Box<Self>>)
        -> Option<Box<dyn BorrowMut<[u8]>>>
    {
        assert!(!self.in_progress, "Can't remove the buffer from an AioCb that's still in-progress.  Did you forget to call aio_return?");
        if let Buffer::BoxedMutSlice(_) = self.buffer {
            let mut oldbuffer = Buffer::None;
            // Safe because the aiocb is not in-progress
            unsafe {
                let unpinned = Pin::get_unchecked_mut(self.as_mut());
                mem::swap(&mut unpinned.buffer, &mut oldbuffer);
            }
            if let Buffer::BoxedMutSlice(inner) = oldbuffer {
                Some(inner)
            } else {
                unreachable!();
            }
        } else {
            None
        }
    }

    /// Returns the underlying file descriptor associated with the `AioCb`
    pub fn fd(&self) -> RawFd {
        self.aiocb.aio_fildes
    }

    /// Constructs a new `AioCb` with no associated buffer.
    ///
    /// The resulting `AioCb` structure is suitable for use with `AioCb::fsync`.
    ///
    /// # Parameters
    ///
    /// * `fd`:           File descriptor.  Required for all aio functions.
    /// * `prio`:         If POSIX Prioritized IO is supported, then the
    ///                   operation will be prioritized at the process's
    ///                   priority level minus `prio`.
    /// * `sigev_notify`: Determines how you will be notified of event
    ///                    completion.
    ///
    /// # Examples
    ///
    /// Create an `AioCb` from a raw file descriptor and use it for an
    /// [`fsync`](#method.fsync) operation.
    ///
    /// ```
    /// # extern crate tempfile;
    /// # extern crate nix;
    /// # use nix::errno::Errno;
    /// # use nix::Error;
    /// # use nix::sys::aio::*;
    /// # use nix::sys::signal::SigevNotify::SigevNone;
    /// # use std::{thread, time};
    /// # use std::os::unix::io::AsRawFd;
    /// # use tempfile::tempfile;
    /// # fn main() {
    /// let f = tempfile().unwrap();
    /// let mut aiocb = AioCb::from_fd( f.as_raw_fd(), 0, SigevNone);
    /// aiocb.fsync(AioFsyncMode::O_SYNC).expect("aio_fsync failed early");
    /// while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
    ///     thread::sleep(time::Duration::from_millis(10));
    /// }
    /// aiocb.aio_return().expect("aio_fsync failed late");
    /// # }
    /// ```
    pub fn from_fd(fd: RawFd, prio: libc::c_int,
                    sigev_notify: SigevNotify) -> Pin<Box<AioCb<'a>>> {
        let mut a = AioCb::common_init(fd, prio, sigev_notify);
        a.aio_offset = 0;
        a.aio_nbytes = 0;
        a.aio_buf = null_mut();

        Box::pin(AioCb {
            aiocb: a,
            mutable: false,
            in_progress: false,
            buffer: Buffer::None,
            _pin: std::marker::PhantomPinned
        })
    }

    fn from_mut_slice_unpinned(fd: RawFd, offs: off_t, buf: &'a mut [u8],
                          prio: libc::c_int, sigev_notify: SigevNotify,
                          opcode: LioOpcode) -> AioCb<'a>
    {
        let mut a = AioCb::common_init(fd, prio, sigev_notify);
        a.aio_offset = offs;
        a.aio_nbytes = buf.len() as size_t;
        a.aio_buf = buf.as_ptr() as *mut c_void;
        a.aio_lio_opcode = opcode as libc::c_int;

        AioCb {
            aiocb: a,
            mutable: true,
            in_progress: false,
            buffer: Buffer::Phantom(PhantomData),
            _pin: std::marker::PhantomPinned
        }
    }

    /// Constructs a new `AioCb` from a mutable slice.
    ///
    /// The resulting `AioCb` will be suitable for both read and write
    /// operations, but only if the borrow checker can guarantee that the slice
    /// will outlive the `AioCb`.  That will usually be the case if the `AioCb`
    /// is stack-allocated.  If the borrow checker gives you trouble, try using
    /// [`from_boxed_mut_slice`](#method.from_boxed_mut_slice) instead.
    ///
    /// # Parameters
    ///
    /// * `fd`:           File descriptor.  Required for all aio functions.
    /// * `offs`:         File offset
    /// * `buf`:          A memory buffer
    /// * `prio`:         If POSIX Prioritized IO is supported, then the
    ///                   operation will be prioritized at the process's
    ///                   priority level minus `prio`
    /// * `sigev_notify`: Determines how you will be notified of event
    ///                   completion.
    /// * `opcode`:       This field is only used for `lio_listio`.  It
    ///                   determines which operation to use for this individual
    ///                   aiocb
    ///
    /// # Examples
    ///
    /// Create an `AioCb` from a mutable slice and read into it.
    ///
    /// ```
    /// # extern crate tempfile;
    /// # extern crate nix;
    /// # use nix::errno::Errno;
    /// # use nix::Error;
    /// # use nix::sys::aio::*;
    /// # use nix::sys::signal::SigevNotify;
    /// # use std::{thread, time};
    /// # use std::io::Write;
    /// # use std::os::unix::io::As>RawFd;
    /// # use tempfile::tempfile;
    /// # fn main() {
    /// const INITIAL: &[u8] = b"abcdef123456";
    /// const LEN: usize = 4;
    /// let mut rbuf = vec![0; LEN];
    /// let mut f = tempfile().unwrap();
    /// f.write_all(INITIAL).unwrap();
    /// {
    ///     let mut aiocb = AioCb::from_mut_slice( f.as_raw_fd(),
    ///         2,   //offset
    ///         &mut rbuf,
    ///         0,   //priority
    ///         SigevNotify::SigevNone,
    ///         LioOpcode::LIO_NOP);
    ///     aiocb.read().unwrap();
    ///     while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
    ///         thread::sleep(time::Duration::from_millis(10));
    ///     }
    ///     assert_eq!(aiocb.aio_return().unwrap() as usize, LEN);
    /// }
    /// assert_eq!(rbuf, b"cdef");
    /// # }
    /// ```
    pub fn from_mut_slice(fd: RawFd, offs: off_t, buf: &'a mut [u8],
                          prio: libc::c_int, sigev_notify: SigevNotify,
                          opcode: LioOpcode) -> Pin<Box<AioCb<'a>>> {
        let mut a = AioCb::common_init(fd, prio, sigev_notify);
        a.aio_offset = offs;
        a.aio_nbytes = buf.len() as size_t;
        a.aio_buf = buf.as_ptr() as *mut c_void;
        a.aio_lio_opcode = opcode as libc::c_int;

        Box::pin(AioCb {
            aiocb: a,
            mutable: true,
            in_progress: false,
            buffer: Buffer::Phantom(PhantomData),
            _pin: std::marker::PhantomPinned
        })
    }

    /// The safest and most flexible way to create an `AioCb`.
    ///
    /// Unlike [`from_slice`], this method returns a structure suitable for
    /// placement on the heap.  It may be used for write operations, but not
    /// read operations.  Unlike `from_ptr`, this method will ensure that the
    /// buffer doesn't `drop` while the kernel is still processing it.  Any
    /// object that can be borrowed as a boxed slice will work.
    ///
    /// # Parameters
    ///
    /// * `fd`:           File descriptor.  Required for all aio functions.
    /// * `offs`:         File offset
    /// * `buf`:          A boxed slice-like object
    /// * `prio`:         If POSIX Prioritized IO is supported, then the
    ///                   operation will be prioritized at the process's
    ///                   priority level minus `prio`
    /// * `sigev_notify`: Determines how you will be notified of event
    ///                   completion.
    /// * `opcode`:       This field is only used for `lio_listio`.  It
    ///                   determines which operation to use for this individual
    ///                   aiocb
    ///
    /// # Examples
    ///
    /// Create an `AioCb` from a Vector and use it for writing
    ///
    /// ```
    /// # extern crate tempfile;
    /// # extern crate nix;
    /// # use nix::errno::Errno;
    /// # use nix::Error;
    /// # use nix::sys::aio::*;
    /// # use nix::sys::signal::SigevNotify;
    /// # use std::{thread, time};
    /// # use std::io::Write;
    /// # use std::os::unix::io::AsRawFd;
    /// # use tempfile::tempfile;
    /// # fn main() {
    /// let wbuf = Box::new(Vec::from("CDEF"));
    /// let expected_len = wbuf.len();
    /// let mut f = tempfile().unwrap();
    /// let mut aiocb = AioCb::from_boxed_slice( f.as_raw_fd(),
    ///     2,   //offset
    ///     wbuf,
    ///     0,   //priority
    ///     SigevNotify::SigevNone,
    ///     LioOpcode::LIO_NOP);
    /// aiocb.write().unwrap();
    /// while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
    ///     thread::sleep(time::Duration::from_millis(10));
    /// }
    /// assert_eq!(aiocb.aio_return().unwrap() as usize, expected_len);
    /// # }
    /// ```
    ///
    /// Create an `AioCb` from a `Bytes` object
    ///
    /// ```
    /// # extern crate bytes;
    /// # extern crate tempfile;
    /// # extern crate nix;
    /// # use bytes::Bytes;
    /// # use nix::sys::aio::*;
    /// # use nix::sys::signal::SigevNotify;
    /// # use std::os::unix::io::AsRawFd;
    /// # use tempfile::tempfile;
    /// # fn main() {
    /// let wbuf = Box::new(Bytes::from(&b"CDEF"[..]));
    /// let mut f = tempfile().unwrap();
    /// let mut aiocb = AioCb::from_boxed_slice( f.as_raw_fd(),
    ///     2,   //offset
    ///     wbuf,
    ///     0,   //priority
    ///     SigevNotify::SigevNone,
    ///     LioOpcode::LIO_NOP);
    /// # }
    /// ```
    ///
    /// If a library needs to work with buffers that aren't `Box`ed, it can
    /// create a `Box`ed container for use with this method.  Here's an example
    /// using an un`Box`ed `Bytes` object.
    ///
    /// ```
    /// # extern crate bytes;
    /// # extern crate tempfile;
    /// # extern crate nix;
    /// # use bytes::Bytes;
    /// # use nix::sys::aio::*;
    /// # use nix::sys::signal::SigevNotify;
    /// # use std::borrow::Borrow;
    /// # use std::os::unix::io::AsRawFd;
    /// # use tempfile::tempfile;
    /// struct BytesContainer(Bytes);
    /// impl Borrow<[u8]> for BytesContainer {
    ///     fn borrow(&self) -> &[u8] {
    ///         self.0.as_ref()
    ///     }
    /// }
    /// fn main() {
    ///     let wbuf = Bytes::from(&b"CDEF"[..]);
    ///     let boxed_wbuf = Box::new(BytesContainer(wbuf));
    ///     let mut f = tempfile().unwrap();
    ///     let mut aiocb = AioCb::from_boxed_slice( f.as_raw_fd(),
    ///         2,   //offset
    ///         boxed_wbuf,
    ///         0,   //priority
    ///         SigevNotify::SigevNone,
    ///         LioOpcode::LIO_NOP);
    /// }
    /// ```
    ///
    /// [`from_slice`]: #method.from_slice
    pub fn from_boxed_slice(fd: RawFd, offs: off_t, buf: Box<dyn Borrow<[u8]>>,
                      prio: libc::c_int, sigev_notify: SigevNotify,
                      opcode: LioOpcode) -> Pin<Box<AioCb<'a>>> {
        let mut a = AioCb::common_init(fd, prio, sigev_notify);
        {
            let borrowed : &dyn Borrow<[u8]> = buf.borrow();
            let slice : &[u8] = borrowed.borrow();
            a.aio_nbytes = slice.len() as size_t;
            a.aio_buf = slice.as_ptr() as *mut c_void;
        }
        a.aio_offset = offs;
        a.aio_lio_opcode = opcode as libc::c_int;

        Box::pin(AioCb {
            aiocb: a,
            mutable: false,
            in_progress: false,
            buffer: Buffer::BoxedSlice(buf),
            _pin: std::marker::PhantomPinned
        })
    }

    /// The safest and most flexible way to create an `AioCb` for reading.
    ///
    /// Like [`from_boxed_slice`], but the slice is a mutable one.  More
    /// flexible than [`from_mut_slice`], because a wide range of objects can be
    /// used.
    ///
    /// # Examples
    ///
    /// Create an `AioCb` from a Vector and use it for reading
    ///
    /// ```
    /// # extern crate tempfile;
    /// # extern crate nix;
    /// # use nix::errno::Errno;
    /// # use nix::Error;
    /// # use nix::sys::aio::*;
    /// # use nix::sys::signal::SigevNotify;
    /// # use std::{thread, time};
    /// # use std::io::Write;
    /// # use std::os::unix::io::AsRawFd;
    /// # use tempfile::tempfile;
    /// # fn main() {
    /// const INITIAL: &[u8] = b"abcdef123456";
    /// const LEN: usize = 4;
    /// let rbuf = Box::new(vec![0; LEN]);
    /// let mut f = tempfile().unwrap();
    /// f.write_all(INITIAL).unwrap();
    /// let mut aiocb = AioCb::from_boxed_mut_slice( f.as_raw_fd(),
    ///     2,   //offset
    ///     rbuf,
    ///     0,   //priority
    ///     SigevNotify::SigevNone,
    ///     LioOpcode::LIO_NOP);
    /// aiocb.read().unwrap();
    /// while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
    ///     thread::sleep(time::Duration::from_millis(10));
    /// }
    /// assert_eq!(aiocb.aio_return().unwrap() as usize, LEN);
    /// let mut buffer = aiocb.boxed_mut_slice().unwrap();
    /// const EXPECT: &[u8] = b"cdef";
    /// assert_eq!(buffer.borrow_mut(), EXPECT);
    /// # }
    /// ```
    ///
    /// [`from_boxed_slice`]: #method.from_boxed_slice
    /// [`from_mut_slice`]: #method.from_mut_slice
    pub fn from_boxed_mut_slice(fd: RawFd, offs: off_t,
                                mut buf: Box<dyn BorrowMut<[u8]>>,
                                prio: libc::c_int, sigev_notify: SigevNotify,
                                opcode: LioOpcode) -> Pin<Box<AioCb<'a>>> {
        let mut a = AioCb::common_init(fd, prio, sigev_notify);
        {
            let borrowed : &mut dyn BorrowMut<[u8]> = buf.borrow_mut();
            let slice : &mut [u8] = borrowed.borrow_mut();
            a.aio_nbytes = slice.len() as size_t;
            a.aio_buf = slice.as_mut_ptr() as *mut c_void;
        }
        a.aio_offset = offs;
        a.aio_lio_opcode = opcode as libc::c_int;

        Box::pin(AioCb {
            aiocb: a,
            mutable: true,
            in_progress: false,
            buffer: Buffer::BoxedMutSlice(buf),
            _pin: std::marker::PhantomPinned
        })
    }

    /// Constructs a new `AioCb` from a mutable raw pointer
    ///
    /// Unlike `from_mut_slice`, this method returns a structure suitable for
    /// placement on the heap.  It may be used for both reads and writes.  Due
    /// to its unsafety, this method is not recommended.  It is most useful when
    /// heap allocation is required but for some reason the data cannot be
    /// wrapped in a `struct` that implements `BorrowMut<[u8]>`
    ///
    /// # Parameters
    ///
    /// * `fd`:           File descriptor.  Required for all aio functions.
    /// * `offs`:         File offset
    /// * `buf`:          Pointer to the memory buffer
    /// * `len`:          Length of the buffer pointed to by `buf`
    /// * `prio`:         If POSIX Prioritized IO is supported, then the
    ///                   operation will be prioritized at the process's
    ///                   priority level minus `prio`
    /// * `sigev_notify`: Determines how you will be notified of event
    ///                   completion.
    /// * `opcode`:       This field is only used for `lio_listio`.  It
    ///                   determines which operation to use for this individual
    ///                   aiocb
    ///
    /// # Safety
    ///
    /// The caller must ensure that the storage pointed to by `buf` outlives the
    /// `AioCb`.  The lifetime checker can't help here.
    pub unsafe fn from_mut_ptr(fd: RawFd, offs: off_t,
                           buf: *mut c_void, len: usize,
                           prio: libc::c_int, sigev_notify: SigevNotify,
                           opcode: LioOpcode) -> Pin<Box<AioCb<'a>>> {
        let mut a = AioCb::common_init(fd, prio, sigev_notify);
        a.aio_offset = offs;
        a.aio_nbytes = len;
        a.aio_buf = buf;
        a.aio_lio_opcode = opcode as libc::c_int;

        Box::pin(AioCb {
            aiocb: a,
            mutable: true,
            in_progress: false,
            _pin: std::marker::PhantomPinned,
            buffer: Buffer::None
        })
    }

    /// Constructs a new `AioCb` from a raw pointer.
    ///
    /// Unlike `from_slice`, this method returns a structure suitable for
    /// placement on the heap.  Due to its unsafety, this method is not
    /// recommended.  It is most useful when heap allocation is required but for
    /// some reason the data cannot be wrapped in a `struct` that implements
    /// `Borrow<[u8]>`
    ///
    /// # Parameters
    ///
    /// * `fd`:           File descriptor.  Required for all aio functions.
    /// * `offs`:         File offset
    /// * `buf`:          Pointer to the memory buffer
    /// * `len`:          Length of the buffer pointed to by `buf`
    /// * `prio`:         If POSIX Prioritized IO is supported, then the
    ///                   operation will be prioritized at the process's
    ///                   priority level minus `prio`
    /// * `sigev_notify`: Determines how you will be notified of event
    ///                   completion.
    /// * `opcode`:       This field is only used for `lio_listio`.  It
    ///                   determines which operation to use for this individual
    ///                   aiocb
    ///
    /// # Safety
    ///
    /// The caller must ensure that the storage pointed to by `buf` outlives the
    /// `AioCb`.  The lifetime checker can't help here.
    pub unsafe fn from_ptr(fd: RawFd, offs: off_t,
                           buf: *const c_void, len: usize,
                           prio: libc::c_int, sigev_notify: SigevNotify,
                           opcode: LioOpcode) -> Pin<Box<AioCb<'a>>> {
        let mut a = AioCb::common_init(fd, prio, sigev_notify);
        a.aio_offset = offs;
        a.aio_nbytes = len;
        // casting a const ptr to a mutable ptr here is ok, because we set the
        // AioCb's mutable field to false
        a.aio_buf = buf as *mut c_void;
        a.aio_lio_opcode = opcode as libc::c_int;

        Box::pin(AioCb {
            aiocb: a,
            mutable: false,
            in_progress: false,
            buffer: Buffer::None,
            _pin: std::marker::PhantomPinned
        })
    }

    fn from_slice_unpinned(fd: RawFd, offs: off_t, buf: &'a [u8],
                           prio: libc::c_int, sigev_notify: SigevNotify,
                           opcode: LioOpcode) -> AioCb
    {
        let mut a = AioCb::common_init(fd, prio, sigev_notify);
        a.aio_offset = offs;
        a.aio_nbytes = buf.len() as size_t;
        // casting an immutable buffer to a mutable pointer looks unsafe,
        // but technically its only unsafe to dereference it, not to create
        // it.
        a.aio_buf = buf.as_ptr() as *mut c_void;
        assert!(opcode != LioOpcode::LIO_READ, "Can't read into an immutable buffer");
        a.aio_lio_opcode = opcode as libc::c_int;

        AioCb {
            aiocb: a,
            mutable: false,
            in_progress: false,
            buffer: Buffer::None,
            _pin: std::marker::PhantomPinned
        }
    }

    /// Like `from_mut_slice`, but works on constant slices rather than
    /// mutable slices.
    ///
    /// An `AioCb` created this way cannot be used with `read`, and its
    /// `LioOpcode` cannot be set to `LIO_READ`.  This method is useful when
    /// writing a const buffer with `AioCb::write`, since `from_mut_slice` can't
    /// work with const buffers.
    ///
    /// # Examples
    ///
    /// Construct an `AioCb` from a slice and use it for writing.
    ///
    /// ```
    /// # extern crate tempfile;
    /// # extern crate nix;
    /// # use nix::errno::Errno;
    /// # use nix::Error;
    /// # use nix::sys::aio::*;
    /// # use nix::sys::signal::SigevNotify;
    /// # use std::{thread, time};
    /// # use std::os::unix::io::AsRawFd;
    /// # use tempfile::tempfile;
    /// # fn main() {
    /// const WBUF: &[u8] = b"abcdef123456";
    /// let mut f = tempfile().unwrap();
    /// let mut aiocb = AioCb::from_slice( f.as_raw_fd(),
    ///     2,   //offset
    ///     WBUF,
    ///     0,   //priority
    ///     SigevNotify::SigevNone,
    ///     LioOpcode::LIO_NOP);
    /// aiocb.write().unwrap();
    /// while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
    ///     thread::sleep(time::Duration::from_millis(10));
    /// }
    /// assert_eq!(aiocb.aio_return().unwrap() as usize, WBUF.len());
    /// # }
    /// ```
    // Note: another solution to the problem of writing const buffers would be
    // to genericize AioCb for both &mut [u8] and &[u8] buffers.  AioCb::read
    // could take the former and AioCb::write could take the latter.  However,
    // then lio_listio wouldn't work, because that function needs a slice of
    // AioCb, and they must all be of the same type.
    pub fn from_slice(fd: RawFd, offs: off_t, buf: &'a [u8],
                      prio: libc::c_int, sigev_notify: SigevNotify,
                      opcode: LioOpcode) -> Pin<Box<AioCb>>
    {
        Box::pin(AioCb::from_slice_unpinned(fd, offs, buf, prio, sigev_notify,
                                            opcode))
    }

    fn common_init(fd: RawFd, prio: libc::c_int,
                   sigev_notify: SigevNotify) -> libc::aiocb {
        // Use mem::zeroed instead of explicitly zeroing each field, because the
        // number and name of reserved fields is OS-dependent.  On some OSes,
        // some reserved fields are used the kernel for state, and must be
        // explicitly zeroed when allocated.
        let mut a = unsafe { mem::zeroed::<libc::aiocb>()};
        a.aio_fildes = fd;
        a.aio_reqprio = prio;
        a.aio_sigevent = SigEvent::new(sigev_notify).sigevent();
        a
    }

    /// Update the notification settings for an existing `aiocb`
    pub fn set_sigev_notify(self: &mut Pin<Box<Self>>,
                            sigev_notify: SigevNotify)
    {
        // Safe because we don't move any of the data
        let selfp = unsafe {
            self.as_mut().get_unchecked_mut()
        };
        selfp.aiocb.aio_sigevent = SigEvent::new(sigev_notify).sigevent();
    }

    /// Cancels an outstanding AIO request.
    ///
    /// The operating system is not required to implement cancellation for all
    /// file and device types.  Even if it does, there is no guarantee that the
    /// operation has not already completed.  So the caller must check the
    /// result and handle operations that were not canceled or that have already
    /// completed.
    ///
    /// # Examples
    ///
    /// Cancel an outstanding aio operation.  Note that we must still call
    /// `aio_return` to free resources, even though we don't care about the
    /// result.
    ///
    /// ```
    /// # extern crate tempfile;
    /// # extern crate nix;
    /// # use nix::errno::Errno;
    /// # use nix::Error;
    /// # use nix::sys::aio::*;
    /// # use nix::sys::signal::SigevNotify;
    /// # use std::{thread, time};
    /// # use std::io::Write;
    /// # use std::os::unix::io::AsRawFd;
    /// # use tempfile::tempfile;
    /// # fn main() {
    /// let wbuf = b"CDEF";
    /// let mut f = tempfile().unwrap();
    /// let mut aiocb = AioCb::from_slice( f.as_raw_fd(),
    ///     2,   //offset
    ///     &wbuf[..],
    ///     0,   //priority
    ///     SigevNotify::SigevNone,
    ///     LioOpcode::LIO_NOP);
    /// aiocb.write().unwrap();
    /// let cs = aiocb.cancel().unwrap();
    /// if cs == AioCancelStat::AioNotCanceled {
    ///     while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
    ///         thread::sleep(time::Duration::from_millis(10));
    ///     }
    /// }
    /// // Must call `aio_return`, but ignore the result
    /// let _ = aiocb.aio_return();
    /// # }
    /// ```
    ///
    /// # References
    ///
    /// [aio_cancel](http://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_cancel.html)
    pub fn cancel(self: &mut Pin<Box<Self>>) -> Result<AioCancelStat> {
        let r = unsafe {
            let selfp = self.as_mut().get_unchecked_mut();
            libc::aio_cancel(selfp.aiocb.aio_fildes, &mut selfp.aiocb)
        };
        match r { 
            libc::AIO_CANCELED => Ok(AioCancelStat::AioCanceled),
            libc::AIO_NOTCANCELED => Ok(AioCancelStat::AioNotCanceled),
            libc::AIO_ALLDONE => Ok(AioCancelStat::AioAllDone),
            -1 => Err(Error::last()),
            _ => panic!("unknown aio_cancel return value")
        }
    }

    fn error_unpinned(self: &mut Self) -> Result<()> {
        let r = unsafe {
            libc::aio_error(&mut self.aiocb as *mut libc::aiocb)
        };
        match r {
            0 => Ok(()),
            num if num > 0 => Err(Error::from_errno(Errno::from_i32(num))),
            -1 => Err(Error::last()),
            num => panic!("unknown aio_error return value {:?}", num)
        }
    }

    /// Retrieve error status of an asynchronous operation.
    ///
    /// If the request has not yet completed, returns `EINPROGRESS`.  Otherwise,
    /// returns `Ok` or any other error.
    ///
    /// # Examples
    ///
    /// Issue an aio operation and use `error` to poll for completion.  Polling
    /// is an alternative to `aio_suspend`, used by most of the other examples.
    ///
    /// ```
    /// # extern crate tempfile;
    /// # extern crate nix;
    /// # use nix::errno::Errno;
    /// # use nix::Error;
    /// # use nix::sys::aio::*;
    /// # use nix::sys::signal::SigevNotify;
    /// # use std::{thread, time};
    /// # use std::os::unix::io::AsRawFd;
    /// # use tempfile::tempfile;
    /// # fn main() {
    /// const WBUF: &[u8] = b"abcdef123456";
    /// let mut f = tempfile().unwrap();
    /// let mut aiocb = AioCb::from_slice( f.as_raw_fd(),
    ///     2,   //offset
    ///     WBUF,
    ///     0,   //priority
    ///     SigevNotify::SigevNone,
    ///     LioOpcode::LIO_NOP);
    /// aiocb.write().unwrap();
    /// while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
    ///     thread::sleep(time::Duration::from_millis(10));
    /// }
    /// assert_eq!(aiocb.aio_return().unwrap() as usize, WBUF.len());
    /// # }
    /// ```
    ///
    /// # References
    ///
    /// [aio_error](http://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_error.html)
    pub fn error(self: &mut Pin<Box<Self>>) -> Result<()> {
        // Safe because error_unpinned doesn't move the data
        let selfp = unsafe {
            self.as_mut().get_unchecked_mut()
        };
        selfp.error_unpinned()
    }

    /// An asynchronous version of `fsync(2)`.
    ///
    /// # References
    ///
    /// [aio_fsync](http://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_fsync.html)
    pub fn fsync(self: &mut Pin<Box<Self>>, mode: AioFsyncMode) -> Result<()> {
        // Safe because we don't move the libc::aiocb
        unsafe {
            let selfp = self.as_mut().get_unchecked_mut();
            Errno::result({
                let p: *mut libc::aiocb = &mut selfp.aiocb;
                libc::aio_fsync(mode as libc::c_int, p)
            }).map(|_| {
                selfp.in_progress = true;
            })
        }
    }

    /// Returns the `aiocb`'s `LioOpcode` field
    ///
    /// If the value cannot be represented as an `LioOpcode`, returns `None`
    /// instead.
    pub fn lio_opcode(&self) -> Option<LioOpcode> {
        match self.aiocb.aio_lio_opcode {
            libc::LIO_READ => Some(LioOpcode::LIO_READ),
            libc::LIO_WRITE => Some(LioOpcode::LIO_WRITE),
            libc::LIO_NOP => Some(LioOpcode::LIO_NOP),
            _ => None
        }
    }

    /// Returns the requested length of the aio operation in bytes
    ///
    /// This method returns the *requested* length of the operation.  To get the
    /// number of bytes actually read or written by a completed operation, use
    /// `aio_return` instead.
    pub fn nbytes(&self) -> usize {
        self.aiocb.aio_nbytes
    }

    /// Returns the file offset stored in the `AioCb`
    pub fn offset(&self) -> off_t {
        self.aiocb.aio_offset
    }

    /// Returns the priority of the `AioCb`
    pub fn priority(&self) -> libc::c_int {
        self.aiocb.aio_reqprio
    }

    /// Asynchronously reads from a file descriptor into a buffer
    ///
    /// # References
    ///
    /// [aio_read](http://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_read.html)
    pub fn read(self: &mut Pin<Box<Self>>) -> Result<()> {
        assert!(self.mutable, "Can't read into an immutable buffer");
        unsafe {
            let selfp = self.as_mut().get_unchecked_mut();
            Errno::result({
                let p: *mut libc::aiocb = &mut selfp.aiocb;
                libc::aio_read(p)
            }).map(|_| {
                selfp.in_progress = true;
            })
        }
    }

    /// Returns the `SigEvent` stored in the `AioCb`
    pub fn sigevent(&self) -> SigEvent {
        SigEvent::from(&self.aiocb.aio_sigevent)
    }

    fn aio_return_unpinned(self: &mut Self) -> Result<isize> {
        unsafe {
            let p: *mut libc::aiocb = &mut self.aiocb;
            self.in_progress = false;
            Errno::result(libc::aio_return(p))
        }
    }

    /// Retrieve return status of an asynchronous operation.
    ///
    /// Should only be called once for each `AioCb`, after `AioCb::error`
    /// indicates that it has completed.  The result is the same as for the
    /// synchronous `read(2)`, `write(2)`, of `fsync(2)` functions.
    ///
    /// # References
    ///
    /// [aio_return](http://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_return.html)
    // Note: this should be just `return`, but that's a reserved word
    pub fn aio_return(self: &mut Pin<Box<Self>>) -> Result<isize> {
        // Safe because aio_return_unpinned does not move the data
        let selfp = unsafe {
            self.as_mut().get_unchecked_mut()
        };
        selfp.aio_return_unpinned()
    }

    /// Asynchronously writes from a buffer to a file descriptor
    ///
    /// # References
    ///
    /// [aio_write](http://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_write.html)
    pub fn write(self: &mut Pin<Box<Self>>) -> Result<()> {
        unsafe {
            let selfp = self.as_mut().get_unchecked_mut();
            Errno::result({
                let p: *mut libc::aiocb = &mut selfp.aiocb;
                libc::aio_write(p)
            }).map(|_| {
                selfp.in_progress = true;
            })
        }
    }
}

/// Cancels outstanding AIO requests for a given file descriptor.
///
/// # Examples
///
/// Issue an aio operation, then cancel all outstanding operations on that file
/// descriptor.
///
/// ```
/// # extern crate tempfile;
/// # extern crate nix;
/// # use nix::errno::Errno;
/// # use nix::Error;
/// # use nix::sys::aio::*;
/// # use nix::sys::signal::SigevNotify;
/// # use std::{thread, time};
/// # use std::io::Write;
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// # fn main() {
/// let wbuf = b"CDEF";
/// let mut f = tempfile().unwrap();
/// let mut aiocb = AioCb::from_slice( f.as_raw_fd(),
///     2,   //offset
///     &wbuf[..],
///     0,   //priority
///     SigevNotify::SigevNone,
///     LioOpcode::LIO_NOP);
/// aiocb.write().unwrap();
/// let cs = aio_cancel_all(f.as_raw_fd()).unwrap();
/// if cs == AioCancelStat::AioNotCanceled {
///     while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
///         thread::sleep(time::Duration::from_millis(10));
///     }
/// }
/// // Must call `aio_return`, but ignore the result
/// let _ = aiocb.aio_return();
/// # }
/// ```
///
/// # References
///
/// [`aio_cancel`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_cancel.html)
pub fn aio_cancel_all(fd: RawFd) -> Result<AioCancelStat> {
    match unsafe { libc::aio_cancel(fd, null_mut()) } {
        libc::AIO_CANCELED => Ok(AioCancelStat::AioCanceled),
        libc::AIO_NOTCANCELED => Ok(AioCancelStat::AioNotCanceled),
        libc::AIO_ALLDONE => Ok(AioCancelStat::AioAllDone),
        -1 => Err(Error::last()),
        _ => panic!("unknown aio_cancel return value")
    }
}

/// Suspends the calling process until at least one of the specified `AioCb`s
/// has completed, a signal is delivered, or the timeout has passed.
///
/// If `timeout` is `None`, `aio_suspend` will block indefinitely.
///
/// # Examples
///
/// Use `aio_suspend` to block until an aio operation completes.
///
/// ```
/// # extern crate tempfile;
/// # extern crate nix;
/// # use nix::sys::aio::*;
/// # use nix::sys::signal::SigevNotify;
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// # fn main() {
/// const WBUF: &[u8] = b"abcdef123456";
/// let mut f = tempfile().unwrap();
/// let mut aiocb = AioCb::from_slice( f.as_raw_fd(),
///     2,   //offset
///     WBUF,
///     0,   //priority
///     SigevNotify::SigevNone,
///     LioOpcode::LIO_NOP);
/// aiocb.write().unwrap();
/// aio_suspend(&[&aiocb], None).expect("aio_suspend failed");
/// assert_eq!(aiocb.aio_return().unwrap() as usize, WBUF.len());
/// # }
/// ```
/// # References
///
/// [`aio_suspend`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_suspend.html)
pub fn aio_suspend(list: &[Pin<&AioCb>], timeout: Option<TimeSpec>) -> Result<()> {
    let plist = list as *const [Pin<&AioCb>] as *const [*const libc::aiocb];
    let p = plist as *const *const libc::aiocb;
    let timep = match timeout {
        None    => null::<libc::timespec>(),
        Some(x) => x.as_ref() as *const libc::timespec
    };
    Errno::result(unsafe {
        libc::aio_suspend(p, list.len() as i32, timep)
    }).map(drop)
}

impl<'a> Debug for AioCb<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("AioCb")
            .field("aiocb", &self.aiocb)
            .field("mutable", &self.mutable)
            .field("in_progress", &self.in_progress)
            .finish()
    }
}

impl<'a> Drop for AioCb<'a> {
    /// If the `AioCb` has no remaining state in the kernel, just drop it.
    /// Otherwise, dropping constitutes a resource leak, which is an error
    fn drop(&mut self) {
        assert!(thread::panicking() || !self.in_progress,
                "Dropped an in-progress AioCb");
    }
}

/// LIO Control Block.
///
/// The basic structure used to issue multiple AIO operations simultaneously.
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
pub struct LioCb<'a> {
    /// A collection of [`AioCb`]s.  All of these will be issued simultaneously
    /// by the [`listio`] method.
    ///
    /// [`AioCb`]: struct.AioCb.html
    /// [`listio`]: #method.listio
    pub aiocbs: Vec<AioCb<'a>>,

    /// The actual list passed to `libc::lio_listio`.
    ///
    /// It must live for as long as any of the operations are still being
    /// processesed, because the aio subsystem uses its address as a unique
    /// identifier.
    list: Vec<*mut libc::aiocb>,

    /// A partial set of results.  This field will get populated by
    /// `listio_resubmit` when an `LioCb` is resubmitted after an error
    results: Vec<Option<Result<isize>>>
}

#[cfg(not(any(target_os = "ios", target_os = "macos")))]
impl<'a> LioCb<'a> {
    /// Initialize an empty `LioCb`
    pub fn with_capacity(capacity: usize) -> LioCb<'a> {
        LioCb {
            aiocbs: Vec::with_capacity(capacity),
            list: Vec::with_capacity(capacity),
            results: Vec::with_capacity(capacity)
        }
    }

    pub fn emplace_slice(&mut self, fd: RawFd, offs: off_t, buf: &'a [u8],
                         prio: libc::c_int, sigev_notify: SigevNotify,
                         opcode: LioOpcode)
    {
        self.aiocbs.push(AioCb::from_slice_unpinned(fd, offs, buf, prio,
                                                    sigev_notify, opcode));
    }

    pub fn emplace_mut_slice(&mut self, fd: RawFd, offs: off_t,
                             buf: &'a mut [u8], prio: libc::c_int,
                             sigev_notify: SigevNotify, opcode: LioOpcode)
    {
        self.aiocbs.push(AioCb::from_mut_slice_unpinned(fd, offs, buf, prio,
                                                        sigev_notify, opcode));
    }

    /// Submits multiple asynchronous I/O requests with a single system call.
    ///
    /// They are not guaranteed to complete atomically, and the order in which
    /// the requests are carried out is not specified.  Reads, writes, and
    /// fsyncs may be freely mixed.
    ///
    /// This function is useful for reducing the context-switch overhead of
    /// submitting many AIO operations.  It can also be used with
    /// `LioMode::LIO_WAIT` to block on the result of several independent
    /// operations.  Used that way, it is often useful in programs that
    /// otherwise make little use of AIO.
    ///
    /// # Examples
    ///
    /// Use `listio` to submit an aio operation and wait for its completion.  In
    /// this case, there is no need to use [`aio_suspend`] to wait or
    /// [`AioCb::error`] to poll.
    ///
    /// ```
    /// # extern crate tempfile;
    /// # extern crate nix;
    /// # use nix::sys::aio::*;
    /// # use nix::sys::signal::SigevNotify;
    /// # use std::os::unix::io::AsRawFd;
    /// # use tempfile::tempfile;
    /// # fn main() {
    /// const WBUF: &[u8] = b"abcdef123456";
    /// let mut f = tempfile().unwrap();
    /// let mut liocb = LioCb::with_capacity(1);
    /// liocb.aiocbs.push(AioCb::from_slice( f.as_raw_fd(),
    ///     2,   //offset
    ///     WBUF,
    ///     0,   //priority
    ///     SigevNotify::SigevNone,
    ///     LioOpcode::LIO_WRITE));
    /// liocb.listio(LioMode::LIO_WAIT,
    ///              SigevNotify::SigevNone).unwrap();
    /// assert_eq!(liocb.aio_return(0).unwrap() as usize, WBUF.len());
    /// # }
    /// ```
    ///
    /// # References
    ///
    /// [`lio_listio`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html)
    ///
    /// [`aio_suspend`]: fn.aio_suspend.html
    /// [`AioCb::error`]: struct.AioCb.html#method.error
    pub fn listio(&mut self, mode: LioMode,
                  sigev_notify: SigevNotify) -> Result<()> {
        let sigev = SigEvent::new(sigev_notify);
        let sigevp = &mut sigev.sigevent() as *mut libc::sigevent;
        self.list.clear();
        for a in &mut self.aiocbs {
            a.in_progress = true;
            self.list.push(a as *mut AioCb<'a>
                             as *mut libc::aiocb);
        }
        let p = self.list.as_ptr();
        Errno::result(unsafe {
            libc::lio_listio(mode as i32, p, self.list.len() as i32, sigevp)
        }).map(drop)
    }

    /// Resubmits any incomplete operations with [`lio_listio`].
    ///
    /// Sometimes, due to system resource limitations, an `lio_listio` call will
    /// return `EIO`, or `EAGAIN`.  Or, if a signal is received, it may return
    /// `EINTR`.  In any of these cases, only a subset of its constituent
    /// operations will actually have been initiated.  `listio_resubmit` will
    /// resubmit any operations that are still uninitiated.
    ///
    /// After calling `listio_resubmit`, results should be collected by
    /// [`LioCb::aio_return`].
    ///
    /// # Examples
    /// ```no_run
    /// # extern crate tempfile;
    /// # extern crate nix;
    /// # use nix::Error;
    /// # use nix::errno::Errno;
    /// # use nix::sys::aio::*;
    /// # use nix::sys::signal::SigevNotify;
    /// # use std::os::unix::io::AsRawFd;
    /// # use std::{thread, time};
    /// # use tempfile::tempfile;
    /// # fn main() {
    /// const WBUF: &[u8] = b"abcdef123456";
    /// let mut f = tempfile().unwrap();
    /// let mut liocb = LioCb::with_capacity(1);
    /// liocb.aiocbs.push(AioCb::from_slice( f.as_raw_fd(),
    ///     2,   //offset
    ///     WBUF,
    ///     0,   //priority
    ///     SigevNotify::SigevNone,
    ///     LioOpcode::LIO_WRITE));
    /// let mut err = liocb.listio(LioMode::LIO_WAIT, SigevNotify::SigevNone);
    /// while err == Err(Error::Sys(Errno::EIO)) ||
    ///       err == Err(Error::Sys(Errno::EAGAIN)) {
    ///     thread::sleep(time::Duration::from_millis(10));
    ///     err = liocb.listio_resubmit(LioMode::LIO_WAIT, SigevNotify::SigevNone);
    /// }
    /// assert_eq!(liocb.aio_return(0).unwrap() as usize, WBUF.len());
    /// # }
    /// ```
    ///
    /// # References
    ///
    /// [`lio_listio`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html)
    ///
    /// [`lio_listio`]: http://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html
    /// [`LioCb::aio_return`]: struct.LioCb.html#method.aio_return
    // Note: the addresses of any EINPROGRESS or EOK aiocbs _must_ not be
    // changed by this method, because the kernel relies on their addresses
    // being stable.
    // Note: aiocbs that are Ok(()) must be finalized by aio_return, or else the
    // sigev_notify will immediately refire.
    pub fn listio_resubmit(&mut self, mode:LioMode,
                           sigev_notify: SigevNotify) -> Result<()> {
        let sigev = SigEvent::new(sigev_notify);
        let sigevp = &mut sigev.sigevent() as *mut libc::sigevent;
        self.list.clear();

        while self.results.len() < self.aiocbs.len() {
            self.results.push(None);
        }

        for (i, a) in self.aiocbs.iter_mut().enumerate() {
            if self.results[i].is_some() {
                // Already collected final status for this operation
                continue;
            }
            match a.error_unpinned() {
                Ok(()) => {
                    // aiocb is complete; collect its status and don't resubmit
                    self.results[i] = Some(a.aio_return_unpinned());
                },
                Err(Error::Sys(Errno::EAGAIN)) => {
                    self.list.push(a as *mut AioCb<'a> as *mut libc::aiocb);
                },
                Err(Error::Sys(Errno::EINPROGRESS)) => {
                    // aiocb is was successfully queued; no need to do anything
                },
                Err(Error::Sys(Errno::EINVAL)) => panic!(
                    "AioCb was never submitted, or already finalized"),
                _ => unreachable!()
            }
        }
        let p = self.list.as_ptr();
        Errno::result(unsafe {
            libc::lio_listio(mode as i32, p, self.list.len() as i32, sigevp)
        }).map(drop)
    }

    /// Collect final status for an individual `AioCb` submitted as part of an
    /// `LioCb`.
    ///
    /// This is just like [`AioCb::aio_return`], except it takes into account
    /// operations that were restarted by [`LioCb::listio_resubmit`]
    ///
    /// [`AioCb::aio_return`]: struct.AioCb.html#method.aio_return
    /// [`LioCb::listio_resubmit`]: #method.listio_resubmit
    pub fn aio_return(&mut self, i: usize) -> Result<isize> {
        if i >= self.results.len() || self.results[i].is_none() {
            self.aiocbs[i].aio_return_unpinned()
        } else {
            self.results[i].unwrap()
        }
    }

    /// Retrieve error status of an individual `AioCb` submitted as part of an
    /// `LioCb`.
    ///
    /// This is just like [`AioCb::error`], except it takes into account
    /// operations that were restarted by [`LioCb::listio_resubmit`]
    ///
    /// [`AioCb::error`]: struct.AioCb.html#method.error
    /// [`LioCb::listio_resubmit`]: #method.listio_resubmit
    pub fn error(&mut self, i: usize) -> Result<()> {
        if i >= self.results.len() || self.results[i].is_none() {
            self.aiocbs[i].error_unpinned()
        } else {
            Ok(())
        }
    }
}

#[cfg(not(any(target_os = "ios", target_os = "macos")))]
impl<'a> Debug for LioCb<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("LioCb")
            .field("aiocbs", &self.aiocbs)
            .finish()
    }
}

//#[cfg(not(any(target_os = "ios", target_os = "macos")))]
//impl<'a> From<Vec<AioCb<'a>>> for LioCb<'a> {
    //fn from(src: Vec<AioCb<'a>>) -> LioCb<'a> {
        //LioCb {
            //list: Vec::with_capacity(src.capacity()),
            //results: Vec::with_capacity(src.capacity()),
            //aiocbs: src,
        //}
    //}
//}