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

#include <stdint.h>

Martin Schläffer committed
6
#include "endian.h"
Martin Schläffer committed
7 8 9 10 11 12 13 14

typedef uint64_t word_t;

#define WORD_T
#define UINT64_T
#define U64TOWORD
#define WORDTOU64

Martin Schläffer committed
15
__forceinline word_t ROR64(word_t x, int n) { return x >> n | x << (64 - n); }
Martin Schläffer committed
16

Martin Schläffer committed
17
__forceinline word_t NOT(word_t a) { return ~a; }
Martin Schläffer committed
18

Martin Schläffer committed
19 20 21
__forceinline word_t XOR(word_t a, word_t b) { return a ^ b; }

__forceinline word_t AND(word_t a, word_t b) { return a & b; }
Martin Schläffer committed
22 23 24 25 26

__forceinline word_t KEYROT(word_t lo2hi, word_t hi2lo) {
  return lo2hi << 32 | hi2lo >> 32;
}

Martin Schläffer committed
27 28 29 30 31 32
__forceinline uint8_t NOTZERO(word_t a, word_t b) {
  uint64_t result = a | b;
  result |= result >> 32;
  result |= result >> 16;
  result |= result >> 8;
  return (uint8_t)result;
Martin Schläffer committed
33 34 35 36
}

__forceinline word_t PAD(int i) { return WORD_T(0x80ull << (56 - 8 * i)); }

Martin Schläffer committed
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 77
__forceinline word_t CLEAR(word_t w, int n) {
  /* undefined for n == 0 */
  uint64_t mask = 0x00ffffffffffffffull >> (n * 8 - 8);
  return AND(w, WORD_T(mask));
}

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

__forceinline word_t LOAD64(const uint8_t* bytes) {
  uint64_t x = *(uint64_t*)bytes;
  return U64TOWORD(U64BIG(x));
}

__forceinline void STORE64(uint8_t* bytes, word_t w) {
  uint64_t x = WORDTOU64(w);
  *(uint64_t*)bytes = U64BIG(x);
}

__forceinline word_t LOAD(const uint8_t* bytes, int n) {
  uint64_t x = *(uint64_t*)bytes & MASK(n);
  return U64TOWORD(U64BIG(x));
}

__forceinline void STORE(uint8_t* bytes, word_t w, int n) {
  uint64_t x = WORDTOU64(w);
  *(uint64_t*)bytes &= ~MASK(n);
  *(uint64_t*)bytes |= U64BIG(x);
}

__forceinline word_t LOADBYTES(const uint8_t* bytes, int n) {
  uint64_t x = 0;
  for (int i = 0; i < n; ++i) ((uint8_t*)&x)[7 - i] = bytes[i];
  return U64TOWORD(x);
}

__forceinline void STOREBYTES(uint8_t* bytes, word_t w, int n) {
  uint64_t x = WORDTOU64(w);
  for (int i = 0; i < n; ++i) bytes[i] = ((uint8_t*)&x)[7 - i];
Martin Schläffer committed
78 79 80
}

#endif /* WORD_H_ */