summaryrefslogtreecommitdiff
path: root/src/libstddjb/sadirname.c
blob: ac818e8fe96fe9654f735b0f2a5464e9bfe56328 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* ISC license. */

#include <sys/types.h>
#include <skalibs/bytestr.h>
#include <skalibs/stralloc.h>
#include <skalibs/djbunix.h>

int sadirname (stralloc *sa, char const *s, size_t len)
{
  if (!len) return stralloc_catb(sa, ".", 1) ;
  while (len && (s[len-1] == '/')) len-- ;
  if (!len) return stralloc_catb(sa, "/", 1) ;
  {
    size_t i = byte_rchr(s, len, '/') ;
    return (i == len) ? stralloc_catb(sa, ".", 1) :
           (i == 0)   ? stralloc_catb(sa, "/", 1) :
                        stralloc_catb(sa, s, i) ;
  }
}