forked from zhemao/glisp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
channels.go
64 lines (54 loc) · 1.3 KB
/
channels.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
package glispext
import (
"errors"
"fmt"
"github.com/zhemao/glisp/interpreter"
)
type SexpChannel chan glisp.Sexp
func (ch SexpChannel) SexpString() string {
return "[chan]"
}
func MakeChanFunction(env *glisp.Glisp, name string,
args []glisp.Sexp) (glisp.Sexp, error) {
if len(args) > 1 {
return glisp.SexpNull, glisp.WrongNargs
}
size := 0
if len(args) == 1 {
switch t := args[0].(type) {
case glisp.SexpInt:
size = int(t)
default:
return glisp.SexpNull, errors.New(
fmt.Sprintf("argument to %s must be int", name))
}
}
return SexpChannel(make(chan glisp.Sexp, size)), nil
}
func ChanTxFunction(env *glisp.Glisp, name string,
args []glisp.Sexp) (glisp.Sexp, error) {
if len(args) < 1 {
return glisp.SexpNull, glisp.WrongNargs
}
var channel chan glisp.Sexp
switch t := args[0].(type) {
case SexpChannel:
channel = chan glisp.Sexp(t)
default:
return glisp.SexpNull, errors.New(
fmt.Sprintf("argument 0 of %s must be channel", name))
}
if name == "send!" {
if len(args) != 2 {
return glisp.SexpNull, glisp.WrongNargs
}
channel <- args[1]
return glisp.SexpNull, nil
}
return <-channel, nil
}
func ImportChannels(env *glisp.Glisp) {
env.AddFunction("make-chan", MakeChanFunction)
env.AddFunction("send!", ChanTxFunction)
env.AddFunction("<!", ChanTxFunction)
}