Skip to content

Composable and self-describing network addresses as a modern Swift library

License

Notifications You must be signed in to change notification settings

lukereichold/swift-multiaddr

Repository files navigation

swift-multiaddr

Carthage compatible GitHub license

multiaddr: Composable and future-proof network addresses, available as a modern, zero-dependency Swift library.

Table of Contents

Install

Swift Package Manager

To use Swift Package Manager, add Multiaddr to your Package.swift file. Alternatively, add it from Xcode directly.

let package = Package(
    name: "myproject",
    dependencies: [
        .package(url: "https://github.com/lukereichold/swift-multiaddr.git", from: "1.0.0"),
    ],
    targets: [
        .target(
            name: "myproject",
            dependencies: ["Multiaddr"]),
    ]
)

Then run swift build.

Carthage

To use Carthage, add Multiaddr to your Cartfile:

github "lukereichold/swift-multiaddr" ~> 1.0.0

Then run carthage update and use the framework in Carthage/Build/<platform>.

Usage

Human-readable encoding

let addr = try Multiaddr("/dns6/foo.com/tcp/443/https")
dump(addr)

 /dns6/foo.com/tcp/443/https
   addresses : 3 elements
     0 : /dns6/foo.com
      - addrProtocol : Multiaddr.Protocol.dns6
       address : Optional<String>
        - some : "foo.com"
     1 : /tcp/443
      - addrProtocol : Multiaddr.Protocol.tcp
       address : Optional<String>
        - some : "443"
     2 : /https
      - addrProtocol : Multiaddr.Protocol.https
      - address : nil

Binary encoding with packing

let serializedData = try addr.binaryPacked()
/// (`Data`) 14 bytes

Binary decoding

let addrFromData = try Multiaddr(serializedData)
/// `[Multiaddr.Address]`  3 values

Equatable Support

assert(addr == addrFromData) /// true

Protocol / address enumeration

print(addr.protocols())
/// `["dns6", "tcp", "https"]`

Encapsulate

let encapsulated = try Multiaddr("/dns4/foo.com").encapsulate("tcp/80/http/bar/baz.jpg")
print(encapsulated) /// `/dns4/foo.com/tcp/80/http/bar/baz.jpg`

Decapsulate

let tcpComponent = try Multiaddr("tcp/80")
let decapsulated = encapsulated.decapsulate(tcpComponent)
print(decapsulated) /// `/dns4/foo.com`

pop()

let popped = addr.pop()
Optional<Address>
   some : /https
    - addrProtocol : Multiaddr.Protocol.https
    - address : nil

Contribute

Contributions welcome. Please check out the issues.

License

MIT © 2019 Luke Reichold