LibCore: Add line iterators to IODevice

This commit is contained in:
AnotherTest 2021-01-11 21:40:09 +03:30 committed by Andreas Kling
parent 7029a8f605
commit 711ced80c0
Notes: sideshowbarker 2024-07-18 23:55:40 +09:00
2 changed files with 43 additions and 0 deletions

View file

@ -315,4 +315,22 @@ bool IODevice::write(const StringView& v)
return write((const u8*)v.characters_without_null_termination(), v.length());
}
LineIterator::LineIterator(IODevice& device, bool is_end)
: m_device(device)
, m_is_end(is_end)
{
++*this;
}
bool LineIterator::at_end() const
{
return m_device->eof();
}
LineIterator& LineIterator::operator++()
{
m_buffer = m_device->read_line();
return *this;
}
}

View file

@ -31,6 +31,28 @@
namespace Core {
// This is not necessarily a valid iterator in all contexts,
// if we had concepts, this would be InputIterator, not Copyable, Movable.
class LineIterator {
AK_MAKE_NONCOPYABLE(LineIterator);
public:
explicit LineIterator(IODevice&, bool is_end = false);
bool operator==(const LineIterator& other) const { return &other == this || (at_end() && other.is_end()) || (other.at_end() && is_end()); }
bool is_end() const { return m_is_end; }
bool at_end() const;
LineIterator& operator++();
StringView operator*() const { return m_buffer; }
private:
NonnullRefPtr<IODevice> m_device;
bool m_is_end { false };
String m_buffer;
};
class IODevice : public Object {
C_OBJECT_ABSTRACT(IODevice)
public:
@ -84,6 +106,9 @@ public:
int printf(const char*, ...);
LineIterator line_begin() & { return LineIterator(*this); }
LineIterator line_end() { return LineIterator(*this, true); }
protected:
explicit IODevice(Object* parent = nullptr);