Method: RbNaCl::Util.check_string

Defined in:
lib/rbnacl/util.rb

.check_string(string, length, description) ⇒ Object

Check a passed in string, converting the argument if necessary

In several places through the codebase we have to be VERY strict with the strings we accept. This method supports that.

Parameters:

  • string (#to_str)

    The input string

  • length (Integer)

    The only acceptable length of the string

  • description (String)

    Description of the string (used in the error)

Raises:

  • (ArgumentError)

    If we cannot convert to a string with #to_str

  • (RbNaCl::LengthError)

    If the string is not the right length



84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/rbnacl/util.rb', line 84

def check_string(string, length, description)
  unless string.respond_to? :to_str
    raise TypeError, "can't convert #{string.class} into String with #to_str"
  end

  string = string.to_str
  unless string.encoding == Encoding::BINARY
    raise EncodingError, "strings must use BINARY encoding (got #{string.encoding})"
  end
  check_length(string, length, description)

  string
end