// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop // UNSUPPORTED: freestanding import Foundation import StdlibUnittest let SIMDCodableTests = TestSuite("SIMDCodable") // Round an integer to the closest representable JS integer value func jsInteger(_ value: T) -> T where T : SIMD, T.Scalar : FixedWidthInteger { // Attempt to round-trip though Double; if that fails it's because the // rounded value is too large to fit in T, so use the largest value that // does fit instead. let upperBound = T.Scalar(Double(T.Scalar.max).nextDown) var result = T() for i in result.indices { result[i] = T.Scalar(exactly: Double(value[i])) ?? upperBound } return result } func testRoundTrip(_ for: T.Type) where T : SIMD, T.Scalar : FixedWidthInteger { let input = jsInteger(T.random(in: T.Scalar.min ... T.Scalar.max)) let encoder = JSONEncoder() let decoder = JSONDecoder() do { let data = try encoder.encode(input) let output = try decoder.decode(T.self, from: data) expectEqual(input, output) } catch { expectUnreachableCatch(error) } } func testRoundTrip(_ for: T.Type) where T : SIMD, T.Scalar : BinaryFloatingPoint, T.Scalar.RawSignificand : FixedWidthInteger { let input = T.random(in: -16 ..< 16) let encoder = JSONEncoder() let decoder = JSONDecoder() do { let data = try encoder.encode(input) let output = try decoder.decode(T.self, from: data) expectEqual(input, output) } catch { expectUnreachableCatch(error) } } // Very basic round-trip test. We can be much more sophisticated in the future, // but we want to at least exercise the API. Also need to add some negative // tests for the error paths, and test a more substantial set of types. SIMDCodableTests.test("roundTrip") { testRoundTrip(SIMD2.self) testRoundTrip(SIMD3.self) testRoundTrip(SIMD4.self) testRoundTrip(SIMD2.self) testRoundTrip(SIMD3.self) testRoundTrip(SIMD4.self) testRoundTrip(SIMD2.self) testRoundTrip(SIMD3.self) testRoundTrip(SIMD4.self) testRoundTrip(SIMD2.self) testRoundTrip(SIMD3.self) testRoundTrip(SIMD4.self) testRoundTrip(SIMD2.self) testRoundTrip(SIMD3.self) testRoundTrip(SIMD4.self) testRoundTrip(SIMD2.self) testRoundTrip(SIMD3.self) testRoundTrip(SIMD4.self) /* Apparently these fail to round trip not only for i386 but also on older macOS versions, so we'll disable them entirely for now. #if !arch(i386) // https://github.com/apple/swift-corelibs-foundation/issues/3548 testRoundTrip(SIMD2.self) testRoundTrip(SIMD3.self) testRoundTrip(SIMD4.self) testRoundTrip(SIMD2.self) testRoundTrip(SIMD3.self) testRoundTrip(SIMD4.self) #endif */ } runAllTests()