CIODevice.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #pragma once
  2. #include <AK/ByteBuffer.h>
  3. #include <AK/StringView.h>
  4. #include <LibCore/CObject.h>
  5. class CIODevice : public CObject {
  6. C_OBJECT(CIODevice)
  7. public:
  8. enum OpenMode {
  9. NotOpen = 0,
  10. ReadOnly = 1,
  11. WriteOnly = 2,
  12. ReadWrite = 3,
  13. Append = 4,
  14. Truncate = 8,
  15. MustBeNew = 16,
  16. };
  17. virtual ~CIODevice() override;
  18. int fd() const { return m_fd; }
  19. unsigned mode() const { return m_mode; }
  20. bool is_open() const { return m_mode != NotOpen; }
  21. bool eof() const { return m_eof; }
  22. int error() const { return m_error; }
  23. const char* error_string() const;
  24. bool has_error() const { return m_error != 0; }
  25. int read(u8* buffer, int length);
  26. ByteBuffer read(int max_size);
  27. ByteBuffer read_line(int max_size);
  28. ByteBuffer read_all();
  29. bool write(const u8*, int size);
  30. bool write(const StringView& v) { return write((const u8*)v.characters_without_null_termination(), v.length()); }
  31. // FIXME: I would like this to be const but currently it needs to call populate_read_buffer().
  32. bool can_read_line();
  33. bool can_read() const;
  34. enum class SeekMode {
  35. SetPosition,
  36. FromCurrentPosition,
  37. FromEndPosition,
  38. };
  39. bool seek(i64, SeekMode = SeekMode::SetPosition, off_t* = nullptr);
  40. virtual bool open(CIODevice::OpenMode) = 0;
  41. virtual bool close();
  42. int printf(const char*, ...);
  43. protected:
  44. explicit CIODevice(CObject* parent = nullptr);
  45. void set_fd(int);
  46. void set_mode(OpenMode mode) { m_mode = mode; }
  47. void set_error(int error) { m_error = error; }
  48. void set_eof(bool eof) { m_eof = eof; }
  49. virtual void did_update_fd(int) {}
  50. private:
  51. bool populate_read_buffer();
  52. bool can_read_from_fd() const;
  53. int m_fd { -1 };
  54. int m_error { 0 };
  55. bool m_eof { false };
  56. OpenMode m_mode { NotOpen };
  57. Vector<u8> m_buffered_data;
  58. };