hyx

Minimalist but powerful terminal hex editor
git clone https://git.sinitax.com/yx7/hyx
Log | Files | Refs | sfeed.txt

common.c (1445B)


      1
      2#include "common.h"
      3
      4#include <stdlib.h>
      5#include <stdio.h>
      6#include <errno.h>
      7#include <time.h>
      8#include <sys/mman.h>
      9
     10unsigned long bit_length(unsigned long n)
     11{
     12    unsigned long r = 0;
     13    do ++r; while (n >>= 1);
     14    return r;
     15}
     16
     17
     18void *malloc_strict(size_t len)
     19{
     20    void *ptr;
     21    errno = 0;
     22    if (!(ptr = malloc(len)) && errno)
     23        pdie("malloc");
     24    return ptr;
     25}
     26
     27void *realloc_strict(void *ptr, size_t len)
     28{
     29    errno = 0;
     30    if (!(ptr = realloc(ptr, len)) && errno)
     31        pdie("realloc");
     32    return ptr;
     33}
     34
     35void *mmap_strict(void *addr, size_t len, int prot, int flags, int fildes, off_t off)
     36{
     37    void *ptr;
     38    if (MAP_FAILED == (ptr = mmap(addr, len, prot, flags, fildes, off)))
     39        pdie("mmap");
     40    return ptr;
     41}
     42
     43void munmap_strict(void *addr, size_t len)
     44{
     45    if (munmap(addr, len))
     46        pdie("munmap");
     47}
     48
     49off_t lseek_strict(int fildes, off_t offset, int whence)
     50{
     51    off_t ret;
     52    if (0 >= (ret = lseek(fildes, offset, whence)))
     53        pdie("lseek");
     54    return ret;
     55}
     56
     57char *fgets_retry(char *s, int size, FILE *stream)
     58{
     59    char *ret;
     60retry:
     61    errno = 0;
     62    if (!(ret = fgets(s, size, stream))) {
     63        if (errno == EINTR)
     64            goto retry;
     65        pdie("fgets");
     66    }
     67    return ret;
     68}
     69
     70uint64_t monotonic_microtime()
     71{
     72    struct timespec t;
     73    if (clock_gettime(CLOCK_MONOTONIC, &t))
     74        pdie("clock_gettime");
     75    return (uint64_t) t.tv_sec * 1000000 + t.tv_nsec / 1000;
     76}
     77