skalibs

Mirror/fork of https://skarnet.org/software/skalibs/
git clone https://ccx.te2000.cz/git/skalibs
Log | Files | Refs | README | LICENSE

siovec_search.c (1011B)


      1 /* ISC license. */
      2 
      3 #include <string.h>
      4 #include <sys/uio.h>
      5 #include <skalibs/posixplz.h>
      6 #include <skalibs/siovec.h>
      7 
      8 size_t siovec_search (struct iovec const *v, unsigned int n, char const *needle, size_t nlen)
      9 {
     10   size_t vlen = siovec_len(v, n) ;
     11   size_t w = 0 ;
     12   unsigned int i = 0 ;
     13   for (; i < n ; i++)
     14   {
     15     char *p = memmem(v[i].iov_base, v[i].iov_len, needle, nlen) ;
     16     if (p) return w + (p - (char *)v[i].iov_base) ;
     17     if (i < n-1 && nlen > 1 && v[i].iov_len)
     18     {
     19       size_t prelen = v[i].iov_len < nlen ? v[i].iov_len : nlen ;
     20       size_t postlen = vlen - w - v[i].iov_len < nlen ? vlen - w - v[i].iov_len : nlen ;
     21       char buf[prelen + postlen - 2] ;
     22       memcpy(buf, (char *)v[i].iov_base + v[i].iov_len - prelen + 1, prelen - 1) ;
     23       siovec_gather(v + i + 1, n - 1 - i, buf + prelen - 1, postlen - 1) ;
     24       p = memmem(buf, prelen + postlen - 2, needle, nlen) ;
     25       if (p) return w + v[i].iov_len - prelen + 1 + (p - buf) ;
     26     }
     27     w += v[i].iov_len ;
     28   }
     29   return w ;
     30 }