Skip to content

Commit 7b3d143

Browse files
committed
feat: Ok returned bytes_written
1 parent 58c44ae commit 7b3d143

File tree

2 files changed

+26
-11
lines changed

2 files changed

+26
-11
lines changed

README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
### Basic example
77

88
```rust
9-
let _ = raw_printer::write_to_device("/dev/usb/lp0", "^FDhello world");
9+
let bytes_written = raw_printer::write_to_device("/dev/usb/lp0", "^FDhello world");
10+
11+
println!("wrote {} bytes", bytes_written);
1012

1113
```
1214

src/lib.rs

+23-10
Original file line numberDiff line numberDiff line change
@@ -17,27 +17,41 @@ mod tests {
1717
}
1818
}
1919

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+
/// ```
2037
#[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> {
2239
use std::fs::OpenOptions;
2340
use std::io::Write;
2441

2542
let device_path = OpenOptions::new().write(true).open(printer);
2643

2744
match device_path {
2845
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)
3148
}
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)),
3650
}
3751
}
3852

3953
#[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> {
4155
use std::ffi::CString;
4256
use std::ptr;
4357
use windows::Win32::Foundation::HANDLE;
@@ -99,10 +113,9 @@ pub fn write_to_device(printer: &str, payload: &str) -> Result<(), std::io::Erro
99113
EndPagePrinter(printer_handle);
100114
EndDocPrinter(printer_handle);
101115
let _ = ClosePrinter(printer_handle);
116+
return Ok(bytes_written as usize);
102117
} else {
103118
return Err(std::io::Error::from(windows::core::Error::from_win32()));
104119
}
105120
}
106-
107-
Ok(())
108121
}

0 commit comments

Comments
 (0)