Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementation of DataConvertible for Bool is incorrect #9

Closed
regexident opened this issue Sep 9, 2017 · 1 comment
Closed

Implementation of DataConvertible for Bool is incorrect #9

regexident opened this issue Sep 9, 2017 · 1 comment

Comments

@regexident
Copy link
Contributor

The way DataConvertible is implemented for Bool in SwiftLMDB right now is this:

extension Bool: DataConvertible {}

which then effectively ends up implementing this for each:

public extension DataConvertible {

    init?(data: Data) {
        guard data.count == MemoryLayout<Self>.size else { return nil }
        self = data.withUnsafeBytes { $0.pointee }
    }
    
    var data: Data {
        var value = self
        return Data(buffer: UnsafeBufferPointer(start: &value, count: 1))
    }
}

This is incorrect as the bitwise representation of Bool is an implementation detail and thus subject to change at will between language versions, breaking your persisted database.

What you should do instead is this:

extension Bool: DataConvertible {
    
    public init?(data: Data) {
        guard data.count == MemoryLayout<UInt8>.size else { return nil }
        self = data.withUnsafeBytes { $0.pointee } != 0
    }

    public var data: Data {
        var value: UInt8 = self ? 1 : 0
        return Data(buffer: UnsafeBufferPointer(start: &value, count: 1))
    }
}
@regexident regexident changed the title SwiftLMDB does not handle binary representation of Bool properly Implementation of DataConvertible for Bool is incorrect Sep 9, 2017
@regexident
Copy link
Contributor Author

Fixed by fe227c5.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant