Statistics
| Branch: | Tag: | Revision:

sssimulator / Matrix / tokens.c @ ec88b090

History | View | Annotate | Download (1.5 KB)

1
/*
2
 * This is SSSim: the Simple & Stupid Simulator
3
 *
4
 *  Copyright (c) 2015 Luca Baldesi
5
 *
6
 *  This is free software; see gpl-3.0.txt
7
 */
8

    
9
#include "tokens.h"
10
#include <malloc.h>
11
#include <string.h>
12

    
13
char * substring_trim(const char * s,uint32_t start,uint32_t len)
14
{
15
        uint32_t leading=0,trailing=0;
16

    
17
        while(leading < len && (s[start+leading] == '\n' || s[start+leading] == ' '))
18
                leading++;
19
        while(trailing < len && (s[start+len-trailing-1] == '\n' || s[start+len-trailing-1] == ' '))
20
                trailing++;
21

    
22
        if(len - leading -trailing > 0)
23
                return strndup(s+start+leading,len-trailing);
24
        else
25
                return NULL;
26
}
27

    
28
void tokens_destroy(char *** sv,uint32_t n)
29
{
30
        uint32_t i;
31

    
32
        if (sv && *sv && **sv)
33
        {
34
                for( i = 0; i < n; i++)
35
                        free((*sv)[i]);
36
                free(*sv);
37
                *sv = NULL;
38
        }
39
}
40

    
41
char ** tokens_create(char * s,const char delim,uint32_t * n)
42
{
43
        char * np =s, *wp = s;
44
        char ** sv = NULL;
45
        uint32_t i;
46

    
47

    
48
        if(s && n && strcmp(s,""))
49
        {
50
                *n = 0;
51
                while((np = strchr(np,delim)))
52
                {
53
                        (*n)++;
54
                        np++;
55
                }
56
                (*n)++;
57
                sv = (char **) malloc(sizeof(char *) * (*n));
58

    
59
                np = s;
60
                for( i=0; i<*n; i++)
61
                {
62
                        np = strchr(np,delim);
63
                        if(np)
64
                        {
65
                                sv[i] = substring_trim(wp,0,np-wp);
66
                                np++;
67
                                wp=np;
68
                        } else
69
                                sv[i] = substring_trim(wp,0,strlen(wp));
70
                }
71
        }
72
        return sv;
73
}
74

    
75
int32_t tokens_check(char ** tokens, uint32_t n, char * target)
76
{
77
        int32_t pos = -1;
78
        uint32_t i;
79

    
80
        if(tokens && *tokens && target)
81
        {
82
                i = 0;
83
                while (pos < 0 && i < n)
84
                {
85
                        if (strcmp(tokens[i], target) == 0)
86
                                pos = i;
87
                        i++;
88
                }
89
        }
90
        return pos;
91
}