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 Date is incorrect #11

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

Implementation of DataConvertible for Date is incorrect #11

regexident opened this issue Sep 9, 2017 · 1 comment

Comments

@regexident
Copy link
Contributor

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

extension Date: 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 Date is a complex type, which cannot simply be memcpy-ed.

What you should do instead is something like this:

extension Date: DataConvertible {

    public init?(data: Data) {
        guard let timeInterval = TimeInterval(data: data) else {
            return nil
        }
        self = Date(timeIntervalSinceReferenceDate: timeInterval)
    }

    public var data: Data {
        return self.timeIntervalSinceReferenceDate.data
    }
}
@regexident regexident changed the title SwiftLMDB does not handle binary representation of Date properly Implementation of DataConvertible for Date 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