From e8f35252262b9efd14c84909f29c81a1434a4451 Mon Sep 17 00:00:00 2001 From: Nik Bougalis Date: Sat, 9 May 2020 20:53:48 -0700 Subject: [PATCH] Improve Slice: Slice should, eventually, be replaced by std::string_view so begin adding some helpful functions to align its interface. --- src/ripple/basics/Slice.h | 48 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/src/ripple/basics/Slice.h b/src/ripple/basics/Slice.h index 126e8ab1c..67c954bb7 100644 --- a/src/ripple/basics/Slice.h +++ b/src/ripple/basics/Slice.h @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -63,7 +64,7 @@ public: } /** Return `true` if the byte range is empty. */ - bool + [[nodiscard]] bool empty() const noexcept { return size_ == 0; @@ -73,12 +74,20 @@ public: This may be zero for an empty range. */ + /** @{ */ std::size_t size() const noexcept { return size_; } + std::size_t + length() const noexcept + { + return size_; + } + /** @} */ + /** Return a pointer to beginning of the storage. @note The return type is guaranteed to be a pointer to a single byte, to facilitate pointer arithmetic. @@ -117,6 +126,21 @@ public: } /** @} */ + /** Shrinks the slice by moving its start forward by n characters. */ + void + remove_prefix(std::size_t n) + { + data_ += n; + size_ -= n; + } + + /** Shrinks the slice by moving its end backward by n characters. */ + void + remove_suffix(std::size_t n) + { + size_ -= n; + } + const_iterator begin() const noexcept { @@ -140,6 +164,28 @@ public: { return data_ + size_; } + + /** Return a "sub slice" of given length starting at the given position + + Note that the subslice encompasses the range [pos, pos + rcount), + where rcount is the smaller of count and size() - pos. + + @param pos position of the first character + @count requested length + + @returns The requested subslice, if the request is valid. + @throws std::out_of_range if pos > size() + */ + Slice + substr( + std::size_t pos, + std::size_t count = std::numeric_limits::max()) const + { + if (pos > size()) + throw std::out_of_range("Requested sub-slice is out of bounds"); + + return {data_ + pos, std::min(count, size() - pos)}; + } }; //------------------------------------------------------------------------------