mpd/src/util/StringBuffer.hxx

94 lines
1.8 KiB
C++
Raw Normal View History

// SPDX-License-Identifier: BSD-2-Clause
// author: Max Kellermann <max.kellermann@gmail.com>
2017-01-17 10:58:07 +01:00
2017-09-13 10:35:11 +02:00
#ifndef STRING_BUFFER_HXX
#define STRING_BUFFER_HXX
2017-01-17 10:58:07 +01:00
#include <array>
/**
* A statically allocated string buffer.
*/
template<typename T, std::size_t CAPACITY>
2017-01-17 10:58:07 +01:00
class BasicStringBuffer {
public:
typedef T value_type;
using reference = T &;
using pointer = T *;
using const_pointer = const T *;
using size_type = std::size_t;
2017-01-17 10:58:07 +01:00
static constexpr value_type SENTINEL = '\0';
protected:
using Array = std::array<value_type, CAPACITY>;
Array the_data;
2017-01-17 10:58:07 +01:00
public:
using iterator = typename Array::iterator;
using const_iterator = typename Array::const_iterator;
static constexpr size_type capacity() noexcept {
2017-01-17 10:58:07 +01:00
return CAPACITY;
}
2018-01-24 12:52:05 +01:00
constexpr bool empty() const noexcept {
2017-01-17 10:58:07 +01:00
return front() == SENTINEL;
}
2022-09-27 21:15:03 +02:00
constexpr void clear() noexcept {
2017-01-17 10:58:07 +01:00
the_data[0] = SENTINEL;
}
2018-01-24 12:52:05 +01:00
constexpr const_pointer c_str() const noexcept {
return the_data.data();
2017-01-17 10:58:07 +01:00
}
2022-09-27 21:15:03 +02:00
constexpr pointer data() noexcept {
return the_data.data();
2017-01-17 10:58:07 +01:00
}
2018-01-24 12:52:05 +01:00
constexpr value_type front() const noexcept {
return the_data.front();
2017-01-17 10:58:07 +01:00
}
/**
* Returns one character. No bounds checking.
*/
2022-09-27 21:15:03 +02:00
constexpr value_type operator[](size_type i) const noexcept {
2017-01-17 10:58:07 +01:00
return the_data[i];
}
/**
* Returns one writable character. No bounds checking.
*/
2022-09-27 21:15:03 +02:00
constexpr reference operator[](size_type i) noexcept {
2017-01-17 10:58:07 +01:00
return the_data[i];
}
constexpr iterator begin() noexcept {
return the_data.begin();
}
constexpr iterator end() noexcept {
return the_data.end();
}
2018-01-24 12:52:05 +01:00
constexpr const_iterator begin() const noexcept {
return the_data.begin();
2017-01-17 10:58:07 +01:00
}
2018-01-24 12:52:05 +01:00
constexpr const_iterator end() const noexcept {
return the_data.end();
2017-01-17 10:58:07 +01:00
}
2018-01-24 12:52:05 +01:00
constexpr operator const_pointer() const noexcept {
2017-01-17 10:58:07 +01:00
return c_str();
}
};
template<std::size_t CAPACITY>
2017-01-17 10:58:07 +01:00
class StringBuffer : public BasicStringBuffer<char, CAPACITY> {};
#endif