Skip to content

Commit

Permalink
Base64#urlsafe_encode now works as in ruby, fixed #3394 (#3403)
Browse files Browse the repository at this point in the history
kostya authored and Ary Borenszweig committed Oct 9, 2016

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent 0c93b1b commit 2da5008
Showing 2 changed files with 9 additions and 12 deletions.
6 changes: 3 additions & 3 deletions spec/std/base64_spec.cr
Original file line number Diff line number Diff line change
@@ -173,15 +173,15 @@ describe "Base64" do
describe "urlsafe" do
it "work" do
s = String.build { |b| (160..179).each { |i| b << i.chr } }
se = "wqDCocKiwqPCpMKlwqbCp8KowqnCqsKrwqzCrcKuwq_CsMKxwrLCsw"
se = "wqDCocKiwqPCpMKlwqbCp8KowqnCqsKrwqzCrcKuwq_CsMKxwrLCsw=="
Base64.urlsafe_encode(s).should eq(se)
end

it "encode to stream" do
s = String.build { |b| (160..179).each { |i| b << i.chr } }
se = "wqDCocKiwqPCpMKlwqbCp8KowqnCqsKrwqzCrcKuwq_CsMKxwrLCsw"
se = "wqDCocKiwqPCpMKlwqbCp8KowqnCqsKrwqzCrcKuwq_CsMKxwrLCsw=="
io = MemoryIO.new
Base64.urlsafe_encode(s, io).should eq(54)
Base64.urlsafe_encode(s, io).should eq(56)
io.rewind
io.gets_to_end.should eq se
end
15 changes: 6 additions & 9 deletions src/base64.cr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# The Base64 module provides for the encoding (`encode`, `strict_encode`,
# `urlsafe_encode`) and decoding (`decode`, `strict_decode`, `urlsafe_decode`)
# `urlsafe_encode`) and decoding (`decode`)
# of binary data using a Base64 representation.
#
# ###Example
@@ -96,7 +96,7 @@ module Base64
end

# :nodoc:
def strict_encode(data, alphabet, pad = false)
private def strict_encode(data, alphabet, pad = false)
slice = data.to_slice
String.new(encode_size(slice.size)) do |buf|
appender = buf.appender
@@ -132,9 +132,9 @@ module Base64
#
# The alphabet uses '-' instead of '+' and '_' instead of '/'.
#
# The `padding` parameter defaults to false. When true, enough `=` characters
# are added to make the output divisible by 3.
def urlsafe_encode(data, padding = false) : String
# The `padding` parameter defaults to true. When false, enough `=` characters
# are not added to make the output divisible by 4.
def urlsafe_encode(data, padding = true) : String
slice = data.to_slice
String.new(encode_size(slice.size)) do |buf|
appender = buf.appender
@@ -149,11 +149,8 @@ module Base64
# Alphabet" in RFC 4648.
#
# The alphabet uses '-' instead of '+' and '_' instead of '/'.
#
# The `padding` parameter defaults to false. When true, enough `=` characters
# are added to make the output divisible by 3.
def urlsafe_encode(data, io : IO)
strict_encode_to_io_internal(data, io, CHARS_SAFE, pad: false)
strict_encode_to_io_internal(data, io, CHARS_SAFE, pad: true)
end

# Returns the Base64-decoded version of `data` as a *Slice(UInt8)*.

0 comments on commit 2da5008

Please sign in to comment.