Fix assert not firing when only x index is out of bounds

Original protection to UB here was to simply check if the produced index
is out of bounds, but that isn't entirely correct imo. What is correct
is to fire if either the x or the y go out of bounds.

This shouldn't cause the UB problem to reappear, and be a little more
"correct" from the user's perspective. I believe that the most correct
way would be to use a boolean return in the setPixel(), and a
std::optional and return None on a failed fetch for the getPixel()
function. I don't know if ya'll are willing to do this, but this seems
sufficient too. Atleast there is a clear place where the programs fails
to work.
This commit is contained in:
Shane Whitmire 2024-02-18 21:44:31 -06:00 committed by Chris Thrasher
parent e50f7b9759
commit 691292b23a

View File

@ -490,8 +490,10 @@ void Image::createMaskFromColor(const Color& color, std::uint8_t alpha)
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
void Image::setPixel(const Vector2u& coords, const Color& color) void Image::setPixel(const Vector2u& coords, const Color& color)
{ {
assert(coords.x < m_size.x && "Image::setPixel() x coordinate is out of bounds");
assert(coords.y < m_size.y && "Image::setPixel() y coordinate is out of bounds");
const auto index = (coords.x + coords.y * m_size.x) * 4; const auto index = (coords.x + coords.y * m_size.x) * 4;
assert(index < m_pixels.size() && "Image::setPixel() cannot access out of bounds pixel");
std::uint8_t* pixel = &m_pixels[index]; std::uint8_t* pixel = &m_pixels[index];
*pixel++ = color.r; *pixel++ = color.r;
*pixel++ = color.g; *pixel++ = color.g;
@ -503,8 +505,10 @@ void Image::setPixel(const Vector2u& coords, const Color& color)
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
Color Image::getPixel(const Vector2u& coords) const Color Image::getPixel(const Vector2u& coords) const
{ {
assert(coords.x < m_size.x && "Image::getPixel() x coordinate is out of bounds");
assert(coords.y < m_size.y && "Image::getPixel() y coordinate is out of bounds");
const auto index = (coords.x + coords.y * m_size.x) * 4; const auto index = (coords.x + coords.y * m_size.x) * 4;
assert(index < m_pixels.size() && "Image::getPixel() cannot access out of bounds pixel");
const std::uint8_t* pixel = &m_pixels[index]; const std::uint8_t* pixel = &m_pixels[index];
return {pixel[0], pixel[1], pixel[2], pixel[3]}; return {pixel[0], pixel[1], pixel[2], pixel[3]};
} }