word.h 1.52 KB
Newer Older
Martin Schläffer committed
1 2 3 4
#ifndef WORD_H_
#define WORD_H_

#include <stdint.h>
Martin Schläffer committed
5
#include <string.h>
Martin Schläffer committed
6

Enrico Pozzobon committed
7 8
#include "endian.h"
#include "forceinline.h"
Martin Schläffer committed
9

Martin Schläffer committed
10 11 12 13 14
typedef union {
  uint64_t x;
  uint32_t w[2];
  uint8_t b[8];
} word_t;
Martin Schläffer committed
15

Martin Schläffer committed
16 17
#define U64TOWORD(x) U64BIG(x)
#define WORDTOU64(x) U64BIG(x)
Enrico Pozzobon committed
18

Martin Schläffer committed
19
forceinline uint64_t ROR(uint64_t x, int n) { return x >> n | x << (-n & 63); }
Martin Schläffer committed
20

Martin Schläffer committed
21
forceinline uint64_t KEYROT(uint64_t lo2hi, uint64_t hi2lo) {
Enrico Pozzobon committed
22 23 24
  return lo2hi << 32 | hi2lo >> 32;
}

Martin Schläffer committed
25
forceinline int NOTZERO(uint64_t a, uint64_t b) {
Enrico Pozzobon committed
26 27 28 29 30 31 32
  uint64_t result = a | b;
  result |= result >> 32;
  result |= result >> 16;
  result |= result >> 8;
  return ((((int)(result & 0xff) - 1) >> 8) & 1) - 1;
}

Martin Schläffer committed
33 34 35
forceinline uint64_t PAD(int i) { return 0x80ull << (56 - 8 * i); }

forceinline uint64_t PRFS_MLEN(uint64_t len) { return len << 51; }
Enrico Pozzobon committed
36

Martin Schläffer committed
37
forceinline uint64_t CLEAR(uint64_t w, int n) {
Enrico Pozzobon committed
38
  /* undefined for n == 0 */
Martin Schläffer committed
39
  uint64_t mask = ~0ull >> (8 * n);
Enrico Pozzobon committed
40 41 42 43 44 45 46 47
  return w & mask;
}

forceinline uint64_t MASK(int n) {
  /* undefined for n == 0 */
  return ~0ull >> (64 - 8 * n);
}

Martin Schläffer committed
48
forceinline uint64_t LOAD(const uint8_t* bytes, int n) {
Enrico Pozzobon committed
49
  uint64_t x = *(uint64_t*)bytes & MASK(n);
Martin Schläffer committed
50
  return U64TOWORD(x);
Enrico Pozzobon committed
51 52
}

Martin Schläffer committed
53
forceinline void STORE(uint8_t* bytes, uint64_t w, int n) {
Enrico Pozzobon committed
54
  *(uint64_t*)bytes &= ~MASK(n);
Martin Schläffer committed
55
  *(uint64_t*)bytes |= WORDTOU64(w);
Enrico Pozzobon committed
56
}
Martin Schläffer committed
57

Martin Schläffer committed
58
forceinline uint64_t LOADBYTES(const uint8_t* bytes, int n) {
Martin Schläffer committed
59
  uint64_t x = 0;
Martin Schläffer committed
60 61
  memcpy(&x, bytes, n);
  return U64TOWORD(x);
Martin Schläffer committed
62 63
}

Martin Schläffer committed
64 65 66
forceinline void STOREBYTES(uint8_t* bytes, uint64_t w, int n) {
  uint64_t x = WORDTOU64(w);
  memcpy(bytes, &x, n);
Martin Schläffer committed
67 68 69
}

#endif /* WORD_H_ */