@@ -17,27 +17,41 @@ mod tests {
17
17
}
18
18
}
19
19
20
+ /// # Platform-specific Behavior
21
+ ///
22
+ /// This function returns a result containing the size of bytes written on success or an error.
23
+ ///
24
+ /// - On Linux and Windows, the result type is `Result<usize, Error>`.
25
+ /// - Note: On Windows, the original bytes written are u32 but cast to usize.
26
+ ///
27
+ /// # Examples
28
+ ///
29
+ /// ```
30
+ /// let zpl = "^FDhello world";
31
+ /// let printer = "/dev/usb/lp0";
32
+ /// let result = raw_printer::write_to_device(printer, zpl);
33
+ ///
34
+ /// assert!(result.is_ok());
35
+ ///
36
+ /// ```
20
37
#[ cfg( target_os = "linux" ) ]
21
- pub fn write_to_device ( printer : & str , payload : & str ) -> Result < ( ) , std:: io:: Error > {
38
+ pub fn write_to_device ( printer : & str , payload : & str ) -> Result < usize , std:: io:: Error > {
22
39
use std:: fs:: OpenOptions ;
23
40
use std:: io:: Write ;
24
41
25
42
let device_path = OpenOptions :: new ( ) . write ( true ) . open ( printer) ;
26
43
27
44
match device_path {
28
45
Ok ( mut device) => {
29
- let _ = device. write ( payload. as_bytes ( ) ) ?;
30
- Ok ( ( ) )
46
+ let bytes_written = device. write ( payload. as_bytes ( ) ) ?;
47
+ Ok ( bytes_written )
31
48
}
32
- Err ( _) => Err ( std:: io:: Error :: new (
33
- std:: io:: ErrorKind :: Other ,
34
- "Failed to open device" ,
35
- ) ) ,
49
+ Err ( e) => Err ( std:: io:: Error :: new ( std:: io:: ErrorKind :: Other , e) ) ,
36
50
}
37
51
}
38
52
39
53
#[ cfg( target_os = "windows" ) ]
40
- pub fn write_to_device ( printer : & str , payload : & str ) -> Result < ( ) , std:: io:: Error > {
54
+ pub fn write_to_device ( printer : & str , payload : & str ) -> Result < usize , std:: io:: Error > {
41
55
use std:: ffi:: CString ;
42
56
use std:: ptr;
43
57
use windows:: Win32 :: Foundation :: HANDLE ;
@@ -99,10 +113,9 @@ pub fn write_to_device(printer: &str, payload: &str) -> Result<(), std::io::Erro
99
113
EndPagePrinter ( printer_handle) ;
100
114
EndDocPrinter ( printer_handle) ;
101
115
let _ = ClosePrinter ( printer_handle) ;
116
+ return Ok ( bytes_written as usize ) ;
102
117
} else {
103
118
return Err ( std:: io:: Error :: from ( windows:: core:: Error :: from_win32 ( ) ) ) ;
104
119
}
105
120
}
106
-
107
- Ok ( ( ) )
108
121
}
0 commit comments