Created
August 26, 2020 11:40
-
-
Save pjmartorell/77a824a51e80e5183396b8b72cd7e81e to your computer and use it in GitHub Desktop.
Calculate the size of Base64.encode64 (strict or not) in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def calculate_base64_size(size, strict: false) | |
# see http://stackoverflow.com/questions/13378815/base64-length-calculation for more details about this calculation | |
code_size = (size * 4) / 3 | |
# Adds padding (0, 1 or 2 '=') depending on the size | |
padding = size % 3 ? (3 - (size % 3)) : 0 | |
# sum plus terminating null character | |
padded_size = code_size + padding + 1 | |
# The RFC 2045 states that 'the encoded output stream must be represented in lines of no more than 76 characters | |
# each', so every implementation is free to choose a number lower than 76 chars. Ruby stdlib for example does it | |
# every 60 chars, feel free to change it to another number depending on the implementation of base64. | |
newline_size = strict ? 0 : (padded_size / 60.0).ceil | |
padded_size + newline_size | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment