From 34ab6bd98622d40d79c902f616c5ea526c287af3 Mon Sep 17 00:00:00 2001 From: Jacek Sieka Date: Mon, 25 Sep 2023 11:30:47 +0200 Subject: [PATCH] rlp: avoid aliasing casts (#637) * also get rid of unused concept --- eth/rlp.nim | 4 ++-- eth/rlp/writer.nim | 25 +++++-------------------- 2 files changed, 7 insertions(+), 22 deletions(-) diff --git a/eth/rlp.nim b/eth/rlp.nim index 8731ae3..48bc929 100644 --- a/eth/rlp.nim +++ b/eth/rlp.nim @@ -133,7 +133,7 @@ proc payloadBytesCount(self: Rlp): int = # check if the size is not bigger than the max that result can hold if lengthBytes > sizeof(result) or - (lengthBytes == sizeof(result) and self.bytes[self.position + 1].int > 127): + (lengthBytes == sizeof(result) and self.bytes[self.position + 1].int > 127): raise newException(UnsupportedRlpError, "Message too large to fit in memory") for i in 1 .. lengthBytes: @@ -317,7 +317,7 @@ proc readImpl(rlp: var Rlp, T: type float64): T = # https://github.com/gopherjs/gopherjs/blob/master/compiler/natives/src/math/math.go let uint64bits = rlp.toInt(uint64) var uint32parts = [uint32(uint64bits), uint32(uint64bits shr 32)] - return cast[ptr float64](unsafeAddr uint32parts)[] + copyMem(addr result, unsafeAddr uint32parts, sizeof(result)) proc readImpl[R, E](rlp: var Rlp, T: type array[R, E]): T = mixin read diff --git a/eth/rlp/writer.nim b/eth/rlp/writer.nim index d1cc97f..7575fbf 100644 --- a/eth/rlp/writer.nim +++ b/eth/rlp/writer.nim @@ -8,23 +8,7 @@ type pendingLists: seq[tuple[remainingItems, outBytes: int]] output: seq[byte] - IntLike* = concept x, y - type T = type(x) - - # arithmetic ops - x + y is T - x * y is T - x - y is T - x div y is T - x mod y is T - - # some int compatibility required for big endian encoding: - x shr int is T - x shl int is T - x and 0xff is int - x < 128 is bool - - Integer* = SomeInteger # or IntLike + Integer* = SomeInteger const wrapObjsInList* = true @@ -157,8 +141,9 @@ proc appendFloat(self: var RlpWriter, data: float64) = # This is not covered in the RLP spec, but Geth uses Go's # `math.Float64bits`, which is defined here: # https://github.com/gopherjs/gopherjs/blob/master/compiler/natives/src/math/math.go - let uintWords = cast[ptr UncheckedArray[uint32]](unsafeAddr data) - let uint64bits = (uint64(uintWords[1]) shl 32) or uint64(uintWords[0]) + var uint32Words: array[2, uint32] + copyMem(addr uint32Words[0], unsafeAddr data, sizeof(uint32Words)) + let uint64bits = (uint64(uint32Words[1]) shl 32) or uint64(uint32Words[0]) self.appendInt(uint64bits) template appendImpl(self: var RlpWriter, i: Integer) = @@ -306,7 +291,7 @@ proc appendRecordType*(self: var RlpWriter, obj: object|tuple, wrapInList = wrap # custom serialization for a field or for the parent object # will be better if field.isSome: - append(self, field.unsafeGet) + append(self, field.unsafeGet) else: append(self, field)