Add objects.isDefaultValue

This commit is contained in:
Zahary Karadjov 2022-12-15 17:11:53 +02:00
parent 7184d2424d
commit f5846de7b2
No known key found for this signature in database
GPG Key ID: C1F42EAFF38D570F
2 changed files with 35 additions and 25 deletions

View File

@ -113,3 +113,10 @@ func isZeroMemory*[T](x: T): bool =
if b != 0: if b != 0:
return false return false
return true return true
func isDefaultValue*[T](x: T): bool =
# TODO: There are ways to optimise this for simple POD types
# (they can be mapped to `isZeroMemory`)
# It may also be beneficial to store the RHS in a const.
# Check the codegen.
x == default(T)

View File

@ -7,6 +7,9 @@ when defined(nimHasUsed):
{.experimental: "notnil".} {.experimental: "notnil".}
template isZeroAndDefault(x: auto): bool =
isZeroMemory(x) and isDefaultValue(x)
suite "Objects": suite "Objects":
test "baseType": test "baseType":
when (not defined(nimTypeNames)) or defined(gcOrc) or defined(gcArc): when (not defined(nimTypeNames)) or defined(gcOrc) or defined(gcArc):
@ -192,7 +195,7 @@ suite "Objects":
not checkedEnumAssign(e3, -1) not checkedEnumAssign(e3, -1)
e3 == A3 e3 == A3
test "isZeroMemory": test "isZeroMemory/isDefaultValue":
type type
Foo = object Foo = object
x: string x: string
@ -217,19 +220,19 @@ suite "Objects":
z12: Baz z12: Baz
check: check:
isZeroMemory z0 isZeroAndDefault z0
isZeroMemory z1 isZeroAndDefault z1
isZeroMemory z2 isZeroAndDefault z2
isZeroMemory z3 isZeroAndDefault z3
isZeroMemory z4 isZeroAndDefault z4
isZeroMemory z5 isZeroAndDefault z5
isZeroMemory z6 isZeroAndDefault z6
isZeroMemory z7 isZeroAndDefault z7
isZeroMemory z8 isZeroAndDefault z8
isZeroMemory z9 isZeroAndDefault z9
isZeroMemory z10 isZeroAndDefault z10
isZeroMemory z11 isZeroAndDefault z11
isZeroMemory z12 isZeroAndDefault z12
var var
nz0 = 1 nz0 = 1
@ -245,14 +248,14 @@ suite "Objects":
nz10 = @[1, 2, 3] nz10 = @[1, 2, 3]
check: check:
not isZeroMemory nz0 not isZeroAndDefault nz0
not isZeroMemory nz1 not isZeroAndDefault nz1
not isZeroMemory nz2 not isZeroAndDefault nz2
not isZeroMemory nz3 not isZeroAndDefault nz3
not isZeroMemory nz4 not isZeroAndDefault nz4
not isZeroMemory nz5 not isZeroAndDefault nz5
not isZeroMemory nz6 not isZeroAndDefault nz6
not isZeroMemory nz7 not isZeroAndDefault nz7
not isZeroMemory nz8 not isZeroAndDefault nz8
not isZeroMemory nz9 not isZeroAndDefault nz9
not isZeroMemory nz10 not isZeroAndDefault nz10