Skip to content

Commit

Permalink
[Buf] Str.encode and Buf.decode
Browse files Browse the repository at this point in the history
Also a few other goodies, such as the Stringy role.
A bunch of tests now pass in t/spec/S32-str/encode.rakudo.
  • Loading branch information
Carl Masak committed May 28, 2010
1 parent 63c5a5c commit c5fdb17
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 1 deletion.
2 changes: 2 additions & 0 deletions build/Makefile.in
Expand Up @@ -190,6 +190,8 @@ CORE_SOURCES = \
src/core/Num.pm \
src/core/Rat.pm \
src/core/Complex.pm \
src/core/Stringy.pm \
src/core/Buf.pm \
src/core/Str.pm \
src/core/Whatever.pm \
src/core/Pair.pm \
Expand Down
42 changes: 42 additions & 0 deletions src/core/Buf.pm
@@ -0,0 +1,42 @@
role Buf[::T = Int] does Stringy {
has @.contents;

multi method new(@contents) {
self.bless(*, :contents(@contents.list));
}

multi method new(*@contents) {
self.bless(*, :contents(@contents.list));
}

multi method decode($encoding = 'UTF-8') {
my @contents = @.contents;
my $str = ~Q:PIR {
$P0 = find_lex '@contents'

.local pmc iterator
iterator = iter $P0
.local pmc sb
sb = new 'StringBuilder'
sb = unicode:""
loop:
unless iterator goto done
$P1 = shift iterator
$I1 = $P1
$S1 = chr $I1
sb .= $S1
goto loop
done:
%r = sb
};
return $str;
}

multi method elems() {
@.contents.elems;
}
}

our multi sub infix:<eqv>(Buf $a, Buf $b) {
return $a.contents ~~ $b.contents;
}
27 changes: 26 additions & 1 deletion src/core/Str.pm
@@ -1,4 +1,4 @@
augment class Str {
augment class Str does Stringy {
multi method Bool { ?(pir::istrue__IP(self)); }

method Str() { self }
Expand All @@ -19,4 +19,29 @@ augment class Str {
method s() {
self.e ?? pir::stat__ISI(self, 1) !! Any;
}

# XXX: We have no $?ENC or $?NF compile-time constants yet.
multi method encode($encoding = 'UTF-8', $nf = '') {
my @bytes = Q:PIR {
.local int bin_coding, i, max, byte
.local string bin_string
.local pmc it, result
$P0 = find_lex 'self'
$S0 = $P0
bin_coding = find_encoding 'fixed_8'
bin_string = trans_encoding $S0, bin_coding
result = new ['Parcel']
i = 0
max = length bin_string
bytes_loop:
if i >= max goto bytes_done
byte = ord bin_string, i
push result, byte
inc i
goto bytes_loop
bytes_done:
%r = result
};
return Buf.new(@bytes);
}
}
2 changes: 2 additions & 0 deletions src/core/Stringy.pm
@@ -0,0 +1,2 @@
role Stringy {
}

0 comments on commit c5fdb17

Please sign in to comment.