apple / apple/swift-binary-parsing
Feature Request: Make ParserSpan copying initializer public
- Dominant language
- Swift
- Stars
- 387
- Forks
- 24
- Avg merge
- 1h 3m
- Merged PRs (30d)
- 2
Description
This internal `ParserSpan` initializer for a copy of another instance would be useful for speculative/transactional parsing where it is ambiguous what kind of structure is being parsed until later in the data, and the parser must make a guess with the ability to commit the state change if successful or discard it if invalid.
https://github.com/apple/swift-binary-parsing/blob/2655f40f579c686d44687ac4fed54c73c3c4be2e/Sources/BinaryParsing/Parser%20Types/ParserSpan.swift#L36-L42
Here is an example where this would be useful, using the `RawSpan` initializer with the `bytes` property of another `ParserSpan` as a workaround for the current API.
```swift
import BinaryParsing
struct RetType {
let customMods: [CustomMod]
init(span: inout ParserSpan) throws {
// It is not known how many custom modifiers there are,
// so a copy of the span is made to try parsing one and the state change
// is committed if successful
var customMods = [CustomMod]()
while true {
var copySpan = ParserSpan(span.bytes)
guard let customMod = try CustomMod(span: ©Span) else {
break
}
customMods.append(customMod)
span = copySpan
}
self.customMods = customMods
}
}
```
An alternative would be to add 'peeking' equivalents for each of the parsing initializers (integers, strings, arrays, etc.), but the copying approach has the benefit of reuse for eager parsing code both in the implementation of this library and for its users, as an initializer accepting a `ParserSpan` can be given either a primary instance or a copy. Committing the state change by assigning the copy span to the primary span is also simpler than seeking by a relative offset equal to the size of what was parsed, which would be needed for peeking APIs.
Contributor guide
Research direction
Start with Sources/BinaryParsing/Parser Types/ParserSpan.swift at the linked initializer around lines 36–42, and inspect the surrounding ParserSpan API. Make the copy initializer available to library users so a ParserSpan can be copied for speculative parsing, then verify the example no longer needs the RawSpan(bytes:) workaround.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- swift
- Domain
- data
- Issue type
- Feature
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 72/100