Properties.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. // Created by zhouzhuo on 07/01/2017.
  18. //
  19. /// An instance property
  20. struct Property {
  21. let key: String
  22. let value: Any
  23. /// An instance property description
  24. struct Description {
  25. public let key: String
  26. public let type: Any.Type
  27. public let offset: Int
  28. public func write(_ value: Any, to storage: UnsafeMutableRawPointer) {
  29. return extensions(of: type).write(value, to: storage.advanced(by: offset))
  30. }
  31. }
  32. }
  33. /// Retrieve properties for `instance`
  34. func getProperties(forInstance instance: Any) -> [Property]? {
  35. if let props = getProperties(forType: type(of: instance)) {
  36. var copy = extensions(of: instance)
  37. let storage = copy.storage()
  38. return props.map {
  39. nextProperty(description: $0, storage: storage)
  40. }
  41. }
  42. return nil
  43. }
  44. private func nextProperty(description: Property.Description, storage: UnsafeRawPointer) -> Property {
  45. return Property(
  46. key: description.key,
  47. value: extensions(of: description.type).value(from: storage.advanced(by: description.offset))
  48. )
  49. }
  50. /// Retrieve property descriptions for `type`
  51. func getProperties(forType type: Any.Type) -> [Property.Description]? {
  52. if let structDescriptor = Metadata.Struct(anyType: type) {
  53. return structDescriptor.propertyDescriptions()
  54. } else if let classDescriptor = Metadata.Class(anyType: type) {
  55. return classDescriptor.propertyDescriptions()
  56. } else if let objcClassDescriptor = Metadata.ObjcClassWrapper(anyType: type),
  57. let targetType = objcClassDescriptor.targetType {
  58. return getProperties(forType: targetType)
  59. }
  60. return nil
  61. }