Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,38 +12,32 @@ public struct AnyEncodable: Encodable {

public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try encodeAny(value, into: &container, encoder: encoder)
}

switch value {
case is NSNull:
/// Encodes a method-channel value.
///
/// Flutter delivers numbers and booleans as `NSNumber`. Swift's `as Bool`
/// succeeds for numeric `0` and `1`, so a boolean is recognized only when
/// the value is a `CFBoolean`. Numeric `0` and `1` stay JSON numbers.
private func encodeAny(
_ value: Any?,
into container: inout SingleValueEncodingContainer,
encoder: Encoder
) throws {
if value == nil || value is NSNull {
try container.encodeNil()
return
}

if let number = value as? NSNumber {
try encode(number, into: &container)
return
}

switch value {
case let stringValue as String:
try container.encode(stringValue)
case let boolValue as Bool:
try container.encode(boolValue)
case let intValue as Int:
try container.encode(intValue)
case let int8Value as Int8:
try container.encode(int8Value)
case let int16Value as Int16:
try container.encode(int16Value)
case let int32Value as Int32:
try container.encode(int32Value)
case let int64Value as Int64:
try container.encode(int64Value)
case let uintValue as UInt:
try container.encode(uintValue)
case let uint8Value as UInt8:
try container.encode(uint8Value)
case let uint16Value as UInt16:
try container.encode(uint16Value)
case let uint32Value as UInt32:
try container.encode(uint32Value)
case let uint64Value as UInt64:
try container.encode(uint64Value)
case let doubleValue as Double:
try container.encode(doubleValue)
case let floatValue as Float:
try container.encode(floatValue)
case let arrayValue as [Any]:
try container.encode(arrayValue.map { AnyEncodable($0) })
case let dictionaryValue as [String: Any]:
Expand All @@ -58,6 +52,21 @@ public struct AnyEncodable: Encodable {
)
}
}

private func encode(
_ number: NSNumber,
into container: inout SingleValueEncodingContainer
) throws {
if CFGetTypeID(number) == CFBooleanGetTypeID() {
try container.encode(number.boolValue)
return
}
if CFNumberIsFloatType(number) {
try container.encode(number.doubleValue)
return
}
try container.encode(number.int64Value)
}
Comment on lines +56 to +69

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The previous implementation of AnyEncodable explicitly supported UInt64 values via case let uint64Value as UInt64:. In the new implementation, all non-boolean and non-floating-point numeric types are cast to NSNumber and encoded using number.int64Value.

However, if a UInt64 value greater than Int64.max (9223372036854775807) is passed, casting it to NSNumber and calling int64Value will cause a silent integer overflow/wrap-around (e.g., UInt64.max becomes -1).

To prevent this regression and preserve correct encoding for large unsigned 64-bit integers, we can inspect the Objective-C type encoding (objCType) of the NSNumber. If it is "Q" (unsigned long long) or "L" (unsigned long), we can safely encode it using uint64Value.

Suggested change
private func encode(
_ number: NSNumber,
into container: inout SingleValueEncodingContainer
) throws {
if CFGetTypeID(number) == CFBooleanGetTypeID() {
try container.encode(number.boolValue)
return
}
if CFNumberIsFloatType(number) {
try container.encode(number.doubleValue)
return
}
try container.encode(number.int64Value)
}
private func encode(
_ number: NSNumber,
into container: inout SingleValueEncodingContainer
) throws {
if CFGetTypeID(number) == CFBooleanGetTypeID() {
try container.encode(number.boolValue)
return
}
let objcType = String(cString: number.objCType)
if objcType == "Q" || objcType == "L" {
try container.encode(number.uint64Value)
return
}
if CFNumberIsFloatType(number) {
try container.encode(number.doubleValue)
return
}
try container.encode(number.int64Value)
}

}

public struct AnyDecodable: Decodable {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// Copyright 2026 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// AnyEncodable is compiled with this file. The macOS CodecUtility.swift is a
// symlink to the iOS source, so this covers both platforms.
//
// swiftc -o codec-check \
// Sources/cloud_functions/CodecUtility.swift \
// Tests/CodecUtilityEncodingTests.swift \
// && ./codec-check

import Foundation

func encodedJSON(_ value: Any) throws -> String {
let data = try JSONEncoder().encode(AnyEncodable(value))
guard let json = String(data: data, encoding: .utf8) else {
throw TestFailure("encoded data is not UTF-8")
}
return json
}

struct TestFailure: Error, CustomStringConvertible {
let description: String
init(_ description: String) { self.description = description }
}

func expect(_ condition: Bool, _ message: String) throws {
if !condition {
throw TestFailure(message)
}
}

func expectJSON(_ value: Any, equals expected: String, _ label: String) throws {
let actual = try encodedJSON(value)
try expect(actual == expected, "\(label): expected \(expected), got \(actual)")
}

func expectNumber(_ value: Any, equals expected: Double, _ label: String) throws {
let json = try encodedJSON(value)
try expect(json != "true" && json != "false", "\(label) encoded as a boolean: \(json)")
let data = Data(json.utf8)
let parsed = try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed])
guard let number = parsed as? NSNumber else {
throw TestFailure("\(label) did not decode as a number: \(json)")
}
try expect(
CFGetTypeID(number) != CFBooleanGetTypeID(),
"\(label) decoded as CFBoolean: \(json)"
)
try expect(number.doubleValue == expected, "\(label): expected \(expected), got \(number)")
}

func runTests() throws {
let cases: [(String, Any, Double)] = [
("double 0", NSNumber(value: 0.0), 0),
("double 1", NSNumber(value: 1.0), 1),
("double -1", NSNumber(value: -1.0), -1),
("double 5.5", NSNumber(value: 5.5), 5.5),
("int 0", NSNumber(value: Int(0)), 0),
("int 1", NSNumber(value: Int(1)), 1),
("swift double 1", 1.0, 1),
("swift int 0", 0, 0),
]

for (label, value, expected) in cases {
try expectNumber(value, equals: expected, label)
}

try expectJSON(NSNumber(value: true), equals: "true", "NSNumber true")
try expectJSON(NSNumber(value: false), equals: "false", "NSNumber false")
try expectJSON(true, equals: "true", "Swift true")
try expectJSON(false, equals: "false", "Swift false")

let payload: [String: Any] = [
"timezoneOffset": NSNumber(value: 1.0),
"enabled": NSNumber(value: true),
"message": "hello",
]
let payloadData = try JSONEncoder().encode(AnyEncodable(payload))
let payloadObject = try JSONSerialization.jsonObject(with: payloadData) as? [String: Any]
guard let payloadObject else {
throw TestFailure("payload did not encode as an object")
}
guard let offset = payloadObject["timezoneOffset"] as? NSNumber else {
throw TestFailure("timezoneOffset missing")
}
try expect(CFGetTypeID(offset) != CFBooleanGetTypeID(), "timezoneOffset became a boolean")
try expect(offset.doubleValue == 1, "timezoneOffset was \(offset)")
guard let enabled = payloadObject["enabled"] as? NSNumber else {
throw TestFailure("enabled missing")
}
try expect(
CFGetTypeID(enabled) == CFBooleanGetTypeID() && enabled.boolValue,
"enabled was not true"
)
try expect(payloadObject["message"] as? String == "hello", "message changed")

print("CodecUtility encoding tests passed")
}

@main
struct CodecUtilityEncodingTests {
static func main() {
do {
try runTests()
} catch {
fputs("\(error)\n", stderr)
exit(EXIT_FAILURE)
}
}
}
Loading