stew/objects: add baseType()
This commit is contained in:
parent
989c33a82b
commit
09e55cd375
|
@ -24,6 +24,7 @@ respective folders
|
|||
- `bitops2` - an updated version of `bitops.nim`, filling in gaps in original code
|
||||
- `byteutils` - utilities that make working with the Nim `byte` type convenient
|
||||
- `endians2` - utilities for converting to and from little / big endian integers
|
||||
- `objects` - get an object's base type at runtime, as a string
|
||||
- `ptrops` - pointer arithmetic utilities
|
||||
- `ranges` - utility functions for working with parts and blobs of memory
|
||||
- `shims` - backports of nim `devel` code to the stable version that Status is using
|
||||
|
|
|
@ -11,4 +11,4 @@ requires "nim >= 0.19.0"
|
|||
|
||||
task test, "Run all tests":
|
||||
exec "nim c -r --threads:off tests/all_tests"
|
||||
exec "nim c -r --threads:on tests/all_tests"
|
||||
exec "nim c -r --threads:on -d:nimTypeNames tests/all_tests"
|
||||
|
|
|
@ -31,3 +31,15 @@ when not compiles(len((1, 2))):
|
|||
func len*(x: tuple): int =
|
||||
arity(type(x))
|
||||
|
||||
# Get an object's base type, as a cstring. Ref objects will have an ":ObjectType"
|
||||
# suffix.
|
||||
# From: https://gist.github.com/stefantalpalaru/82dc71bb547d6f9178b916e3ed5b527d
|
||||
proc baseType*(obj: RootObj): cstring =
|
||||
when not defined(nimTypeNames):
|
||||
raiseAssert("you need to compile this with '-d:nimTypeNames'")
|
||||
else:
|
||||
{.emit: "result = `obj`->m_type->name;".}
|
||||
|
||||
proc baseType*(obj: ref RootObj): cstring =
|
||||
obj[].baseType
|
||||
|
||||
|
|
|
@ -16,6 +16,7 @@ import
|
|||
test_bitseqs,
|
||||
test_byteutils,
|
||||
test_endians2,
|
||||
test_objects,
|
||||
test_ptrops,
|
||||
test_result,
|
||||
test_varints
|
||||
|
|
|
@ -0,0 +1,36 @@
|
|||
import unittest,
|
||||
../stew/objects
|
||||
|
||||
when defined(nimHasUsed):
|
||||
{.used.}
|
||||
|
||||
suite "Objects":
|
||||
test "baseType":
|
||||
type
|
||||
Foo = ref object of RootObj
|
||||
Bar = ref object of Foo
|
||||
Baz = object of RootObj
|
||||
Bob = object of Baz
|
||||
Bill = ref object of Bob
|
||||
|
||||
var
|
||||
foo = Foo()
|
||||
bar = Bar()
|
||||
baz = Baz()
|
||||
bob = Bob()
|
||||
bill = Bill()
|
||||
|
||||
when defined(nimTypeNames):
|
||||
check:
|
||||
foo.baseType == "Foo:ObjectType"
|
||||
bar.baseType == "Bar:ObjectType"
|
||||
baz.baseType == "Baz"
|
||||
bob.baseType == "Bob"
|
||||
bill.baseType == "Bill:ObjectType"
|
||||
|
||||
proc f(o: Foo) =
|
||||
check $o.type == "Foo"
|
||||
check o.baseType == "Bar:ObjectType"
|
||||
|
||||
f(bar)
|
||||
|
Loading…
Reference in New Issue