Bug 1639958 part 2: Add Buffer::AllocForOverwrite to fallibly create a default-initialized Buffer. r=froydnj

This also uses MakeUniqueForOverwrite* in two places where we immediately copy
over the Buffer from a Span.
Adds move assignment operator as well.

Differential Revision: https://phabricator.services.mozilla.com/D75510
This commit is contained in:
Bob Owen 2020-05-22 07:48:02 +00:00
Родитель c7b447903d
Коммит 3dc49fb3d2
1 изменённых файлов: 33 добавлений и 2 удалений

Просмотреть файл

@ -56,6 +56,17 @@ class Buffer final {
aOther.mLength = 0;
}
/**
* Move assignment. Sets the moved-from Buffer to zero-length
* state.
*/
Buffer<T>& operator=(Buffer<T>&& aOther) {
mData = std::move(aOther.mData);
mLength = aOther.mLength;
aOther.mLength = 0;
return *this;
}
/**
* Construct by copying the elements of a Span.
*
@ -63,7 +74,7 @@ class Buffer final {
* allocation.
*/
explicit Buffer(mozilla::Span<const T> aSpan)
: mData(mozilla::MakeUnique<T[]>(aSpan.Length())),
: mData(mozilla::MakeUniqueForOverwrite<T[]>(aSpan.Length())),
mLength(aSpan.Length()) {
std::copy(aSpan.cbegin(), aSpan.cend(), mData.get());
}
@ -74,7 +85,11 @@ class Buffer final {
* Allocates the internal buffer fallibly.
*/
static mozilla::Maybe<Buffer<T>> CopyFrom(mozilla::Span<const T> aSpan) {
auto data = mozilla::MakeUniqueFallible<T[]>(aSpan.Length());
if (aSpan.IsEmpty()) {
return Some(Buffer());
}
auto data = mozilla::MakeUniqueForOverwriteFallible<T[]>(aSpan.Length());
if (!data) {
return mozilla::Nothing();
}
@ -110,6 +125,22 @@ class Buffer final {
return mozilla::Some(Buffer(std::move(data), aLength));
}
/**
* Create a new Buffer with an internal buffer of requested length.
*
* This uses MakeUniqueFallibleForOverwrite so the contents will be
* default-initialized.
*
* Allocates the internal buffer fallibly.
*/
static Maybe<Buffer<T>> AllocForOverwrite(size_t aLength) {
auto data = MakeUniqueForOverwriteFallible<T[]>(aLength);
if (!data) {
return Nothing();
}
return Some(Buffer(std::move(data), aLength));
}
mozilla::Span<const T> AsSpan() const {
return mozilla::MakeSpan(mData.get(), mLength);
}