#!/usr/local/bin/ruby -d -Kn

require 'textbuf'


def ev( code, bind = nil )
  unless bind then
    bind = TOPLEVEL_BINDING
  end
  eval code, bind
end


$assert_n = 1

def chk( code, bind = nil )
  unless ev( code, bind ) then
    raise ArgumentError, "\n\ntest #{$assert_n} fail: #{code}"
  end
  $assert_n += 1
end

def try( code, bind = nil )
  print "try test #{$assert_n}..."
  ev code, bind
  puts "ok"
  $assert_n += 1
end


###
###
###

puts 'fundamental test'

buf = StringBuffer.new
try "buf.inspect"

m = buf.new_mark
try "m.inspect"

try "GC.start"

#----

puts 'insertion test'

str1 = 'string1'
str2 = 'string2'
str3 = 'string3'
m.insert str1
m.insert str2
m.insert str3

$whole = str1 + str2 + str3

chk 'm.index == $whole.size'
chk "m.index == m.byte_index"

#----

puts 'back test'

m.back 1
chk 'm.index == $whole.size - 1'
chk 'm.index == m.byte_index'

m.back 1
chk 'm.index == $whole.size - 2'
chk "m.index == m.byte_index"

m.back 1
chk 'm.index == $whole.size - 3'
chk "m.index == m.byte_index"

#----

puts 'forward test'

m.forward 1
chk 'm.index == $whole.size - 2'
chk "m.index == m.byte_index"

m.forward 1
chk 'm.index == $whole.size - 1'
chk "m.index == m.byte_index"

m.forward 1
chk 'm.index == $whole.size'
chk "m.index == m.byte_index"

#----

puts 'motion test (big)'

m.forward 1000
m.back    1000
m.forward 1000
m.back    1000
m.forward 1000
m.back    1000

chk 'm.index == 0'
chk "m.index == m.byte_index"

#----

puts 'substr test'

chk 'm[5] == $whole[0,5]'
chk 'm[1000] == $whole'

#---

puts 'mark test'

m2 = buf.new_mark
chk 'm2.index == 0'
chk "m2.index == m2.byte_index"

m2.forward 1
chk 'm2.index == 1'
chk "m2.index == m2.byte_index"

m2.forward 1
chk 'm2.index == 2'
chk "m2.index == m2.byte_index"

m2.forward 1
chk 'm2.index == 3'
chk "m2.index == m2.byte_index"

chk 'm2[5] == $whole[3,5]'

m3 = buf.new_mark(0)
chk 'm3.index == 0'
chk "m3.index == m3.byte_index"

m2.back 1
chk 'm2.index == 2'
chk "m2.index == m2.byte_index"

m2.back 1
chk 'm2.index == 1'
chk "m2.index == m2.byte_index"

m2.back 1
chk 'm2.index == 0'
chk "m2.index == m2.byte_index"

chk 'm2[5] == $whole[0,5]'


#----

puts 'insert again'

m2.forward 1000

1.times do
  0.upto( 9 ) do |i|
    m2.insert i.to_s
    m2.back 1
  end
end
m2.back 1000

chk "m2[1000] == buf.string"


#----

m2.head
chk "m2.index == 0"
m2.tail
chk "m2.index == buf.size"
m2.head
chk "m2.index == 0"


#----

buf.size.times do
  m2.delete 1
end
chk "buf.size == 0"


#----

print "\n\nok\n\n\n"
