Skip to content

Commit

Permalink
Implement b"..." byte array literals.
Browse files Browse the repository at this point in the history
Objects are interpolated with calls to write. There
is also a B"..." form which returns a byte sting with
the data field that b"..." would have. In fact b"..."
is completely equivalent to B"...".data (for now).
  • Loading branch information
StefanKarpinski committed Jul 10, 2011
1 parent f9e1dbe commit 6c0f464
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions j/string.j
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ check_utf8 (s::ByteString) = is_valid_utf8(s) ? s : error("invalid UTF-8 sequen

## string interpolation parsing ##

function interp_parse(str::String, unescape::Function)
function interp_parse(str::String, unescape::Function, printer::Function)
strs = {}
i = j = start(str)
while !done(str,j)
Expand All @@ -461,18 +461,26 @@ function interp_parse(str::String, unescape::Function)
if !isempty(str[i:])
push(strs, unescape(str[i:j-1]))
end
length(strs) > 1 ? expr(:call,:strcat,strs...) :
!isa(strs[1],String) ? expr(:call,:string,strs[1]) : strs[1]
length(strs) == 1 && isa(strs[1],ByteString) ? strs[1] :
expr(:call, :print_to_string, printer, strs...)
end

interp_parse(str::String, u::Function) = interp_parse(str, u, print)
interp_parse(str::String) = interp_parse(str, s->check_utf8(unescape_string(s)))

function interp_parse_bytes(s)
writer(x...) = for w=x; write(w); end
interp_parse(s, unescape_string, writer)
end

## core string macros ##

macro str(s); interp_parse(s); end
macro S_str(s); interp_parse(s); end
macro I_str(s); interp_parse(s, unbackslash); end
macro E_str(s); check_utf8(unescape_string(s)); end
macro B_str(s); interp_parse_bytes(s); end
macro b_str(s); ex = interp_parse_bytes(s); :(($ex).data); end

## shell-like command parsing ##

Expand Down

1 comment on commit 6c0f464

@StefanKarpinski
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Closes #11.

Please sign in to comment.