source: libabac/abac_util.c @ 7cefdb4

Last change on this file since 7cefdb4 was 0a1ee31, checked in by Mei <mei@…>, 11 years ago

1) merged with ted's changes

  • Property mode set to 100644
File size: 2.4 KB
Line 
1
2/* abac_util.c */
3
4#include <err.h>
5#include <stdlib.h>
6#include <string.h>
7#include <assert.h>
8#include <ctype.h>
9#include <stdio.h>
10
11#include <abac_util.h>
12
13/**
14 * Malloc, fatal on error.
15 */
16void *abac_xmalloc(size_t size) {
17    void *ret;
18   
19    ret = malloc(size);
20    if (ret == NULL)
21        err(1, "malloc");
22
23    return ret;
24}
25
26void abac_chunk_free(abac_chunk_t *chunk)
27{
28   if(chunk->len)
29       free(chunk->ptr);
30   chunk->len=0;
31   chunk->ptr=NULL;
32}
33
34int abac_chunk_null(abac_chunk_t *chunk)
35{
36    if(chunk->ptr==NULL) return 1;
37    return 0;
38}
39
40int abac_chunk_show(abac_chunk_t *chunk)
41{
42    if(chunk->ptr==NULL) {
43        fprintf(stderr,"abac_chunk_show: chunk is NULL\n");
44        return 1;
45    }
46    fprintf(stderr,"abac_chunk_show: chunk is not NULL (%ld)\n",(long)chunk->ptr);
47    return 0;
48}
49
50/**
51 * strdup fatal on error
52 */
53char *abac_xstrdup(char *source) {
54    char *ret;
55
56    if (source == NULL)
57        return NULL;
58
59    ret = strdup(source);
60    if (ret == NULL)
61        err(1, "strdup");
62
63    return ret;
64}
65
66void *abac_xrealloc(void *ptr, size_t size) {
67    void *ret = realloc(ptr, size);
68    if (ret == NULL)
69        err(1, "couldn't realloc %zu bytes\n", size);
70    return ret;
71}
72
73/**
74 * Split a string based on the given delimiter.  The substrings are pointers
75 * into string, which has string terminators added to slice it into substrings.
76 * Do not free the returned substrings.  num passes in the maximum number of
77 * substrings to create and is returned as the number actually created.
78 */
79#define MAXSPLIT    1024
80void abac_split(char *string, char *delim, char **ret, int *num) {
81    int len = strlen(delim);
82    char *start = string;
83    int count = 0;
84    int lim = (num && *num > 0) ? *num : MAXSPLIT;
85
86    // split the string by the delim.  Split into at most lim parts
87    while ((start = strstr(string, delim)) != NULL && count < lim-1) {
88        *start = 0;
89        ret[count++] = string;
90        string = start + len;
91    }
92    ret[count++] = string;
93
94    *num = count;
95}
96
97int abac_clean_name(char *string) {
98    int i;
99
100    assert(string != NULL);
101
102    // must start with a letter/number
103    if (!isalnum(string[0])) return 0;
104
105    // Name must be alphanumeric or - or _ or :
106    for (i = 1; string[i] != '\0'; ++i)
107        if (!isalnum(string[i]) && string[i] != '-' && string[i] != '_' &&
108                string[i] != ':')
109            return 0;
110
111    return 1;
112}
113
Note: See TracBrowser for help on using the repository browser.