Class: Dommy::TextDecoder
- Inherits:
-
Object
- Object
- Dommy::TextDecoder
- Includes:
- Bridge::Methods
- Defined in:
- lib/dommy/text_codec.rb
Overview
‘TextDecoder` — decodes bytes into a String. Supports utf-8, utf-16, utf-16le, utf-16be, iso-8859-1 (best-effort).
Instance Attribute Summary collapse
-
#encoding ⇒ Object
readonly
Returns the value of attribute encoding.
Instance Method Summary collapse
- #__js_call__(method, args) ⇒ Object
- #__js_get__(key) ⇒ Object
-
#decode(input = nil, options = nil) ⇒ Object
decode(bytes, stream) → String.
- #fatal? ⇒ Boolean
- #ignore_bom? ⇒ Boolean
-
#initialize(label = "utf-8", options = nil) ⇒ TextDecoder
constructor
A new instance of TextDecoder.
Methods included from Bridge::Methods
Constructor Details
#initialize(label = "utf-8", options = nil) ⇒ TextDecoder
Returns a new instance of TextDecoder.
40 41 42 43 44 45 46 |
# File 'lib/dommy/text_codec.rb', line 40 def initialize(label = "utf-8", = nil) label = "utf-8" if label.nil? || label.equal?(Bridge::UNDEFINED) @encoding = normalize_encoding(label.to_s) opts = .is_a?(Hash) ? : {} @fatal = truthy?(opts["fatal"] || opts[:fatal]) @ignore_bom = truthy?(opts["ignoreBOM"] || opts[:ignoreBOM]) end |
Instance Attribute Details
#encoding ⇒ Object (readonly)
Returns the value of attribute encoding.
48 49 50 |
# File 'lib/dommy/text_codec.rb', line 48 def encoding @encoding end |
Instance Method Details
#__js_call__(method, args) ⇒ Object
84 85 86 87 88 89 |
# File 'lib/dommy/text_codec.rb', line 84 def __js_call__(method, args) case method when "decode" decode(args[0], args[1]) end end |
#__js_get__(key) ⇒ Object
74 75 76 77 78 79 80 |
# File 'lib/dommy/text_codec.rb', line 74 def __js_get__(key) case key when "encoding" then @encoding when "fatal" then @fatal when "ignoreBOM" then @ignore_bom end end |
#decode(input = nil, options = nil) ⇒ Object
decode(bytes, stream) → String. Accepts a Bytes buffer (JS ArrayBuffer / TypedArray), an Array<Integer>, or a binary String. With ‘fatal: true` an invalid sequence throws a TypeError; otherwise it is replaced with U+FFFD. A leading BOM is stripped unless `ignoreBOM` was set.
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/dommy/text_codec.rb', line 57 def decode(input = nil, = nil) stream = .is_a?(Hash) && truthy?(["stream"] || [:stream]) bytes = extract_bytes(input) if @encoding == "utf-8" decode_utf8(bytes, stream) else # Non-UTF-8 (utf-16le/be, iso-8859-1): no streaming/exact-FFFD semantics, # best-effort via Ruby's transcoder. bytes = strip_bom(bytes) unless @ignore_bom raw = bytes.force_encoding(ruby_encoding) raise Bridge::TypeError, "decode failed" if @fatal && !raw.valid_encoding? raw.encode(Encoding::UTF_8, invalid: :replace, undef: :replace) end end |
#fatal? ⇒ Boolean
50 |
# File 'lib/dommy/text_codec.rb', line 50 def fatal? = @fatal |
#ignore_bom? ⇒ Boolean
51 |
# File 'lib/dommy/text_codec.rb', line 51 def ignore_bom? = @ignore_bom |