Debian Codegraph @

compiler/natives/src/time/time.go

raw
1 // +build js
2
3 package time
4
5 import (
6 "runtime"
7
8 "github.com/gopherjs/gopherjs/js"
9 )
10
11 // Make sure time.Unix func and time.Time struct it returns are always included with this package (despite DCE),
12 // because they're needed for internalization/externalization of time.Time/Date. See issue https://github.com/gopherjs/gopherjs/issues/279.
13 func init() {
14 // avoid dead code elimination
15 var _ Time = Unix(0, 0)
16 }
17
18 type runtimeTimer struct {
19 i int32
20 when int64
21 period int64
22 f func(interface{}, uintptr)
23 arg interface{}
24 timeout *js.Object
25 active bool
26 }
27
28 func initLocal() {
29 d := js.Global.Get("Date").New()
30 s := d.String()
31 i := indexByte(s, '(')
32 j := indexByte(s, ')')
33 if i == -1 || j == -1 {
34 localLoc.name = "UTC"
35 return
36 }
37 localLoc.name = s[i+1 : j]
38 localLoc.zone = []zone{{localLoc.name, d.Call("getTimezoneOffset").Int() * -60, false}}
39 }
40
41 func runtimeNano() int64 {
42 return js.Global.Get("Date").New().Call("getTime").Int64() * int64(Millisecond)
43 }
44
45 func now() (sec int64, nsec int32, mono int64) {
46 n := runtimeNano()
47 return n / int64(Second), int32(n % int64(Second)), n
48 }
49
50 func Sleep(d Duration) {
51 c := make(chan struct{})
52 js.Global.Call("$setTimeout", js.InternalObject(func() { close(c) }), int(d/Millisecond))
53 <-c
54 }
55
56 func startTimer(t *runtimeTimer) {
57 t.active = true
58 diff := (t.when - runtimeNano()) / int64(Millisecond)
59 if diff > 1<<31-1 { // math.MaxInt32
60 return
61 }
62 if diff < 0 {
63 diff = 0
64 }
65 t.timeout = js.Global.Call("$setTimeout", js.InternalObject(func() {
66 t.active = false
67 if t.period != 0 {
68 t.when += t.period
69 startTimer(t)
70 }
71 go t.f(t.arg, 0)
72 }), diff+1)
73 }
74
75 func stopTimer(t *runtimeTimer) bool {
76 js.Global.Call("clearTimeout", t.timeout)
77 wasActive := t.active
78 t.active = false
79 return wasActive
80 }
81
82 func loadLocation(name string) (*Location, error) {
83 return loadZoneFile(runtime.GOROOT()+"/lib/time/zoneinfo.zip", name)
84 }
85
86 func forceZipFileForTesting(zipOnly bool) {
87 }
88
89 func initTestingZone() {
90 z, err := loadLocation("America/Los_Angeles")
91 if err != nil {
92 panic("cannot load America/Los_Angeles for testing: " + err.Error())
93 }
94 z.name = "Local"
95 localLoc = *z
96 }
97
98 // indexByte is copied from strings package to avoid importing it (since the real time package doesn't).
99 func indexByte(s string, c byte) int {
100 return js.InternalObject(s).Call("indexOf", js.Global.Get("String").Call("fromCharCode", c)).Int()
101 }