aboutsummaryrefslogtreecommitdiff
path: root/nerv/tnn/sutil.lua
blob: 6a968b769d4d7c5cb90abfda4a2370aa1dfeb824 (plain) (blame)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
local Util = nerv.class("nerv.SUtil") --Scheduler Utility

function Util.simple_split(inputstr, sep)
    if sep == nil then
        sep = "%s"
    end
    local t={} ; i=1
    for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
        t[i] = str
        i = i + 1
    end
    return t
end

function Util.parse_schedule(str)
    --parse a string like "1.2*10:1.5" to a list of numbers
    local sch = {}
    local s = Util.simple_split(str, ':')
    for i = 1, #s do
        local p = Util.simple_split(s[i], "%*")
        if #p ~= 2 and #p ~= 1 then
            nerv.error("nerv.SUtil:parse_schedule error, unit(%s) not proper, has %d components.", s[i], #p)
        end
        if p[2] == nil then
            p[2] = "1"
        end 
        p[1] = tonumber(p[1])
        p[2] = tonumber(p[2])
        for j = 1, p[2] do
            table.insert(sch, p[1])
        end 
    end 

    --for i = 1, #sch do
    --    print(sch[i])
    --end
    return sch
end

function Util.sche_get(s, it)
    --get s[it]
    if s == nil then
        nerv.info("Util.sche_get: warning, scheule is nil, returning zero...")
        return 0
    end
    if #s >= it then
        return s[it]
    else
        nerv.info("Util.sche_get: warning, it(%d) > #schedule(%d), returning the last one of schedule(%f)...", it, #s, s[#s])
        return s[#s]
    end
end

function Util.parse_commands_set(str)
    local coms = {}
    local s = Util.simple_split(str, ':,')
    for i = 1 ,#s do
        if coms[s[i]] == 1 then
            nerv.warning("nerv.SUtil.parse_commands_set command(%s) appered more than once in command_set(%s)", s[i], str)
        end
        coms[s[i]] = 1
    end
    return coms
end

function Util.log_redirect(fn)
    nerv.log_fh = assert(io.open(fn, "w"))
    nerv.info("CAUTION[LOG_REDIRECT], all nerv.printf/info/warning/error calls will be double-written to %s", fn)
    nerv.printf = 
        function (fmt, ...)
            io.write(nerv.sprintf(fmt, ...))
            nerv.log_fh:write(nerv.sprintf(fmt, ...))
            nerv.log_fh:flush()
        end
    nerv.error = 
        function (fmt, ...)
            nerv.log_fh:write(nerv.sprintf("[nerv] internal error:" .. fmt .. "\n", ...))
            error(nerv.sprintf("[nerv] internal error: " .. fmt .. "\n", ...))
        end
end