Class: PDF::Reader::TypeCheck

Inherits:
Object
  • Object
show all
Defined in:
lib/pdf/reader/type_check.rb

Overview

Cast untrusted input (usually parsed out of a PDF file) to a known type

Class Method Summary collapse

Class Method Details

.cast_to_int!(obj) ⇒ Object

: (untyped) -> Integer



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/pdf/reader/type_check.rb', line 13

def self.cast_to_int!(obj)
  if obj.is_a?(Integer)
    obj
  elsif obj.nil?
    0
  elsif obj.respond_to?(:to_i)
    obj.to_i
  else
    raise MalformedPDFError, "Unable to cast to integer"
  end
end

.cast_to_numeric!(obj) ⇒ Object

: (untyped) -> Numeric



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/pdf/reader/type_check.rb', line 26

def self.cast_to_numeric!(obj)
  if obj.is_a?(Numeric)
    obj
  elsif obj.nil?
    0
  elsif obj.respond_to?(:to_f)
    obj.to_f
  elsif obj.respond_to?(:to_i)
    obj.to_i
  else
    raise MalformedPDFError, "Unable to cast to numeric"
  end
end

.cast_to_pdf_dict!(obj) ⇒ Object

: (untyped) -> Hash[Symbol, untyped]



77
78
79
80
81
82
83
84
85
# File 'lib/pdf/reader/type_check.rb', line 77

def self.cast_to_pdf_dict!(obj)
  if obj.is_a?(Hash)
    obj
  elsif obj.respond_to?(:to_h)
    obj.to_h
  else
    raise MalformedPDFError, "Unable to cast to hash"
  end
end

.cast_to_pdf_dict_with_stream_values!(obj) ⇒ Object

: (untyped) -> Hash[Symbol, PDF::Reader::Stream]



88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/pdf/reader/type_check.rb', line 88

def self.cast_to_pdf_dict_with_stream_values!(obj)
  if obj.is_a?(Hash)
    result = Hash.new
    obj.each do |k, v|
      raise MalformedPDFError, "Expected a stream" unless v.is_a?(PDF::Reader::Stream)
      result[cast_to_symbol!(k)] = v
    end
    result
  elsif obj.respond_to?(:to_h)
    cast_to_pdf_dict_with_stream_values!(obj.to_h)
  else
    raise MalformedPDFError, "Unable to cast to hash"
  end
end

.cast_to_string!(string) ⇒ Object

: (untyped) -> String



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/pdf/reader/type_check.rb', line 41

def self.cast_to_string!(string)
  if string.is_a?(String)
    string
  elsif string.nil?
    ""
  elsif string.respond_to?(:to_s)
    string.to_s
  else
    raise MalformedPDFError, "Unable to cast to string"
  end
end

.cast_to_symbol(obj) ⇒ Object

: (untyped) -> Symbol | nil



54
55
56
57
58
59
60
61
62
63
64
# File 'lib/pdf/reader/type_check.rb', line 54

def self.cast_to_symbol(obj)
  if obj.is_a?(Symbol)
    obj
  elsif obj.nil?
    nil
  elsif obj.respond_to?(:to_sym)
    obj.to_sym
  else
    raise MalformedPDFError, "Unable to cast to symbol"
  end
end

.cast_to_symbol!(obj) ⇒ Object

: (untyped) -> Symbol



67
68
69
70
71
72
73
74
# File 'lib/pdf/reader/type_check.rb', line 67

def self.cast_to_symbol!(obj)
  res = cast_to_symbol(obj)
  if res.nil?
    raise MalformedPDFError, "Unable to cast to symbol"
  else
    res
  end
end