// Copyright 2014, 2015 by Sascha L. Teichmann
// Use of this source code is governed by the MIT license
// that can be found in the LICENSE file.

package common

import (
	"math/rand"
	"testing"
)

const spanItems = 3000

func TestSpans(t *testing.T) {

	sp := NewSpanPool()
	var s *Span

	for i := 0; i < spanItems; i++ {
		s = sp.Insert(s, int32(i), 42)
	}

	if n := s.Len(); n != 1 {
		t.Errorf("inc: Span length %d expected 1\n", n)
		t.Errorf("spans: %s\n", s)
	}

	sp.FreeAll(s)

	s = nil
	for i := spanItems - 1; i >= 0; i-- {
		s = sp.Insert(s, int32(i), 42)
	}

	if n := s.Len(); n != 1 {
		t.Errorf("dec: Span length %d expected 1\n", n)
		t.Errorf("spans: %s\n", s)
	}

	sp.FreeAll(s)

	s = nil
	for i := 0; i < spanItems/2; i++ {
		j := spanItems - 1 - i
		s = sp.Insert(s, int32(i), 42)
		s = sp.Insert(s, int32(j), 21)
	}

	if n := s.Len(); n != 2 {
		t.Errorf("two: Span length %d expected 2\n", n)
		t.Errorf("spans: %s\n", s)
	}

	sp.FreeAll(s)

	inp := make([]int32, spanItems)
	for i := 0; i < spanItems; i++ {
		inp[i] = int32(i)
	}

	for i := 0; i < spanItems; i++ {
		i1 := rand.Int31n(int32(spanItems))
		i2 := rand.Int31n(int32(spanItems))
		inp[i1], inp[i2] = inp[i2], inp[i1]
	}

	s = nil
	for i := 0; i < spanItems; i++ {
		s = sp.Insert(s, inp[i], 42)
	}

	if n := s.Len(); n != 1 {
		t.Errorf("rand: Span length %d expected 1\n", n)
		t.Errorf("spans: %s\n", s)
	}

	sp.FreeAll(s)
}