Module: Tessel::Color

Defined in:
lib/tessel.rb

Class Method Summary collapse

Class Method Details

.pack(value) ⇒ Object

Raises:

  • (TypeError)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/tessel.rb', line 26

def pack(value)
  bytes = case value
  when String
    if value.bytesize == 4 && !value.start_with?("#")
      value.bytes
    else
    hex = value.delete_prefix("#")
    raise ArgumentError, "color must be #rrggbb or #rrggbbaa" unless [6, 8].include?(hex.length) && hex.match?(/\A[0-9a-fA-F]+\z/)

    hex.scan(/../).map { |part| part.to_i(16) }
    end
  when Array
    raise TypeError, "color must contain 3 or 4 channels" unless [3, 4].include?(value.length)
    raise TypeError, "color channels must be integers" unless value.all? { |channel| channel.is_a?(Integer) }
    raise ArgumentError, "color channels must be between 0 and 255" unless value.all? { |channel| (0..255).cover?(channel) }

    value
  else
    if value.respond_to?(:to_bytes)
      Array(value.to_bytes)
    else
      raise TypeError, "unsupported color: #{value.class}"
    end
  end
  bytes = bytes.dup
  bytes << 255 if bytes.length == 3
  raise TypeError, "color must contain 3 or 4 channels" unless bytes.length == 4
  raise ArgumentError, "color channels must be between 0 and 255" unless bytes.all? { |channel| channel.is_a?(Integer) && (0..255).cover?(channel) }

  bytes.pack("C*").b.freeze
end