From a490f24a2dff0dd03a2858472ee4a52be9c5986c Mon Sep 17 00:00:00 2001 From: Sam Atkins Date: Wed, 27 Apr 2022 12:46:22 +0100 Subject: LibWeb: Add StateTransaction RAII to CSS TokenStream This is modeled after the one in ISO8601Parser. It rolls back the TokenStream state automatically at the end of scope unless told to commit the changes. This should be less error-prone than remembering to manually call `rewind_to_position()` at the correct time. For convenience, a StateTransaction can have "child" transactions. When a transaction is committed, it automatically commits its parents too. This is useful in situations where you have several nested and don't want to have to remember to manually `commit()` them all. --- Userland/Libraries/LibWeb/CSS/Parser/Parser.h | 38 +++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.h b/Userland/Libraries/LibWeb/CSS/Parser/Parser.h index 3df4321ec9..6617ffaedd 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.h +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.h @@ -55,6 +55,43 @@ private: template class TokenStream { public: + class StateTransaction { + public: + explicit StateTransaction(TokenStream& token_stream) + : m_token_stream(token_stream) + , m_saved_iterator_offset(token_stream.m_iterator_offset) + { + } + + ~StateTransaction() + { + if (!m_commit) + m_token_stream.m_iterator_offset = m_saved_iterator_offset; + } + + StateTransaction create_child() { return StateTransaction(*this); } + + void commit() + { + m_commit = true; + if (m_parent) + m_parent->commit(); + } + + private: + explicit StateTransaction(StateTransaction& parent) + : m_parent(&parent) + , m_token_stream(parent.m_token_stream) + , m_saved_iterator_offset(parent.m_token_stream.m_iterator_offset) + { + } + + StateTransaction* m_parent { nullptr }; + TokenStream& m_token_stream; + int m_saved_iterator_offset { 0 }; + bool m_commit { false }; + }; + explicit TokenStream(Vector const&); ~TokenStream() = default; @@ -66,6 +103,7 @@ public: T const& current_token(); void reconsume_current_input_token(); + StateTransaction begin_transaction() { return StateTransaction(*this); } int position() const { return m_iterator_offset; } void rewind_to_position(int); -- cgit v1.2.3