wl-app

example app to learn the basic of wayland
Log | Files | Refs | README

buf.c (2036B)


      1 #include <assert.h>
      2 #include <errno.h>
      3 #include <stdint.h>
      4 #include <stdio.h>
      5 #include <stdlib.h>
      6 #include <string.h>
      7 #include <sys/socket.h>
      8 #include <sys/un.h>
      9 
     10 #include "types.h"
     11 
     12 #define roundup_4(n) (((n) + 3) & -4)
     13 
     14 // buf_write_u32/u16 are literally the same thing just different types
     15 void buf_write_u32(char *buf, uint64_t *buf_size, uint64_t buf_cap,
     16                    uint32_t x) {
     17   assert(*buf_size + sizeof(x) <= buf_cap); // prevent buffer overflow
     18 
     19   assert(((size_t)buf + *buf_size) % sizeof(x) == 0); // fail if not divisible
     20 
     21   *(uint32_t *)(buf + *buf_size) = x;
     22   *buf_size += sizeof(x);
     23 }
     24 
     25 void buf_write_u16(char *buf, uint64_t *buf_size, uint64_t buf_cap,
     26                    uint16_t x) {
     27   assert(*buf_size + sizeof(x) <= buf_cap); // prevent buffer overflow
     28   assert(((size_t)buf + *buf_size) % sizeof(x) ==
     29          0); // ensure each element is ui16
     30 
     31   *(uint16_t *)(buf + *buf_size) = x;
     32   *buf_size += sizeof(x);
     33 }
     34 
     35 void buf_write_string(char *buf, uint64_t *buf_size, uint64_t buf_cap,
     36                       char *src, uint32_t src_len) {
     37   assert(*buf_size + src_len <= buf_cap); // prevent buffer overflow
     38 
     39   buf_write_u32(buf, buf_size, buf_cap, src_len);
     40   memcpy(buf + *buf_size, src, roundup_4(src_len));
     41   *buf_size += roundup_4(src_len);
     42 }
     43 
     44 uint32_t buf_read_u32(char **buf, uint64_t *buf_size) {
     45   assert(*buf_size >= sizeof(uint32_t));        // prevent buffer overflow
     46   assert((size_t)*buf % sizeof(uint32_t) == 0); // ensure each element is ui32
     47 
     48   uint32_t res = *(uint32_t *)(*buf);
     49   *buf += sizeof(res);
     50   *buf_size -= sizeof(res);
     51 
     52   return res;
     53 }
     54 
     55 uint16_t buf_read_u16(char **buf, uint64_t *buf_size) {
     56   assert(*buf_size >= sizeof(uint16_t)); // prevent bufer overflow
     57   assert((size_t)*buf % sizeof(uint16_t) == 0);
     58 
     59   uint16_t res = *(uint16_t *)(*buf);
     60   *buf += sizeof(res);
     61   *buf_size -= sizeof(res);
     62 
     63   return res;
     64 }
     65 
     66 void buf_read_n(char **buf, uint64_t *buf_size, char *dst, uint64_t n) {
     67   assert(*buf_size >= n);
     68 
     69   memcpy(dst, *buf, n);
     70 
     71   *buf += n;
     72   *buf_size -= n;
     73 }