Created
June 7, 2011 10:45
-
-
Save alisdair/1012026 to your computer and use it in GitHub Desktop.
String#unpack format string width
This file contains 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
# http://www.ruby-doc.org/core/classes/String.html#M001112 | |
# | |
# Calculate how many bytes String#unpack will read for a format string. | |
# | |
# Only guaranteed to work with the characters defined in classes, which are | |
# the sensible ones you should be using anyway. So there. | |
# | |
# Notably will not work with x, X, @, and so on. | |
def width(format) | |
classes = { "AazCc" => 1, "Ssn" => 2, "LlNVFfeg" => 4, "QqDdEG" => 8 } | |
bytes = Hash[classes.map {|k,v| k.each_char.map {|x| [x, v] } }.reduce(:+)] | |
directives = format.scan(/([A-Za-z])(\d*)/) | |
directives.map { |c,n| b = bytes[c] * [1, n.to_i].max }.reduce(:+) | |
end | |
p width("NnccNcc") | |
p width("N2s48") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment