Bug 1025173 - Nullable copy, move, and assignment should not transfer |mValue| if |mIsNull|. r=bz

This commit is contained in:
Nathan Yee 2014-08-28 22:37:00 +02:00
parent d956f98bcb
commit 667bcd280f

View File

@ -10,6 +10,7 @@
#include "mozilla/Assertions.h"
#include "nsTArrayForwardDeclare.h"
#include "mozilla/Move.h"
#include "mozilla/Maybe.h"
class nsCycleCollectionTraversalCallback;
@ -21,73 +22,66 @@ template <typename T>
struct Nullable
{
private:
// mIsNull MUST COME FIRST because otherwise the casting in our array
// conversion operators would shift where it is found in the struct.
bool mIsNull;
T mValue;
Maybe<T> mValue;
public:
Nullable()
: mIsNull(true)
: mValue()
{}
explicit Nullable(T aValue)
: mIsNull(false)
, mValue(aValue)
{}
: mValue()
{
mValue.emplace(aValue);
}
explicit Nullable(Nullable<T>&& aOther)
: mIsNull(aOther.mIsNull)
, mValue(mozilla::Move(aOther.mValue))
: mValue(mozilla::Move(aOther.mValue))
{}
Nullable(const Nullable<T>& aOther)
: mIsNull(aOther.mIsNull)
, mValue(aOther.mValue)
: mValue(aOther.mValue)
{}
void operator=(const Nullable<T>& aOther)
{
mIsNull = aOther.mIsNull;
mValue = aOther.mValue;
}
void SetValue(T aValue) {
mValue = aValue;
mIsNull = false;
mValue.reset();
mValue.emplace(aValue);
}
// For cases when |T| is some type with nontrivial copy behavior, we may want
// to get a reference to our internal copy of T and work with it directly
// instead of relying on the copying version of SetValue().
T& SetValue() {
mIsNull = false;
return mValue;
if (mValue.isNothing()) {
mValue.emplace();
}
return mValue.ref();
}
void SetNull() {
mIsNull = true;
mValue.reset();
}
const T& Value() const {
MOZ_ASSERT(!mIsNull);
return mValue;
return mValue.ref();
}
T& Value() {
MOZ_ASSERT(!mIsNull);
return mValue;
return mValue.ref();
}
bool IsNull() const {
return mIsNull;
return mValue.isNothing();
}
bool Equals(const Nullable<T>& aOtherNullable) const
{
return (mIsNull && aOtherNullable.mIsNull) ||
(!mIsNull && !aOtherNullable.mIsNull &&
mValue == aOtherNullable.mValue);
return mValue == aOtherNullable.mValue;
}
bool operator==(const Nullable<T>& aOtherNullable) const
@ -99,23 +93,6 @@ public:
{
return !Equals(aOtherNullable);
}
// Make it possible to use a const Nullable of an array type with other
// array types.
template<typename U>
operator const Nullable< nsTArray<U> >&() const {
// Make sure that T is ok to reinterpret to nsTArray<U>
const nsTArray<U>& arr = mValue;
(void)arr;
return *reinterpret_cast<const Nullable< nsTArray<U> >*>(this);
}
template<typename U>
operator const Nullable< FallibleTArray<U> >&() const {
// Make sure that T is ok to reinterpret to FallibleTArray<U>
const FallibleTArray<U>& arr = mValue;
(void)arr;
return *reinterpret_cast<const Nullable< FallibleTArray<U> >*>(this);
}
};