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
#![deny(missing_docs)]

//! A crate implementing cancellable synchronous network I/O.
//!
//! This crate exposes structs [TcpStream](struct.TcpStream.html),
//! [TcpListener](struct.TcpListener.html) and [UdpSocket](struct.UdpSocket.html)
//! that are similar to their std::net variants, except that I/O operations
//! can be cancelled through [Canceller](struct.Canceller.html) objects
//! created with them.
//!
//! Most methods work as they do in the std::net implementations, and you
//! should refer to the [original documentation](https://doc.rust-lang.org/std/net/)
//! for details and examples.
//!
//! Main differences with the original std::net implementations :
//! * Methods that return a [TcpStream](struct.TcpStream.html), a
//! [TcpListener](struct.TcpListener.html), or an [UdpSocket](struct.UdpSocket.html)
//! also return a [Canceller](struct.Canceller.html) object.
//! * There are no peek() methods (yet?)
//! * [TcpListener](struct.TcpListener.html) and [UdpSocket](struct.UdpSocket.html)
//! are not `Sync` (yet?)
//!
//! # Example
//! ```
//! use cancellable_io::*;
//! let (listener, canceller) = TcpListener::bind("127.0.0.1:0").unwrap();
//! let handle = std::thread::spawn(move || {
//!     println!("Waiting for connections.");
//!     let r = listener.accept();
//!     assert!(is_cancelled(&r.unwrap_err()));
//!     println!("Server cancelled.");
//! });
//!
//! std::thread::sleep(std::time::Duration::from_secs(2));
//! canceller.cancel().unwrap();
//! handle.join().unwrap();
//! ```

extern crate mio;

use std::cell::RefCell;
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::io;
use std::io::{Read, Write};
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
use std::sync::{Arc, RwLock};
use std::time::Duration;

use mio::*;

const STOP_TOKEN: Token = Token(0);
const OBJECT_TOKEN: Token = Token(1);

/// An object that can be used to cancel an i/o operation.
///
/// It is created with the object it can cancel.
/// When an operation is cancelled, it returns an error that can be
/// identified with the [is_cancelled](fn.is_cancelled.html) function.
#[derive(Clone, Debug)]
pub struct Canceller {
    set_readiness: SetReadiness,
}

/// A TCP stream between a local and a remote socket.
///
/// The socket will be closed when the value is dropped.
///
/// The [read](struct.TcpStream.html#method.read) and
/// [write](struct.TcpStream.html#method.write) methods can be interrupted
/// using the [Canceller](struct.Canceller.html) object created with the
/// stream.
///
/// Otherwise similar to
/// [std::net::TcpStream](https://doc.rust-lang.org/std/net/struct.TcpStream.html).
pub struct TcpStream {
    stream: mio::net::TcpStream,
    poll: Poll,
    _stop_registration: Registration,
    events: Events,
    options: Arc<RwLock<TcpStreamOptions>>,
}

struct TcpStreamOptions {
    read_timeout: Option<Duration>,
    write_timeout: Option<Duration>,
    nonblocking: bool,
}

/// A TCP socket server, listening for connections.
///
/// The socket will be closed when the value is dropped.
///
/// The [accept](struct.TcpListener.html#method.accept) and the
/// [incoming](struct.TcpListener.html#method.incoming) methods can be
/// interrupted using the [Canceller](struct.Canceller.html) object
/// created with the socket.
///
/// Otherwise similar to
/// [std::net::TcpListener](https://doc.rust-lang.org/std/net/struct.TcpListener.html).
pub struct TcpListener {
    listener: mio::net::TcpListener,
    poll: Poll,
    _stop_registration: Registration,

    // RefCell makes TcpListener !Sync while std::net::TcpListener is, but
    // using a Mutex would conflict with nonblocking mode, and allocating
    // events on each call to accept() is not that nice. So let's keep it
    // this way for now. One can always use try_clone() anyway if sharing
    // a socket between threads is needed.
    events: RefCell<Events>,
    options: Arc<RwLock<TcpListenerOptions>>,
}

struct TcpListenerOptions {
    timeout: Option<Duration>,
    nonblocking: bool,
}

/// An iterator that infinitely [accept](struct.TcpListener.html#method.accept)s
/// connections on a TcpListener.
///
/// It is created by the [incoming](struct.TcpListener.html#method.incoming) method.
pub struct Incoming<'a> {
    listener: &'a TcpListener,
}

/// An UDP socket bound to an address.
///
/// The [recv_from](struct.UdpSocket.html#method.recv_from),
/// [send_to](struct.UdpSocket.html#method.send_to),
/// [recv](struct.UdpSocket.html#method.recv), and
/// [send](struct.UdpSocket.html#method.send) can be interrupted using the
/// [Canceller](struct.Canceller.html) object created with the socket.
///
/// Otherwise similar to
/// [std::net::UdpSocket](https://doc.rust-lang.org/std/net/struct.UdpSocket.html).
pub struct UdpSocket {
    socket: mio::net::UdpSocket,
    poll: Poll,
    _stop_registration: Registration,
    events: RefCell<Events>, // !Sync, cf TcpListener.
    options: Arc<RwLock<UdpSocketOptions>>,
}

struct UdpSocketOptions {
    read_timeout: Option<Duration>,
    write_timeout: Option<Duration>,
    nonblocking: bool,
}

impl Canceller {
    /// Cancels an operation on the associated object.
    ///
    /// The pending operation is aborted and returns an error that can be
    /// checked by the [is_cancelled](fn.is_cancelled.html) function. If
    /// there is no pending operation, the next one will be cancelled.
    pub fn cancel(&self) -> io::Result<()> {
        self.set_readiness.set_readiness(Ready::readable())
    }
}

fn cancelled_error() -> io::Error {
    // Can't use ErrorKind::Interrupted because it causes silent retries
    // from various library functions.
    io::Error::new(io::ErrorKind::Other, "cancelled")
}

/// Checks if the error returned by a method was caused by the operation
/// being cancelled.
pub fn is_cancelled(e: &io::Error) -> bool {
    e.kind() == io::ErrorKind::Other && e.to_string() == "cancelled"
}

impl TcpStream {
    fn simple_connect(address: &SocketAddr) -> io::Result<(Self, Canceller)> {
        let poll = Poll::new()?;

        let (stop_registration, stop_set_readiness) = Registration::new2();
        poll.register(
            &stop_registration,
            STOP_TOKEN,
            Ready::readable(),
            PollOpt::edge(),
        )?;

        let stream = mio::net::TcpStream::connect(address)?;
        poll.register(
            &stream,
            OBJECT_TOKEN,
            Ready::readable() | Ready::writable(),
            PollOpt::level(),
        )?;

        let events = Events::with_capacity(4);

        Ok((
            TcpStream {
                stream,
                poll,
                _stop_registration: stop_registration,
                events,
                options: Arc::new(RwLock::new(TcpStreamOptions {
                    read_timeout: None,
                    write_timeout: None,
                    nonblocking: false,
                })),
            },
            Canceller {
                set_readiness: stop_set_readiness,
            },
        ))
    }

    /// Creates a new TCP stream with an object used to cancel read/write
    /// operations, and connects it to a remote address.
    pub fn connect<A: ToSocketAddrs>(address: A) -> io::Result<(Self, Canceller)> {
        let mut error = io::Error::from(io::ErrorKind::InvalidInput);
        for a in address.to_socket_addrs()? {
            match Self::simple_connect(&a) {
                Ok(r) => return Ok(r),
                Err(e) => error = e,
            }
        }
        Err(error)
    }

    /// Returns the socket address of the remote peer of this TCP connection.
    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
        self.stream.peer_addr()
    }

    /// Returns the socket address of the local half of this TCP connection.
    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        self.stream.local_addr()
    }

    /// Shuts down the read, write, or both halves of this connection.
    pub fn shutdown(&self, how: std::net::Shutdown) -> io::Result<()> {
        self.stream.shutdown(how)
    }

    /// Creates a new independently owned handle to the underlying socket.
    /// The [Canceller](struct.Canceller.html)s associated with the original
    /// object and its clone are also independent.
    pub fn try_clone(&self) -> io::Result<(Self, Canceller)> {
        let poll = Poll::new()?;

        let (stop_registration, stop_set_readiness) = Registration::new2();
        poll.register(
            &stop_registration,
            STOP_TOKEN,
            Ready::readable(),
            PollOpt::edge(),
        )?;

        let stream = self.stream.try_clone()?;
        poll.register(
            &stream,
            OBJECT_TOKEN,
            Ready::readable() | Ready::writable(),
            PollOpt::level(),
        )?;

        let events = Events::with_capacity(4);

        Ok((
            TcpStream {
                stream,
                poll,
                _stop_registration: stop_registration,
                events,
                options: self.options.clone(),
            },
            Canceller {
                set_readiness: stop_set_readiness,
            },
        ))
    }

    /// Sets the read timeout.
    pub fn set_read_timeout(&self, duration: Option<Duration>) -> io::Result<()> {
        self.options.write().unwrap().read_timeout = duration;
        Ok(())
    }

    /// Sets the write timeout.
    pub fn set_write_timeout(&self, duration: Option<Duration>) -> io::Result<()> {
        self.options.write().unwrap().write_timeout = duration;
        Ok(())
    }

    /// Gets the read timeout.
    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
        Ok(self.options.read().unwrap().read_timeout)
    }

    /// Gets the write timeout.
    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
        Ok(self.options.read().unwrap().write_timeout)
    }

    //pub fn peek(&self)

    /// Sets the value of the `TCP_NODELAY` option on this socket.
    pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
        self.stream.set_nodelay(nodelay)
    }

    /// Gets the value of the `TCP_NODELAY` option for this socket.
    pub fn nodelay(&self) -> io::Result<bool> {
        self.stream.nodelay()
    }

    /// Sets the value for the `IP_TTL` option on this socket.
    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
        self.stream.set_ttl(ttl)
    }

    /// Gets the value for the `IP_TTL` option for this socket.
    pub fn ttl(&self) -> io::Result<u32> {
        self.stream.ttl()
    }

    /// Gets the value of the `SO_ERROR` option for this socket.
    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
        self.stream.take_error()
    }

    /// Moves this TCP stream into or out of nonblocking mode.
    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        self.options.write().unwrap().nonblocking = nonblocking;
        Ok(())
    }
}

impl Read for TcpStream {
    /// Reads data from the socket. This operation can be cancelled
    /// by the associated [Canceller](struct.Canceller.html) object.
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.poll.reregister(
            &self.stream,
            OBJECT_TOKEN,
            Ready::readable(),
            PollOpt::level(),
        )?;
        if self.options.read().unwrap().nonblocking {
            self.poll
                .poll(&mut self.events, Some(Duration::from_millis(0)))?;
            for event in self.events.iter() {
                let t = event.token();
                if t == OBJECT_TOKEN {
                    if event.readiness().is_readable() {
                        return self.stream.read(buf);
                    }
                } else if t == STOP_TOKEN {
                    return Err(cancelled_error());
                }
            }
            Err(io::Error::from(io::ErrorKind::WouldBlock))
        } else {
            let read_timeout = self.options.read().unwrap().read_timeout;
            loop {
                self.poll.poll(&mut self.events, read_timeout)?;
                for event in self.events.iter() {
                    let t = event.token();
                    if t == OBJECT_TOKEN {
                        if event.readiness().is_readable() {
                            return self.stream.read(buf);
                        }
                    } else if t == STOP_TOKEN {
                        return Err(cancelled_error());
                    }
                }
                if read_timeout.is_some() {
                    return Err(io::Error::from(io::ErrorKind::TimedOut));
                }
            }
        }
    }
}

impl Write for TcpStream {
    /// Writes data to the socket. This operation can be cancelled
    /// by the associated [Canceller](struct.Canceller.html) object.
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.poll.reregister(
            &self.stream,
            OBJECT_TOKEN,
            Ready::writable(),
            PollOpt::level(),
        )?;
        if self.options.read().unwrap().nonblocking {
            self.poll
                .poll(&mut self.events, Some(Duration::from_millis(0)))?;
            for event in self.events.iter() {
                let t = event.token();
                if t == OBJECT_TOKEN {
                    if event.readiness().is_writable() {
                        return self.stream.write(buf);
                    }
                } else if t == STOP_TOKEN {
                    return Err(cancelled_error());
                }
            }
            Err(io::Error::from(io::ErrorKind::WouldBlock))
        } else {
            let write_timeout = self.options.read().unwrap().write_timeout;
            loop {
                self.poll.poll(&mut self.events, write_timeout)?;
                for event in self.events.iter() {
                    let t = event.token();
                    if t == OBJECT_TOKEN {
                        if event.readiness().is_writable() {
                            return self.stream.write(buf);
                        }
                    } else if t == STOP_TOKEN {
                        return Err(cancelled_error());
                    }
                }
                if write_timeout.is_some() {
                    return Err(io::Error::from(io::ErrorKind::TimedOut));
                }
            }
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        self.poll.reregister(
            &self.stream,
            OBJECT_TOKEN,
            Ready::writable(),
            PollOpt::level(),
        )?;
        loop {
            self.poll.poll(&mut self.events, None)?;
            for event in self.events.iter() {
                let t = event.token();
                if t == OBJECT_TOKEN {
                    if event.readiness().is_writable() {
                        return self.stream.flush();
                    }
                } else if t == STOP_TOKEN {
                    return Err(cancelled_error());
                }
            }
        }
    }
}

impl Debug for TcpStream {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        self.stream.fmt(f)
    }
}

impl TcpListener {
    fn simple_bind(address: &SocketAddr) -> io::Result<(Self, Canceller)> {
        let poll = Poll::new()?;

        let (stop_registration, stop_set_readiness) = Registration::new2();
        poll.register(
            &stop_registration,
            STOP_TOKEN,
            Ready::readable(),
            PollOpt::edge(),
        )?;

        let listener = mio::net::TcpListener::bind(address)?;
        poll.register(&listener, OBJECT_TOKEN, Ready::readable(), PollOpt::level())?;

        let events = Events::with_capacity(4);

        Ok((
            TcpListener {
                listener,
                poll,
                _stop_registration: stop_registration,
                events: RefCell::new(events),
                options: Arc::new(RwLock::new(TcpListenerOptions {
                    timeout: None,
                    nonblocking: false,
                })),
            },
            Canceller {
                set_readiness: stop_set_readiness,
            },
        ))
    }

    /// Creates a new [TcpListener](struct.TcpListener.html) which will be
    /// bound to the specified address, together with an object that allows
    /// cancelling [accept](struct.TcpListener.html#method.accept) operations.
    pub fn bind<A: ToSocketAddrs>(address: A) -> io::Result<(Self, Canceller)> {
        let mut error = io::Error::from(io::ErrorKind::InvalidInput);
        for a in address.to_socket_addrs()? {
            match Self::simple_bind(&a) {
                Ok(r) => return Ok(r),
                Err(e) => error = e,
            }
        }
        Err(error)
    }

    /// Returns the local socket address of this listener.
    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        self.listener.local_addr()
    }

    /// Creates a new independently owned handle to the underlying socket.
    pub fn try_clone(&self) -> io::Result<(Self, Canceller)> {
        let poll = Poll::new()?;

        let (stop_registration, stop_set_readiness) = Registration::new2();
        poll.register(
            &stop_registration,
            STOP_TOKEN,
            Ready::readable(),
            PollOpt::edge(),
        )?;

        let listener = self.listener.try_clone()?;
        poll.register(&listener, OBJECT_TOKEN, Ready::readable(), PollOpt::level())?;

        let events = Events::with_capacity(4);

        Ok((
            TcpListener {
                listener,
                poll,
                _stop_registration: stop_registration,
                events: RefCell::new(events),
                options: self.options.clone(),
            },
            Canceller {
                set_readiness: stop_set_readiness,
            },
        ))
    }

    /// Accepts a new incoming connection from this listener.
    ///
    /// This method can be cancelled by the associated [Canceller](struct.Canceller.html)
    /// object.
    ///
    /// This method returns a [TcpStream](struct.TcpStream.html) with an
    /// associated [Canceller](struct.Canceller.html) and the address of the
    /// remote peer.
    pub fn accept(&self) -> io::Result<(TcpStream, Canceller, SocketAddr)> {
        let mut events = self.events.borrow_mut();
        if self.options.read().unwrap().nonblocking {
            self.poll
                .poll(&mut events, Some(Duration::from_millis(0)))?;
            for event in events.iter() {
                let t = event.token();
                if t == OBJECT_TOKEN {
                    let (stream, addr) = self.listener.accept()?;
                    let poll = Poll::new()?;

                    let stop_token = Token(0);
                    let (stop_registration, stop_set_readiness) = Registration::new2();
                    poll.register(
                        &stop_registration,
                        stop_token,
                        Ready::readable(),
                        PollOpt::edge(),
                    )?;

                    let stream_token = Token(1);
                    poll.register(
                        &stream,
                        stream_token,
                        Ready::readable() | Ready::writable(),
                        PollOpt::level(),
                    )?;

                    let events = Events::with_capacity(4);

                    return Ok((
                        TcpStream {
                            stream,
                            poll,
                            _stop_registration: stop_registration,
                            events,
                            options: Arc::new(RwLock::new(TcpStreamOptions {
                                read_timeout: None,
                                write_timeout: None,
                                nonblocking: false,
                            })),
                        },
                        Canceller {
                            set_readiness: stop_set_readiness,
                        },
                        addr,
                    ));
                } else if t == STOP_TOKEN {
                    return Err(cancelled_error());
                }
            }
            Err(io::Error::from(io::ErrorKind::WouldBlock))
        } else {
            let timeout = self.options.read().unwrap().timeout;
            loop {
                self.poll.poll(&mut events, timeout)?;
                for event in events.iter() {
                    let t = event.token();
                    if t == OBJECT_TOKEN {
                        let (stream, addr) = self.listener.accept()?;
                        let poll = Poll::new()?;

                        let stop_token = Token(0);
                        let (stop_registration, stop_set_readiness) = Registration::new2();
                        poll.register(
                            &stop_registration,
                            stop_token,
                            Ready::readable(),
                            PollOpt::edge(),
                        )?;

                        let stream_token = Token(1);
                        poll.register(
                            &stream,
                            stream_token,
                            Ready::readable() | Ready::writable(),
                            PollOpt::level(),
                        )?;

                        let events = Events::with_capacity(4);

                        return Ok((
                            TcpStream {
                                stream,
                                poll,
                                _stop_registration: stop_registration,
                                events,
                                options: Arc::new(RwLock::new(TcpStreamOptions {
                                    read_timeout: None,
                                    write_timeout: None,
                                    nonblocking: false,
                                })),
                            },
                            Canceller {
                                set_readiness: stop_set_readiness,
                            },
                            addr,
                        ));
                    } else if t == STOP_TOKEN {
                        return Err(cancelled_error());
                    }
                }
                if timeout.is_some() {
                    return Err(io::Error::from(io::ErrorKind::TimedOut));
                }
            }
        }
    }

    /// Returns an iterator over the connections being received by this listener.
    ///
    /// The iteration can be cancelled by the associated [Canceller](struct.Canceller.html)
    /// object. If the iteration is cancelled, the next() method will return an
    /// error that can be identified with [is_cancelled](fn.is_cancelled.html).
    pub fn incoming(&self) -> Incoming {
        Incoming { listener: self }
    }

    /// Sets the value for the `IP_TTL` option on this socket.
    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
        self.listener.set_ttl(ttl)
    }

    /// Gets the value for the `IP_TTL` option for this socket.
    pub fn ttl(&self) -> io::Result<u32> {
        self.listener.ttl()
    }

    /// Gets the value for the `SO_ERROR` option for this socket.
    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
        self.listener.take_error()
    }

    /// Moves this TCP connection into or out of non blocking mode.
    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        self.options.write().unwrap().nonblocking = nonblocking;
        Ok(())
    }
}

impl Debug for TcpListener {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        self.listener.fmt(f)
    }
}

impl<'a> Iterator for Incoming<'a> {
    type Item = io::Result<(TcpStream, Canceller, SocketAddr)>;

    fn next(&mut self) -> Option<Self::Item> {
        Some(self.listener.accept())
    }
}

impl UdpSocket {
    fn simple_bind(address: &SocketAddr) -> io::Result<(Self, Canceller)> {
        let poll = Poll::new()?;

        let (stop_registration, stop_set_readiness) = Registration::new2();
        poll.register(
            &stop_registration,
            STOP_TOKEN,
            Ready::readable(),
            PollOpt::edge(),
        )?;

        let socket = mio::net::UdpSocket::bind(address)?;
        poll.register(
            &socket,
            OBJECT_TOKEN,
            Ready::readable() | Ready::writable(),
            PollOpt::level(),
        )?;

        let events = Events::with_capacity(4);

        Ok((
            UdpSocket {
                socket,
                poll,
                _stop_registration: stop_registration,
                events: RefCell::new(events),
                options: Arc::new(RwLock::new(UdpSocketOptions {
                    read_timeout: None,
                    write_timeout: None,
                    nonblocking: false,
                })),
            },
            Canceller {
                set_readiness: stop_set_readiness,
            },
        ))
    }

    /// Creates an UDP socket from the given address, together with an
    /// object that can be used to cancel send/recv operations.
    pub fn bind<A: ToSocketAddrs>(address: A) -> io::Result<(Self, Canceller)> {
        let mut error = io::Error::from(io::ErrorKind::InvalidInput);
        for a in address.to_socket_addrs()? {
            match Self::simple_bind(&a) {
                Ok(r) => return Ok(r),
                Err(e) => error = e,
            }
        }
        Err(error)
    }

    /// Receives a single datagram message from the socket.
    ///
    /// This method can be cancelled by the associated [Canceller](struct.Canceller.html)
    /// object.
    pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
        self.poll.reregister(
            &self.socket,
            OBJECT_TOKEN,
            Ready::readable(),
            PollOpt::level(),
        )?;
        let mut events = self.events.borrow_mut();
        if self.options.read().unwrap().nonblocking {
            self.poll
                .poll(&mut events, Some(Duration::from_millis(0)))?;
            for event in events.iter() {
                let t = event.token();
                if t == OBJECT_TOKEN {
                    if event.readiness().is_readable() {
                        return self.socket.recv_from(buf);
                    }
                } else if t == STOP_TOKEN {
                    return Err(cancelled_error());
                }
            }
            Err(io::Error::from(io::ErrorKind::WouldBlock))
        } else {
            let read_timeout = self.options.read().unwrap().read_timeout;
            loop {
                self.poll.poll(&mut events, read_timeout)?;
                for event in events.iter() {
                    let t = event.token();
                    if t == OBJECT_TOKEN {
                        if event.readiness().is_readable() {
                            return self.socket.recv_from(buf);
                        }
                    } else if t == STOP_TOKEN {
                        return Err(cancelled_error());
                    }
                }
                if read_timeout.is_some() {
                    return Err(io::Error::from(io::ErrorKind::TimedOut));
                }
            }
        }
    }

    /// Sends a single datagram message to the given address.
    ///
    /// This method can be cancelled by the associated [Canceller](struct.Canceller.html)
    /// object.
    pub fn send_to(&self, buf: &[u8], addr: &SocketAddr) -> io::Result<usize> {
        self.poll.reregister(
            &self.socket,
            OBJECT_TOKEN,
            Ready::writable(),
            PollOpt::level(),
        )?;
        let mut events = self.events.borrow_mut();
        if self.options.read().unwrap().nonblocking {
            self.poll
                .poll(&mut events, Some(Duration::from_millis(0)))?;
            for event in events.iter() {
                let t = event.token();
                if t == OBJECT_TOKEN {
                    if event.readiness().is_writable() {
                        return self.socket.send_to(buf, addr);
                    }
                } else if t == STOP_TOKEN {
                    return Err(cancelled_error());
                }
            }
            Err(io::Error::from(io::ErrorKind::WouldBlock))
        } else {
            let write_timeout = self.options.read().unwrap().write_timeout;
            loop {
                self.poll.poll(&mut events, write_timeout)?;
                for event in events.iter() {
                    let t = event.token();
                    if t == OBJECT_TOKEN {
                        if event.readiness().is_writable() {
                            return self.socket.send_to(buf, addr);
                        }
                    } else if t == STOP_TOKEN {
                        return Err(cancelled_error());
                    }
                }
                if write_timeout.is_some() {
                    return Err(io::Error::from(io::ErrorKind::TimedOut));
                }
            }
        }
    }

    /// Gets the socket address that this object was created from.
    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        self.socket.local_addr()
    }

    /// Creates a new independently owned handle to the underlying socket.
    pub fn try_clone(&self) -> io::Result<(Self, Canceller)> {
        let poll = Poll::new()?;

        let (stop_registration, stop_set_readiness) = Registration::new2();
        poll.register(
            &stop_registration,
            STOP_TOKEN,
            Ready::readable(),
            PollOpt::edge(),
        )?;

        let socket = self.socket.try_clone()?;
        poll.register(
            &socket,
            OBJECT_TOKEN,
            Ready::readable() | Ready::writable(),
            PollOpt::level(),
        )?;

        let events = Events::with_capacity(4);

        Ok((
            UdpSocket {
                socket,
                poll,
                _stop_registration: stop_registration,
                events: RefCell::new(events),
                options: self.options.clone(),
            },
            Canceller {
                set_readiness: stop_set_readiness,
            },
        ))
    }

    /// Sets the read timeout to the timeout specified.
    pub fn set_read_timeout(&self, duration: Option<Duration>) -> io::Result<()> {
        self.options.write().unwrap().read_timeout = duration;
        Ok(())
    }

    /// Sets the write timeout to the timeout specified.
    pub fn set_write_timeout(&self, duration: Option<Duration>) -> io::Result<()> {
        self.options.write().unwrap().write_timeout = duration;
        Ok(())
    }

    /// Returns the read timeout of this socket.
    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
        Ok(self.options.read().unwrap().read_timeout)
    }

    /// Returns the write timeout of this socket.
    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
        Ok(self.options.read().unwrap().write_timeout)
    }

    /// Sets the value of the `SO_BROADCAST` option for this socket.
    pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
        self.socket.set_broadcast(broadcast)
    }

    /// Gets the value of the `SO_BROADCAST` option for this socket.
    pub fn broadcast(&self) -> io::Result<bool> {
        self.socket.broadcast()
    }

    /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
    pub fn set_multicast_loop_v4(&self, multicast_loop: bool) -> io::Result<()> {
        self.socket.set_multicast_loop_v4(multicast_loop)
    }

    /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
    pub fn multicast_loop_v4(&self) -> io::Result<bool> {
        self.socket.multicast_loop_v4()
    }

    /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
    pub fn set_multicast_ttl_v4(&self, multicast_ttl: u32) -> io::Result<()> {
        self.socket.set_multicast_ttl_v4(multicast_ttl)
    }

    /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
    pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
        self.socket.multicast_ttl_v4()
    }

    /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
    pub fn set_multicast_loop_v6(&self, multicast_loop: bool) -> io::Result<()> {
        self.socket.set_multicast_loop_v6(multicast_loop)
    }

    /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
    pub fn multicast_loop_v6(&self) -> io::Result<bool> {
        self.socket.multicast_loop_v6()
    }

    /// Sets the value for the `IP_TTL` option on this socket.
    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
        self.socket.set_ttl(ttl)
    }

    /// Gets the value for the `IP_TTL` option for this socket.
    pub fn ttl(&self) -> io::Result<u32> {
        self.socket.ttl()
    }

    /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
    pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
        self.socket.join_multicast_v4(multiaddr, interface)
    }

    /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
    pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
        self.socket.join_multicast_v6(multiaddr, interface)
    }

    /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
    pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
        self.socket.leave_multicast_v4(multiaddr, interface)
    }

    /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
    pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
        self.socket.leave_multicast_v6(multiaddr, interface)
    }

    /// Gets the value of the `SO_ERROR` option for this socket.
    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
        self.socket.take_error()
    }

    /// Sets the value for the `IPV6_V6ONLY` option on this socket.
    pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
        self.socket.set_only_v6(only_v6)
    }

    /// Gets the value for the `IPV6_V6ONLY` option for this socket.
    pub fn only_v6(&self) -> io::Result<bool> {
        self.socket.only_v6()
    }

    fn simple_connect(&self, address: SocketAddr) -> io::Result<()> {
        self.socket.connect(address)
    }

    /// Connects this socket to a remote address.
    pub fn connect<A: ToSocketAddrs>(&self, address: A) -> io::Result<()> {
        let mut error = io::Error::from(io::ErrorKind::InvalidInput);
        for a in address.to_socket_addrs()? {
            match self.simple_connect(a) {
                Ok(r) => return Ok(r),
                Err(e) => error = e,
            }
        }
        Err(error)
    }

    /// Moves this socket into or out of non blocking mode.
    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        self.options.write().unwrap().nonblocking = nonblocking;
        Ok(())
    }

    /// Receives a single datagram from the connected remote address.
    ///
    /// This method can be cancelled by the associated [Canceller](struct.Canceller.html)
    /// object.
    pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.poll.reregister(
            &self.socket,
            OBJECT_TOKEN,
            Ready::readable(),
            PollOpt::level(),
        )?;
        let mut events = self.events.borrow_mut();
        if self.options.read().unwrap().nonblocking {
            self.poll
                .poll(&mut events, Some(Duration::from_millis(0)))?;
            for event in events.iter() {
                let t = event.token();
                if t == OBJECT_TOKEN {
                    if event.readiness().is_readable() {
                        return self.socket.recv(buf);
                    }
                } else if t == STOP_TOKEN {
                    return Err(cancelled_error());
                }
            }
            Err(io::Error::from(io::ErrorKind::WouldBlock))
        } else {
            let read_timeout = self.options.read().unwrap().read_timeout;
            loop {
                self.poll.poll(&mut events, read_timeout)?;
                for event in events.iter() {
                    let t = event.token();
                    if t == OBJECT_TOKEN {
                        if event.readiness().is_readable() {
                            return self.socket.recv(buf);
                        }
                    } else if t == STOP_TOKEN {
                        return Err(cancelled_error());
                    }
                }
                if read_timeout.is_some() {
                    return Err(io::Error::from(io::ErrorKind::TimedOut));
                }
            }
        }
    }

    /// Sends a single datagram to the connected remote address.
    ///
    /// This method can be cancelled by the associated [Canceller](struct.Canceller.html)
    /// object.
    pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
        self.poll.reregister(
            &self.socket,
            OBJECT_TOKEN,
            Ready::writable(),
            PollOpt::level(),
        )?;
        let mut events = self.events.borrow_mut();
        if self.options.read().unwrap().nonblocking {
            self.poll
                .poll(&mut events, Some(Duration::from_millis(0)))?;
            for event in events.iter() {
                let t = event.token();
                if t == OBJECT_TOKEN {
                    if event.readiness().is_writable() {
                        return self.socket.send(buf);
                    }
                } else if t == STOP_TOKEN {
                    return Err(cancelled_error());
                }
            }
            Err(io::Error::from(io::ErrorKind::WouldBlock))
        } else {
            let write_timeout = self.options.read().unwrap().write_timeout;
            loop {
                self.poll.poll(&mut events, write_timeout)?;
                for event in events.iter() {
                    let t = event.token();
                    if t == OBJECT_TOKEN {
                        if event.readiness().is_writable() {
                            return self.socket.send(buf);
                        }
                    } else if t == STOP_TOKEN {
                        return Err(cancelled_error());
                    }
                }
                if write_timeout.is_some() {
                    return Err(io::Error::from(io::ErrorKind::TimedOut));
                }
            }
        }
    }
}

impl Debug for UdpSocket {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        self.socket.fmt(f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Barrier};
    use std::thread;

    #[test]
    fn test_is_cancelled() {
        assert_eq!(
            is_cancelled(&io::Error::new(io::ErrorKind::Interrupted, "")),
            false
        );
        assert_eq!(
            is_cancelled(&io::Error::new(io::ErrorKind::Other, "")),
            false
        );
        assert_eq!(is_cancelled(&cancelled_error()), true);
    }

    #[test]
    fn test_simple_connection() {
        let (listener, listener_canceller) = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let handle = thread::spawn(move || {
            for r in listener.incoming() {
                match r {
                    Ok((mut stream, _canceller, _addr)) => {
                        thread::spawn(move || {
                            let mut buf = [0; 3];
                            stream.read_exact(&mut buf).unwrap();
                            assert_eq!(&buf, b"foo");
                            stream.write_all(b"bar").unwrap();
                        });
                    }
                    Err(ref e) if is_cancelled(e) => break,
                    Err(ref e) => panic!("{:?}", e),
                }
            }
        });

        for _ in 0..3 {
            let (mut stream, _stream_canceller) = TcpStream::connect(&addr).unwrap();
            stream.write_all(b"foo").unwrap();
            stream.flush().unwrap();
            let mut buf = Vec::new();
            assert_eq!(stream.read_to_end(&mut buf).unwrap(), 3);
            assert_eq!(&buf[..], b"bar");
        }

        listener_canceller.cancel().unwrap();

        handle.join().unwrap();
    }

    #[test]
    fn test_cancel_stream() {
        let (listener, _listener_canceller) = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let server = thread::spawn(move || {
            let (mut stream, _canceller, _addr) = listener.accept().unwrap();
            let mut buf = [0; 16];
            assert_eq!(stream.read(&mut buf).unwrap(), 0);
        });

        let (mut stream, stream_canceller) = TcpStream::connect(&addr).unwrap();
        let client = thread::spawn(move || {
            let mut buf = [0; 16];
            assert!(is_cancelled(&stream.read(&mut buf).unwrap_err()));
        });

        thread::sleep(Duration::from_secs(1));
        stream_canceller.cancel().unwrap();

        client.join().unwrap();
        server.join().unwrap();
    }

    #[test]
    fn test_non_blocking() {
        let barrier = Arc::new(Barrier::new(3));
        let barrier_server = barrier.clone();
        let (listener, _listener_canceller) = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let server = thread::spawn(move || {
            let (mut stream, _canceller, _addr) = listener.accept().unwrap();
            // Wait for the client to attempt reading when no data is there.
            barrier_server.wait();
            stream.write(b"foo").unwrap();
            // Wake up the client now that there is data.
            barrier_server.wait();
            barrier_server.wait();
            barrier_server.wait();
            let mut buf = [0; 16];
            assert_eq!(stream.read(&mut buf).unwrap(), 0);
        });

        let barrier_client = barrier.clone();
        let (mut stream, stream_canceller) = TcpStream::connect(&addr).unwrap();
        stream.set_nonblocking(true).unwrap();
        let client = thread::spawn(move || {
            let mut buf = [0; 3];
            // Attempt reading while there is no data available.
            assert_eq!(
                stream.read(&mut buf).unwrap_err().kind(),
                io::ErrorKind::WouldBlock
            );
            // Tell the server it can put some data now.
            barrier_client.wait();
            // Wait until the server has put some data.
            barrier_client.wait();
            // Some data is available now.
            stream.read_exact(&mut buf).unwrap();
            assert_eq!(&buf, b"foo");
            // Tell the main thread it can cancel the stream now.
            barrier_client.wait();
            // Wait for the stream to be cancelled.
            barrier_client.wait();
            // It is cancelled now.
            assert!(is_cancelled(&stream.read(&mut buf).unwrap_err()));
        });

        // Wait until the client has attempted is first read.
        barrier.wait();
        // Wait until the server has written some data.
        barrier.wait();
        // Wait until the client has done is second read.
        barrier.wait();
        stream_canceller.cancel().unwrap();
        // Tell the client it can attempt reading again.
        barrier.wait();

        client.join().unwrap();
        server.join().unwrap();
    }

    #[test]
    fn test_udp() {
        let barrier = Arc::new(Barrier::new(3));
        let (socket1, canceller1) = UdpSocket::bind("127.0.0.1:0").unwrap();
        let (socket2, canceller2) = UdpSocket::bind("127.0.0.1:0").unwrap();
        let address1 = socket1.local_addr().unwrap();
        let address2 = socket2.local_addr().unwrap();
        let barrier1 = barrier.clone();
        let barrier2 = barrier.clone();
        let thread1 = thread::spawn(move || {
            let mut buf = [0; 16];
            assert_eq!(socket1.recv_from(&mut buf).unwrap(), (3, address2));
            assert_eq!(socket1.send_to(b"bar", &address2).unwrap(), 3);
            barrier1.wait();
            assert!(is_cancelled(&socket1.recv_from(&mut buf).unwrap_err()));
        });
        let thread2 = thread::spawn(move || {
            assert_eq!(socket2.send_to(b"foo", &address1).unwrap(), 3);
            let mut buf = [0; 16];
            assert_eq!(socket2.recv_from(&mut buf).unwrap(), (3, address1));
            barrier2.wait();
            assert!(is_cancelled(&socket2.recv_from(&mut buf).unwrap_err()));
        });
        barrier.wait();
        canceller1.cancel().unwrap();
        canceller2.cancel().unwrap();
        thread1.join().unwrap();
        thread2.join().unwrap();
    }

    /* TcpListener is !Sync.
    #[test]
    fn test_sync() {
        let listener = Arc::new(TcpListener::bind("127.0.0.1:0").unwrap().0);
        let listener2 = listener.clone();
        let t = thread::spawn(move|| {
            listener.accept().unwrap();
        });
        listener2.accept().unwrap();
        t.join().unwrap();
    }*/
}