CIODevice.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 eof() const { return m_eof; }
  21. int error() const { return m_error; }
  22. const char* error_string() const;
  23. bool has_error() const { return m_error != 0; }
  24. int read(u8* buffer, int length);
  25. ByteBuffer read(int max_size);
  26. ByteBuffer read_line(int max_size);
  27. ByteBuffer read_all();
  28. bool write(const u8*, int size);
  29. bool write(const StringView& v) { return write((const u8*)v.characters_without_null_termination(), v.length()); }
  30. // FIXME: I would like this to be const but currently it needs to call populate_read_buffer().
  31. bool can_read_line();
  32. bool can_read() const;
  33. enum class SeekMode {
  34. SetPosition,
  35. FromCurrentPosition,
  36. FromEndPosition,
  37. };
  38. bool seek(i64, SeekMode = SeekMode::SetPosition, off_t* = nullptr);
  39. virtual bool open(CIODevice::OpenMode) = 0;
  40. virtual bool close();
  41. int printf(const char*, ...);
  42. protected:
  43. explicit CIODevice(CObject* parent = nullptr);
  44. void set_fd(int);
  45. void set_mode(OpenMode mode) { m_mode = mode; }
  46. void set_error(int error) { m_error = error; }
  47. void set_eof(bool eof) { m_eof = eof; }
  48. virtual void did_update_fd(int) {}
  49. private:
  50. bool populate_read_buffer();
  51. bool can_read_from_fd() const;
  52. int m_fd { -1 };
  53. int m_error { 0 };
  54. bool m_eof { false };
  55. OpenMode m_mode { NotOpen };
  56. Vector<u8> m_buffered_data;
  57. };