Giter Site home page Giter Site logo

cborswift's Introduction

CBORSwift

build status cocoapods compatible Licence

The Concise Binary Object Representation (CBOR) is a data format whose design goals include the possibility of extremely small code size, fairly small message size, and extensibility without the need for version negotiation.

CBORSwift has implemented CBOR with Swift useful for both iOS and macOS projects.

Getting Started

These instructions will help you to add CBORSwift to your current Xcode project in a few lines.

Please note that currently, major 7 is supported for only Simple Values (True, False). Other majors are completed.

Installation

Cocoapods

The easiest way to import CBORSwift to your current project is to use Cocoapods. Just add the following to your Podfile

pod 'CBORSwift'

Manual

You can also download the whole code manually and copy the following classes to your project based on your needs

CBOR.swift
Decoder.swift
Encoder.swift
Extensions.swift
MajorTypes.swift

Usage

Using CBORSwift is as simple as possible. You'll need to call 2 functions for encoding and decoding. The most important point is that You have to use NSObject instances and subclasses for encoding and decoding parameters. You can find more useful use cases in Encoder and Decoder unit tests. There is also a comprehensive CBOR example in the General unit test.

All tests are verified using CBOR official tool

For all Encoding and Decoding situations, you can use encode-decode either as a function, or as an extension:

var encoded = CBOR.encode(NSOBJECT_ITEM)
var decoded = CBOR.decode(NSOBJECT_ITEM)

var encoded = NSOBJECT_ITEM.encode()
var decoded = NSOBJECT_ITEM.decode()

Numbers (Positive, Negative) - major 0 and 1

Just create NSNumber instance and pass it to encode- decode function. Or, you can call encode-decode directly from the instance:

var encoded = CBOR.encode(NSNumber(value: 30))
var encoded = NSNumber(value: 3428).encode()

var encoded = CBOR.encode(NSNumber(value: -15))
var encoded = NSNumber(value: -42949295).encode()

var decoded = CBOR.decode([0x0A])
var decoded = [0x0A].decode()

var decoded = CBOR.decode([0x39, 0x01, 0x00])
var decoded = [0x39, 0x01, 0x00].decode()

Byte Strings - major 2

You'll need to create an instance of NSByteString class, and start playing with it:

var str = NSByteString("2525")

var encoded = CBOR.encode(str)
var encoded = str.encode()

var decoded = CBOR.decode([0x42, 0x25, 0x25])
var decoded = [0x42, 0x25, 0x25].decode()

Text Strings - major 3

New an instance of NSString, and that's it:

var encoded = CBOR.encode("hello" as NSString)
var encoded = ("hello" as NSString).encode()

var decoded = CBOR.decode([0x65, 0x68, 0x65, 0x6C, 0x6C, 0x6F])
var decoded = [0x65, 0x68, 0x65, 0x6C, 0x6C, 0x6F].decode()

Array - major 4

New an instance of NSArray:

var encoded = CBOR.encode([10] as NSArray)
var encoded = ([10, 15, -9] as NSArray).encode()

var decoded = CBOR.decode([0x81, 0x0A])
var decoded = [0x81, 0x0A].decode()

Map - major 5

Map actually is same as NSDictionary in Apple programming systems:

var encoded = CBOR.encode(["sure":"shahbazi", "name":"hassan"] as NSDictionary)
var encoded = (["sure":"shahbazi", "name":"hassan"] as NSDictionary).encode()

var decoded = CBOR.decode([0xA1, 0x65, 0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x65, 0x77, 0x6F, 0x72, 0x6C, 0x64])
var decoded = [0xA1, 0x65, 0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x65, 0x77, 0x6F, 0x72, 0x6C, 0x64].decode()

Tagged values - major 6

To encode or decode a tagged value, just create a NSTag instance, specify the tags and the values, and call encode/decode functions.

var encoded = CBOR.encode(NSTag(tag: 5, NSNumber(value: 10))
var encoded =  NSTag(tag: 5, NSNumber(value: 10)).encode()

var decoded = CBOR.decode([0xC5, 0x0A])
var decoded = [0xC5, 0x0A].decode()

Bool - major 7

Boolian values are major7 and known as the Simple Values:

var encoded = CBOR.encode(NSSimpleValue(false))
var encoded = CBOR.encode(NSSimpleValue(true))

var decoded = CBOR.decode([0xF4])
var decoded = CBOR.decode([0xF5])

Contribution

Please ensure your pull request adheres to the following guidelines:

  • Alphabetize your entry.
  • Search previous suggestions before making a new one, as yours may be a duplicate.
  • Suggested READMEs should be beautiful or stand out in some way.
  • Make an individual pull request for each suggestion.
  • New categories, or improvements to the existing categorization are welcome.
  • Keep descriptions short and simple, but descriptive.
  • Start the description with a capital and end with a full stop/period.
  • Check your spelling and grammar.
  • Make sure your text editor is set to remove trailing whitespace.

Thank you for your suggestions!

Authors

License

This project is licensed under the MIT License - see the LICENSE.md file for details

cborswift's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

phisakel

cborswift's Issues

Supporting Unicode languages

CBOR Swift does not support Unicode languages and to solve this problem you should implement as follows:

In "Extensions" :

public var ascii_bytes: [UInt8] {
        // To supporting unicode languages it should return with .utf8 encoding
        return self.data(using: .ascii)?.bytes ?? self.data(using: .utf8)!.bytes
    }

In "Encoder":

@objc override func encode() -> String {
        
        // To support Unicode languages, the string encoding must be specified before giving the string length
        let asciiBytes = self.ascii_bytes
        let encodedArray = Encoder.prepareByteArray(major: .major3, measure: asciiBytes.count)
        let headerData  = Data(bytes: encodedArray).binary_decimal.hex
        let strData     = Data(bytes: asciiBytes).hexString
        
        return headerData.appending(strData)
    }

Problem with NSData as Value when Decoding

I have this sample use case where I have a JSON-like NSDictionary but I want to put some random NSData to prove that I can add something like a small UIImage/Audio file into CBOR.

func test_2_encodeMap_2() {

        // begin generating some random NSData
        let length = 2048
        let bytes = [UInt32](repeating: 0, count: length).map { _ in arc4random() }
        let data = Data(bytes: bytes, count: length)
        // end generating some random NSData
        
        let json: NSDictionary = [
            "_id": "123abc",
            "color": "Red",
            "age": 56,
            "mileage": 56.444,
            "tags": [
                "a", "b", "d", 4
            ],
            "data": data
        ]
        
        
        var encoded = CBOR.encode(json as NSDictionary)
        var decoded = CBOR.decode(encoded!) as! NSDictionary
}

It encodes fine but crashes saying "Thread 1: Fatal error: Array index is out of range" at Decoder.swift on Line 77

What am I doing wrong?

Problem with big integers

Hello, I'm implementing encode/decode and noticed a problem with both of them when using big numbers. I'm using the following set of data.

let barr = [**1531842146400**,[1332, 0, "0.3.0-dev", "0.3.0-dev", "4.0.2", "866191031649643", "8935101811542082547", "M95FAR02A08","AXN_2.32_3337_15010801", 3, 0],[1398, 8, NSSimpleValue(nil), NSSimpleValue(nil), NSSimpleValue(nil), NSSimpleValue(nil), NSSimpleValue(nil)],[1376, 7, 1]] as [Any]

 let cc = CBOR.encode(barr as NSArray)

which encoded using the playground results in 9f1b00000164a8e830608b1905340069302e332e302d64657669302e332e302d64657665342e302e326f38363631393130333136343936343373383933353130313831313534323038323534376b4d393546415230324130387641584e5f322e33325f333333375f313530313038303103008719057608f6f6f6f6f6831905600701ff

My problem is that the first value 1531842146400 since it's a bit integer can't be encoded (crashes) and when decoding it returns an empty array not showing any values. But if I use a smaller number everything works fine. What can I do to work around this situation?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.