Module: KSUID::Utils Private

Defined in:
lib/ksuid/utils.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Utility functions for converting between different encodings

Class Method Summary collapse

Class Method Details

.byte_string_from_array(bytes) ⇒ Array<Integer>

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Converts a byte string into a byte array

Parameters:

  • bytes (String)

    a byte string

Returns:

  • (Array<Integer>)

    an array of bytes from the byte string



12
13
14
# File 'lib/ksuid/utils.rb', line 12

def self.byte_string_from_array(bytes)
  bytes.pack('C*')
end

.bytes_to_hex_string(bytes) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Converts a byte string or byte array into a hex-encoded string

Parameters:

  • bytes (String, Array<Integer>)

    the byte string or array

Returns:

  • (String)

    the byte string as a hex-encoded string



20
21
22
23
24
25
26
# File 'lib/ksuid/utils.rb', line 20

def self.bytes_to_hex_string(bytes)
  bytes = bytes.bytes if bytes.is_a?(String)

  byte_string_from_array(bytes)
    .unpack1('H*')
    .upcase
end

.int_from_bytes(bytes) ⇒ Integer

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Converts a byte string or byte array into an integer

Parameters:

  • bytes (String, Array<Integer>)

    the byte string or array

Returns:

  • (Integer)

    the resulting integer



32
33
34
35
36
37
38
39
# File 'lib/ksuid/utils.rb', line 32

def self.int_from_bytes(bytes)
  bytes = bytes.bytes if bytes.is_a?(String)

  bytes
    .map { |byte| byte.to_s(2).rjust(8, '0') }
    .join('')
    .to_i(2)
end

.int_to_bytes(int, bits = 32) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Converts an integer into a network-ordered (big endian) byte string

Parameters:

  • int (Integer)

    the integer to convert

  • bits (Integer) (defaults to: 32)

    the expected number of bits for the result

Returns:

  • (String)

    the byte string



46
47
48
49
50
51
52
53
54
# File 'lib/ksuid/utils.rb', line 46

def self.int_to_bytes(int, bits = 32)
  int
    .to_s(2)
    .rjust(bits, '0')
    .split('')
    .each_slice(8)
    .map { |digits| digits.join.to_i(2) }
    .pack("C#{bits / 8}")
end