I have to read a int8_t
from a buffer, read a uint8_t
from the camera's current settings, add them together, keep new value within the bounds 0 to 100 and write the new value to the camera's current settings. This seems quite easy to me, and yet here I have a rather large bit of code.
The brace style is company-mandated.
Is there a way to remove some of the complexity from this code?
Ranges:
plusZoomPercentage
: full range of int8_t
.
currentZoomPercentage
and getZoomPercentage()
: 0 to 100, 0 and 100 included.
newZoomPercentage
: To be between 0 and 100, 0 and 100 included.
Header file:
/*Zooms to the provided percentage of maximum zoom level.*/
void zoomToPercentage(uint8_t percentage);
/*Retrieves the current targeted percentage of maximum zoom level (if the camera is currently at 50% zoom, but is zooming towards 60%, return 60.)*/
uint8_t getZoomPercentage();
Calling implementation:
int8_t plusZoomPercentage;
if (!unabto_query_read_int8(readBuffer, &plusZoomPercentage))
{
return AER_REQ_TOO_SMALL;
}
if (plusZoomPercentage == 0)
{
return AER_REQ_RESPONSE_READY;
}
uint8_t currentZoomPercentage = getZoomPercentage();
uint8_t newZoomPercentage = currentZoomPercentage + plusZoomPercentage;
if (plusZoomPercentage > 0)
{
/*Check for overflow or otherwise going out of bounds*/
if (newZoomPercentage > 100 || newZoomPercentage < currentZoomPercentage)
{
zoomToPercentage(100);
}
else
{
zoomToPercentage(newZoomPercentage);
}
}
else
{
if (newZoomPercentage > currentZoomPercentage)
{
zoomToPercentage(0);
}
else
{
zoomToPercentage(newZoomPercentage);
}
}
return AER_REQ_RESPONSE_READY;