rawfile.rs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. use alloc::Vec;
  2. use core::ops::Deref;
  3. use super::{types::*, Pal, Sys};
  4. use c_str::CStr;
  5. use header::fcntl;
  6. pub struct RawFile(c_int);
  7. impl RawFile {
  8. pub fn open(path: &CStr, oflag: c_int, mode: mode_t) -> Result<RawFile, ()> {
  9. match Sys::open(path, oflag, mode) {
  10. -1 => Err(()),
  11. n => Ok(RawFile(n)),
  12. }
  13. }
  14. pub fn dup(&self) -> Result<RawFile, ()> {
  15. match Sys::dup(self.0) {
  16. -1 => Err(()),
  17. n => Ok(RawFile(n)),
  18. }
  19. }
  20. pub fn as_raw_fd(&self) -> c_int {
  21. self.0
  22. }
  23. pub fn into_raw_fd(self) -> c_int {
  24. self.0
  25. }
  26. pub fn from_raw_fd(fd: c_int) -> Self {
  27. RawFile(fd)
  28. }
  29. }
  30. impl Drop for RawFile {
  31. fn drop(&mut self) {
  32. let _ = Sys::close(self.0);
  33. }
  34. }
  35. impl Deref for RawFile {
  36. type Target = c_int;
  37. fn deref(&self) -> &c_int {
  38. &self.0
  39. }
  40. }
  41. pub fn file_read_all(path: &CStr) -> Result<Vec<u8>, ()> {
  42. let file = RawFile::open(path, fcntl::O_RDONLY, 0)?;
  43. let mut buf = Vec::new();
  44. let mut len = 0;
  45. loop {
  46. if len >= buf.capacity() {
  47. buf.reserve(32);
  48. unsafe {
  49. let capacity = buf.capacity();
  50. buf.set_len(capacity);
  51. }
  52. }
  53. let read = Sys::read(*file, &mut buf[len..]);
  54. len += read as usize;
  55. if read == 0 {
  56. unsafe {
  57. buf.set_len(len);
  58. }
  59. return Ok(buf);
  60. }
  61. if read < 0 {
  62. unsafe {
  63. buf.set_len(len);
  64. }
  65. return Err(());
  66. }
  67. }
  68. }