base64: encode_url (#6622)

pull/6623/head
Daniel Däschle 2020-10-15 16:04:06 +02:00 committed by GitHub
parent 31ef921ef2
commit df82ef6bc7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 2 deletions

View File

@ -48,6 +48,26 @@ pub fn encode(data string) string {
return tos(buffer, encode_in_buffer(data, buffer)) return tos(buffer, encode_in_buffer(data, buffer))
} }
// decode decodes base64url string to string
pub fn decode_url(data string) string {
mut result := data.replace('-', '+') // 62nd char of encoding
result = data.replace('_', '/') // 63rd char of encoding
match result.len % 4 { // Pad with trailing '='s
2 { result += "==" } // 2 pad chars
3 { result += "=" } // 1 pad char
else { } // no padding
}
return base64.decode(data)
}
// encode encodes given string to base64url string
pub fn encode_url(data string) string {
mut result := base64.encode(data)
// 62nd char of encoding, 63rd char of encoding, remove any trailing '='s
result = result.replace_each(['+', '-', '/', '_', '=', ''])
return result
}
/* /*
decode_in_buffer - expects a string reference, and a buffer in which to store its decoded version. decode_in_buffer - expects a string reference, and a buffer in which to store its decoded version.
@param data - a reference/pointer to the input string that will be decoded. @param data - a reference/pointer to the input string that will be decoded.

View File

@ -67,3 +67,13 @@ fn test_encode() {
} }
} }
} }
fn test_encode_url() {
test := base64.encode_url('Hello Base64Url encoding!')
assert test == 'SGVsbG8gQmFzZTY0VXJsIGVuY29kaW5nIQ'
}
fn test_decode_url() {
test := base64.decode_url("SGVsbG8gQmFzZTY0VXJsIGVuY29kaW5nIQ")
assert test == 'Hello Base64Url encoding!'
}