word.h 1.58 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"
Enrico Pozzobon committed
7
#include "forceinline.h"
Martin Schläffer committed
8 9 10 11 12 13 14 15

typedef uint64_t word_t;

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

Enrico Pozzobon committed
16
forceinline word_t ROR(word_t x, int n) { return x >> n | x << (64 - n); }
Martin Schläffer committed
17

Enrico Pozzobon committed
18
forceinline word_t NOT(word_t a) { return ~a; }
Martin Schläffer committed
19

Enrico Pozzobon committed
20
forceinline word_t XOR(word_t a, word_t b) { return a ^ b; }
Martin Schläffer committed
21

Enrico Pozzobon committed
22
forceinline word_t AND(word_t a, word_t b) { return a & b; }
Martin Schläffer committed
23

Enrico Pozzobon committed
24
forceinline word_t KEYROT(word_t lo2hi, word_t hi2lo) {
Martin Schläffer committed
25 26 27
  return lo2hi << 32 | hi2lo >> 32;
}

Enrico Pozzobon committed
28
forceinline int ISZERO(word_t a, word_t b) {
Martin Schläffer committed
29 30 31 32
  uint64_t result = a | b;
  result |= result >> 32;
  result |= result >> 16;
  result |= result >> 8;
Enrico Pozzobon committed
33
  return ((((int)(result & 0xff) - 1) >> 8) & 1) - 1;
Martin Schläffer committed
34 35
}

Enrico Pozzobon committed
36
forceinline word_t PAD(int i) { return 0x80ull << (56 - 8 * i); }
Martin Schläffer committed
37

Enrico Pozzobon committed
38
forceinline word_t CLEAR(word_t w, int n) {
Martin Schläffer committed
39 40
  /* undefined for n == 0 */
  uint64_t mask = 0x00ffffffffffffffull >> (n * 8 - 8);
Enrico Pozzobon committed
41
  return w & mask;
Martin Schläffer committed
42 43
}

Enrico Pozzobon committed
44
forceinline uint64_t MASK(int n) {
Martin Schläffer committed
45 46 47 48
  /* undefined for n == 0 */
  return ~0ull >> (64 - 8 * n);
}

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

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

Enrico Pozzobon committed
59
forceinline word_t LOADBYTES(const uint8_t* bytes, int n) {
Martin Schläffer committed
60 61
  uint64_t x = 0;
  for (int i = 0; i < n; ++i) ((uint8_t*)&x)[7 - i] = bytes[i];
Enrico Pozzobon committed
62
  return x;
Martin Schläffer committed
63 64
}

Enrico Pozzobon committed
65 66
forceinline void STOREBYTES(uint8_t* bytes, word_t w, int n) {
  for (int i = 0; i < n; ++i) bytes[i] = ((uint8_t*)&w)[7 - i];
Martin Schläffer committed
67 68 69
}

#endif /* WORD_H_ */