I have some code for checking a binary header to see if a binary file is meant to be read by a certain program, and I could use some extra eyes to review it.
Assume the following typedef
s:
namespace Types
{
using Byte = std::uint8_t; // From <cstdint>
using UInt32 = std::uint32_t;
using String = std::string; // From <string>
}
// This is a vector of bytes loaded from a binary file.
using ByteBuffer = std::vector<Types::Byte>; // From <vector>
Also assume the following constants:
namespace Constants
{
const Types::String G_BINARY_HEADER_STRING = "A2FORMAT";
const Types::Byte G_BINARY_MAJOR_VERSION = 0x00;
const Types::Byte G_BINARY_MINOR_VERSION = 0x01;
const Types::UInt32 G_BINARY_HEADER_SIZE = 14;
}
Here is the binary-header-validating code:
bool isBufferValid (ByteBuffer &a_buffer)
{
// Get the size of the buffer. Make a cursor here, too.
Types::UInt32 l_size = a_buffer.size();
Types::UInt32 l_cursor = 0;
// Check to see if the size exceeds 14 bytes.
if (l_size <= Constants::G_BINARY_HEADER_SIZE)
return false;
// Bytes #1 to #8 are the characters in the binary header string.
for (l_cursor = 0; l_cursor < Constants::G_BINARY_HEADER_STRING.size(); ++l_cursor)
{
if (a_buffer.at(l_cursor) != Constants::G_BINARY_HEADER_STRING.at(l_cursor))
{
return false;
}
}
// Byte #9 indicates the engine's major version.
//
// If the byte found doesn't match the current major version, then it is invalid.
if (a_buffer.at(8) != Constants::G_BINARY_MAJOR_VERSION)
return false;
// Byte #10 indicates the engine's minor version.
//
// If this byte given is greater than the current minor version, then it is invalid.
if (a_buffer.at(9) > Constants::G_BINARY_MINOR_VERSION)
return false;
// Bytes #11 through #14 make up a 32-bit unsigned integer that indicates how many
// bytes of data reside after the binary header.
//
// These bytes are arranged in Little Endian Notation.
Types::UInt32 l_sizeOfData = 0;
for (Types::UInt32 i = 0, j = 10; j < 14; i++, j++)
l_sizeOfData |= a_buffer.at(j) << (i * 8);
// If the amount of bytes in the buffer, after the header, do not match the number found
// in the integer above, then the buffer is invalid.
if (l_size - Constants::G_BINARY_HEADER_SIZE != l_sizeOfData)
return false;
// Remove the header from the buffer, because it has been confirmed valid, and is
// therefore ready to use.
a_buffer.erase(a_buffer.begin(), a_buffer.begin() + Constants::G_BINARY_HEADER_SIZE);
return true;
}
Is there anything I can do to make this code more efficient? Are there also any steps I can take to make this validation more effective?