GY-63_MS5611/libraries/Adler/Adler32.cpp

135 lines
2.3 KiB
C++
Raw Normal View History

2022-06-16 03:46:28 -04:00
//
// FILE: Adler32.cpp
// AUTHOR: Rob Tillaart
2022-10-27 04:21:11 -04:00
// VERSION: 0.2.2
2022-06-16 03:46:28 -04:00
// DATE: 2022-01-27
// PURPOSE: Arduino Library for calculating Adler-32 checksum
// URL: https://github.com/RobTillaart/Adler
// https://en.wikipedia.org/wiki/Adler-32
//
// HISTORY: see CHANGELOG.md
#include "Adler32.h"
Adler32::Adler32()
{
begin(1, 0);
}
void Adler32::begin(uint32_t s1, uint32_t s2)
{
_s1 = s1;
_s2 = s2;
_count = 0;
}
// reference implementation
// void Adler32::add(uint8_t value)
// {
// _count++;
// _s1 += value;
// if (_s1 >= ADLER32_MOD_PRIME) _s1 -= ADLER32_MOD_PRIME;
// _s2 += _s1;
// if (_s2 >= ADLER32_MOD_PRIME) _s2 -= ADLER32_MOD_PRIME;
// }
// optimized version (~10% faster)
void Adler32::add(uint8_t value)
{
_count++;
_s1 += value;
_s2 += _s1;
if (_s2 >= ADLER32_MOD_PRIME)
{
_s2 -= ADLER32_MOD_PRIME;
if (_s1 >= ADLER32_MOD_PRIME) _s1 -= ADLER32_MOD_PRIME;
}
}
// straightforward going through the array.
// small footprint.
2022-09-21 03:34:38 -04:00
// returns current Adler value
uint32_t Adler32::add(uint8_t * array, uint16_t length)
2022-06-16 03:46:28 -04:00
{
while (length--)
{
add(*array++);
}
2022-09-21 03:34:38 -04:00
return (_s2 << 16) | _s1;
2022-06-16 03:46:28 -04:00
}
// Optimized version
// S1 grows linear
// S2 grows quadratic
// only do modulo when S2 reaches halfway uint32_t
// and at the end of the loop.
2022-09-21 03:34:38 -04:00
// returns current Adler value
uint32_t Adler32::addFast(uint8_t * array, uint16_t length)
2022-06-16 03:46:28 -04:00
{
_count += length;
uint32_t s1 = _s1;
uint32_t s2 = _s2;
for (uint16_t i = 0; i < length;)
{
// if S2 is halfway it is time to do modulo
while ((i < length) && (s2 < 2147483648ULL))
{
s1 += array[i++];
s2 += s1;
}
if (s2 >= ADLER32_MOD_PRIME)
{
s2 %= ADLER32_MOD_PRIME;
if (s1 >= ADLER32_MOD_PRIME) s1 %= ADLER32_MOD_PRIME;
}
}
_s1 = s1;
_s2 = s2;
2022-09-21 03:34:38 -04:00
return (s2 << 16) | s1;
2022-06-16 03:46:28 -04:00
}
uint32_t Adler32::getAdler()
{
return (_s2 << 16) | _s1;
};
2022-09-21 03:34:38 -04:00
uint32_t Adler32::count()
{
return _count;
};
2022-06-16 03:46:28 -04:00
//////////////////////////////////////////////////////////////
//
// wrappers for strings.
//
void Adler32::add(char value)
{
add((uint8_t) value);
}
2022-09-21 03:34:38 -04:00
uint32_t Adler32::add(char * array, uint16_t length)
2022-06-16 03:46:28 -04:00
{
2022-09-21 03:34:38 -04:00
return add((uint8_t *) array, length);
2022-06-16 03:46:28 -04:00
}
2022-09-21 03:34:38 -04:00
uint32_t Adler32::addFast(char * array, uint16_t length)
2022-06-16 03:46:28 -04:00
{
2022-09-21 03:34:38 -04:00
return addFast((uint8_t *) array, length);
2022-06-16 03:46:28 -04:00
}
// -- END OF FILE --