aboutsummaryrefslogtreecommitdiff
path: root/src/base/string/split.c
blob: 6b0a9fd779f2dc347565a4472816e3a0c288f3a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "internal.h"

// split will split the string by the given token.
// returns a stretchy buffer of strings that result from the partition.
// it is the caller's responsibility to clean the memory.
string*
string·split(string s, byte* tok)
{
    string* fields = nil;
    vlong start  = 0;

    vlong sL   = string·len(s);
    vlong tokL = str·len(tok);
    if(sL == 0 || tokL == 0)
        return nil;

    mem·buffit(fields, 5);

    for(vlong i = 0; i < sL - tokL; i++){
        if((tokL == 1 && s[i] == tokL) || !memcmp(s + i, tok, tokL)){
            mem·bufpush(fields, string·makelen(s + start, i - start));
            if(fields[mem·buflen(fields) - 1] == nil) goto cleanup;

            start = i + tokL;
            i += tokL - 1;
        }
    }

    mem·bufpush(fields, string·makelen(s + start, sL - start));

    return fields;

cleanup:
    for(vlong i = 0; i < mem·buflen(fields); i++)
        string·free(fields[i]);

    mem·buffree(fields);
    return nil;
}