//
//  Data.swift
//  USB Meter
//
//  Created by Bogdan Timofte on 08/03/2020.
//  Copyright © 2020 Bogdan Timofte. All rights reserved.
//

import Foundation

extension Data {
    
    var hexEncodedStringValue : String {
        get{
            return map { String(format: "%02hhx", $0) }.joined()
        }
    }
//Ceva mostenit
//    init<T>(from value: T) {
//        var value = value
//        self.init(buffer: UnsafeBufferPointer(start: &value, count: 1))
//    }
    
    func value<T>(from: Int) -> T {
        let to = from + MemoryLayout<T>.size
        return self.subdata(in: from..<to).withUnsafeBytes { $0.load(as: T.self) }
    }

    func value<T>() -> T {
        return self.withUnsafeBytes { $0.load(as: T.self) }
    }

    func subdata(in range: ClosedRange<Index>) -> Data {
        return subdata(in: range.lowerBound ..< range.upperBound)
    }
    
    func subdata(from: Int, length: Int) -> Data {
        return subdata(in: self.startIndex + from ..< self.startIndex.advanced(by: from + length))
    }

    func subdata(from: Int, to: Int) -> Data {
        return subdata(in: self.startIndex + from ... self.startIndex.advanced(by: to))
    }

    
    var utf8String: String {
        return string(as: .utf8)
    }

    var asciiString: String {
        return string(as: .ascii)
    }

    func string(as encoding: String.Encoding) -> String {
        return String(data: self, encoding: encoding) ?? ""
    }
}
