/
Javascript.pm6
97 lines (75 loc) · 2.24 KB
/
Javascript.pm6
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use v6;
#------------------------------------------------------------------------------
unit package BSON:auth<github:MARTIMM>;
use BSON;
#------------------------------------------------------------------------------
class Javascript {
has Str $.javascript;
has $.scope;
has Buf $!encoded-scope;
has Bool $.has-javascript = False;
has Bool $.has-scope = False;
#---------------------------------------------------------------------------
submethod BUILD (
Str :$!javascript,
:$!scope where (.^name eq 'BSON::Document' or $_ ~~ Any)
) {
$!has-javascript = ?$!javascript;
$!has-scope = ?$!scope;
$!encoded-scope = $!scope.encode if $!has-scope;
}
#---------------------------------------------------------------------------
method perl ( Int $indent = 0 --> Str ) {
$indent = 0 if $indent < 0;
my Str $perl = "BSON::Javascript.new\(";
my $jvs-i1 = ' ' x ($indent + 1);
my $jvs-i2 = ' ' x ($indent + 2);
if $!javascript {
$perl ~= "\n$jvs-i1\:javascript\(\n";
$perl ~= (map {$jvs-i2 ~ $_}, $!javascript.lines).join("\n");
$perl ~= "\n$jvs-i1)";
if $!scope {
$perl ~= ",\n";
}
else {
$perl ~= "\n";
}
}
if $!scope {
$perl ~= $jvs-i1 ~ ":scope\(\n{$!scope.perl($indent+2)}";
$perl ~= $jvs-i1 ~ ")\n";
}
$perl ~= ' ' x $indent ~ ")";
}
#---------------------------------------------------------------------------
method encode ( --> Buf ) {
my Buf $js;
if $!has-javascript {
$js = encode-string($!javascript);
$js ~= $!encoded-scope if $!has-scope;
}
else {
die X::BSON.new(
:operation<encode>, :type<Javscript>,
:error('cannot process empty javascript code')
);
}
$js
}
#---------------------------------------------------------------------------
method decode (
Buf:D $b, Int:D $index is copy, :$bson-doc, Buf :$scope
--> BSON::Javascript
) {
my $js;
if ?$scope and ?$bson-doc {
$bson-doc.decode($scope);
$js = BSON::Javascript.new(
:javascript( decode-string( $b, $index)), :scope($bson-doc)
);
}
else {
$js = BSON::Javascript.new( :javascript( decode-string( $b, $index)));
}
}
}