zeolite-lang-0.20.0.0: lib/container/src/type-map.0rx
/* -----------------------------------------------------------------------------
Copyright 2019-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]
define TypeMap {
@value SearchTree<TypeKey<any>,GenericValue<any>> tree
new () {
return TypeMap{ SearchTree<TypeKey<any>,GenericValue<any>>.new() }
}
duplicate () {
return #self{ tree.duplicate() }
}
set (k,v) {
\ tree.set(k,GenericValue:create<?>(v))
return self
}
remove (k) {
\ tree.remove(k)
return self
}
get (k) {
scoped {
optional GenericValue<any> value <- tree.get(k)
} in if (present(value)) {
return require(value).check<#x>()
} else {
return empty
}
}
}
define TypeKey {
$ReadOnly[counterMutex,index]$
@category Mutex counterMutex <- SpinlockMutex.new()
@category Int counter <- 0
@value Int index
new () {
scoped {
\ counterMutex.lock()
} cleanup {
\ counterMutex.unlock()
} in return TypeKey<#x>{ (counter <- counter+1) }
}
formatted () {
return String.builder()
.append(typename<#self>())
.append("{")
.append(index)
.append("}")
.build()
}
lessThan (l,r) {
return l.get() < r.get()
}
equals (l,r) {
return l.get() == r.get()
}
@value get () -> (Int)
get () {
return index
}
}
concrete GenericValue<|#x> {
@category create<#x> (#x) -> (GenericValue<#x>)
@value check<#y> () -> (optional #y)
}
define GenericValue {
$ReadOnly[value]$
@value #x value
create (v) {
return GenericValue<#x>{ v }
}
check () {
return reduce<#x,#y>(value)
}
}