Skip to content

Commit

Permalink
feat: Ok returned bytes_written
Browse files Browse the repository at this point in the history
  • Loading branch information
mushonnip committed Nov 13, 2023
1 parent 58c44ae commit 7b3d143
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 11 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
### Basic example

```rust
let _ = raw_printer::write_to_device("/dev/usb/lp0", "^FDhello world");
let bytes_written = raw_printer::write_to_device("/dev/usb/lp0", "^FDhello world");

println!("wrote {} bytes", bytes_written);

```

Expand Down
33 changes: 23 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,41 @@ mod tests {
}
}

/// # Platform-specific Behavior
///
/// This function returns a result containing the size of bytes written on success or an error.
///
/// - On Linux and Windows, the result type is `Result<usize, Error>`.
/// - Note: On Windows, the original bytes written are u32 but cast to usize.
///
/// # Examples
///
/// ```
/// let zpl = "^FDhello world";
/// let printer = "/dev/usb/lp0";
/// let result = raw_printer::write_to_device(printer, zpl);
///
/// assert!(result.is_ok());
///
/// ```
#[cfg(target_os = "linux")]
pub fn write_to_device(printer: &str, payload: &str) -> Result<(), std::io::Error> {
pub fn write_to_device(printer: &str, payload: &str) -> Result<usize, std::io::Error> {
use std::fs::OpenOptions;
use std::io::Write;

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

match device_path {
Ok(mut device) => {
let _ = device.write(payload.as_bytes())?;
Ok(())
let bytes_written = device.write(payload.as_bytes())?;
Ok(bytes_written)
}
Err(_) => Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Failed to open device",
)),
Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
}
}

#[cfg(target_os = "windows")]
pub fn write_to_device(printer: &str, payload: &str) -> Result<(), std::io::Error> {
pub fn write_to_device(printer: &str, payload: &str) -> Result<usize, std::io::Error> {
use std::ffi::CString;
use std::ptr;
use windows::Win32::Foundation::HANDLE;
Expand Down Expand Up @@ -99,10 +113,9 @@ pub fn write_to_device(printer: &str, payload: &str) -> Result<(), std::io::Erro
EndPagePrinter(printer_handle);
EndDocPrinter(printer_handle);
let _ = ClosePrinter(printer_handle);
return Ok(bytes_written as usize);
} else {
return Err(std::io::Error::from(windows::core::Error::from_win32()));
}
}

Ok(())
}

0 comments on commit 7b3d143

Please sign in to comment.