SwiftMsgPack

1.0.0

MessagePack library for Swift
jayadamsmorgan/SwiftMsgPack

What's New

v1.0.0

2024-06-12T22:36:55Z

SwiftMsgPack

Really simple Swift library for MessagePack

Usage

Package.swift
// swift-tools-version: 5.8

import PackageDescription

let package = Package(
    name: "MsgPackTest",
    dependencies: [
        .package(url: "https://github.com/jayadamsmorgan/SwiftMsgPack", branch: "main")
    ],
    targets: [
        .executableTarget(
            name: "SwiftMsgPackExample",
            dependencies: ["SwiftMsgPack"]
        )
    ]
)

Implementation

Check Example.swift for async implementations too!

import Foundation
import SwiftMsgPack

struct Example: MessagePackable {

    var name: String = "John Doe"
    var age: Int = 42
    var data: Data = Data([0x01, 0x02, 0x03])
    var array: [Int] = [1, 2, 3]
    var map: [String: Int] = ["a": 1, "b": 2, "c": 3]
    var timestamp: Date = Date()

    func packValue() -> MessagePackValue {
        return .structure([
            .string(name, encoding: .utf8),
            .value(age),
            .valueWithOption(data, option: .bin_8),
            .value(array),
            .value(map),
            .value(timestamp),
        ])
    }
}

@main
public struct ExampleApp {

    static func main() {
        let example = Example()
        do {
            let packed: Data = try example.pack().get()
            print("Packed:\n\(packed.withUnsafeBytes(Array.init))")
            let unpacked: [Any?] = try MessagePackData(data: packed).unpack().get()
            print("Unpacked:\n\(unpacked)")
        } catch {
            print("Unpacking error: \(error)")
        }
    }
}

Description

  • Swift Tools 5.8.0
View More Packages from this Author

Dependencies

  • None
Last updated: Thu Oct 17 2024 20:35:16 GMT-0900 (Hawaii-Aleutian Daylight Time)