Merge branch 'basetype'

This commit is contained in:
Ștefan Talpalaru 2020-03-30 19:56:37 +02:00
commit 4477f45c40
No known key found for this signature in database
GPG Key ID: CBF7934204F1B6F9
5 changed files with 51 additions and 1 deletions

View File

@ -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

View File

@ -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"

View File

@ -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

View File

@ -16,6 +16,7 @@ import
test_bitseqs,
test_byteutils,
test_endians2,
test_objects,
test_ptrops,
test_result,
test_varints

36
tests/test_objects.nim Normal file
View File

@ -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)