ucx/string.c

Wed, 08 Feb 2012 23:43:02 +0100

author
Mike Becker <universe@uap-core.de>
date
Wed, 08 Feb 2012 23:43:02 +0100
changeset 24
e04822101291
parent 20
db7d9860dbbd
child 30
23bb65cbf7a4
permissions
-rw-r--r--

changed make clean + added dlist_clone with copy test + added va_end statements to string.c

/*
 * File:   sstring.c
 * Author: olaf
 *
 * Created on 17. Juni 2010, 13:27
 */

#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

#include "string.h"

sstr_t sstr (char *s) {
    sstr_t string;
    string.ptr = s;
    string.length = strlen(s);
    return string;
}

sstr_t sstrn (char *s, size_t n) {
    sstr_t string;
    string.ptr = s;
    string.length = n;
    return string;
}

size_t sstrnlen (size_t n, sstr_t s, ...) {
    va_list ap;
    size_t size = s.length;
    va_start(ap, s);

    for (int i=0;i<n-1;i++) {
        sstr_t str = va_arg(ap, sstr_t);
        size += str.length;
    }
    va_end(ap);

    return size;
}

sstr_t sstrcat (sstr_t s, ...) {
    va_list ap;
    va_start(ap, s);
    s.ptr[0] = 0;

    sstr_t str = va_arg (ap, sstr_t);
    while (str.ptr != NULL) {
        s.ptr = strncat (s.ptr, str.ptr, s.length);
        str = va_arg (ap, sstr_t);
    }
    va_end(ap);

    return s;
}

sstr_t sstrncat (size_t n, sstr_t s, sstr_t c1, ...) {
    va_list ap;
    va_start(ap, c1);
    s.ptr[0] = 0;

    s.ptr = strncat (s.ptr, c1.ptr, s.length);
    for (int i=0;i<n-1;i++) {
        sstr_t str = va_arg (ap, sstr_t);
        s.ptr = strncat (s.ptr, str.ptr, s.length);
    }
    va_end(ap);

    return s;
}

sstr_t sstrsubs (sstr_t s, size_t start) {
    return sstrsubsl (s, start, s.length-start);
}

sstr_t sstrsubsl (sstr_t s, size_t start, size_t length) {
    sstr_t new_sstr;
    if (start < 0 || start >= s.length || length < 0) {
        return s;
    }
    if (length > s.length-start) {
        length = s.length-start;
    }
    new_sstr.ptr = &s.ptr[start];
    new_sstr.length = length;
    return new_sstr;
}

int sstrcmp(sstr_t s1, sstr_t s2) {
    return strncmp(s1.ptr, s2.ptr, s1.length>s2.length ? s2.length: s1.length);
}

sstr_t sstrdub(sstr_t s) {
    sstr_t newstring;
    newstring.ptr = (char*) malloc(s.length + 1);
    if (newstring.ptr != NULL) {
        newstring.length = s.length;
        newstring.ptr[newstring.length] = 0;

        memcpy(newstring.ptr, s.ptr, s.length);
    }

    return newstring;
}

mercurial