DataBuf::c_data() returns nullptr when empty + avoid duplication

After the previous commit, I realized that std::vector::data() also
returns nullptr when the vector is empty. So I decided to emulate this
behavior in DataBuf::c_data().

Anyways, the changes done in the previous commit are valid and allow us
to avoid some processing when the DataBuf is empty.
main
Luis Díaz Más 3 years ago
parent c3d0100d48
commit 6964f5f9f2

@ -201,7 +201,7 @@ struct EXIV2API DataBuf {
int cmpBytes(size_t offset, const void* buf, size_t bufsize) const; int cmpBytes(size_t offset, const void* buf, size_t bufsize) const;
//! Returns a data pointer. //! Returns a data pointer.
byte* data(size_t offset = 0); [[nodiscard]] byte* data(size_t offset = 0);
//! Returns a (read-only) data pointer. //! Returns a (read-only) data pointer.
[[nodiscard]] const byte* c_data(size_t offset = 0) const; [[nodiscard]] const byte* c_data(size_t offset = 0) const;

@ -172,21 +172,14 @@ int Exiv2::DataBuf::cmpBytes(size_t offset, const void* buf, size_t bufsize) con
} }
byte* Exiv2::DataBuf::data(size_t offset) { byte* Exiv2::DataBuf::data(size_t offset) {
if (offset >= pData_.size()) { return const_cast<byte*>(c_data(offset));
throw std::out_of_range("Overflow in Exiv2::DataBuf::c_data");
}
if (pData_.empty() || pData_.size() == offset) {
return nullptr;
}
return &pData_[offset];
} }
const byte* Exiv2::DataBuf::c_data(size_t offset) const { const byte* Exiv2::DataBuf::c_data(size_t offset) const {
if (offset >= pData_.size()) { if (pData_.empty()) {
throw std::out_of_range("Overflow in Exiv2::DataBuf::c_data");
}
if (pData_.empty() || pData_.size() == offset) {
return nullptr; return nullptr;
} else if (offset >= pData_.size()) {
throw std::out_of_range("Overflow in Exiv2::DataBuf::c_data");
} }
return &pData_[offset]; return &pData_[offset];
} }

@ -48,7 +48,8 @@ TEST(DataBuf, canBeConstructedFromExistingData) {
TEST(DataBuf, tryingToAccessTooFarElementThrows) { TEST(DataBuf, tryingToAccessTooFarElementThrows) {
const std::array<byte, 4> data {'h', 'o', 'l', 'a'}; const std::array<byte, 4> data {'h', 'o', 'l', 'a'};
DataBuf instance(data.data(), data.size()); DataBuf instance(data.data(), data.size());
ASSERT_THROW(instance.data(4), std::out_of_range); ASSERT_THROW([[maybe_unused]] auto d = instance.data(4), std::out_of_range);
ASSERT_THROW([[maybe_unused]] auto d = instance.c_data(4), std::out_of_range);
} }
// Test methods like DataBuf::read_uint32 and DataBuf::write_uint32. // Test methods like DataBuf::read_uint32 and DataBuf::write_uint32.

Loading…
Cancel
Save