This repository has been archived by the owner on Aug 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathlib.rs
1734 lines (1566 loc) · 51.7 KB
/
lib.rs
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
// Copyright (c) 2015-2016 Anatoly Ikorsky
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
//! Named-Pipe is a wrapper for overlapped (asyncronous) IO of Windows's named pipes.
//!
//! # Description
//!
//! You can use `wait` or `wait_all` to *select(2)*-like wait for multiple pending IO operations
//! (which is read/write from/to `PipeServer`/`PipeClient` or waiting for new client).
//!
//! Or you can use `ConnectingServer::wait` or `io::Read` and `io::Write` implementaions for
//! `PipeServer` and `PipeClient` for syncronous communication.
//!
//! For better understanding please refer to [Named Pipes documentation on MSDN]
//! (https://www.google.com/search?q=msdn+named+pipes&ie=utf-8&oe=utf-8).
//!
//! # Usage
//!
//! To create new pipe instance use [`PipeOptions`](struct.PipeOptions.html) structure.
//!
//! To connect to a pipe server use [`PipeClient`](struct.PipeClient.html) structure.
use winapi::{
ctypes::*,
shared::{minwindef::*, ntdef::HANDLE, winerror::*},
um::{
errhandlingapi::*, fileapi::*, handleapi::*, ioapiset::*, minwinbase::*, namedpipeapi::*,
synchapi::*, winbase::*, winnt::*,
},
};
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::io;
use std::marker::PhantomData;
use std::mem;
use std::os::windows::ffi::OsStrExt;
use std::ptr;
use std::sync::Arc;
use std::time::Duration;
#[derive(Debug)]
struct Handle {
value: HANDLE,
}
impl Drop for Handle {
fn drop(&mut self) {
let _ = unsafe { CloseHandle(self.value) };
}
}
unsafe impl Sync for Handle {}
unsafe impl Send for Handle {}
#[derive(Debug)]
struct Event {
handle: Handle,
}
impl Event {
fn new() -> io::Result<Event> {
let handle = unsafe { CreateEventW(ptr::null_mut(), 1, 0, ptr::null()) };
if handle != ptr::null_mut() {
Ok(Event {
handle: Handle { value: handle },
})
} else {
Err(io::Error::last_os_error())
}
}
fn reset(&self) -> io::Result<()> {
let result = unsafe { ResetEvent(self.handle.value) };
if result != 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
fn set(&self) -> io::Result<()> {
let result = unsafe { SetEvent(self.handle.value) };
if result != 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
}
struct Overlapped {
ovl: Box<OVERLAPPED>,
event: Event,
}
impl fmt::Debug for Overlapped {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Overlapped")
.field("ovl", &"OVERLAPPED")
.field("event", &self.event)
.finish()
}
}
unsafe impl Send for Overlapped {}
unsafe impl Sync for Overlapped {}
impl Overlapped {
fn new() -> io::Result<Overlapped> {
let event = Event::new()?;
let mut ovl: Box<OVERLAPPED> = Box::new(unsafe { mem::zeroed() });
ovl.hEvent = event.handle.value;
Ok(Overlapped {
ovl: ovl,
event: event,
})
}
fn clear(&mut self) -> io::Result<()> {
self.event.reset()?;
self.ovl = Box::new(unsafe { mem::zeroed() });
self.ovl.hEvent = self.event.handle.value;
Ok(())
}
fn get_mut(&mut self) -> &mut OVERLAPPED {
&mut self.ovl
}
}
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum OpenMode {
/// Read only pipe instance
Read,
/// Write only pipe instance
Write,
/// Read-write pipe instance
Duplex,
}
impl OpenMode {
fn val(&self) -> u32 {
match self {
&OpenMode::Read => PIPE_ACCESS_INBOUND,
&OpenMode::Write => PIPE_ACCESS_OUTBOUND,
&OpenMode::Duplex => PIPE_ACCESS_DUPLEX,
}
}
}
/// Options and flags which can be used to configure how a pipe is created.
///
/// This builder exposes the ability to configure how a `ConnectingServer` is created.
///
/// Builder defaults:
///
/// - **open_mode** - `Duplex`
/// - **in_buffer** - 65536
/// - **out_buffer** - 65536
/// - **first** - true
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct PipeOptions {
name: Arc<Vec<u16>>,
open_mode: OpenMode,
out_buffer: u32,
in_buffer: u32,
first: bool,
}
impl PipeOptions {
fn create_named_pipe(&self, first: bool) -> io::Result<Handle> {
let handle = unsafe {
CreateNamedPipeW(
self.name.as_ptr(),
self.open_mode.val()
| FILE_FLAG_OVERLAPPED
| if first {
FILE_FLAG_FIRST_PIPE_INSTANCE
} else {
0
},
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
self.out_buffer,
self.in_buffer,
0,
ptr::null_mut(),
)
};
if handle != INVALID_HANDLE_VALUE {
Ok(Handle { value: handle })
} else {
Err(io::Error::last_os_error())
}
}
pub fn new<T: AsRef<OsStr>>(name: T) -> PipeOptions {
let mut full_name: OsString = name.as_ref().into();
full_name.push("\x00");
let full_name = full_name.encode_wide().collect::<Vec<u16>>();
PipeOptions {
name: Arc::new(full_name),
open_mode: OpenMode::Duplex,
out_buffer: 65536,
in_buffer: 65536,
first: true,
}
}
/// Is this instance (or instances) will be first for this pipe name? Defaults to `true`.
pub fn first(&mut self, val: bool) -> &mut PipeOptions {
self.first = val;
self
}
/// Open mode for pipe instance. Defaults to `Duplex`.
pub fn open_mode(&mut self, val: OpenMode) -> &mut PipeOptions {
self.open_mode = val;
self
}
/// Input buffer size for pipe instance. Defaults to 65536
pub fn in_buffer(&mut self, val: u32) -> &mut PipeOptions {
self.in_buffer = val;
self
}
/// Output buffer size for pipe instance. Defaults to 65536.
pub fn out_buffer(&mut self, val: u32) -> &mut PipeOptions {
self.out_buffer = val;
self
}
/// Creates single instance of pipe with this options.
pub fn single(&self) -> io::Result<ConnectingServer> {
let mut pipes = self.multiple(1)?;
match pipes.pop() {
Some(pipe) => Ok(pipe),
None => unreachable!(),
}
}
/// Creates multiple instances of pipe with this options.
pub fn multiple(&self, num: u32) -> io::Result<Vec<ConnectingServer>> {
if num == 0 {
return Ok(Vec::new());
}
let mut out = Vec::with_capacity(num as usize);
let mut first = self.first;
for _ in 0..num {
let handle = self.create_named_pipe(first)?;
first = false;
let mut ovl = Overlapped::new()?;
let pending = connect_named_pipe(&handle, &mut ovl)?;
out.push(ConnectingServer {
handle: handle,
ovl: ovl,
pending: pending,
});
}
Ok(out)
}
}
/// Pipe instance waiting for new client. Can be used with [`wait`](fn.wait.html) and [`wait_all`]
/// (fn.wait_all.html) functions.
#[derive(Debug)]
pub struct ConnectingServer {
handle: Handle,
ovl: Overlapped,
pending: bool,
}
impl ConnectingServer {
/// Waites for client infinitely.
pub fn wait(self) -> io::Result<PipeServer> {
match self.wait_ms(INFINITE)? {
Ok(pipe_server) => Ok(pipe_server),
Err(_) => unreachable!(),
}
}
/// Waites for client. Note that `timeout` 0xFFFFFFFF stands for infinite waiting.
pub fn wait_ms(mut self, timeout: u32) -> io::Result<Result<PipeServer, ConnectingServer>> {
if self.pending {
match wait_for_single_obj(&mut self, timeout)? {
Some(_) => {
let mut dummy = 0;
get_ovl_result(&mut self, &mut dummy)?;
self.pending = false;
}
None => return Ok(Err(self)),
}
}
let ConnectingServer {
handle, mut ovl, ..
} = self;
ovl.clear()?;
Ok(Ok(PipeServer {
handle: Some(handle),
ovl: Some(ovl),
read_timeout: None,
write_timeout: None,
}))
}
}
/// Pipe server connected to a client.
#[derive(Debug)]
pub struct PipeServer {
handle: Option<Handle>,
ovl: Option<Overlapped>,
read_timeout: Option<u32>,
write_timeout: Option<u32>,
}
impl PipeServer {
/// This function will flush buffers and disconnect server from client. Then will start waiting
/// for a new client.
pub fn disconnect(mut self) -> io::Result<ConnectingServer> {
let handle = self.handle.take().unwrap();
let mut ovl = self.ovl.take().unwrap();
let mut result = unsafe { FlushFileBuffers(handle.value) };
if result != 0 {
result = unsafe { DisconnectNamedPipe(handle.value) };
if result != 0 {
ovl.clear()?;
let pending = connect_named_pipe(&handle, &mut ovl)?;
Ok(ConnectingServer {
handle: handle,
ovl: ovl,
pending: pending,
})
} else {
Err(io::Error::last_os_error())
}
} else {
Err(io::Error::last_os_error())
}
}
/// Initializes asyncronous read opeation.
///
/// # Unsafety
/// It's unsafe to leak returned handle because read operation should be cancelled
/// by handle's destructor to not to write into `buf` that may be deallocated.
unsafe fn read_async<'a, 'b: 'a>(
&'a mut self,
buf: &'b mut [u8],
) -> io::Result<ReadHandle<'a, Self>> {
init_read(self, buf)
}
/// Initializes asyncronous read operation and takes ownership of buffer and server.
pub fn read_async_owned(self, buf: Vec<u8>) -> io::Result<ReadHandle<'static, Self>> {
init_read_owned(self, buf)
}
/// Initializes asyncronous write operation.
///
/// # Unsafety
/// It's unsafe to leak returned handle because write operation should be cancelled
/// by handle's destructor to not to read from `buf` that may be deallocated.
unsafe fn write_async<'a, 'b: 'a>(
&'a mut self,
buf: &'b [u8],
) -> io::Result<WriteHandle<'a, Self>> {
init_write(self, buf)
}
/// Initializes asyncronous write operation and takes ownership of buffer and server.
pub fn write_async_owned(self, buf: Vec<u8>) -> io::Result<WriteHandle<'static, Self>> {
init_write_owned(self, buf)
}
/// Allows you to set read timeout in milliseconds.
///
/// Note that zero value will return immediately and 0xFFFFFFFF will wait forever. Also note
/// that nanos will be ignored and also if number of milliseconds is greater than 0xFFFFFFFF
/// then it will write 0xFFFFFFFF as a timeout value.
///
/// Defaults to None (infinite).
pub fn set_read_timeout(&mut self, read_timeout: Option<Duration>) {
self.read_timeout = read_timeout.map(|dur| {
let val = dur.as_millis();
if val > 0xFFFFFFFF {
0xFFFFFFFF
} else {
val as u32
}
});
}
/// Allows you to set write timeout in milliseconds.
///
/// Note that zero value will return immediately and 0xFFFFFFFF will wait forever.Also note
/// that nanos will be ignored and also if number of milliseconds is greater than 0xFFFFFFFF
/// then it will write 0xFFFFFFFF as a timeout value.
///
/// Defaults to None (infinite).
pub fn set_write_timeout(&mut self, write_timeout: Option<Duration>) {
self.write_timeout = write_timeout.map(|dur| {
let val = dur.as_millis();
if val > 0xFFFFFFFF {
0xFFFFFFFF
} else {
val as u32
}
});
}
pub fn get_read_timeout(&self) -> Option<Duration> {
self.read_timeout
.clone()
.map(|millis| Duration::from_millis(millis as u64))
}
pub fn get_write_timeout(&self) -> Option<Duration> {
self.write_timeout
.clone()
.map(|millis| Duration::from_millis(millis as u64))
}
fn get_read_timeout_ms(&self) -> Option<u32> {
self.read_timeout.clone()
}
fn get_write_timeout_ms(&self) -> Option<u32> {
self.write_timeout.clone()
}
}
impl io::Read for PipeServer {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let read_handle = unsafe { self.read_async(buf) };
let result = read_handle
.and_then(|read_handle| read_handle.wait())
.map(|x| x.0);
match result {
Ok(x) => Ok(x),
Err(err) => {
if err.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
Ok(0)
} else {
Err(err)
}
}
}
}
}
impl io::Write for PipeServer {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let write_handle = unsafe { self.write_async(buf) };
write_handle
.and_then(|write_handle| write_handle.wait())
.map(|x| x.0)
}
fn flush(&mut self) -> io::Result<()> {
match self.handle {
Some(ref handle) => {
let result = unsafe { FlushFileBuffers(handle.value) };
if result != 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
None => unreachable!(),
}
}
}
impl Drop for PipeServer {
fn drop(&mut self) {
if let Some(ref handle) = self.handle {
let _ = unsafe { FlushFileBuffers(handle.value) };
let _ = unsafe { DisconnectNamedPipe(handle.value) };
}
}
}
/// Pipe client connected to a server.
#[derive(Debug)]
pub struct PipeClient {
handle: Handle,
ovl: Overlapped,
read_timeout: Option<u32>,
write_timeout: Option<u32>,
}
impl PipeClient {
fn create_file(name: &Vec<u16>, mode: DWORD) -> io::Result<Handle> {
loop {
let handle = unsafe {
CreateFileW(
name.as_ptr(),
mode,
0,
ptr::null_mut(),
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
ptr::null_mut(),
)
};
if handle != INVALID_HANDLE_VALUE {
return Ok(Handle { value: handle });
}
match unsafe { GetLastError() } {
ERROR_PIPE_BUSY => {
unsafe { WaitNamedPipeW(name.as_ptr(), 0) };
}
ERROR_ACCESS_DENIED => match mode {
mode if mode == (GENERIC_READ | GENERIC_WRITE) => {
return PipeClient::create_file(name, GENERIC_READ | FILE_WRITE_ATTRIBUTES);
}
mode if mode == (GENERIC_READ | FILE_WRITE_ATTRIBUTES) => {
return PipeClient::create_file(name, GENERIC_WRITE | FILE_READ_ATTRIBUTES);
}
_ => {
return Err(io::Error::last_os_error());
}
},
_ => {
return Err(io::Error::last_os_error());
}
}
}
}
/// Will wait for server infinitely.
pub fn connect<T: AsRef<OsStr>>(name: T) -> io::Result<PipeClient> {
PipeClient::connect_ms(name, 0xFFFFFFFF)
}
/// Will wait for server. Note that `timeout` 0xFFFFFFFF stands for infinite waiting.
pub fn connect_ms<T: AsRef<OsStr>>(name: T, timeout: u32) -> io::Result<PipeClient> {
let mut full_name: OsString = name.as_ref().into();
full_name.push("\x00");
let full_name = full_name.encode_wide().collect::<Vec<u16>>();
let mut waited = false;
loop {
match PipeClient::create_file(&full_name, GENERIC_READ | GENERIC_WRITE) {
Ok(handle) => {
let result = unsafe {
let mut mode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT;
SetNamedPipeHandleState(
handle.value,
&mut mode,
ptr::null_mut(),
ptr::null_mut(),
)
};
if result != 0 {
return Ok(PipeClient {
handle: handle,
ovl: Overlapped::new()?,
read_timeout: None,
write_timeout: None,
});
} else {
return Err(io::Error::last_os_error());
}
}
Err(err) => {
if err.raw_os_error().unwrap() == ERROR_PIPE_BUSY as i32 {
if !waited {
waited = true;
let result = unsafe { WaitNamedPipeW(full_name.as_ptr(), timeout) };
if result == 0 {
return Err(err);
}
} else {
return Err(err);
}
} else {
return Err(err);
}
}
}
}
}
/// Initializes asyncronous read operation.
///
/// # Unsafety
/// It's unsafe to leak returned handle because write operation should be cancelled
/// by handle's destructor to not to write into `buf` that may be deallocated.
unsafe fn read_async<'a, 'b: 'a>(
&'a mut self,
buf: &'b mut [u8],
) -> io::Result<ReadHandle<'a, Self>> {
init_read(self, buf)
}
/// Initializes asyncronous read operation and takes ownership of buffer and client.
pub fn read_async_owned(self, buf: Vec<u8>) -> io::Result<ReadHandle<'static, Self>> {
init_read_owned(self, buf)
}
/// Initializes asyncronous write operation.
///
/// # Unsafety
/// It's unsafe to leak returned handle because write operation should be cancelled
/// by handle's destructor to not to read from `buf` that may be deallocated.
unsafe fn write_async<'a, 'b: 'a>(
&'a mut self,
buf: &'b [u8],
) -> io::Result<WriteHandle<'a, Self>> {
init_write(self, buf)
}
/// Initializes asyncronous write operation and takes ownership of buffer and client.
pub fn write_async_owned(self, buf: Vec<u8>) -> io::Result<WriteHandle<'static, Self>> {
init_write_owned(self, buf)
}
/// Allows you to set read timeout in milliseconds.
///
/// Note that zero value will return immediately and 0xFFFFFFFF will wait forever. Also note
/// that nanos will be ignored and also if number of milliseconds is greater than 0xFFFFFFFF
/// then it will write 0xFFFFFFFF as a timeout value.
///
/// Defaults to None (infinite).
pub fn set_read_timeout(&mut self, read_timeout: Option<Duration>) {
self.read_timeout = read_timeout.map(|dur| {
let val = dur.as_millis();
if val > 0xFFFFFFFF {
0xFFFFFFFF
} else {
val as u32
}
});
}
/// Allows you to set write timeout in milliseconds.
///
/// Note that zero value will return immediately and 0xFFFFFFFF will wait forever.Also note
/// that nanos will be ignored and also if number of milliseconds is greater than 0xFFFFFFFF
/// then it will write 0xFFFFFFFF as a timeout value.
///
/// Defaults to None (infinite).
pub fn set_write_timeout(&mut self, write_timeout: Option<Duration>) {
self.write_timeout = write_timeout.map(|dur| {
let val = dur.as_millis();
if val > 0xFFFFFFFF {
0xFFFFFFFF
} else {
val as u32
}
});
}
pub fn get_read_timeout(&self) -> Option<Duration> {
self.read_timeout
.clone()
.map(|millis| Duration::from_millis(millis as u64))
}
pub fn get_write_timeout(&self) -> Option<Duration> {
self.write_timeout
.clone()
.map(|millis| Duration::from_millis(millis as u64))
}
fn get_read_timeout_ms(&self) -> Option<u32> {
self.read_timeout.clone()
}
fn get_write_timeout_ms(&self) -> Option<u32> {
self.write_timeout.clone()
}
}
unsafe impl Send for PipeClient {}
impl io::Read for PipeClient {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let read_handle = unsafe { self.read_async(buf) };
read_handle
.and_then(|read_handle| read_handle.wait())
.map(|x| x.0)
}
}
impl io::Write for PipeClient {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let write_handle = unsafe { self.write_async(buf) };
write_handle
.and_then(|write_handle| write_handle.wait())
.map(|x| x.0)
}
fn flush(&mut self) -> io::Result<()> {
let result = unsafe { FlushFileBuffers(self.handle.value) };
if result != 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
}
#[derive(Debug)]
pub struct PipeIoObj<'a> {
handle: HANDLE,
ovl: &'a mut Overlapped,
}
#[allow(dead_code)]
#[derive(Debug)]
pub struct PipeIoHandles<'a> {
pipe_handle: HANDLE,
event_handle: HANDLE,
_phantom: PhantomData<&'a ()>,
}
/// This trait used for genericity.
pub trait PipeIo {
fn io_obj<'a>(&'a mut self) -> PipeIoObj<'a>;
fn io_handles<'a>(&'a self) -> PipeIoHandles<'a>;
fn get_read_timeout(&self) -> Option<u32>;
fn get_write_timeout(&self) -> Option<u32>;
}
impl PipeIo for PipeServer {
fn io_obj<'a>(&'a mut self) -> PipeIoObj<'a> {
let raw_handle = match self.handle {
Some(ref handle) => handle.value,
None => unreachable!(),
};
let ovl = match self.ovl {
Some(ref mut ovl) => ovl,
None => unreachable!(),
};
PipeIoObj {
handle: raw_handle,
ovl: ovl,
}
}
fn io_handles<'a>(&'a self) -> PipeIoHandles<'a> {
let pipe_handle = match self.handle {
Some(ref handle) => handle.value,
None => unreachable!(),
};
let event_handle = match self.ovl {
Some(ref ovl) => ovl.ovl.hEvent,
None => unreachable!(),
};
PipeIoHandles {
pipe_handle: pipe_handle,
event_handle: event_handle,
_phantom: PhantomData,
}
}
fn get_read_timeout(&self) -> Option<u32> {
Self::get_read_timeout_ms(self)
}
fn get_write_timeout(&self) -> Option<u32> {
Self::get_write_timeout_ms(self)
}
}
impl PipeIo for PipeClient {
fn io_obj<'a>(&'a mut self) -> PipeIoObj<'a> {
PipeIoObj {
handle: self.handle.value,
ovl: &mut self.ovl,
}
}
fn io_handles<'a>(&'a self) -> PipeIoHandles<'a> {
PipeIoHandles {
pipe_handle: self.handle.value,
event_handle: self.ovl.ovl.hEvent,
_phantom: PhantomData,
}
}
fn get_read_timeout(&self) -> Option<u32> {
Self::get_read_timeout_ms(self)
}
fn get_write_timeout(&self) -> Option<u32> {
Self::get_write_timeout_ms(self)
}
}
impl<'a, T: PipeIo> PipeIo for ReadHandle<'a, T> {
fn io_obj<'b>(&'b mut self) -> PipeIoObj<'b> {
match self.io {
Some(ref mut io) => return io.io_obj(),
_ => (),
}
match self.io_ref {
Some(ref mut io) => return io.io_obj(),
_ => (),
}
unreachable!();
}
fn io_handles<'b>(&'b self) -> PipeIoHandles<'b> {
match self.io {
Some(ref io) => return io.io_handles(),
_ => (),
}
match self.io_ref {
Some(ref io) => return io.io_handles(),
_ => (),
}
unreachable!();
}
fn get_read_timeout(&self) -> Option<u32> {
match self.io {
Some(ref io) => return io.get_read_timeout(),
_ => (),
}
match self.io_ref {
Some(ref io) => return io.get_read_timeout(),
_ => (),
}
unreachable!();
}
fn get_write_timeout(&self) -> Option<u32> {
match self.io {
Some(ref io) => return io.get_write_timeout(),
_ => (),
}
match self.io_ref {
Some(ref io) => return io.get_write_timeout(),
_ => (),
}
unreachable!();
}
}
impl<'a, T: PipeIo> PipeIo for WriteHandle<'a, T> {
fn io_obj<'b>(&'b mut self) -> PipeIoObj<'b> {
match self.io {
Some(ref mut io) => return io.io_obj(),
_ => (),
}
match self.io_ref {
Some(ref mut io) => return io.io_obj(),
_ => (),
}
unreachable!();
}
fn io_handles<'b>(&'b self) -> PipeIoHandles<'b> {
match self.io {
Some(ref io) => return io.io_handles(),
_ => (),
}
match self.io_ref {
Some(ref io) => return io.io_handles(),
_ => (),
}
unreachable!();
}
fn get_read_timeout(&self) -> Option<u32> {
match self.io {
Some(ref io) => return io.get_read_timeout(),
_ => (),
}
match self.io_ref {
Some(ref io) => return io.get_read_timeout(),
_ => (),
}
unreachable!();
}
fn get_write_timeout(&self) -> Option<u32> {
match self.io {
Some(ref io) => return io.get_write_timeout(),
_ => (),
}
match self.io_ref {
Some(ref io) => return io.get_write_timeout(),
_ => (),
}
unreachable!();
}
}
impl PipeIo for ConnectingServer {
fn io_obj<'a>(&'a mut self) -> PipeIoObj<'a> {
PipeIoObj {
handle: self.handle.value,
ovl: &mut self.ovl,
}
}
fn io_handles<'a>(&'a self) -> PipeIoHandles<'a> {
PipeIoHandles {
pipe_handle: self.handle.value,
event_handle: self.ovl.ovl.hEvent,
_phantom: PhantomData,
}
}
fn get_read_timeout(&self) -> Option<u32> {
None
}
fn get_write_timeout(&self) -> Option<u32> {
None
}
}
/// Pending read operation. Can be used with [`wait`](fn.wait.html) and [`wait_all`]
/// (fn.wait_all.html) functions.
pub struct ReadHandle<'a, T: PipeIo> {
io: Option<T>,
io_ref: Option<&'a mut dyn PipeIo>,
bytes_read: u32,
pending: bool,
buffer: Option<Vec<u8>>,
}
impl<'a, T: fmt::Debug + PipeIo> fmt::Debug for ReadHandle<'a, T> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.io_ref {
Some(ref io) => fmt
.debug_struct("ReadHandle")
.field("io", &self.io)
.field("io_ref", &io.io_handles())
.field("bytes_read", &self.bytes_read)
.field("pending", &self.pending)
.field("buffer", &self.buffer)
.finish(),
None => fmt
.debug_struct("ReadHandle")
.field("io", &self.io)
.field("io_ref", &"None")
.field("bytes_read", &self.bytes_read)
.field("pending", &self.pending)
.field("buffer", &self.buffer)
.finish(),
}
}
}
impl<'a, T: PipeIo> Drop for ReadHandle<'a, T> {
fn drop(&mut self) {
let timeout = self.get_read_timeout().unwrap_or(INFINITE);
if self.pending && timeout > 0 {
let result = unsafe {
let io_obj = self.io_obj();
CancelIoEx(io_obj.handle, &mut *io_obj.ovl.ovl)
};
if result == FALSE {
let error = io::Error::last_os_error();
match error.raw_os_error().unwrap() as u32 {
ERROR_IO_PENDING => (/* OK */),
_ => panic!("CANCEL ERROR {:?}", error),
}
}
}
}
}
impl<'a, T: PipeIo> ReadHandle<'a, T> {
fn wait_impl(&mut self) -> io::Result<()> {
if self.pending {
let timeout = self.get_read_timeout().unwrap_or(INFINITE);
match wait_for_single_obj(self, timeout)? {
Some(_) => {
let mut count = 0;
self.pending = false;
match get_ovl_result(self, &mut count)? {
0 => Err(io::Error::last_os_error()),
_ => {
self.bytes_read = count;
Ok(())
}
}
}
None => Err(io::Error::new(
io::ErrorKind::TimedOut,
"timed out while reading from pipe",
)),