Hacker News new | past | comments | ask | show | jobs | submit login
Convert hex to binary faster than xxd - part 1/2
2 points by textmode on April 25, 2021 | hide | past | favorite

   #include <unistd.h>
   #include <poll.h>
   #include <errno.h>
   #include <sys/types.h>
   #include <sys/stat.h>
   
   #ifndef EINTR
   #define EINTR (-5004)
   #endif
   #ifndef EAGAIN
   #define EAGAIN (-5011)
   #endif
   #ifndef EWOULDBLOCK
   #define EWOULDBLOCK (-7011)
   #endif
   
   int writeall(int fd,const void *xv,long long xlen)
   {
     const unsigned char *x = xv;
     long long w;
     while (xlen > 0) {
       w = xlen;
       if (w > 1048576) w = 1048576;
       w = write(fd,x,w);
       if (w < 0) {
         if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
           struct pollfd p;
           p.fd = fd;
           p.events = POLLOUT | POLLERR;
           poll(&p,1,-1);
           continue;
         }
         return -1;
       }
       x += w;
       xlen -= w;
     }
     return 0;
   }
   long long readblock(int fd, void *x, long long xlen) {
       long long r;
       char *buf = x;
       while (xlen > 0) {
           r = xlen;
           if (r > 1048576) r = 1048576;
           r = read(fd, buf, r);
           if (r == 0) break;
           if (r == -1) {
               if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
                   struct pollfd p;
                   p.fd = fd;
                   p.events = POLLIN;
                   poll(&p, 1, -1);
                   continue;
               }
               return -1;
           }
           buf += r; xlen -= r;
       }
       return (buf - (char *)x);
   }
   int fsyncfd(int fd) {
       struct stat st;
       if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
           if (fsync(fd) == -1) return -1;
       }
       return 0;
   }



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: