Class: LazyString
- Inherits:
-
Object
- Object
- LazyString
- Defined in:
- lib/lazy-string.rb
Overview
- Author
-
Natsuki Kawai ([email protected])
- Copyright
-
Copyright © 2012 Natsuki Kawai
- License
-
2-clause BSDL or Ruby’s
Defined Under Namespace
Classes: LazySubString, SubString
Instance Attribute Summary collapse
-
#size ⇒ Object
(also: #length)
readonly
Returns the value of attribute size.
Instance Method Summary collapse
-
#<<(other) ⇒ Object
TODO: Add ‘add’ method to add a substring of a String.
- #[](*args) ⇒ Object
-
#initialize(*args) ⇒ LazyString
constructor
A new instance of LazyString.
- #to_str ⇒ Object (also: #to_s)
- #unpack(template) ⇒ Object
Constructor Details
#initialize(*args) ⇒ LazyString
Returns a new instance of LazyString.
38 39 40 41 42 43 44 45 46 |
# File 'lib/lazy-string.rb', line 38 def initialize(*args) @size = 0 @chain = [] if args.size == 3 @chain << SubString.new(0, LazySubString.new(*args)) @size = args[2] end end |
Instance Attribute Details
#size ⇒ Object (readonly) Also known as: length
Returns the value of attribute size.
114 115 116 |
# File 'lib/lazy-string.rb', line 114 def size @size end |
Instance Method Details
#<<(other) ⇒ Object
TODO: Add ‘add’ method to add a substring of a String.
49 50 51 52 53 54 55 56 |
# File 'lib/lazy-string.rb', line 49 def <<(other) if other.respond_to?(:to_int) return self << ('' << other) end @chain << SubString.new(@size, other) @size += other.size end |
#[](*args) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/lazy-string.rb', line 58 def [](*args) if args.size == 2 start = args[0] last = start + args[1] length = args[1] e = @chain.each curr = nil begin curr = e.next end while curr.start + curr.value.size < start value = curr.value sub_start = start - curr.start sub_length = value.size - sub_start if sub_length >= length return LazyString.new(value, sub_start, length) else res = LazyString.new(value, sub_start, sub_length) length -= sub_length while length > 0 curr = e.next if length < curr.value.length res << LazyString.new(curr.value, 0, length) length = 0 else res << curr.value length -= curr.value.length end end return res end elsif args.respond_to?(:to_int) warn "#{self.class.name}#[pos] has not implemented yet. Calling #{self.class.name}#to_str." to_str[*args] else # args is one Range object. warn "#{self.class.name}#[range] has not implemented yet. Calling #{self.class.name}#to_str." to_str[*args] end end |
#to_str ⇒ Object Also known as: to_s
105 106 107 108 109 110 111 |
# File 'lib/lazy-string.rb', line 105 def to_str res = '' @chain.each do |substr| res << substr.value end return res end |
#unpack(template) ⇒ Object
99 100 101 102 103 |
# File 'lib/lazy-string.rb', line 99 def unpack(template) # TODO: Optimize here. # (Stop concat the front strings if template start with "x".) to_str.unpack(template) end |