-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
time_runits.go
69 lines (60 loc) · 1.89 KB
/
time_runits.go
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
// Code generated by __generator__/interpreter.go at once
package builtin
import (
"fmt"
"strconv"
"github.com/ysugimoto/falco/interpreter/context"
"github.com/ysugimoto/falco/interpreter/function/errors"
"github.com/ysugimoto/falco/interpreter/value"
)
const Time_runits_Name = "time.runits"
var Time_runits_ArgumentTypes = []value.Type{value.StringType, value.RTimeType}
func Time_runits_Validate(args []value.Value) error {
if len(args) != 2 {
return errors.ArgumentNotEnough(Time_runits_Name, 2, args)
}
for i := range args {
if args[i].Type() != Time_runits_ArgumentTypes[i] {
return errors.TypeMismatch(Time_runits_Name, i+1, Time_runits_ArgumentTypes[i], args[i].Type())
}
}
return nil
}
// Fastly built-in function implementation of time.runits
// Arguments may be:
// - STRING, RTIME
// Reference: https://developer.fastly.com/reference/vcl/functions/date-and-time/time-runits/
func Time_runits(ctx *context.Context, args ...value.Value) (value.Value, error) {
// Argument validations
if err := Time_runits_Validate(args); err != nil {
return value.Null, err
}
unit := value.Unwrap[*value.String](args[0]).Value
rtime := value.Unwrap[*value.RTime](args[1]).Value
switch unit {
case "s":
return &value.String{
Value: fmt.Sprintf("%d", int64(rtime.Seconds())),
}, nil
case "ms":
v := float64(rtime.Milliseconds()) / 1000
return &value.String{
Value: strconv.FormatFloat(v, 'f', 3, 64),
}, nil
case "us":
v := float64(rtime.Microseconds()) / 1000000
return &value.String{
Value: strconv.FormatFloat(v, 'f', 6, 64),
}, nil
case "ns":
v := float64(rtime.Nanoseconds()) / 1000000000
return &value.String{
Value: strconv.FormatFloat(v, 'f', 9, 64),
}, nil
default:
ctx.FastlyError = &value.String{Value: "EINVAL"}
return &value.String{IsNotSet: true}, errors.New(Time_runits_Name,
"Invalid unit string %s, allow either of s, ms, us and ns", unit,
)
}
}