aboutsummaryrefslogtreecommitdiff
path: root/src/common.hff
blob: a54fd32c79c81fbf1a404a42ed88c4075dfb7247 (plain) (blame)
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
import "libc.hff";

/// Macros

defmacro assert {
(ex, s, ...args) [
   (do
      if !(ex) {
         fprintf(stderr, "%s:%d: assertion failed: ", #FILE, #LINE);
         fprintf(stderr, s, args);
         fprintf(stderr, "\n");
         abort();
      }
   )
]
}

defmacro foreach(x, i, a, &body) [
   {
      let $a = a;
      for let i = 0z; i < $a.#len; ++i {
         let x = $a[i];
         { body }
      }
   }
]

defmacro foreach_ptr(x, i, a, &body) [
   {
      let $a = a;
      for let i = 0z; i < $a.#len; ++i {
         let x = &$a[i];
         { body }
      }
   }
]

defmacro streq(a,b) [ (strcmp(a,b) == 0) ]
defmacro strcieq(a,b) [ (strcasecmp(a,b) == 0) ]

defmacro with_tmpchange(var,x,&body) [
   { let $tmp = (var);
       (var) = x;
       { body }
       (var) = $tmp; }
]

defmacro MAX(a,b) [((a) > (b) ? (a) : (b))]

defmacro container_of(x, T, fld) [
   (as(*T)(as(*void)(x) - offsetof(T, fld)))
]

// Inline functions
fn bswap32(x u32) u32 {
   return (x >> 24)
        | ((x >> 8) & 0x00FF00)
        | ((x << 8) & 0xFF0000)
        | (x << 24);
}

fn bswap64(x u64) u64 {
   return (as(u64)bswap32(x) << 32)
        | (bswap32(x >> 32));
}

fn spanz(x *const u8) [#]const u8 {
   return x[0::strlen(x)];
}