OtherExtension.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright 1999-2101 Alibaba Group.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. //
  17. // OtherExtension.swift
  18. // HandyJSON
  19. //
  20. // Created by zhouzhuo on 08/01/2017.
  21. //
  22. protocol UTF8Initializable {
  23. init?(validatingUTF8: UnsafePointer<CChar>)
  24. }
  25. extension String : UTF8Initializable {}
  26. extension Array where Element : UTF8Initializable {
  27. init(utf8Strings: UnsafePointer<CChar>) {
  28. var strings = [Element]()
  29. var pointer = utf8Strings
  30. while let string = Element(validatingUTF8: pointer) {
  31. strings.append(string)
  32. while pointer.pointee != 0 {
  33. pointer.advance()
  34. }
  35. pointer.advance()
  36. guard pointer.pointee != 0 else {
  37. break
  38. }
  39. }
  40. self = strings
  41. }
  42. }
  43. extension Strideable {
  44. mutating func advance() {
  45. self = advanced(by: 1)
  46. }
  47. }
  48. extension UnsafePointer {
  49. init<T>(_ pointer: UnsafePointer<T>) {
  50. self = UnsafeRawPointer(pointer).assumingMemoryBound(to: Pointee.self)
  51. }
  52. }
  53. func relativePointer<T, U, V>(base: UnsafePointer<T>, offset: U) -> UnsafePointer<V> where U : FixedWidthInteger {
  54. return UnsafeRawPointer(base).advanced(by: Int(integer: offset)).assumingMemoryBound(to: V.self)
  55. }
  56. extension Int {
  57. fileprivate init<T : FixedWidthInteger>(integer: T) {
  58. switch integer {
  59. case let value as Int: self = value
  60. case let value as Int32: self = Int(value)
  61. case let value as Int16: self = Int(value)
  62. case let value as Int8: self = Int(value)
  63. default: self = 0
  64. }
  65. }
  66. }