aboutsummaryrefslogtreecommitdiff
path: root/system/libraries/string/location.zig
blob: ff1c915d9a9cd3eb2a5c55fd6dd61d3d2a9232d1 (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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//! Location utilities

pub fn getStackName(location: []const u8) []const u8 {
    if (location.len == 0 or (location.len == 1 and location[0] == '/')) {
        return "/";
    }

    var last_slash: usize = 0;
    for (location, 0..) |c, i| {
        if (c == '/') {
            last_slash = i;
        }
    }

    if (last_slash == location.len - 1 and location.len > 1) {
        var i: usize = location.len - 2;
        while (i > 0) : (i -= 1) {
            if (location[i] == '/') {
                return location[i + 1 .. location.len - 1];
            }
        }
        return location[1 .. location.len - 1];
    }

    if (last_slash + 1 < location.len) {
        return location[last_slash + 1 ..];
    }

    return location;
}

pub fn parent(location: []const u8, buf: []u8) []const u8 {
    if (location.len <= 1) {
        buf[0] = '/';
        return buf[0..1];
    }

    var end = location.len;
    if (location[end - 1] == '/') {
        end -= 1;
    }

    var i: usize = end;
    while (i > 0) : (i -= 1) {
        if (location[i - 1] == '/') {
            if (i == 1) {
                buf[0] = '/';
                return buf[0..1];
            }
            for (location[0 .. i - 1], 0..) |c, j| {
                buf[j] = c;
            }
            return buf[0 .. i - 1];
        }
    }

    buf[0] = '/';
    return buf[0..1];
}