is it possible to construct simd_float4x4 from a string, eg: I had a string which stored simd_float4x4.debugdescription's value ?
Asked
Active
Viewed 883 times
1
-
1Are you looking for an efficient SIMD implementation of `atof()`? There's an x86 SIMD `atoi()` at [How to implement atoi using SIMD?](https://stackoverflow.com/q/35127060), but NEON has different horizontal-add instructions. If you want to parse commas, [Fastest way to get IPv4 address from string](https://stackoverflow.com/q/31679341) might be interesting, but again that's very x86-specific. ARM doesn't have `pmovmskb`. (And arbitrary-length FP values as strings wouldn't work well, unlike dotted-quads). – Peter Cordes Jul 29 '18 at 15:19
1 Answers
2
Here is an extension
for simd_float4x4
that adds a failable init
that takes a debug description and creates the simd_float4x4
. It is a failable init
because the string might be ill formed.
import simd
extension simd_float4x4 {
init?(_ string: String) {
let prefix = "simd_float4x4"
guard string.hasPrefix(prefix) else { return nil }
let csv = string.dropFirst(prefix.count).components(separatedBy: ",")
let filtered = csv.map { $0.filter { Array("-01234567890.").contains($0) } }
let floats = filtered.compactMap(Float.init)
guard floats.count == 16 else { return nil }
let f0 = float4(Array(floats[0...3]))
let f1 = float4(Array(floats[4...7]))
let f2 = float4(Array(floats[8...11]))
let f3 = float4(Array(floats[12...15]))
self = simd_float4x4(f0, f1, f2, f3)
}
}
Test
let col0 = float4(0.1, 0.2, 0.3, 0.4)
let col1 = float4(1.1, 1.2, 1.3, 1.4)
let col2 = float4(2.1, 2.2, 2.3, 2.4)
let col3 = float4(-3.1, -3.2, -3.3, -3.4)
var x = simd_float4x4(col0, col1, col2, col3)
print(x)
let xDesc = x.debugDescription
if let y = simd_float4x4(xDesc) {
print(y)
}
Output
simd_float4x4([[0.1, 0.2, 0.3, 0.4)], [1.1, 1.2, 1.3, 1.4)], [2.1, 2.2, 2.3, 2.4)], [-3.1, -3.2, -3.3, -3.4)]]) simd_float4x4([[0.1, 0.2, 0.3, 0.4)], [1.1, 1.2, 1.3, 1.4)], [2.1, 2.2, 2.3, 2.4)], [-3.1, -3.2, -3.3, -3.4)]])

vacawama
- 150,663
- 30
- 266
- 294