summaryrefslogtreecommitdiff
path: root/src/storage/codec.c
blob: af061ce099345f7b24549056e294d652ffbd3a83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include "storage/codec.h"

void
tiny_codec_put_u32(unsigned char *output, uint32_t value)
{
  if (output == NULL)
    {
      return;
    }
  output[0] = (unsigned char)value;
  output[1] = (unsigned char)(value >> 8);
  output[2] = (unsigned char)(value >> 16);
  output[3] = (unsigned char)(value >> 24);
}

void
tiny_codec_put_u64(unsigned char *output, uint64_t value)
{
  unsigned index;
  if (output == NULL)
    {
      return;
    }
  for (index = 0; index < 8; ++index)
    {
      output[index] = (unsigned char)(value >> (index * 8));
    }
}

uint32_t
tiny_codec_get_u32(const unsigned char *input)
{
  if (input == NULL)
    {
      return 0;
    }
  return (uint32_t)input[0] | ((uint32_t)input[1] << 8) | ((uint32_t)input[2] << 16)
         | ((uint32_t)input[3] << 24);
}

uint64_t
tiny_codec_get_u64(const unsigned char *input)
{
  uint64_t value = 0;
  int index;
  if (input == NULL)
    {
      return 0;
    }
  for (index = 7; index >= 0; --index)
    {
      value = (value << 8) | input[index];
    }
  return value;
}

uint32_t
tiny_codec_crc32(const unsigned char *data, size_t length)
{
  uint32_t crc = 0xffffffffU;
  size_t index;
  if (data == NULL && length != 0)
    {
      return 0;
    }
  for (index = 0; index < length; ++index)
    {
      unsigned bit;
      crc ^= data[index];
      for (bit = 0; bit < 8; ++bit)
        {
          crc = (crc >> 1) ^ (0xedb88320U & (uint32_t)-(int32_t)(crc & 1));
        }
    }
  return ~crc;
}