Skip to content

Ability to decode String into BigInt/BigUInt #126

Closed
@bogdan

Description

@bogdan

Current implementation of Codable protocol inside bigint is pretty esoteric: there is no backend api that would produce such an output if not built specificically for this library:

[<sign>, <word0>, <word1>, ...]

Most apis encode bigint as string - the majority decimal some hex.

Therefore, I propose to extend decoder implementation to support strings "1234567890" treated as decimal "0x1234567890" treated as hex.

Sample implementation:

extension BigInt: Codable {
    public init(from decoder: Decoder) throws {
        // Try decoding from a string first
        if let stringValue = try? decoder.singleValueContainer().decode(String.self) {
            if stringValue.hasPrefix("0x") || stringValue.hasPrefix("0X") {
                guard let bigInt = BigInt(stringValue.dropFirst(2), radix: 16) else {
                    throw DecodingError.dataCorruptedError(
                        in: try decoder.singleValueContainer(),
                        debugDescription: "Invalid hex string for BigInt"
                    )
                }
                self = bigInt
            } else {
                guard let bigInt = BigInt(stringValue, radix: 10) else {
                    throw DecodingError.dataCorruptedError(
                        in: try decoder.singleValueContainer(),
                        debugDescription: "Invalid decimal string for BigInt"
                    )
                }
                self = bigInt
            }
            return
        }
        // current impelementation
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions