packages feed

zeolite-lang-0.22.0.0: lib/container/test/hashed-set.0rt

/* -----------------------------------------------------------------------------
Copyright 2021 Kevin P. Barry

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----------------------------------------------------------------------------- */

// Author: Kevin P. Barry [ta0kira@gmail.com]

testcase "HashedSet tests" {
  success
}

unittest addAndRemove {
  HashedSet<Int> set <- HashedSet<Int>.default()
  Int hash <- 13
  Int max  <- 20
  $ReadOnly[hash,max]$

  // Populate the set in a pseudo-random order.
  traverse (Counter.zeroIndexed(max) -> Int i) {
    \ set.add((i*hash)%max)
    \ Testing.checkEquals(set.size(),i+1)
  }

  // Remove only the odd elements.
  traverse (Counter.zeroIndexed(max) -> Int i) {
    if (i%2 == 1) {
      // Remove it twice to ensure idempotence.
      \ set.remove(i).remove(i)
    }
    \ Testing.checkEquals(set.size(),max-(i+1)/2)
  }

  // Validate set membership.
  traverse (Counter.zeroIndexed(max) -> Int i) {
    \ Testing.checkEquals(set.member(i),i%2 == 0)
  }
}

unittest append {
  HashedSet<Int> set <- HashedSet<Int>.new()
  \ set.append(3)
  \ Testing.checkEquals(set.size(),1)
  \ Testing.checkTrue(set.member(3))
}

unittest removeNotPresent {
  HashedSet<Int> set <- HashedSet<Int>.new().add(1).add(2).add(4)
  \ set.remove(3)
  \ Testing.checkEquals(set.size(),3)
}

unittest defaultOrder {
  HashedSet<Int> set <- HashedSet<Int>.new()
  Int hash <- 13
  Int max  <- 20
  $ReadOnly[hash,max]$

  // Populate the set in a pseudo-random order.
  traverse (Counter.zeroIndexed(max) -> Int i) {
    \ set.add((i*hash)%max)
  }

  Vector<Bool> visited <- Vector:createSize<Bool>(max)

  // Validate traversal coverage.
  Int index <- 0
  traverse (set.defaultOrder() -> Int entry) {
    \ Testing.checkFalse(visited.readAt(entry))
    \ visited.writeAt(entry,true)
    index <- index+1
  }

  \ Testing.checkEquals(index,max)
}

unittest defaultOrderEmpty {
  traverse (HashedSet<Int>.new().defaultOrder() -> _) {
    fail("not empty")
  }
}

unittest duplicate {
  HashedSet<Int> set <- HashedSet<Int>.new().add(1).add(2)

  HashedSet<Int> copy <- set.duplicate()
  \ Testing.checkEquals(copy.size(),2)
  \ Testing.checkTrue(copy.member(1))
  \ Testing.checkTrue(copy.member(1))

  \ copy.remove(2)
  \ Testing.checkEquals(copy.size(),1)
  \ Testing.checkTrue(copy.member(1))
  \ Testing.checkTrue(set.member(2))
}