diff --git a/README.md b/README.md index 2cf39c9..5d3e47b 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/stew.nimble b/stew.nimble index dbaaf7f..aee44f7 100644 --- a/stew.nimble +++ b/stew.nimble @@ -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" diff --git a/stew/objects.nim b/stew/objects.nim index 01b0f6a..f18f1f9 100644 --- a/stew/objects.nim +++ b/stew/objects.nim @@ -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 + diff --git a/tests/all_tests.nim b/tests/all_tests.nim index e4c84ec..cbe41ce 100644 --- a/tests/all_tests.nim +++ b/tests/all_tests.nim @@ -16,6 +16,7 @@ import test_bitseqs, test_byteutils, test_endians2, + test_objects, test_ptrops, test_result, test_varints diff --git a/tests/test_objects.nim b/tests/test_objects.nim new file mode 100644 index 0000000..c0ef8b1 --- /dev/null +++ b/tests/test_objects.nim @@ -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) +