瀏覽代碼

1.update resources

wenweiwei 4 年之前
父節點
當前提交
3459e4a7ae
共有 100 個文件被更改,包括 53507 次插入866 次删除
  1. 6 5
      BFCommonKit.podspec
  2. 6 0
      BFCommonKit/Assets/Resources/Xcassets.xcassets/Contents.json
  3. 22 0
      BFCommonKit/Assets/Resources/Xcassets.xcassets/icon_detail_back.imageset/Contents.json
  4. 0 0
      BFCommonKit/Assets/Resources/Xcassets.xcassets/icon_detail_back.imageset/icon_detail_back@2x.png
  5. 0 0
      BFCommonKit/Assets/Resources/Xcassets.xcassets/icon_detail_back.imageset/icon_detail_back@3x.png
  6. 22 0
      BFCommonKit/Assets/Resources/Xcassets.xcassets/placehold_image.imageset/Contents.json
  7. 0 0
      BFCommonKit/Assets/Resources/Xcassets.xcassets/placehold_image.imageset/placehold_image@2x.png
  8. 0 0
      BFCommonKit/Assets/Resources/Xcassets.xcassets/placehold_image.imageset/placehold_image@3x.png
  9. 6 0
      Example/BFCommonKit.xcodeproj/project.pbxproj
  10. 30 14
      Example/Podfile.lock
  11. 58 0
      Example/Pods/FDFullscreenPopGesture/FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h
  12. 227 0
      Example/Pods/FDFullscreenPopGesture/FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.m
  13. 22 0
      Example/Pods/FDFullscreenPopGesture/LICENSE
  14. 62 0
      Example/Pods/FDFullscreenPopGesture/README.md
  15. 16 7
      Example/Pods/Local Podspecs/BFCommonKit.podspec.json
  16. 30 14
      Example/Pods/Manifest.lock
  17. 1340 826
      Example/Pods/Pods.xcodeproj/project.pbxproj
  18. 204 0
      Example/Pods/Realm/LICENSE
  19. 72 0
      Example/Pods/Realm/README.md
  20. 43 0
      Example/Pods/Realm/Realm/NSError+RLMSync.m
  21. 116 0
      Example/Pods/Realm/Realm/RLMAPIKeyAuth.mm
  22. 964 0
      Example/Pods/Realm/Realm/RLMAccessor.mm
  23. 254 0
      Example/Pods/Realm/Realm/RLMAnalytics.mm
  24. 413 0
      Example/Pods/Realm/Realm/RLMApp.mm
  25. 613 0
      Example/Pods/Realm/Realm/RLMArray.mm
  26. 389 0
      Example/Pods/Realm/Realm/RLMBSON.mm
  27. 127 0
      Example/Pods/Realm/Realm/RLMClassInfo.mm
  28. 460 0
      Example/Pods/Realm/Realm/RLMCollection.mm
  29. 36 0
      Example/Pods/Realm/Realm/RLMConstants.m
  30. 88 0
      Example/Pods/Realm/Realm/RLMCredentials.mm
  31. 192 0
      Example/Pods/Realm/Realm/RLMDecimal128.mm
  32. 84 0
      Example/Pods/Realm/Realm/RLMEmailPasswordAuth.mm
  33. 113 0
      Example/Pods/Realm/Realm/RLMEmbeddedObject.mm
  34. 88 0
      Example/Pods/Realm/Realm/RLMFindOneAndModifyOptions.mm
  35. 87 0
      Example/Pods/Realm/Realm/RLMFindOptions.mm
  36. 163 0
      Example/Pods/Realm/Realm/RLMListBase.mm
  37. 575 0
      Example/Pods/Realm/Realm/RLMManagedArray.mm
  38. 180 0
      Example/Pods/Realm/Realm/RLMMigration.mm
  39. 67 0
      Example/Pods/Realm/Realm/RLMMongoClient.mm
  40. 419 0
      Example/Pods/Realm/Realm/RLMMongoCollection.mm
  41. 229 0
      Example/Pods/Realm/Realm/RLMNetworkTransport.mm
  42. 242 0
      Example/Pods/Realm/Realm/RLMObject.mm
  43. 747 0
      Example/Pods/Realm/Realm/RLMObjectBase.mm
  44. 128 0
      Example/Pods/Realm/Realm/RLMObjectId.mm
  45. 372 0
      Example/Pods/Realm/Realm/RLMObjectSchema.mm
  46. 241 0
      Example/Pods/Realm/Realm/RLMObjectStore.mm
  47. 555 0
      Example/Pods/Realm/Realm/RLMObservation.mm
  48. 164 0
      Example/Pods/Realm/Realm/RLMOptionalBase.mm
  49. 127 0
      Example/Pods/Realm/Realm/RLMPredicateUtil.mm
  50. 642 0
      Example/Pods/Realm/Realm/RLMProperty.mm
  51. 42 0
      Example/Pods/Realm/Realm/RLMProviderClient.mm
  52. 59 0
      Example/Pods/Realm/Realm/RLMPushClient.mm
  53. 1571 0
      Example/Pods/Realm/Realm/RLMQueryUtil.mm
  54. 40 0
      Example/Pods/Realm/Realm/RLMRealm+Sync.mm
  55. 1003 0
      Example/Pods/Realm/Realm/RLMRealm.mm
  56. 77 0
      Example/Pods/Realm/Realm/RLMRealmConfiguration+Sync.mm
  57. 345 0
      Example/Pods/Realm/Realm/RLMRealmConfiguration.mm
  58. 157 0
      Example/Pods/Realm/Realm/RLMRealmUtil.mm
  59. 572 0
      Example/Pods/Realm/Realm/RLMResults.mm
  60. 377 0
      Example/Pods/Realm/Realm/RLMSchema.mm
  61. 31 0
      Example/Pods/Realm/Realm/RLMSwiftSupport.m
  62. 215 0
      Example/Pods/Realm/Realm/RLMSyncConfiguration.mm
  63. 275 0
      Example/Pods/Realm/Realm/RLMSyncManager.mm
  64. 327 0
      Example/Pods/Realm/Realm/RLMSyncSession.mm
  65. 126 0
      Example/Pods/Realm/Realm/RLMSyncUtil.mm
  66. 69 0
      Example/Pods/Realm/Realm/RLMThreadSafeReference.mm
  67. 60 0
      Example/Pods/Realm/Realm/RLMUpdateChecker.mm
  68. 35 0
      Example/Pods/Realm/Realm/RLMUpdateResult.mm
  69. 325 0
      Example/Pods/Realm/Realm/RLMUser.mm
  70. 68 0
      Example/Pods/Realm/Realm/RLMUserAPIKey.mm
  71. 510 0
      Example/Pods/Realm/Realm/RLMUtil.mm
  72. 33 0
      Example/Pods/Realm/Realm/Realm.modulemap
  73. 1386 0
      Example/Pods/Realm/build.sh
  74. 126 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/Info.plist
  75. 22875 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/external/json/json.hpp
  76. 2819 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/external/mpark/variant.hpp
  77. 1831 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm.h
  78. 32 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm.hpp
  79. 608 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/alloc.hpp
  80. 781 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/alloc_slab.hpp
  81. 2091 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array.hpp
  82. 90 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_backlink.hpp
  83. 218 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_basic.hpp
  84. 377 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_basic_tpl.hpp
  85. 118 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_binary.hpp
  86. 142 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_blob.hpp
  87. 206 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_blobs_big.hpp
  88. 274 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_blobs_small.hpp
  89. 156 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_bool.hpp
  90. 109 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_decimal128.hpp
  91. 369 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_direct.hpp
  92. 240 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_fixed_bytes.hpp
  93. 383 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_integer.hpp
  94. 132 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_key.hpp
  95. 99 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_list.hpp
  96. 138 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_mixed.hpp
  97. 70 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_ref.hpp
  98. 170 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_string.hpp
  99. 173 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_string_short.hpp
  100. 136 0
      Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_timestamp.hpp

+ 6 - 5
BFCommonKit.podspec

@@ -8,7 +8,7 @@
 
 Pod::Spec.new do |s|
   s.name             = 'BFCommonKit'
-  s.version          = '1.1.1'
+  s.version          = '1.1.2'
   s.summary          = 'A short description of BFCommonKit.'
   s.swift_version    = '5.0'
 # This description is used to generate tags and improve search results.
@@ -72,10 +72,11 @@ TODO: Add long description of the pod here.
     dd.frameworks = 'UIKit','MessageUI','WebKit'
     dd.dependency 'BFCommonKit/BFCategorys'
   end
-
-   s.resource_bundles = {
-     'BFCommonKit_Resources' => ['BFCommonKit/Assets/Resources/*.png']
-   }
+  s.subspec 'Resources' do |rr|
+    rr.resource_bundles = {
+      'BFCommonKit_Resources' => ['BFCommonKit/Assets/Resources/*']
+    }
+  end
   # s.resources = 'BFCommonKit/Assets/Resources/*.png'
   # s.public_header_files = 'Pod/Classes/**/*.h'
   # s.frameworks = 'UIKit', 'AVFoundation','CoreMedia', 'QuartzCore'

+ 6 - 0
BFCommonKit/Assets/Resources/Xcassets.xcassets/Contents.json

@@ -0,0 +1,6 @@
+{
+  "info" : {
+    "author" : "xcode",
+    "version" : 1
+  }
+}

+ 22 - 0
BFCommonKit/Assets/Resources/Xcassets.xcassets/icon_detail_back.imageset/Contents.json

@@ -0,0 +1,22 @@
+{
+  "images" : [
+    {
+      "idiom" : "universal",
+      "scale" : "1x"
+    },
+    {
+      "filename" : "icon_detail_back@2x.png",
+      "idiom" : "universal",
+      "scale" : "2x"
+    },
+    {
+      "filename" : "icon_detail_back@3x.png",
+      "idiom" : "universal",
+      "scale" : "3x"
+    }
+  ],
+  "info" : {
+    "author" : "xcode",
+    "version" : 1
+  }
+}

+ 0 - 0
BFCommonKit/Assets/Resources/icon_detail_back@2x.png → BFCommonKit/Assets/Resources/Xcassets.xcassets/icon_detail_back.imageset/icon_detail_back@2x.png


+ 0 - 0
BFCommonKit/Assets/Resources/icon_detail_back@3x.png → BFCommonKit/Assets/Resources/Xcassets.xcassets/icon_detail_back.imageset/icon_detail_back@3x.png


+ 22 - 0
BFCommonKit/Assets/Resources/Xcassets.xcassets/placehold_image.imageset/Contents.json

@@ -0,0 +1,22 @@
+{
+  "images" : [
+    {
+      "idiom" : "universal",
+      "scale" : "1x"
+    },
+    {
+      "filename" : "placehold_image@2x.png",
+      "idiom" : "universal",
+      "scale" : "2x"
+    },
+    {
+      "filename" : "placehold_image@3x.png",
+      "idiom" : "universal",
+      "scale" : "3x"
+    }
+  ],
+  "info" : {
+    "author" : "xcode",
+    "version" : 1
+  }
+}

+ 0 - 0
BFCommonKit/Assets/Resources/placehold_image@2x.png → BFCommonKit/Assets/Resources/Xcassets.xcassets/placehold_image.imageset/placehold_image@2x.png


+ 0 - 0
BFCommonKit/Assets/Resources/placehold_image@3x.png → BFCommonKit/Assets/Resources/Xcassets.xcassets/placehold_image.imageset/placehold_image@3x.png


+ 6 - 0
Example/BFCommonKit.xcodeproj/project.pbxproj

@@ -272,9 +272,12 @@
 				"${PODS_ROOT}/Target Support Files/Pods-BFCommonKit_Example/Pods-BFCommonKit_Example-frameworks.sh",
 				"${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework",
 				"${BUILT_PRODUCTS_DIR}/BFCommonKit/BFCommonKit.framework",
+				"${BUILT_PRODUCTS_DIR}/FDFullscreenPopGesture/FDFullscreenPopGesture.framework",
 				"${BUILT_PRODUCTS_DIR}/KeychainAccess/KeychainAccess.framework",
 				"${BUILT_PRODUCTS_DIR}/Kingfisher/Kingfisher.framework",
 				"${BUILT_PRODUCTS_DIR}/KingfisherWebP/KingfisherWebP.framework",
+				"${BUILT_PRODUCTS_DIR}/Realm/Realm.framework",
+				"${BUILT_PRODUCTS_DIR}/RealmSwift/RealmSwift.framework",
 				"${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework",
 				"${BUILT_PRODUCTS_DIR}/Toast-Swift/Toast_Swift.framework",
 				"${BUILT_PRODUCTS_DIR}/libwebp/libwebp.framework",
@@ -283,9 +286,12 @@
 			outputPaths = (
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework",
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/BFCommonKit.framework",
+				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FDFullscreenPopGesture.framework",
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/KeychainAccess.framework",
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Kingfisher.framework",
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/KingfisherWebP.framework",
+				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Realm.framework",
+				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RealmSwift.framework",
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SnapKit.framework",
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Toast_Swift.framework",
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/libwebp.framework",

+ 30 - 14
Example/Podfile.lock

@@ -1,25 +1,28 @@
 PODS:
   - Alamofire (4.9.1)
-  - BFCommonKit (1.0.9):
-    - BFCommonKit/BFBase (= 1.0.9)
-    - BFCommonKit/BFCategorys (= 1.0.9)
-    - BFCommonKit/BFConfig (= 1.0.9)
-    - BFCommonKit/BFDebug (= 1.0.9)
-    - BFCommonKit/BFEnums (= 1.0.9)
-    - BFCommonKit/BFUtility (= 1.0.9)
-  - BFCommonKit/BFBase (1.0.9):
+  - BFCommonKit (1.1.1):
+    - BFCommonKit/BFBase (= 1.1.1)
+    - BFCommonKit/BFCategorys (= 1.1.1)
+    - BFCommonKit/BFConfig (= 1.1.1)
+    - BFCommonKit/BFDebug (= 1.1.1)
+    - BFCommonKit/BFEnums (= 1.1.1)
+    - BFCommonKit/BFUtility (= 1.1.1)
+    - BFCommonKit/Resources (= 1.1.1)
+  - BFCommonKit/BFBase (1.1.1):
     - Alamofire (= 4.9.1)
     - BFCommonKit/BFCategorys
     - BFCommonKit/BFConfig
     - BFCommonKit/BFUtility
+    - FDFullscreenPopGesture (= 1.1)
+    - RealmSwift (= 10.7.6)
     - SnapKit (= 5.0.1)
-  - BFCommonKit/BFCategorys (1.0.9):
+  - BFCommonKit/BFCategorys (1.1.1):
     - KingfisherWebP (= 1.3.0)
-  - BFCommonKit/BFConfig (1.0.9)
-  - BFCommonKit/BFDebug (1.0.9):
+  - BFCommonKit/BFConfig (1.1.1)
+  - BFCommonKit/BFDebug (1.1.1):
     - BFCommonKit/BFCategorys
-  - BFCommonKit/BFEnums (1.0.9)
-  - BFCommonKit/BFUtility (1.0.9):
+  - BFCommonKit/BFEnums (1.1.1)
+  - BFCommonKit/BFUtility (1.1.1):
     - Alamofire (= 4.9.1)
     - BFCommonKit/BFCategorys
     - BFCommonKit/BFConfig
@@ -27,6 +30,8 @@ PODS:
     - Kingfisher (= 6.3.0)
     - KingfisherWebP (= 1.3.0)
     - Toast-Swift (= 5.0.1)
+  - BFCommonKit/Resources (1.1.1)
+  - FDFullscreenPopGesture (1.1)
   - KeychainAccess (4.2.2)
   - Kingfisher (6.3.0)
   - KingfisherWebP (1.3.0):
@@ -41,6 +46,11 @@ PODS:
   - libwebp/mux (1.2.0):
     - libwebp/demux
   - libwebp/webp (1.2.0)
+  - Realm (10.7.6):
+    - Realm/Headers (= 10.7.6)
+  - Realm/Headers (10.7.6)
+  - RealmSwift (10.7.6):
+    - Realm (= 10.7.6)
   - SnapKit (5.0.1)
   - Toast-Swift (5.0.1)
 
@@ -50,10 +60,13 @@ DEPENDENCIES:
 SPEC REPOS:
   trunk:
     - Alamofire
+    - FDFullscreenPopGesture
     - KeychainAccess
     - Kingfisher
     - KingfisherWebP
     - libwebp
+    - Realm
+    - RealmSwift
     - SnapKit
     - Toast-Swift
 
@@ -63,11 +76,14 @@ EXTERNAL SOURCES:
 
 SPEC CHECKSUMS:
   Alamofire: 85e8a02c69d6020a0d734f6054870d7ecb75cf18
-  BFCommonKit: 9523ec22780f7d5db0d637071ec80a81782bb93e
+  BFCommonKit: b58e30bb0cefb7925fd35c949009b467582067e5
+  FDFullscreenPopGesture: a8a620179e3d9c40e8e00256dcee1c1a27c6d0f0
   KeychainAccess: c0c4f7f38f6fc7bbe58f5702e25f7bd2f65abf51
   Kingfisher: 6c3df386db71d82c0817a429d2c9421a77396529
   KingfisherWebP: dec17a5eb1af2658791bde1f93ae9a853678f826
   libwebp: e90b9c01d99205d03b6bb8f2c8c415e5a4ef66f0
+  Realm: ed860452717c8db8f4bf832b6807f7f2ce708839
+  RealmSwift: e31c4ddbcc42ac879313d656b86f9ca539f6f4f4
   SnapKit: 97b92857e3df3a0c71833cce143274bf6ef8e5eb
   Toast-Swift: 9b6a70f28b3bf0b96c40d46c0c4b9d6639846711
 

+ 58 - 0
Example/Pods/FDFullscreenPopGesture/FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h

@@ -0,0 +1,58 @@
+// The MIT License (MIT)
+//
+// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all
+// copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+// SOFTWARE.
+
+#import <UIKit/UIKit.h>
+
+/// "UINavigation+FDFullscreenPopGesture" extends UINavigationController's swipe-
+/// to-pop behavior in iOS 7+ by supporting fullscreen pan gesture. Instead of
+/// screen edge, you can now swipe from any place on the screen and the onboard
+/// interactive pop transition works seamlessly.
+///
+/// Adding the implementation file of this category to your target will
+/// automatically patch UINavigationController with this feature.
+@interface UINavigationController (FDFullscreenPopGesture)
+
+/// The gesture recognizer that actually handles interactive pop.
+@property (nonatomic, strong, readonly) UIPanGestureRecognizer *fd_fullscreenPopGestureRecognizer;
+
+/// A view controller is able to control navigation bar's appearance by itself,
+/// rather than a global way, checking "fd_prefersNavigationBarHidden" property.
+/// Default to YES, disable it if you don't want so.
+@property (nonatomic, assign) BOOL fd_viewControllerBasedNavigationBarAppearanceEnabled;
+
+@end
+
+/// Allows any view controller to disable interactive pop gesture, which might
+/// be necessary when the view controller itself handles pan gesture in some
+/// cases.
+@interface UIViewController (FDFullscreenPopGesture)
+
+/// Whether the interactive pop gesture is disabled when contained in a navigation
+/// stack.
+@property (nonatomic, assign) BOOL fd_interactivePopDisabled;
+
+/// Indicate this view controller prefers its navigation bar hidden or not,
+/// checked when view controller based navigation bar's appearance is enabled.
+/// Default to NO, bars are more likely to show.
+@property (nonatomic, assign) BOOL fd_prefersNavigationBarHidden;
+
+@end

+ 227 - 0
Example/Pods/FDFullscreenPopGesture/FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.m

@@ -0,0 +1,227 @@
+// The MIT License (MIT)
+//
+// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all
+// copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+// SOFTWARE.
+
+#import "UINavigationController+FDFullscreenPopGesture.h"
+#import <objc/runtime.h>
+
+@interface _FDFullscreenPopGestureRecognizerDelegate : NSObject <UIGestureRecognizerDelegate>
+
+@property (nonatomic, weak) UINavigationController *navigationController;
+
+@end
+
+@implementation _FDFullscreenPopGestureRecognizerDelegate
+
+- (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)gestureRecognizer
+{
+    // Ignore when no view controller is pushed into the navigation stack.
+    if (self.navigationController.viewControllers.count <= 1) {
+        return NO;
+    }
+    
+    // Disable when the active view controller doesn't allow interactive pop.
+    UIViewController *topViewController = self.navigationController.viewControllers.lastObject;
+    if (topViewController.fd_interactivePopDisabled) {
+        return NO;
+    }
+
+    // Ignore pan gesture when the navigation controller is currently in transition.
+    if ([[self.navigationController valueForKey:@"_isTransitioning"] boolValue]) {
+        return NO;
+    }
+    
+    // Prevent calling the handler when the gesture begins in an opposite direction.
+    CGPoint translation = [gestureRecognizer translationInView:gestureRecognizer.view];
+    if (translation.x <= 0) {
+        return NO;
+    }
+    
+    return YES;
+}
+
+@end
+
+typedef void (^_FDViewControllerWillAppearInjectBlock)(UIViewController *viewController, BOOL animated);
+
+@interface UIViewController (FDFullscreenPopGesturePrivate)
+
+@property (nonatomic, copy) _FDViewControllerWillAppearInjectBlock fd_willAppearInjectBlock;
+
+@end
+
+@implementation UIViewController (FDFullscreenPopGesturePrivate)
+
++ (void)load
+{
+    Method originalMethod = class_getInstanceMethod(self, @selector(viewWillAppear:));
+    Method swizzledMethod = class_getInstanceMethod(self, @selector(fd_viewWillAppear:));
+    method_exchangeImplementations(originalMethod, swizzledMethod);
+}
+
+- (void)fd_viewWillAppear:(BOOL)animated
+{
+    // Forward to primary implementation.
+    [self fd_viewWillAppear:animated];
+    
+    if (self.fd_willAppearInjectBlock) {
+        self.fd_willAppearInjectBlock(self, animated);
+    }
+}
+
+- (_FDViewControllerWillAppearInjectBlock)fd_willAppearInjectBlock
+{
+    return objc_getAssociatedObject(self, _cmd);
+}
+
+- (void)setFd_willAppearInjectBlock:(_FDViewControllerWillAppearInjectBlock)block
+{
+    objc_setAssociatedObject(self, @selector(fd_willAppearInjectBlock), block, OBJC_ASSOCIATION_COPY_NONATOMIC);
+}
+
+@end
+
+@implementation UINavigationController (FDFullscreenPopGesture)
+
++ (void)load
+{
+    // Inject "-pushViewController:animated:"
+    Method originalMethod = class_getInstanceMethod(self, @selector(pushViewController:animated:));
+    Method swizzledMethod = class_getInstanceMethod(self, @selector(fd_pushViewController:animated:));
+    method_exchangeImplementations(originalMethod, swizzledMethod);
+}
+
+- (void)fd_pushViewController:(UIViewController *)viewController animated:(BOOL)animated
+{
+    if (![self.interactivePopGestureRecognizer.view.gestureRecognizers containsObject:self.fd_fullscreenPopGestureRecognizer]) {
+        
+        // Add our own gesture recognizer to where the onboard screen edge pan gesture recognizer is attached to.
+        [self.interactivePopGestureRecognizer.view addGestureRecognizer:self.fd_fullscreenPopGestureRecognizer];
+
+        // Forward the gesture events to the private handler of the onboard gesture recognizer.
+        NSArray *internalTargets = [self.interactivePopGestureRecognizer valueForKey:@"targets"];
+        id internalTarget = [internalTargets.firstObject valueForKey:@"target"];
+        SEL internalAction = NSSelectorFromString(@"handleNavigationTransition:");
+        self.fd_fullscreenPopGestureRecognizer.delegate = self.fd_popGestureRecognizerDelegate;
+        [self.fd_fullscreenPopGestureRecognizer addTarget:internalTarget action:internalAction];
+
+        // Disable the onboard gesture recognizer.
+        self.interactivePopGestureRecognizer.enabled = NO;
+    }
+    
+    // Handle perferred navigation bar appearance.
+    [self fd_setupViewControllerBasedNavigationBarAppearanceIfNeeded:viewController];
+    
+    // Forward to primary implementation.
+    [self fd_pushViewController:viewController animated:animated];
+}
+
+- (void)fd_setupViewControllerBasedNavigationBarAppearanceIfNeeded:(UIViewController *)appearingViewController
+{
+    if (!self.fd_viewControllerBasedNavigationBarAppearanceEnabled) {
+        return;
+    }
+    
+    __weak typeof(self) weakSelf = self;
+    _FDViewControllerWillAppearInjectBlock block = ^(UIViewController *viewController, BOOL animated) {
+        __strong typeof(weakSelf) strongSelf = weakSelf;
+        if (strongSelf) {
+            [strongSelf setNavigationBarHidden:viewController.fd_prefersNavigationBarHidden animated:animated];
+        }
+    };
+    
+    // Setup will appear inject block to appearing view controller.
+    // Setup disappearing view controller as well, because not every view controller is added into
+    // stack by pushing, maybe by "-setViewControllers:".
+    appearingViewController.fd_willAppearInjectBlock = block;
+    UIViewController *disappearingViewController = self.viewControllers.lastObject;
+    if (disappearingViewController && !disappearingViewController.fd_willAppearInjectBlock) {
+        disappearingViewController.fd_willAppearInjectBlock = block;
+    }
+}
+
+- (_FDFullscreenPopGestureRecognizerDelegate *)fd_popGestureRecognizerDelegate
+{
+    _FDFullscreenPopGestureRecognizerDelegate *delegate = objc_getAssociatedObject(self, _cmd);
+
+    if (!delegate) {
+        delegate = [[_FDFullscreenPopGestureRecognizerDelegate alloc] init];
+        delegate.navigationController = self;
+        
+        objc_setAssociatedObject(self, _cmd, delegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    return delegate;
+}
+
+- (UIPanGestureRecognizer *)fd_fullscreenPopGestureRecognizer
+{
+    UIPanGestureRecognizer *panGestureRecognizer = objc_getAssociatedObject(self, _cmd);
+
+    if (!panGestureRecognizer) {
+        panGestureRecognizer = [[UIPanGestureRecognizer alloc] init];
+        panGestureRecognizer.maximumNumberOfTouches = 1;
+        
+        objc_setAssociatedObject(self, _cmd, panGestureRecognizer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    return panGestureRecognizer;
+}
+
+- (BOOL)fd_viewControllerBasedNavigationBarAppearanceEnabled
+{
+    NSNumber *number = objc_getAssociatedObject(self, _cmd);
+    if (number) {
+        return number.boolValue;
+    }
+    self.fd_viewControllerBasedNavigationBarAppearanceEnabled = YES;
+    return YES;
+}
+
+- (void)setFd_viewControllerBasedNavigationBarAppearanceEnabled:(BOOL)enabled
+{
+    SEL key = @selector(fd_viewControllerBasedNavigationBarAppearanceEnabled);
+    objc_setAssociatedObject(self, key, @(enabled), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+@end
+
+@implementation UIViewController (FDFullscreenPopGesture)
+
+- (BOOL)fd_interactivePopDisabled
+{
+    return [objc_getAssociatedObject(self, _cmd) boolValue];
+}
+
+- (void)setFd_interactivePopDisabled:(BOOL)disabled
+{
+    objc_setAssociatedObject(self, @selector(fd_interactivePopDisabled), @(disabled), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+- (BOOL)fd_prefersNavigationBarHidden
+{
+    return [objc_getAssociatedObject(self, _cmd) boolValue];
+}
+
+- (void)setFd_prefersNavigationBarHidden:(BOOL)hidden
+{
+    objc_setAssociatedObject(self, @selector(fd_prefersNavigationBarHidden), @(hidden), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+@end

+ 22 - 0
Example/Pods/FDFullscreenPopGesture/LICENSE

@@ -0,0 +1,22 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+

+ 62 - 0
Example/Pods/FDFullscreenPopGesture/README.md

@@ -0,0 +1,62 @@
+# FDFullscreenPopGesture
+An UINavigationController's category to enable fullscreen pop gesture in an iOS7+ system style with AOP.
+
+# Overview
+
+![snapshot](https://raw.githubusercontent.com/forkingdog/FDFullscreenPopGesture/master/Snapshots/snapshot0.gif)
+
+这个扩展来自 @J_雨 同学的这个很天才的思路,他的文章地址:[http://www.jianshu.com/p/d39f7d22db6c](http://www.jianshu.com/p/d39f7d22db6c)
+
+# Usage
+
+**AOP**, just add 2 files and **no need** for any setups, all navigation controllers will be able to use fullscreen pop gesture automatically.  
+
+To disable this pop gesture of a navigation controller:  
+
+``` objc
+navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
+```
+
+To disable this pop gesture of a view controller:  
+
+``` objc
+viewController.fd_interactivePopDisabled = YES;
+```
+
+Require at least iOS **7.0**.
+
+# View Controller Based Navigation Bar Appearance
+
+It handles navigation bar transition properly when using fullscreen gesture to push or pop a view controller:  
+
+- with bar -> without bar
+- without bar -> with bar
+- without bar -> without bar
+
+![snapshot with bar states](https://raw.githubusercontent.com/forkingdog/FDFullscreenPopGesture/master/Snapshots/snapshot1.gif)
+
+This opmiziation is enabled by default, from now on you don't need to call **UINavigationController**'s `-setNavigationBarHidden:animated:` method, instead, use view controller's specific API to hide its bar:  
+
+``` objc
+- (void)viewDidLoad {
+    [super viewDidLoad];
+    self.fd_prefersNavigationBarHidden = NO;
+}
+```
+
+And this property is **YES** by default.
+
+# Installation
+
+Use cocoapods  
+
+``` ruby
+pod 'FDFullscreenPopGesture', '1.1'
+```
+# Release Notes
+
+**1.1** - View controller based navigation bar appearance and transition.  
+**1.0** - Fullscreen pop gesture.  
+
+# License  
+MIT

+ 16 - 7
Example/Pods/Local Podspecs/BFCommonKit.podspec.json

@@ -1,6 +1,6 @@
 {
   "name": "BFCommonKit",
-  "version": "1.0.9",
+  "version": "1.1.1",
   "summary": "A short description of BFCommonKit.",
   "swift_versions": "5.0",
   "description": "TODO: Add long description of the pod here.",
@@ -14,16 +14,11 @@
   },
   "source": {
     "git": "https://git.yishihui.com/wenweiwei/BFCommonKit.git",
-    "tag": "1.0.9"
+    "tag": "1.1.1"
   },
   "platforms": {
     "ios": "10.0"
   },
-  "resource_bundles": {
-    "BFCommonKit_Resources": [
-      "BFCommonKit/Assets/Resources/*.png"
-    ]
-  },
   "subspecs": [
     {
       "name": "BFConfig",
@@ -44,6 +39,12 @@
         "SnapKit": [
           "5.0.1"
         ],
+        "RealmSwift": [
+          "10.7.6"
+        ],
+        "FDFullscreenPopGesture": [
+          "1.1"
+        ],
         "BFCommonKit/BFUtility": [
 
         ],
@@ -122,6 +123,14 @@
 
         ]
       }
+    },
+    {
+      "name": "Resources",
+      "resource_bundles": {
+        "BFCommonKit_Resources": [
+          "BFCommonKit/Assets/Resources/*"
+        ]
+      }
     }
   ],
   "swift_version": "5.0"

+ 30 - 14
Example/Pods/Manifest.lock

@@ -1,25 +1,28 @@
 PODS:
   - Alamofire (4.9.1)
-  - BFCommonKit (1.0.9):
-    - BFCommonKit/BFBase (= 1.0.9)
-    - BFCommonKit/BFCategorys (= 1.0.9)
-    - BFCommonKit/BFConfig (= 1.0.9)
-    - BFCommonKit/BFDebug (= 1.0.9)
-    - BFCommonKit/BFEnums (= 1.0.9)
-    - BFCommonKit/BFUtility (= 1.0.9)
-  - BFCommonKit/BFBase (1.0.9):
+  - BFCommonKit (1.1.1):
+    - BFCommonKit/BFBase (= 1.1.1)
+    - BFCommonKit/BFCategorys (= 1.1.1)
+    - BFCommonKit/BFConfig (= 1.1.1)
+    - BFCommonKit/BFDebug (= 1.1.1)
+    - BFCommonKit/BFEnums (= 1.1.1)
+    - BFCommonKit/BFUtility (= 1.1.1)
+    - BFCommonKit/Resources (= 1.1.1)
+  - BFCommonKit/BFBase (1.1.1):
     - Alamofire (= 4.9.1)
     - BFCommonKit/BFCategorys
     - BFCommonKit/BFConfig
     - BFCommonKit/BFUtility
+    - FDFullscreenPopGesture (= 1.1)
+    - RealmSwift (= 10.7.6)
     - SnapKit (= 5.0.1)
-  - BFCommonKit/BFCategorys (1.0.9):
+  - BFCommonKit/BFCategorys (1.1.1):
     - KingfisherWebP (= 1.3.0)
-  - BFCommonKit/BFConfig (1.0.9)
-  - BFCommonKit/BFDebug (1.0.9):
+  - BFCommonKit/BFConfig (1.1.1)
+  - BFCommonKit/BFDebug (1.1.1):
     - BFCommonKit/BFCategorys
-  - BFCommonKit/BFEnums (1.0.9)
-  - BFCommonKit/BFUtility (1.0.9):
+  - BFCommonKit/BFEnums (1.1.1)
+  - BFCommonKit/BFUtility (1.1.1):
     - Alamofire (= 4.9.1)
     - BFCommonKit/BFCategorys
     - BFCommonKit/BFConfig
@@ -27,6 +30,8 @@ PODS:
     - Kingfisher (= 6.3.0)
     - KingfisherWebP (= 1.3.0)
     - Toast-Swift (= 5.0.1)
+  - BFCommonKit/Resources (1.1.1)
+  - FDFullscreenPopGesture (1.1)
   - KeychainAccess (4.2.2)
   - Kingfisher (6.3.0)
   - KingfisherWebP (1.3.0):
@@ -41,6 +46,11 @@ PODS:
   - libwebp/mux (1.2.0):
     - libwebp/demux
   - libwebp/webp (1.2.0)
+  - Realm (10.7.6):
+    - Realm/Headers (= 10.7.6)
+  - Realm/Headers (10.7.6)
+  - RealmSwift (10.7.6):
+    - Realm (= 10.7.6)
   - SnapKit (5.0.1)
   - Toast-Swift (5.0.1)
 
@@ -50,10 +60,13 @@ DEPENDENCIES:
 SPEC REPOS:
   trunk:
     - Alamofire
+    - FDFullscreenPopGesture
     - KeychainAccess
     - Kingfisher
     - KingfisherWebP
     - libwebp
+    - Realm
+    - RealmSwift
     - SnapKit
     - Toast-Swift
 
@@ -63,11 +76,14 @@ EXTERNAL SOURCES:
 
 SPEC CHECKSUMS:
   Alamofire: 85e8a02c69d6020a0d734f6054870d7ecb75cf18
-  BFCommonKit: 9523ec22780f7d5db0d637071ec80a81782bb93e
+  BFCommonKit: b58e30bb0cefb7925fd35c949009b467582067e5
+  FDFullscreenPopGesture: a8a620179e3d9c40e8e00256dcee1c1a27c6d0f0
   KeychainAccess: c0c4f7f38f6fc7bbe58f5702e25f7bd2f65abf51
   Kingfisher: 6c3df386db71d82c0817a429d2c9421a77396529
   KingfisherWebP: dec17a5eb1af2658791bde1f93ae9a853678f826
   libwebp: e90b9c01d99205d03b6bb8f2c8c415e5a4ef66f0
+  Realm: ed860452717c8db8f4bf832b6807f7f2ce708839
+  RealmSwift: e31c4ddbcc42ac879313d656b86f9ca539f6f4f4
   SnapKit: 97b92857e3df3a0c71833cce143274bf6ef8e5eb
   Toast-Swift: 9b6a70f28b3bf0b96c40d46c0c4b9d6639846711
 

文件差異過大導致無法顯示
+ 1340 - 826
Example/Pods/Pods.xcodeproj/project.pbxproj


+ 204 - 0
Example/Pods/Realm/LICENSE

@@ -0,0 +1,204 @@
+TABLE OF CONTENTS
+
+1. Apache License version 2.0
+2. Export Compliance
+
+1. -------------------------------------------------------------------------------
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+2. -------------------------------------------------------------------------------
+
+EXPORT COMPLIANCE
+
+You understand that the Software may contain cryptographic functions that may be
+subject to export restrictions, and you represent and warrant that you are not
+(i) located in a jurisdiction that is subject to United States economic
+sanctions (“Prohibited Jurisdiction”), including Cuba, Iran, North Korea,
+Sudan, Syria or the Crimea region, (ii) a person listed on any U.S. government
+blacklist (to include the List of Specially Designated Nationals and Blocked
+Persons or the Consolidated Sanctions List administered by the U.S. Department
+of the Treasury’s Office of Foreign Assets Control, or the Denied Persons List
+or Entity List administered by the U.S. Department of Commerce)
+(“Sanctioned Person”), or (iii) controlled or 50% or more owned by a Sanctioned
+Person.
+
+You agree to comply with all export, re-export and import restrictions and
+regulations of the U.S. Department of Commerce or other agency or authority of
+the United States or other applicable countries. You also agree not to transfer,
+or authorize the transfer of, directly or indirectly, of the Software to any
+Prohibited Jurisdiction, or otherwise in violation of any such restrictions or
+regulations.

+ 72 - 0
Example/Pods/Realm/README.md

@@ -0,0 +1,72 @@
+![Realm](https://github.com/realm/realm-cocoa/raw/master/logo.png)
+
+Realm is a mobile database that runs directly inside phones, tablets or wearables.
+This repository holds the source code for the iOS, macOS, tvOS & watchOS versions of Realm Swift & Realm Objective-C.
+
+## Features
+
+* **Mobile-first:** Realm is the first database built from the ground up to run directly inside phones, tablets and wearables.
+* **Simple:** Data is directly [exposed as objects](https://realm.io/docs/objc/latest/#models) and [queryable by code](https://realm.io/docs/objc/latest/#queries), removing the need for ORM's riddled with performance & maintenance issues. Most of our users pick it up intuitively, getting simple apps up & running in minutes.
+* **Modern:** Realm supports relationships, generics, vectorization and Swift.
+* **Fast:** Realm is faster than even raw SQLite on common operations, while maintaining an extremely rich feature set.
+
+## Getting Started
+
+Please see the detailed instructions in our docs to add [Realm Objective-C](https://realm.io/docs/objc/latest/#installation) _or_ [Realm Swift](https://realm.io/docs/swift/latest/#installation) to your Xcode project.
+
+## Documentation
+
+### Realm Objective-C
+
+The documentation can be found at [realm.io/docs/objc/latest](https://realm.io/docs/objc/latest).  
+The API reference is located at [realm.io/docs/objc/latest/api/](https://realm.io/docs/objc/latest/api/).
+
+### Realm Swift
+
+The documentation can be found at [realm.io/docs/swift/latest](https://realm.io/docs/swift/latest).  
+The API reference is located at [realm.io/docs/swift/latest/api/](https://realm.io/docs/swift/latest/api/).
+
+## Getting Help
+
+- **Need help with your code?**: Look for previous questions with the[`realm` tag](https://stackoverflow.com/questions/tagged/realm?sort=newest) on Stack Overflow or [ask a new question](https://stackoverflow.com/questions/ask?tags=realm). For general discussion that might be considered too broad for Stack Overflow, use the [Community Forum](https://developer.mongodb.com/community/forums/tags/c/realm/9/realm-sdk).
+- **Have a bug to report?** [Open a GitHub issue](https://github.com/realm/realm-cocoa/issues/new). If possible, include the version of Realm, a full log, the Realm file, and a project that shows the issue.
+- **Have a feature request?** [Open a GitHub issue](https://github.com/realm/realm-cocoa/issues/new). Tell us what the feature should do and why you want the feature.
+
+## Building Realm
+
+In case you don't want to use the precompiled version, you can build Realm yourself from source.
+
+Prerequisites:
+
+* Building Realm requires Xcode 11.x or newer.
+* Building Realm documentation requires [jazzy](https://github.com/realm/jazzy)
+
+Once you have all the necessary prerequisites, building Realm.framework just takes a single command: `sh build.sh build`. You'll need an internet connection the first time you build Realm to download the core binary.
+
+Run `sh build.sh help` to see all the actions you can perform (build ios/osx, generate docs, test, etc.).
+
+## Contributing
+
+See [CONTRIBUTING.md](CONTRIBUTING.md) for more details!
+
+This project adheres to the [Contributor Covenant Code of Conduct](https://realm.io/conduct).
+By participating, you are expected to uphold this code. Please report
+unacceptable behavior to [info@realm.io](mailto:info@realm.io).
+
+## License
+
+Realm Objective-C & Realm Swift are published under the Apache 2.0 license.  
+Realm Core is also published under the Apache 2.0 license and is available
+[here](https://github.com/realm/realm-core).
+
+**This product is not being made available to any person located in Cuba, Iran,
+North Korea, Sudan, Syria or the Crimea region, or to any other person that is
+not eligible to receive the product under U.S. law.**
+
+## Feedback
+
+**_If you use Realm and are happy with it, all we ask is that you please consider sending out a tweet mentioning [@realm](https://twitter.com/realm) to share your thoughts!_**
+
+**_And if you don't like it, please let us know what you would like improved, so we can fix it!_**
+
+![analytics](https://ga-beacon.appspot.com/UA-50247013-2/realm-cocoa/README?pixel)

+ 43 - 0
Example/Pods/Realm/Realm/NSError+RLMSync.m

@@ -0,0 +1,43 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2017 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "NSError+RLMSync.h"
+
+#import "RLMSyncUtil.h"
+
+@implementation NSError (RLMSync)
+
+- (RLMSyncErrorActionToken *)rlmSync_errorActionToken {
+    if (self.domain != RLMSyncErrorDomain) {
+        return nil;
+    }
+    if (self.code == RLMSyncErrorClientResetError
+        || self.code == RLMSyncErrorPermissionDeniedError) {
+        return (RLMSyncErrorActionToken *)self.userInfo[kRLMSyncErrorActionTokenKey];
+    }
+    return nil;
+}
+
+- (NSString *)rlmSync_clientResetBackedUpRealmPath {
+    if (self.domain == RLMSyncErrorDomain && self.code == RLMSyncErrorClientResetError) {
+        return self.userInfo[kRLMSyncPathOfRealmBackupCopyKey];
+    }
+    return nil;
+}
+
+@end

+ 116 - 0
Example/Pods/Realm/Realm/RLMAPIKeyAuth.mm

@@ -0,0 +1,116 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMAPIKeyAuth.h"
+#import "RLMProviderClient_Private.hpp"
+
+#import "RLMApp_Private.hpp"
+#import "RLMUserAPIKey_Private.hpp"
+#import "RLMObjectId_Private.hpp"
+
+@implementation RLMAPIKeyAuth
+
+- (realm::app::App::UserAPIKeyProviderClient)client {
+    return self.app._realmApp->provider_client<realm::app::App::UserAPIKeyProviderClient>();
+}
+
+- (std::shared_ptr<realm::SyncUser>)currentUser {
+    return self.app._realmApp->current_user();
+}
+
+- (void)createAPIKeyWithName:(NSString *)name
+                  completion:(RLMOptionalUserAPIKeyBlock)completion {
+    
+    self.client.create_api_key(name.UTF8String, self.currentUser,
+                               ^(realm::util::Optional<realm::app::App::UserAPIKey> userAPIKey,
+                                 realm::util::Optional<realm::app::AppError> error) {
+        if (error && error->error_code) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+        
+        if (userAPIKey) {
+            return completion([[RLMUserAPIKey alloc] initWithUserAPIKey:userAPIKey.value()], nil);
+        }
+        
+        return completion(nil, nil);
+    });
+}
+
+- (void)fetchAPIKey:(RLMObjectId *)objectId
+         completion:(RLMOptionalUserAPIKeyBlock)completion {
+    self.client.fetch_api_key(objectId.value,
+                              self.currentUser,
+                              ^(realm::util::Optional<realm::app::App::UserAPIKey> userAPIKey,
+                                realm::util::Optional<realm::app::AppError> error) {
+        if (error && error->error_code) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+        
+        if (userAPIKey) {
+            return completion([[RLMUserAPIKey alloc] initWithUserAPIKey:userAPIKey.value()], nil);
+        }
+        
+        return completion(nil, nil);
+    });
+}
+
+- (void)fetchAPIKeysWithCompletion:(RLMUserAPIKeysBlock)completion {
+    self.client.fetch_api_keys(self.currentUser,
+                               ^(const std::vector<realm::app::App::UserAPIKey>& userAPIKeys,
+                                 realm::util::Optional<realm::app::AppError> error) {
+        if (error && error->error_code) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+        
+        NSMutableArray *apiKeys = [[NSMutableArray alloc] init];
+        for(auto &userAPIKey : userAPIKeys) {
+            [apiKeys addObject:[[RLMUserAPIKey alloc] initWithUserAPIKey:userAPIKey]];
+        }
+        
+        return completion(apiKeys, nil);
+    });
+}
+
+- (void)deleteAPIKey:(RLMObjectId *)objectId
+          completion:(RLMAPIKeyAuthOptionalErrorBlock)completion {
+    self.client.delete_api_key(objectId.value,
+                               self.currentUser,
+                               ^(realm::util::Optional<realm::app::AppError> error) {
+        [self handleResponse:error completion:completion];
+    });
+}
+
+- (void)enableAPIKey:(RLMObjectId *)objectId
+          completion:(RLMAPIKeyAuthOptionalErrorBlock)completion {
+    self.client.enable_api_key(objectId.value,
+                               self.currentUser,
+                               ^(realm::util::Optional<realm::app::AppError> error) {
+        [self handleResponse:error completion:completion];
+    });
+}
+
+- (void)disableAPIKey:(RLMObjectId *)objectId
+           completion:(RLMAPIKeyAuthOptionalErrorBlock)completion {
+    self.client.disable_api_key(objectId.value,
+                                self.currentUser,
+                                ^(realm::util::Optional<realm::app::AppError> error) {
+        [self handleResponse:error completion:completion];
+    });
+}
+
+@end

+ 964 - 0
Example/Pods/Realm/Realm/RLMAccessor.mm

@@ -0,0 +1,964 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMAccessor.hpp"
+
+#import "RLMArray_Private.hpp"
+#import "RLMListBase.h"
+#import "RLMObjectId_Private.hpp"
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMObjectStore.h"
+#import "RLMObject_Private.hpp"
+#import "RLMObservation.hpp"
+#import "RLMProperty_Private.h"
+#import "RLMRealm_Private.hpp"
+#import "RLMResults_Private.hpp"
+#import "RLMSchema_Private.h"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/results.hpp>
+#import <realm/object-store/property.hpp>
+
+#import <objc/runtime.h>
+#import <objc/message.h>
+
+#pragma mark - Helper functions
+
+namespace realm {
+template<>
+Obj Obj::get<Obj>(ColKey col) const {
+    ObjKey key = get<ObjKey>(col);
+    return key ? get_target_table(col)->get_object(key) : Obj();
+}
+}
+
+namespace {
+using realm::ColKey;
+
+realm::Property const& get_property(__unsafe_unretained RLMObjectBase *const obj, NSUInteger index) {
+    return obj->_info->objectSchema->persisted_properties[index];
+}
+
+realm::Property const& get_property(__unsafe_unretained RLMObjectBase *const obj,
+                                    __unsafe_unretained RLMProperty *const prop) {
+    if (prop.linkOriginPropertyName) {
+        return obj->_info->objectSchema->computed_properties[prop.index];
+    }
+    return obj->_info->objectSchema->persisted_properties[prop.index];
+}
+
+template<typename T>
+bool is_null(T const& v) {
+    return !v;
+}
+template<>
+bool is_null(realm::Timestamp const& v) {
+    return v.is_null();
+}
+template<>
+bool is_null(realm::ObjectId const&) {
+    return false;
+}
+template<>
+bool is_null(realm::Decimal128 const& v) {
+    return v.is_null();
+}
+
+template<typename T>
+T get(__unsafe_unretained RLMObjectBase *const obj, NSUInteger index) {
+    RLMVerifyAttached(obj);
+    return obj->_row.get<T>(get_property(obj, index).column_key);
+}
+
+template<typename T>
+id getBoxed(__unsafe_unretained RLMObjectBase *const obj, NSUInteger index) {
+    RLMVerifyAttached(obj);
+    auto& prop = get_property(obj, index);
+    RLMAccessorContext ctx(obj, &prop);
+    auto value = obj->_row.get<T>(prop.column_key);
+    return is_null(value) ? nil : ctx.box(std::move(value));
+}
+
+template<typename T>
+void setValue(__unsafe_unretained RLMObjectBase *const obj, ColKey key, T val) {
+    obj->_row.set(key, val);
+}
+
+void setValue(__unsafe_unretained RLMObjectBase *const obj, ColKey key,
+              __unsafe_unretained NSString *const val) {
+    RLMTranslateError([&] {
+        obj->_row.set(key, RLMStringDataWithNSString(val));
+    });
+}
+
+[[gnu::noinline]]
+void setNull(realm::Obj& row, ColKey key) {
+    RLMTranslateError([&] { row.set_null(key); });
+}
+
+void setValue(__unsafe_unretained RLMObjectBase *const obj,
+              ColKey key, __unsafe_unretained NSDate *const date) {
+    if (date) {
+        obj->_row.set(key, RLMTimestampForNSDate(date));
+    }
+    else {
+        setNull(obj->_row, key);
+    }
+}
+
+void setValue(__unsafe_unretained RLMObjectBase *const obj, ColKey key,
+              __unsafe_unretained NSData *const data) {
+    RLMTranslateError([&] {
+        obj->_row.set(key, RLMBinaryDataForNSData(data));
+    });
+}
+
+void setValue(__unsafe_unretained RLMObjectBase *const obj, ColKey key,
+              __unsafe_unretained RLMObjectBase *const val) {
+    if (!val) {
+        obj->_row.set(key, realm::null());
+        return;
+    }
+
+    if (!val->_row) {
+        RLMAccessorContext{obj, key}.createObject(val, {.create = true}, false, {});
+    }
+
+    // make sure it is the correct type
+    auto table = val->_row.get_table();
+    if (table != obj->_row.get_table()->get_link_target(key)) {
+        @throw RLMException(@"Can't set object of type '%@' to property of type '%@'",
+                            val->_objectSchema.className,
+                            obj->_info->propertyForTableColumn(key).objectClassName);
+    }
+    if (!table->is_embedded()) {
+        obj->_row.set(key, val->_row.get_key());
+    }
+    else if (obj->_row.get_linked_object(key).get_key() != val->_row.get_key()) {
+        @throw RLMException(@"Can't set link to existing managed embedded object");
+    }
+}
+
+// array getter/setter
+RLMArray *getArray(__unsafe_unretained RLMObjectBase *const obj, NSUInteger propIndex) {
+    RLMVerifyAttached(obj);
+    auto prop = obj->_info->rlmObjectSchema.properties[propIndex];
+    return [[RLMManagedArray alloc] initWithParent:obj property:prop];
+}
+
+void setValue(__unsafe_unretained RLMObjectBase *const obj, ColKey key,
+              __unsafe_unretained id<NSFastEnumeration> const value) {
+    auto prop = obj->_info->propertyForTableColumn(key);
+    RLMValidateValueForProperty(value, obj->_info->rlmObjectSchema, prop, true);
+
+    realm::List list(obj->_realm->_realm, obj->_row, key);
+    RLMClassInfo *info = obj->_info;
+    if (list.get_type() == realm::PropertyType::Object) {
+        info = &obj->_info->linkTargetType(prop.index);
+    }
+    RLMAccessorContext ctx(*info);
+    RLMTranslateError([&] {
+        list.assign(ctx, value, realm::CreatePolicy::ForceCreate);
+    });
+}
+
+void setValue(__unsafe_unretained RLMObjectBase *const obj, ColKey key,
+              __unsafe_unretained NSNumber<RLMInt> *const intObject) {
+    if (intObject) {
+        obj->_row.set(key, intObject.longLongValue);
+    }
+    else {
+        setNull(obj->_row, key);
+    }
+}
+
+void setValue(__unsafe_unretained RLMObjectBase *const obj, ColKey key,
+              __unsafe_unretained NSNumber<RLMFloat> *const floatObject) {
+    if (floatObject) {
+        obj->_row.set(key, floatObject.floatValue);
+    }
+    else {
+        setNull(obj->_row, key);
+    }
+}
+
+void setValue(__unsafe_unretained RLMObjectBase *const obj, ColKey key,
+              __unsafe_unretained NSNumber<RLMDouble> *const doubleObject) {
+    if (doubleObject) {
+        obj->_row.set(key, doubleObject.doubleValue);
+    }
+    else {
+        setNull(obj->_row, key);
+    }
+}
+
+void setValue(__unsafe_unretained RLMObjectBase *const obj, ColKey key,
+              __unsafe_unretained NSNumber<RLMBool> *const boolObject) {
+    if (boolObject) {
+        obj->_row.set(key, (bool)boolObject.boolValue);
+    }
+    else {
+        setNull(obj->_row, key);
+    }
+}
+
+void setValue(__unsafe_unretained RLMObjectBase *const obj, ColKey key,
+              __unsafe_unretained RLMDecimal128 *const value) {
+    if (value) {
+        obj->_row.set(key, value.decimal128Value);
+    }
+    else {
+        setNull(obj->_row, key);
+    }
+}
+
+void setValue(__unsafe_unretained RLMObjectBase *const obj, ColKey key,
+              __unsafe_unretained RLMObjectId *const value) {
+    if (value) {
+        obj->_row.set(key, value.value);
+    }
+    else {
+        setNull(obj->_row, key);
+    }
+}
+
+RLMLinkingObjects *getLinkingObjects(__unsafe_unretained RLMObjectBase *const obj,
+                                     __unsafe_unretained RLMProperty *const property) {
+    RLMVerifyAttached(obj);
+    auto& objectInfo = obj->_realm->_info[property.objectClassName];
+    auto& linkOrigin = obj->_info->objectSchema->computed_properties[property.index].link_origin_property_name;
+    auto linkingProperty = objectInfo.objectSchema->property_for_name(linkOrigin);
+    auto backlinkView = obj->_row.get_backlink_view(objectInfo.table(), linkingProperty->column_key);
+    realm::Results results(obj->_realm->_realm, std::move(backlinkView));
+    return [RLMLinkingObjects resultsWithObjectInfo:objectInfo results:std::move(results)];
+}
+
+// any getter/setter
+template<typename Type, typename StorageType=Type>
+id makeGetter(NSUInteger index) {
+    return ^(__unsafe_unretained RLMObjectBase *const obj) {
+        return static_cast<Type>(get<StorageType>(obj, index));
+    };
+}
+
+template<typename Type>
+id makeBoxedGetter(NSUInteger index) {
+    return ^(__unsafe_unretained RLMObjectBase *const obj) {
+        return getBoxed<Type>(obj, index);
+    };
+}
+template<typename Type>
+id makeOptionalGetter(NSUInteger index) {
+    return ^(__unsafe_unretained RLMObjectBase *const obj) {
+        return getBoxed<realm::util::Optional<Type>>(obj, index);
+    };
+}
+template<typename Type>
+id makeNumberGetter(NSUInteger index, bool boxed, bool optional) {
+    if (optional) {
+        return makeOptionalGetter<Type>(index);
+    }
+    if (boxed) {
+        return makeBoxedGetter<Type>(index);
+    }
+    return makeGetter<Type>(index);
+}
+template<typename Type>
+id makeWrapperGetter(NSUInteger index, bool optional) {
+    if (optional) {
+        return makeOptionalGetter<Type>(index);
+    }
+    return makeBoxedGetter<Type>(index);
+}
+
+// dynamic getter with column closure
+id managedGetter(RLMProperty *prop, const char *type) {
+    NSUInteger index = prop.index;
+    if (prop.array && prop.type != RLMPropertyTypeLinkingObjects) {
+        return ^id(__unsafe_unretained RLMObjectBase *const obj) {
+            return getArray(obj, index);
+        };
+    }
+
+    bool boxed = *type == '@';
+    switch (prop.type) {
+        case RLMPropertyTypeInt:
+            if (prop.optional || boxed) {
+                return makeNumberGetter<long long>(index, boxed, prop.optional);
+            }
+            switch (*type) {
+                case 'c': return makeGetter<char, int64_t>(index);
+                case 's': return makeGetter<short, int64_t>(index);
+                case 'i': return makeGetter<int, int64_t>(index);
+                case 'l': return makeGetter<long, int64_t>(index);
+                case 'q': return makeGetter<long long, int64_t>(index);
+                default:
+                    @throw RLMException(@"Unexpected property type for Objective-C type code");
+            }
+        case RLMPropertyTypeFloat:
+            return makeNumberGetter<float>(index, boxed, prop.optional);
+        case RLMPropertyTypeDouble:
+            return makeNumberGetter<double>(index, boxed, prop.optional);
+        case RLMPropertyTypeBool:
+            return makeNumberGetter<bool>(index, boxed, prop.optional);
+        case RLMPropertyTypeString:
+            return makeBoxedGetter<realm::StringData>(index);
+        case RLMPropertyTypeDate:
+            return makeBoxedGetter<realm::Timestamp>(index);
+        case RLMPropertyTypeData:
+            return makeBoxedGetter<realm::BinaryData>(index);
+        case RLMPropertyTypeObject:
+            return makeBoxedGetter<realm::Obj>(index);
+        case RLMPropertyTypeDecimal128:
+            return makeBoxedGetter<realm::Decimal128>(index);
+        case RLMPropertyTypeObjectId:
+            return makeWrapperGetter<realm::ObjectId>(index, prop.optional);
+        case RLMPropertyTypeAny:
+            @throw RLMException(@"Cannot create accessor class for schema with Mixed properties");
+        case RLMPropertyTypeLinkingObjects:
+            return ^(__unsafe_unretained RLMObjectBase *const obj) {
+                return getLinkingObjects(obj, prop);
+            };
+    }
+}
+
+template<typename ArgType, typename StorageType=ArgType>
+id makeSetter(__unsafe_unretained RLMProperty *const prop) {
+    NSUInteger index = prop.index;
+    NSString *name = prop.name;
+    if (prop.isPrimary) {
+        return ^(__unused RLMObjectBase *obj, __unused ArgType val) {
+            @throw RLMException(@"Primary key can't be changed after an object is inserted.");
+        };
+    }
+
+    return ^(__unsafe_unretained RLMObjectBase *const obj, ArgType val) {
+        RLMVerifyInWriteTransaction(obj);
+        RLMObservationTracker tracker(obj->_realm);
+        tracker.willChange(RLMGetObservationInfo(obj->_observationInfo, obj->_row.get_key(), *obj->_info), name);
+        if constexpr (std::is_same_v<ArgType, RLMObjectBase *>) {
+            tracker.trackDeletions();
+        }
+        setValue(obj, get_property(obj, index).column_key, static_cast<StorageType>(val));
+    };
+}
+
+// dynamic setter with column closure
+id managedSetter(RLMProperty *prop, const char *type) {
+    if (prop.array && prop.type != RLMPropertyTypeLinkingObjects) {
+        return makeSetter<id<NSFastEnumeration>>(prop);
+    }
+
+    bool boxed = prop.optional || *type == '@';
+    switch (prop.type) {
+        case RLMPropertyTypeInt:
+            if (boxed) {
+                return makeSetter<NSNumber<RLMInt> *>(prop);
+            }
+            switch (*type) {
+                case 'c': return makeSetter<char, long long>(prop);
+                case 's': return makeSetter<short, long long>(prop);
+                case 'i': return makeSetter<int, long long>(prop);
+                case 'l': return makeSetter<long, long long>(prop);
+                case 'q': return makeSetter<long long>(prop);
+                default:
+                    @throw RLMException(@"Unexpected property type for Objective-C type code");
+            }
+        case RLMPropertyTypeFloat:
+            return boxed ? makeSetter<NSNumber<RLMFloat> *>(prop) : makeSetter<float>(prop);
+        case RLMPropertyTypeDouble:
+            return boxed ? makeSetter<NSNumber<RLMDouble> *>(prop) : makeSetter<double>(prop);
+        case RLMPropertyTypeBool:
+            return boxed ? makeSetter<NSNumber<RLMBool> *>(prop) : makeSetter<BOOL, bool>(prop);
+        case RLMPropertyTypeString:         return makeSetter<NSString *>(prop);
+        case RLMPropertyTypeDate:           return makeSetter<NSDate *>(prop);
+        case RLMPropertyTypeData:           return makeSetter<NSData *>(prop);
+        case RLMPropertyTypeAny:            return nil;
+        case RLMPropertyTypeLinkingObjects: return nil;
+        case RLMPropertyTypeObject:         return makeSetter<RLMObjectBase *>(prop);
+        case RLMPropertyTypeObjectId:       return makeSetter<RLMObjectId *>(prop);
+        case RLMPropertyTypeDecimal128:     return makeSetter<RLMDecimal128 *>(prop);
+    }
+}
+
+// call getter for superclass for property at key
+id superGet(RLMObjectBase *obj, NSString *propName) {
+    typedef id (*getter_type)(RLMObjectBase *, SEL);
+    RLMProperty *prop = obj->_objectSchema[propName];
+    Class superClass = class_getSuperclass(obj.class);
+    getter_type superGetter = (getter_type)[superClass instanceMethodForSelector:prop.getterSel];
+    return superGetter(obj, prop.getterSel);
+}
+
+// call setter for superclass for property at key
+void superSet(RLMObjectBase *obj, NSString *propName, id val) {
+    typedef void (*setter_type)(RLMObjectBase *, SEL, RLMArray *ar);
+    RLMProperty *prop = obj->_objectSchema[propName];
+    Class superClass = class_getSuperclass(obj.class);
+    setter_type superSetter = (setter_type)[superClass instanceMethodForSelector:prop.setterSel];
+    superSetter(obj, prop.setterSel, val);
+}
+
+// getter/setter for unmanaged object
+id unmanagedGetter(RLMProperty *prop, const char *) {
+    // only override getters for RLMArray and linking objects properties
+    if (prop.type == RLMPropertyTypeLinkingObjects) {
+        return ^(RLMObjectBase *) { return [RLMResults emptyDetachedResults]; };
+    }
+    if (prop.array) {
+        NSString *propName = prop.name;
+        if (prop.type == RLMPropertyTypeObject) {
+            NSString *objectClassName = prop.objectClassName;
+            return ^(RLMObjectBase *obj) {
+                id val = superGet(obj, propName);
+                if (!val) {
+                    val = [[RLMArray alloc] initWithObjectClassName:objectClassName];
+                    superSet(obj, propName, val);
+                }
+                return val;
+            };
+        }
+        auto type = prop.type;
+        auto optional = prop.optional;
+        return ^(RLMObjectBase *obj) {
+            id val = superGet(obj, propName);
+            if (!val) {
+                val = [[RLMArray alloc] initWithObjectType:type optional:optional];
+                superSet(obj, propName, val);
+            }
+            return val;
+        };
+    }
+    return nil;
+}
+
+id unmanagedSetter(RLMProperty *prop, const char *) {
+    // Only RLMArray needs special handling for the unmanaged setter
+    if (!prop.array) {
+        return nil;
+    }
+
+    NSString *propName = prop.name;
+    return ^(RLMObjectBase *obj, id<NSFastEnumeration> values) {
+        auto prop = obj->_objectSchema[propName];
+        RLMValidateValueForProperty(values, obj->_objectSchema, prop, true);
+
+        // make copy when setting (as is the case for all other variants)
+        RLMArray *ar;
+        if (prop.type == RLMPropertyTypeObject)
+            ar = [[RLMArray alloc] initWithObjectClassName:prop.objectClassName];
+        else
+            ar = [[RLMArray alloc] initWithObjectType:prop.type optional:prop.optional];
+        [ar addObjects:values];
+        superSet(obj, propName, ar);
+    };
+}
+
+void addMethod(Class cls, __unsafe_unretained RLMProperty *const prop,
+               id (*getter)(RLMProperty *, const char *),
+               id (*setter)(RLMProperty *, const char *)) {
+    SEL sel = prop.getterSel;
+    auto getterMethod = class_getInstanceMethod(cls, sel);
+    if (!getterMethod) {
+        return;
+    }
+
+    const char *getterType = method_getTypeEncoding(getterMethod);
+    if (id block = getter(prop, getterType)) {
+        class_addMethod(cls, sel, imp_implementationWithBlock(block), getterType);
+    }
+
+    if (!(sel = prop.setterSel)) {
+        return;
+    }
+    auto setterMethod = class_getInstanceMethod(cls, sel);
+    if (!setterMethod) {
+        return;
+    }
+    if (id block = setter(prop, getterType)) { // note: deliberately getterType as it's easier to grab the relevant type from
+        class_addMethod(cls, sel, imp_implementationWithBlock(block), method_getTypeEncoding(setterMethod));
+    }
+}
+
+Class createAccessorClass(Class objectClass,
+                          RLMObjectSchema *schema,
+                          const char *accessorClassName,
+                          id (*getterGetter)(RLMProperty *, const char *),
+                          id (*setterGetter)(RLMProperty *, const char *)) {
+    REALM_ASSERT_DEBUG(RLMIsObjectOrSubclass(objectClass));
+
+    // create and register proxy class which derives from object class
+    Class accClass = objc_allocateClassPair(objectClass, accessorClassName, 0);
+    if (!accClass) {
+        // Class with that name already exists, so just return the pre-existing one
+        // This should only happen for our standalone "accessors"
+        return objc_lookUpClass(accessorClassName);
+    }
+
+    // override getters/setters for each propery
+    for (RLMProperty *prop in schema.properties) {
+        addMethod(accClass, prop, getterGetter, setterGetter);
+    }
+    for (RLMProperty *prop in schema.computedProperties) {
+        addMethod(accClass, prop, getterGetter, setterGetter);
+    }
+
+    objc_registerClassPair(accClass);
+
+    return accClass;
+}
+} // anonymous namespace
+
+#pragma mark - Public Interface
+
+Class RLMManagedAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema, const char *name) {
+    return createAccessorClass(objectClass, schema, name, managedGetter, managedSetter);
+}
+
+Class RLMUnmanagedAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema) {
+    return createAccessorClass(objectClass, schema,
+                               [@"RLM:Unmanaged " stringByAppendingString:schema.className].UTF8String,
+                               unmanagedGetter, unmanagedSetter);
+}
+
+// implement the class method className on accessors to return the className of the
+// base object
+void RLMReplaceClassNameMethod(Class accessorClass, NSString *className) {
+    Class metaClass = object_getClass(accessorClass);
+    IMP imp = imp_implementationWithBlock(^(Class){ return className; });
+    class_addMethod(metaClass, @selector(className), imp, "@@:");
+}
+
+// implement the shared schema method
+void RLMReplaceSharedSchemaMethod(Class accessorClass, RLMObjectSchema *schema) {
+    Class metaClass = object_getClass(accessorClass);
+    IMP imp = imp_implementationWithBlock(^(Class cls) {
+        if (cls == accessorClass) {
+            return schema;
+        }
+
+        // If we aren't being called directly on the class this was overriden
+        // for, the class is either a subclass which we haven't initialized yet,
+        // or it's a runtime-generated class which should use the parent's
+        // schema. We check for the latter by checking if the immediate
+        // descendent of the desired class is a class generated by us (there
+        // may be further subclasses not generated by us for things like KVO).
+        Class parent = class_getSuperclass(cls);
+        while (parent != accessorClass) {
+            cls = parent;
+            parent = class_getSuperclass(cls);
+        }
+
+        static const char accessorClassPrefix[] = "RLM:";
+        if (!strncmp(class_getName(cls), accessorClassPrefix, sizeof(accessorClassPrefix) - 1)) {
+            return schema;
+        }
+
+        return [RLMSchema sharedSchemaForClass:cls];
+    });
+    class_addMethod(metaClass, @selector(sharedSchema), imp, "@@:");
+}
+
+void RLMDynamicValidatedSet(RLMObjectBase *obj, NSString *propName, id val) {
+    RLMVerifyAttached(obj);
+    RLMObjectSchema *schema = obj->_objectSchema;
+    RLMProperty *prop = schema[propName];
+    if (!prop) {
+        @throw RLMException(@"Invalid property name '%@' for class '%@'.",
+                            propName, obj->_objectSchema.className);
+    }
+    if (prop.isPrimary) {
+        @throw RLMException(@"Primary key can't be changed to '%@' after an object is inserted.", val);
+    }
+
+    // Because embedded objects cannot be created directly, we accept anything
+    // that can be converted to an embedded object for dynamic link set operations.
+    bool is_embedded = prop.type == RLMPropertyTypeObject && obj->_info->linkTargetType(prop.index).objectSchema->is_embedded;
+    RLMValidateValueForProperty(val, schema, prop, !is_embedded);
+    RLMDynamicSet(obj, prop, RLMCoerceToNil(val));
+}
+
+// Precondition: the property is not a primary key
+void RLMDynamicSet(__unsafe_unretained RLMObjectBase *const obj,
+                   __unsafe_unretained RLMProperty *const prop,
+                   __unsafe_unretained id const val) {
+    REALM_ASSERT_DEBUG(!prop.isPrimary);
+    realm::Object o(obj->_info->realm->_realm, *obj->_info->objectSchema, obj->_row);
+    RLMAccessorContext c(obj);
+    RLMTranslateError([&] {
+        o.set_property_value(c, get_property(obj, prop).name, val ?: NSNull.null);
+    });
+}
+
+id RLMDynamicGet(__unsafe_unretained RLMObjectBase *const obj, __unsafe_unretained RLMProperty *const prop) {
+    realm::Object o(obj->_realm->_realm, *obj->_info->objectSchema, obj->_row);
+    RLMAccessorContext c(obj);
+    c.currentProperty = prop;
+    return RLMTranslateError([&] {
+        return RLMCoerceToNil(o.get_property_value<id>(c, get_property(obj, prop)));
+    });
+}
+
+id RLMDynamicGetByName(__unsafe_unretained RLMObjectBase *const obj,
+                       __unsafe_unretained NSString *const propName) {
+    RLMProperty *prop = obj->_objectSchema[propName];
+    if (!prop) {
+        @throw RLMException(@"Invalid property name '%@' for class '%@'.",
+                            propName, obj->_objectSchema.className);
+    }
+    return RLMDynamicGet(obj, prop);
+}
+
+RLMAccessorContext::~RLMAccessorContext() = default;
+
+RLMAccessorContext::RLMAccessorContext(RLMAccessorContext& parent, realm::Obj const& obj,
+                                       realm::Property const& property)
+: _realm(parent._realm)
+, _info(property.type == realm::PropertyType::Object ? parent._info.linkTargetType(property) : parent._info)
+, _parentObject(obj)
+, _parentObjectInfo(&parent._info)
+, _colKey(property.column_key)
+{
+}
+
+RLMAccessorContext::RLMAccessorContext(RLMClassInfo& info)
+: _realm(info.realm), _info(info)
+{
+}
+
+RLMAccessorContext::RLMAccessorContext(__unsafe_unretained RLMObjectBase *const parent,
+                                       const realm::Property *prop)
+: _realm(parent->_realm)
+, _info(prop && prop->type == realm::PropertyType::Object ? parent->_info->linkTargetType(*prop)
+                                                          : *parent->_info)
+, _parentObjectInfo(parent->_info)
+{
+}
+
+RLMAccessorContext::RLMAccessorContext(__unsafe_unretained RLMObjectBase *const parent,
+                                       realm::ColKey col)
+: _realm(parent->_realm)
+, _info(_realm->_info[parent->_info->propertyForTableColumn(col).objectClassName])
+, _parentObject(parent->_row)
+, _parentObjectInfo(parent->_info)
+, _colKey(col)
+{
+}
+
+id RLMAccessorContext::defaultValue(__unsafe_unretained NSString *const key) {
+    if (!_defaultValues) {
+        _defaultValues = RLMDefaultValuesForObjectSchema(_info.rlmObjectSchema);
+    }
+    return _defaultValues[key];
+}
+
+id RLMAccessorContext::propertyValue(__unsafe_unretained id const obj, size_t propIndex,
+                                     __unsafe_unretained RLMProperty *const prop) {
+    // Property value from an NSArray
+    if ([obj respondsToSelector:@selector(objectAtIndex:)]) {
+        return propIndex < [obj count] ? [obj objectAtIndex:propIndex] : nil;
+    }
+
+    // Property value from an NSDictionary
+    if ([obj respondsToSelector:@selector(objectForKey:)]) {
+        return [obj objectForKey:prop.name];
+    }
+
+    // Property value from an instance of this object type
+    id value;
+    if ([obj isKindOfClass:_info.rlmObjectSchema.objectClass] && prop.swiftIvar) {
+        if (prop.array) {
+            return static_cast<RLMListBase *>(object_getIvar(obj, prop.swiftIvar))._rlmArray;
+        }
+        else { // optional
+            value = RLMGetOptional(static_cast<RLMOptionalBase *>(object_getIvar(obj, prop.swiftIvar)));
+        }
+    }
+    else {
+    // Property value from some object that's KVC-compatible
+        value = RLMValidatedValueForProperty(obj, [obj respondsToSelector:prop.getterSel] ? prop.getterName : prop.name,
+                                             _info.rlmObjectSchema.className);
+    }
+    return value ?: NSNull.null;
+}
+
+realm::Obj RLMAccessorContext::create_embedded_object() {
+    if (!_parentObject) {
+        @throw RLMException(@"Embedded objects cannot be created directly");
+    }
+    return _parentObject.create_and_set_linked_object(_colKey);
+}
+
+id RLMAccessorContext::box(realm::List&& l) {
+    REALM_ASSERT(_parentObjectInfo);
+    REALM_ASSERT(currentProperty);
+    return [[RLMManagedArray alloc] initWithList:std::move(l)
+                                      parentInfo:_parentObjectInfo
+                                        property:currentProperty];
+}
+
+id RLMAccessorContext::box(realm::Object&& o) {
+    REALM_ASSERT(currentProperty);
+    return RLMCreateObjectAccessor(_info.linkTargetType(currentProperty.index), o.obj());
+}
+
+id RLMAccessorContext::box(realm::Obj&& r) {
+    return RLMCreateObjectAccessor(_info, std::move(r));
+}
+
+id RLMAccessorContext::box(realm::Results&& r) {
+    REALM_ASSERT(currentProperty);
+    return [RLMResults resultsWithObjectInfo:_realm->_info[currentProperty.objectClassName]
+                                     results:std::move(r)];
+}
+
+using realm::ObjKey;
+using realm::CreatePolicy;
+
+template<>
+realm::Timestamp RLMAccessorContext::unbox(__unsafe_unretained id const value, CreatePolicy, ObjKey) {
+    id v = RLMCoerceToNil(value);
+    return RLMTimestampForNSDate(v);
+}
+
+template<>
+bool RLMAccessorContext::unbox(__unsafe_unretained id const v, CreatePolicy, ObjKey) {
+    return [v boolValue];
+}
+template<>
+double RLMAccessorContext::unbox(__unsafe_unretained id const v, CreatePolicy, ObjKey) {
+    return [v doubleValue];
+}
+template<>
+float RLMAccessorContext::unbox(__unsafe_unretained id const v, CreatePolicy, ObjKey) {
+    return [v floatValue];
+}
+template<>
+long long RLMAccessorContext::unbox(__unsafe_unretained id const v, CreatePolicy, ObjKey) {
+    return [v longLongValue];
+}
+template<>
+realm::BinaryData RLMAccessorContext::unbox(id v, CreatePolicy, ObjKey) {
+    v = RLMCoerceToNil(v);
+    return RLMBinaryDataForNSData(v);
+}
+template<>
+realm::StringData RLMAccessorContext::unbox(id v, CreatePolicy, ObjKey) {
+    v = RLMCoerceToNil(v);
+    return RLMStringDataWithNSString(v);
+}
+template<>
+realm::Decimal128 RLMAccessorContext::unbox(id v, CreatePolicy, ObjKey) {
+    return RLMObjcToDecimal128(v);
+}
+template<>
+realm::ObjectId RLMAccessorContext::unbox(id v, CreatePolicy, ObjKey) {
+    return static_cast<RLMObjectId *>(v).value;
+}
+template<>
+realm::UUID RLMAccessorContext::unbox(id, CreatePolicy, ObjKey) {
+    REALM_UNREACHABLE();
+}
+template<>
+realm::Mixed RLMAccessorContext::unbox(id, CreatePolicy, ObjKey) {
+    REALM_UNREACHABLE();
+}
+template<>
+realm::object_store::Set RLMAccessorContext::unbox(id, CreatePolicy, ObjKey) {
+    REALM_UNREACHABLE();
+}
+template<>
+realm::object_store::Dictionary RLMAccessorContext::unbox(id, CreatePolicy, ObjKey) {
+    REALM_UNREACHABLE();
+}
+
+template<typename Fn>
+static auto to_optional(__unsafe_unretained id const value, Fn&& fn) {
+    id v = RLMCoerceToNil(value);
+    return v && v != NSNull.null ? realm::util::make_optional(fn(v)) : realm::util::none;
+}
+
+template<>
+realm::util::Optional<bool> RLMAccessorContext::unbox(__unsafe_unretained id const v, CreatePolicy, ObjKey) {
+    return to_optional(v, [&](__unsafe_unretained id v) { return (bool)[v boolValue]; });
+}
+template<>
+realm::util::Optional<double> RLMAccessorContext::unbox(__unsafe_unretained id const v, CreatePolicy, ObjKey) {
+    return to_optional(v, [&](__unsafe_unretained id v) { return [v doubleValue]; });
+}
+template<>
+realm::util::Optional<float> RLMAccessorContext::unbox(__unsafe_unretained id const v, CreatePolicy, ObjKey) {
+    return to_optional(v, [&](__unsafe_unretained id v) { return [v floatValue]; });
+}
+template<>
+realm::util::Optional<int64_t> RLMAccessorContext::unbox(__unsafe_unretained id const v, CreatePolicy, ObjKey) {
+    return to_optional(v, [&](__unsafe_unretained id v) { return [v longLongValue]; });
+}
+template<>
+realm::util::Optional<realm::ObjectId> RLMAccessorContext::unbox(__unsafe_unretained id const v, CreatePolicy, ObjKey) {
+    return to_optional(v, [&](__unsafe_unretained RLMObjectId *v) { return v.value; });
+}
+template<>
+realm::util::Optional<realm::UUID> RLMAccessorContext::unbox(__unsafe_unretained id const, CreatePolicy, ObjKey) {
+    REALM_UNREACHABLE();
+}
+
+std::pair<realm::Obj, bool>
+RLMAccessorContext::createObject(id value, realm::CreatePolicy policy,
+                                 bool forceCreate, ObjKey existingKey) {
+    if (!value || value == NSNull.null) {
+        @throw RLMException(@"Must provide a non-nil value.");
+    }
+
+    if ([value isKindOfClass:[NSArray class]] && [value count] > _info.objectSchema->persisted_properties.size()) {
+        @throw RLMException(@"Invalid array input: more values (%llu) than properties (%llu).",
+                            (unsigned long long)[value count],
+                            (unsigned long long)_info.objectSchema->persisted_properties.size());
+    }
+
+    RLMObjectBase *objBase = RLMDynamicCast<RLMObjectBase>(value);
+    realm::Obj obj, *outObj = nullptr;
+    if (objBase) {
+        if (objBase.isInvalidated) {
+            if (policy.create && !policy.copy) {
+                @throw RLMException(@"Adding a deleted or invalidated object to a Realm is not permitted");
+            }
+            else {
+                @throw RLMException(@"Object has been deleted or invalidated.");
+            }
+        }
+        if (policy.copy) {
+            if (policy.update || !forceCreate) {
+                // create(update: true) is a no-op when given an object already in
+                // the Realm which is of the correct type
+                if (objBase->_realm == _realm && objBase->_row.get_table() == _info.table() && !_info.table()->is_embedded()) {
+                    return {objBase->_row, true};
+                }
+            }
+            // Otherwise we copy the object
+            objBase = nil;
+        }
+        else {
+            outObj = &objBase->_row;
+            // add() on an object already managed by this Realm is a no-op
+            if (objBase->_realm == _realm) {
+                return {objBase->_row, true};
+            }
+            if (!policy.create) {
+                return {realm::Obj(), false};
+            }
+            if (objBase->_realm) {
+                @throw RLMException(@"Object is already managed by another Realm. Use create instead to copy it into this Realm.");
+            }
+            if (objBase->_observationInfo && objBase->_observationInfo->hasObservers()) {
+                @throw RLMException(@"Cannot add an object with observers to a Realm");
+            }
+
+            REALM_ASSERT([objBase->_objectSchema.className isEqualToString:_info.rlmObjectSchema.className]);
+            REALM_ASSERT([objBase isKindOfClass:_info.rlmObjectSchema.unmanagedClass]);
+
+            objBase->_info = &_info;
+            objBase->_realm = _realm;
+            objBase->_objectSchema = _info.rlmObjectSchema;
+        }
+    }
+    if (!policy.create) {
+        return {realm::Obj(), false};
+    }
+    if (!outObj) {
+        outObj = &obj;
+    }
+
+    try {
+        realm::Object::create(*this, _realm->_realm, *_info.objectSchema,
+                              (id)value, policy, existingKey, outObj).obj();
+    }
+    catch (std::exception const& e) {
+        @throw RLMException(e);
+    }
+
+    if (objBase) {
+        for (RLMProperty *prop in _info.rlmObjectSchema.properties) {
+            // set the ivars for object and array properties to nil as otherwise the
+            // accessors retain objects that are no longer accessible via the properties
+            // this is mainly an issue when the object graph being added has cycles,
+            // as it's not obvious that the user has to set the *ivars* to nil to
+            // avoid leaking memory
+            if (prop.type == RLMPropertyTypeObject && !prop.swiftIvar) {
+                ((void(*)(id, SEL, id))objc_msgSend)(objBase, prop.setterSel, nil);
+            }
+        }
+
+        object_setClass(objBase, _info.rlmObjectSchema.accessorClass);
+        RLMInitializeSwiftAccessorGenerics(objBase);
+    }
+    return {*outObj, false};
+}
+
+template<>
+realm::Obj RLMAccessorContext::unbox(__unsafe_unretained id const v, CreatePolicy policy, ObjKey key) {
+    return createObject(v, policy, false, key).first;
+}
+
+void RLMAccessorContext::will_change(realm::Obj const& row, realm::Property const& prop) {
+    auto obsInfo = RLMGetObservationInfo(nullptr, row.get_key(), _info);
+    if (!_observationHelper) {
+        if (obsInfo || prop.type == realm::PropertyType::Object) {
+            _observationHelper = std::make_unique<RLMObservationTracker>(_info.realm);
+        }
+    }
+    if (_observationHelper) {
+        _observationHelper->willChange(obsInfo, _info.propertyForTableColumn(prop.column_key).name);
+        if (prop.type == realm::PropertyType::Object) {
+            _observationHelper->trackDeletions();
+        }
+    }
+}
+
+void RLMAccessorContext::did_change() {
+    if (_observationHelper) {
+        _observationHelper->didChange();
+    }
+}
+
+RLMOptionalId RLMAccessorContext::value_for_property(__unsafe_unretained id const obj,
+                                                     realm::Property const&, size_t propIndex) {
+    auto prop = _info.rlmObjectSchema.properties[propIndex];
+    id value = propertyValue(obj, propIndex, prop);
+    if (value) {
+        RLMValidateValueForProperty(value, _info.rlmObjectSchema, prop);
+    }
+
+    return RLMOptionalId{value};
+}
+
+RLMOptionalId RLMAccessorContext::default_value_for_property(realm::ObjectSchema const&,
+                                                             realm::Property const& prop)
+{
+    return RLMOptionalId{defaultValue(@(prop.name.c_str()))};
+}
+
+bool RLMAccessorContext::is_same_list(realm::List const& list, __unsafe_unretained id const v) const noexcept {
+    return [v respondsToSelector:@selector(isBackedByList:)] && [v isBackedByList:list];
+}
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wincomplete-implementation"
+@implementation RLMManagedPropertyAccessor
+@end
+#pragma clang diagnostic pop

+ 254 - 0
Example/Pods/Realm/Realm/RLMAnalytics.mm

@@ -0,0 +1,254 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2015 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+// Asynchronously submits build information to Realm if running in an iOS
+// simulator or on OS X if a debugger is attached. Does nothing if running on an
+// iOS / watchOS device or if a debugger is *not* attached.
+//
+// To be clear: this does *not* run when your app is in production or on
+// your end-user’s devices; it will only run in the simulator or when a debugger
+// is attached.
+//
+// Why are we doing this? In short, because it helps us build a better product
+// for you. None of the data personally identifies you, your employer or your
+// app, but it *will* help us understand what language you use, what iOS
+// versions you target, etc. Having this info will help prioritizing our time,
+// adding new features and deprecating old features. Collecting an anonymized
+// bundle & anonymized MAC is the only way for us to count actual usage of the
+// other metrics accurately. If we don’t have a way to deduplicate the info
+// reported, it will be useless, as a single developer building their Swift app
+// 10 times would report 10 times more than a single Objective-C developer that
+// only builds once, making the data all but useless.
+// No one likes sharing data unless it’s necessary, we get it, and we’ve
+// debated adding this for a long long time. Since Realm is a free product
+// without an email signup, we feel this is a necessary step so we can collect
+// relevant data to build a better product for you. If you truly, absolutely
+// feel compelled to not send this data back to Realm, then you can set an env
+// variable named REALM_DISABLE_ANALYTICS. Since Realm is free we believe
+// letting these analytics run is a small price to pay for the product & support
+// we give you.
+//
+// Currently the following information is reported:
+// - What version of Realm is being used, and from which language (obj-c or Swift).
+// - What version of OS X it's running on (in case Xcode aggressively drops
+//   support for older versions again, we need to know what we need to support).
+// - The minimum iOS/OS X version that the application is targeting (again, to
+//   help us decide what versions we need to support).
+// - An anonymous MAC address and bundle ID to aggregate the other information on.
+// - What version of Swift is being used (if applicable).
+
+#import "RLMAnalytics.hpp"
+
+#import <Foundation/Foundation.h>
+
+#if TARGET_IPHONE_SIMULATOR || TARGET_OS_MAC || (TARGET_OS_WATCH && TARGET_OS_SIMULATOR) || (TARGET_OS_TV && TARGET_OS_SIMULATOR)
+#import "RLMRealm.h"
+#import "RLMUtil.hpp"
+
+#import <array>
+#import <sys/socket.h>
+#import <sys/sysctl.h>
+#import <net/if.h>
+#import <net/if_dl.h>
+
+#import <CommonCrypto/CommonDigest.h>
+
+#ifndef REALM_COCOA_VERSION
+#import "RLMVersion.h"
+#endif
+
+// Declared for RealmSwiftObjectUtil
+@interface NSObject (SwiftVersion)
++ (NSString *)swiftVersion;
+@end
+
+// Wrapper for sysctl() that handles the memory management stuff
+static auto RLMSysCtl(int *mib, u_int mibSize, size_t *bufferSize) {
+    std::unique_ptr<void, decltype(&free)> buffer(nullptr, &free);
+
+    int ret = sysctl(mib, mibSize, nullptr, bufferSize, nullptr, 0);
+    if (ret != 0) {
+        return buffer;
+    }
+
+    buffer.reset(malloc(*bufferSize));
+    if (!buffer) {
+        return buffer;
+    }
+
+    ret = sysctl(mib, mibSize, buffer.get(), bufferSize, nullptr, 0);
+    if (ret != 0) {
+        buffer.reset();
+    }
+
+    return buffer;
+}
+
+// Get the version of OS X we're running on (even in the simulator this gives
+// the OS X version and not the simulated iOS version)
+static NSString *RLMOSVersion() {
+    std::array<int, 2> mib = {{CTL_KERN, KERN_OSRELEASE}};
+    size_t bufferSize;
+    auto buffer = RLMSysCtl(&mib[0], mib.size(), &bufferSize);
+    if (!buffer) {
+        return nil;
+    }
+
+    return [[NSString alloc] initWithBytesNoCopy:buffer.release()
+                                          length:bufferSize - 1
+                                        encoding:NSUTF8StringEncoding
+                                    freeWhenDone:YES];
+}
+
+// Hash the data in the given buffer and convert it to a hex-format string
+static NSString *RLMHashData(const void *bytes, size_t length) {
+    unsigned char buffer[CC_SHA256_DIGEST_LENGTH];
+    CC_SHA256(bytes, static_cast<CC_LONG>(length), buffer);
+
+    char formatted[CC_SHA256_DIGEST_LENGTH * 2 + 1];
+    for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; ++i) {
+        sprintf(formatted + i * 2, "%02x", buffer[i]);
+    }
+
+    return [[NSString alloc] initWithBytes:formatted
+                                    length:CC_SHA256_DIGEST_LENGTH * 2
+                                  encoding:NSUTF8StringEncoding];
+}
+
+// Returns the hash of the MAC address of the first network adaptor since the
+// vendorIdentifier isn't constant between iOS simulators.
+static NSString *RLMMACAddress() {
+    int en0 = static_cast<int>(if_nametoindex("en0"));
+    if (!en0) {
+        return nil;
+    }
+
+    std::array<int, 6> mib = {{CTL_NET, PF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, en0}};
+    size_t bufferSize;
+    auto buffer = RLMSysCtl(&mib[0], mib.size(), &bufferSize);
+    if (!buffer) {
+        return nil;
+    }
+
+    // sockaddr_dl struct is immediately after the if_msghdr struct in the buffer
+    auto sockaddr = reinterpret_cast<sockaddr_dl *>(static_cast<if_msghdr *>(buffer.get()) + 1);
+    auto mac = reinterpret_cast<const unsigned char *>(sockaddr->sdl_data + sockaddr->sdl_nlen);
+
+    return RLMHashData(mac, 6);
+}
+
+static NSDictionary *RLMAnalyticsPayload() {
+    NSBundle *appBundle = NSBundle.mainBundle;
+    NSString *hashedBundleID = appBundle.bundleIdentifier;
+
+    // Main bundle isn't always the one of interest (e.g. when running tests
+    // it's xctest rather than the app's bundle), so look for one with a bundle ID
+    if (!hashedBundleID) {
+        for (NSBundle *bundle in NSBundle.allBundles) {
+            if ((hashedBundleID = bundle.bundleIdentifier)) {
+                appBundle = bundle;
+                break;
+            }
+        }
+    }
+
+    // If we found a bundle ID anywhere, hash it as it could contain sensitive
+    // information (e.g. the name of an unnanounced product)
+    if (hashedBundleID) {
+        NSData *data = [hashedBundleID dataUsingEncoding:NSUTF8StringEncoding];
+        hashedBundleID = RLMHashData(data.bytes, data.length);
+    }
+
+    NSString *osVersionString = [[NSProcessInfo processInfo] operatingSystemVersionString];
+    Class swiftDecimal128 = NSClassFromString(@"RealmSwiftDecimal128");
+    BOOL isSwift = swiftDecimal128 != nil;
+
+    static NSString *kUnknownString = @"unknown";
+    NSString *hashedMACAddress = RLMMACAddress() ?: kUnknownString;
+
+    return @{
+             @"event": @"Run",
+             @"properties": @{
+                     // MixPanel properties
+                     @"token": @"ce0fac19508f6c8f20066d345d360fd0",
+
+                     // Anonymous identifiers to deduplicate events
+                     @"distinct_id": hashedMACAddress,
+                     @"Anonymized MAC Address": hashedMACAddress,
+                     @"Anonymized Bundle ID": hashedBundleID ?: kUnknownString,
+
+                     // Which version of Realm is being used
+                     @"Binding": @"cocoa",
+                     @"Language": isSwift ? @"swift" : @"objc",
+                     @"Realm Version": REALM_COCOA_VERSION,
+#if TARGET_OS_WATCH
+                     @"Target OS Type": @"watchos",
+#elif TARGET_OS_TV
+                     @"Target OS Type": @"tvos",
+#elif TARGET_OS_IPHONE
+                     @"Target OS Type": @"ios",
+#else
+                     @"Target OS Type": @"osx",
+#endif
+                     @"Clang Version": @__clang_version__,
+                     @"Clang Major Version": @__clang_major__,
+                     // Current OS version the app is targetting
+                     @"Target OS Version": osVersionString,
+                     // Minimum OS version the app is targetting
+                     @"Target OS Minimum Version": appBundle.infoDictionary[@"MinimumOSVersion"] ?: kUnknownString,
+
+                     // Host OS version being built on
+                     @"Host OS Type": @"osx",
+                     @"Host OS Version": RLMOSVersion() ?: kUnknownString,
+
+#ifdef SWIFT_PACKAGE
+                    @"Installation Method": @"Swift Package Manager",
+#elif defined(COCOAPODS)
+                    @"Installation Method": @"CocoaPods",
+#elif defined(CARTHAGE)
+                    @"Installation Method": @"Carthage",
+#elif defined(REALM_IOS_STATIC)
+                    @"Installation Method": @"Static Framework",
+#else
+                    @"Installation Method": @"Other",
+#endif
+                 }
+          };
+}
+
+void RLMSendAnalytics() {
+    if (getenv("REALM_DISABLE_ANALYTICS") || !RLMIsDebuggerAttached() || RLMIsRunningInPlayground()) {
+        return;
+    }
+    NSArray *urlStrings = @[@"https://webhooks.mongodb-realm.com/api/client/v2.0/app/realmsdkmetrics-zmhtm/service/metric_webhook/incoming_webhook/metric?data=%@",
+                            @"https://api.mixpanel.com/track/?data=%@&ip=1"];
+    NSData *payload = [NSJSONSerialization dataWithJSONObject:RLMAnalyticsPayload() options:0 error:nil];
+
+    for (NSString *urlString in urlStrings) {
+        NSString *formatted = [NSString stringWithFormat:urlString, [payload base64EncodedStringWithOptions:0]];
+        // No error handling or anything because logging errors annoyed people for no
+        // real benefit, and it's not clear what else we could do
+        [[NSURLSession.sharedSession dataTaskWithURL:[NSURL URLWithString:formatted]] resume];
+    }
+}
+
+#else
+
+void RLMSendAnalytics() {}
+
+#endif

+ 413 - 0
Example/Pods/Realm/Realm/RLMApp.mm

@@ -0,0 +1,413 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMApp_Private.hpp"
+
+#import "RLMBSON_Private.hpp"
+#import "RLMCredentials_Private.hpp"
+#import "RLMEmailPasswordAuth.h"
+#import "RLMPushClient_Private.hpp"
+#import "RLMSyncManager_Private.hpp"
+#import "RLMUser_Private.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/sync/sync_manager.hpp>
+#import <realm/sync/config.hpp>
+
+#if !defined(REALM_COCOA_VERSION)
+#import "RLMVersion.h"
+#endif
+
+using namespace realm;
+
+#pragma mark CocoaNetworkTransport
+namespace {
+    /// Internal transport struct to bridge RLMNetworkingTransporting to the GenericNetworkTransport.
+    class CocoaNetworkTransport : public realm::app::GenericNetworkTransport {
+    public:
+        CocoaNetworkTransport(id<RLMNetworkTransport> transport) : m_transport(transport) {};
+
+        void send_request_to_server(const app::Request request,
+                                    std::function<void(const app::Response)> completion) override {
+            // Convert the app::Request to an RLMRequest
+            auto rlmRequest = [RLMRequest new];
+            rlmRequest.url = @(request.url.data());
+            rlmRequest.body = @(request.body.data());
+            NSMutableDictionary *headers = [NSMutableDictionary new];
+            for (auto header : request.headers) {
+                headers[@(header.first.data())] = @(header.second.data());
+            }
+            rlmRequest.headers = headers;
+            rlmRequest.method = static_cast<RLMHTTPMethod>(request.method);
+            rlmRequest.timeout = request.timeout_ms / 1000;
+
+            // Send the request through to the Cocoa level transport
+            [m_transport sendRequestToServer:rlmRequest completion:^(RLMResponse *response) {
+                __block std::map<std::string, std::string> bridgingHeaders;
+                [response.headers enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *) {
+                    bridgingHeaders[key.UTF8String] = value.UTF8String;
+                }];
+
+                // Convert the RLMResponse to an app:Response and pass downstream to
+                // the object store
+                completion({
+                    .body = response.body.UTF8String,
+                    .headers = bridgingHeaders,
+                    .http_status_code = static_cast<int>(response.httpStatusCode),
+                    .custom_status_code = static_cast<int>(response.customStatusCode)
+                });
+            }];
+        }
+
+        id<RLMNetworkTransport> transport() const {
+            return m_transport;
+        }
+    private:
+        id<RLMNetworkTransport> m_transport;
+    };
+}
+
+#pragma mark RLMAppConfiguration
+@implementation RLMAppConfiguration {
+    realm::app::App::Config _config;
+}
+
+- (instancetype)initWithConfig:(const realm::app::App::Config &)config {
+    if (self = [super init]) {
+        _config = config;
+        return self;
+    }
+
+    return nil;
+}
+
+- (instancetype)initWithBaseURL:(nullable NSString *)baseURL
+                      transport:(nullable id<RLMNetworkTransport>)transport
+                   localAppName:(nullable NSString *)localAppName
+                localAppVersion:(nullable NSString *)localAppVersion {
+    return [self initWithBaseURL:baseURL
+                       transport:transport
+                    localAppName:localAppName
+                 localAppVersion:localAppVersion
+         defaultRequestTimeoutMS:6000];
+}
+
+- (instancetype)initWithBaseURL:(nullable NSString *)baseURL
+                      transport:(nullable id<RLMNetworkTransport>)transport
+                   localAppName:(NSString *)localAppName
+                localAppVersion:(nullable NSString *)localAppVersion
+        defaultRequestTimeoutMS:(NSUInteger)defaultRequestTimeoutMS {
+    if (self = [super init]) {
+        self.baseURL = baseURL;
+        self.transport = transport;
+        self.localAppName = localAppName;
+        self.localAppVersion = localAppVersion;
+        self.defaultRequestTimeoutMS = defaultRequestTimeoutMS;
+
+        _config.platform = "Realm Cocoa";
+
+        RLMNSStringToStdString(_config.platform_version, [[NSProcessInfo processInfo] operatingSystemVersionString]);
+        RLMNSStringToStdString(_config.sdk_version, REALM_COCOA_VERSION);
+        return self;
+    }
+    return nil;
+}
+
+- (realm::app::App::Config&)config {
+    return _config;
+}
+
+- (void)setAppId:(NSString *)appId {
+    RLMNSStringToStdString(_config.app_id, appId);
+}
+
+- (NSString *)baseURL {
+    if (_config.base_url) {
+        return @(_config.base_url->c_str());
+    }
+
+    return nil;
+}
+
+- (void)setBaseURL:(nullable NSString *)baseURL {
+    std::string base_url;
+    RLMNSStringToStdString(base_url, baseURL);
+    _config.base_url = base_url.empty() ? util::none : util::Optional(base_url);
+    return;
+}
+
+- (id<RLMNetworkTransport>)transport {
+    return static_cast<CocoaNetworkTransport*>(_config.transport_generator().get())->transport();
+}
+
+- (void)setTransport:(id<RLMNetworkTransport>)transport {
+    if (transport) {
+        _config.transport_generator = [transport]{
+            return std::make_unique<CocoaNetworkTransport>(transport);
+        };
+    } else {
+        _config.transport_generator = []{
+            return std::make_unique<CocoaNetworkTransport>([RLMNetworkTransport new]);
+        };
+    }
+}
+
+- (NSString *)localAppName {
+    if (_config.local_app_name) {
+        return @((_config.base_url)->c_str());
+    }
+
+    return nil;
+}
+
+- (void)setLocalAppName:(nullable NSString *)localAppName {
+    std::string local_app_name;
+    RLMNSStringToStdString(local_app_name, localAppName);
+    _config.local_app_name = local_app_name.empty() ? util::none : util::Optional(local_app_name);
+    return;
+}
+
+- (NSString *)localAppVersion {
+    if (_config.local_app_version) {
+        return @(_config.base_url->c_str());
+    }
+
+    return nil;
+}
+
+- (void)setLocalAppVersion:(nullable NSString *)localAppVersion {
+    std::string local_app_version;
+    RLMNSStringToStdString(local_app_version, localAppVersion);
+    _config.local_app_version = local_app_version.empty() ? util::none : util::Optional(local_app_version);
+    return;
+}
+
+- (NSUInteger)defaultRequestTimeoutMS {
+    return _config.default_request_timeout_ms.value_or(6000U);
+}
+
+- (void)setDefaultRequestTimeoutMS:(NSUInteger)defaultRequestTimeoutMS {
+    _config.default_request_timeout_ms = (uint64_t)defaultRequestTimeoutMS;
+}
+
+@end
+
+NSError *RLMAppErrorToNSError(realm::app::AppError const& appError) {
+    return [[NSError alloc] initWithDomain:@(appError.error_code.category().name())
+                                      code:appError.error_code.value()
+                                  userInfo:@{
+                                      @(appError.error_code.category().name()) : @(appError.error_code.message().data()),
+                                      NSLocalizedDescriptionKey : @(appError.message.c_str())
+                                  }];
+}
+
+#pragma mark RLMAppSubscriptionToken
+@implementation RLMAppSubscriptionToken {
+@public
+    std::unique_ptr<realm::Subscribable<app::App>::Token> _token;
+}
+
+- (instancetype)initWithToken:(realm::Subscribable<app::App>::Token&&)token {
+    if (self = [super init]) {
+        _token = std::make_unique<realm::Subscribable<app::App>::Token>(std::move(token));
+        return self;
+    }
+
+    return nil;
+}
+
+- (NSUInteger)value {
+    return _token->value();
+}
+@end
+
+#pragma mark RLMApp
+@interface RLMApp() <ASAuthorizationControllerDelegate> {
+    std::shared_ptr<realm::app::App> _app;
+    __weak id<RLMASLoginDelegate> _authorizationDelegate API_AVAILABLE(ios(13.0), macos(10.15), tvos(13.0), watchos(6.0));
+}
+
+@end
+
+@implementation RLMApp : NSObject
+
+- (instancetype)initWithApp:(std::shared_ptr<realm::app::App>)app {
+    if (self = [super init]) {
+        _configuration = [[RLMAppConfiguration alloc] initWithConfig:app->config()];
+        _app = app;
+        _syncManager = [[RLMSyncManager alloc] initWithSyncManager:_app->sync_manager()];
+        return self;
+    }
+
+    return nil;
+}
+
+- (instancetype)initWithId:(NSString *)appId
+             configuration:(RLMAppConfiguration *)configuration
+             rootDirectory:(NSURL *)rootDirectory {
+    if ([appId length] == 0) {
+        @throw RLMException(@"AppId cannot be an empty string");
+    }
+
+    if (self = [super init]) {
+        if (!configuration) {
+            configuration = [[RLMAppConfiguration alloc] initWithBaseURL:nil
+                                                               transport:nil
+                                                            localAppName:nil
+                                                         localAppVersion:nil];
+        }
+        _configuration = configuration;
+        [_configuration setAppId:appId];
+
+        _app = RLMTranslateError([&] {
+            return app::App::get_shared_app(configuration.config,
+                                            [RLMSyncManager configurationWithRootDirectory:rootDirectory appId:appId]);
+        });
+
+        _syncManager = [[RLMSyncManager alloc] initWithSyncManager:_app->sync_manager()];
+        return self;
+    }
+    return nil;
+}
+
+static NSMutableDictionary *s_apps = [NSMutableDictionary new];
+static std::mutex& s_appMutex = *new std::mutex();
+
++ (void)resetAppCache {
+    std::lock_guard<std::mutex> lock(s_appMutex);
+    [s_apps removeAllObjects];
+    app::App::clear_cached_apps();
+}
+
++ (instancetype)appWithId:(NSString *)appId
+            configuration:(RLMAppConfiguration *)configuration
+            rootDirectory:(NSURL *)rootDirectory {
+    std::lock_guard<std::mutex> lock(s_appMutex);
+    if (RLMApp *app = s_apps[appId]) {
+        return app;
+    }
+
+    RLMApp *app = [[RLMApp alloc] initWithId:appId configuration:configuration rootDirectory:rootDirectory];
+    s_apps[appId] = app;
+    return app;
+}
+
++ (instancetype)appWithId:(NSString *)appId configuration:(RLMAppConfiguration *)configuration {
+    return [self appWithId:appId configuration:configuration rootDirectory:nil];
+}
+
++ (instancetype)appWithId:(NSString *)appId {
+    return [self appWithId:appId configuration:nil];
+}
+
+- (std::shared_ptr<realm::app::App>)_realmApp {
+    return _app;
+}
+
+- (NSDictionary<NSString *, RLMUser *> *)allUsers {
+    NSMutableDictionary *buffer = [NSMutableDictionary new];
+    for (auto&& user : _app->sync_manager()->all_users()) {
+        NSString *identity = @(user->identity().c_str());
+        buffer[identity] = [[RLMUser alloc] initWithUser:std::move(user) app:self];
+    }
+    return buffer;
+}
+
+- (RLMUser *)currentUser {
+    if (auto user = _app->sync_manager()->get_current_user()) {
+        return [[RLMUser alloc] initWithUser:user app:self];
+    }
+    return nil;
+}
+
+- (RLMEmailPasswordAuth *)emailPasswordAuth {
+    return [[RLMEmailPasswordAuth alloc] initWithApp: self];
+}
+
+- (void)loginWithCredential:(RLMCredentials *)credentials
+                 completion:(RLMUserCompletionBlock)completionHandler {
+    auto completion = ^(std::shared_ptr<SyncUser> user, util::Optional<app::AppError> error) {
+        if (error && error->error_code) {
+            return completionHandler(nil, RLMAppErrorToNSError(*error));
+        }
+
+        completionHandler([[RLMUser alloc] initWithUser:user app:self], nil);
+    };
+    return RLMTranslateError([&] {
+        return _app->log_in_with_credentials(credentials.appCredentials, completion);
+    });
+}
+
+- (RLMUser *)switchToUser:(RLMUser *)syncUser {
+    return RLMTranslateError([&] {
+        return [[RLMUser alloc] initWithUser:_app->switch_user(syncUser._syncUser) app:self];
+    });
+}
+
+- (RLMPushClient *)pushClientWithServiceName:(NSString *)serviceName {
+    return RLMTranslateError([&] {
+        return [[RLMPushClient alloc] initWithPushClient:_app->push_notification_client(serviceName.UTF8String)];
+    });
+}
+
+#pragma mark - Sign In With Apple Extension
+
+- (void)setAuthorizationDelegate:(id<RLMASLoginDelegate>)authorizationDelegate API_AVAILABLE(ios(13.0), macos(10.15), tvos(13.0), watchos(6.0)) {
+    _authorizationDelegate = authorizationDelegate;
+}
+
+- (id<RLMASLoginDelegate>)authorizationDelegate API_AVAILABLE(ios(13.0), macos(10.15), tvos(13.0), watchos(6.0)) {
+    return _authorizationDelegate;
+}
+
+- (void)setASAuthorizationControllerDelegateForController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0), macos(10.15), tvos(13.0), watchos(6.0)) {
+    controller.delegate = self;
+}
+
+- (void)authorizationController:(__unused ASAuthorizationController *)controller
+   didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0), macos(10.15), tvos(13.0), watchos(6.0)) {
+    NSString *jwt = [[NSString alloc] initWithData:((ASAuthorizationAppleIDCredential *)authorization.credential).identityToken
+                                             encoding:NSUTF8StringEncoding];
+       [self loginWithCredential:[RLMCredentials credentialsWithAppleToken:jwt]
+                      completion:^(RLMUser *user, NSError *error) {
+           if (user) {
+               [self.authorizationDelegate authenticationDidCompleteWithUser:user];
+           } else {
+               [self.authorizationDelegate authenticationDidCompleteWithError:error];
+           }
+       }];
+}
+
+- (void)authorizationController:(__unused ASAuthorizationController *)controller
+           didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0), macos(10.15), tvos(13.0), watchos(6.0)) {
+    [self.authorizationDelegate authenticationDidCompleteWithError:error];
+}
+
+- (RLMAppSubscriptionToken *)subscribe:(RLMAppNotificationBlock)block {
+    return [[RLMAppSubscriptionToken alloc] initWithToken:_app->subscribe([block, self] (auto&) {
+        block(self);
+    })];
+}
+
+- (void)unsubscribe:(RLMAppSubscriptionToken *)token {
+    return _app->unsubscribe(*token->_token);
+}
+
+@end
+
+

+ 613 - 0
Example/Pods/Realm/Realm/RLMArray.mm

@@ -0,0 +1,613 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMArray_Private.hpp"
+
+#import "RLMObjectSchema.h"
+#import "RLMObjectStore.h"
+#import "RLMObject_Private.h"
+#import "RLMProperty_Private.h"
+#import "RLMQueryUtil.hpp"
+#import "RLMSchema_Private.h"
+#import "RLMSwiftSupport.h"
+#import "RLMThreadSafeReference_Private.hpp"
+#import "RLMUtil.hpp"
+
+// See -countByEnumeratingWithState:objects:count
+@interface RLMArrayHolder : NSObject {
+@public
+    std::unique_ptr<id[]> items;
+}
+@end
+@implementation RLMArrayHolder
+@end
+
+@interface RLMArray () <RLMThreadConfined_Private>
+@end
+
+@implementation RLMArray {
+@public
+    // Backing array when this instance is unmanaged
+    NSMutableArray *_backingArray;
+}
+
+#pragma mark - Initializers
+
+- (instancetype)initWithObjectClassName:(__unsafe_unretained NSString *const)objectClassName {
+    REALM_ASSERT([objectClassName length] > 0);
+    self = [super init];
+    if (self) {
+        _objectClassName = objectClassName;
+        _type = RLMPropertyTypeObject;
+    }
+    return self;
+}
+
+- (instancetype)initWithObjectType:(RLMPropertyType)type optional:(BOOL)optional {
+    self = [super init];
+    if (self) {
+        _type = type;
+        _optional = optional;
+    }
+    return self;
+}
+
+#pragma mark - Convenience wrappers used for all RLMArray types
+
+- (void)addObjects:(id<NSFastEnumeration>)objects {
+    for (id obj in objects) {
+        [self addObject:obj];
+    }
+}
+
+- (void)addObject:(id)object {
+    [self insertObject:object atIndex:self.count];
+}
+
+- (void)removeLastObject {
+    NSUInteger count = self.count;
+    if (count) {
+        [self removeObjectAtIndex:count-1];
+    }
+}
+
+- (id)objectAtIndexedSubscript:(NSUInteger)index {
+    return [self objectAtIndex:index];
+}
+
+- (void)setObject:(id)newValue atIndexedSubscript:(NSUInteger)index {
+    [self replaceObjectAtIndex:index withObject:newValue];
+}
+
+- (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending {
+    return [self sortedResultsUsingDescriptors:@[[RLMSortDescriptor sortDescriptorWithKeyPath:keyPath ascending:ascending]]];
+}
+
+- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ... {
+    va_list args;
+    va_start(args, predicateFormat);
+    NSUInteger index = [self indexOfObjectWhere:predicateFormat args:args];
+    va_end(args);
+    return index;
+}
+
+- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args {
+    return [self indexOfObjectWithPredicate:[NSPredicate predicateWithFormat:predicateFormat
+                                                                   arguments:args]];
+}
+
+#pragma mark - Unmanaged RLMArray implementation
+
+- (RLMRealm *)realm {
+    return nil;
+}
+
+- (id)firstObject {
+    if (self.count) {
+        return [self objectAtIndex:0];
+    }
+    return nil;
+}
+
+- (id)lastObject {
+    NSUInteger count = self.count;
+    if (count) {
+        return [self objectAtIndex:count-1];
+    }
+    return nil;
+}
+
+- (id)objectAtIndex:(NSUInteger)index {
+    validateArrayBounds(self, index);
+    return [_backingArray objectAtIndex:index];
+}
+
+- (NSUInteger)count {
+    return _backingArray.count;
+}
+
+- (BOOL)isInvalidated {
+    return NO;
+}
+
+- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
+                                  objects:(__unused __unsafe_unretained id [])buffer
+                                    count:(__unused NSUInteger)len {
+    if (state->state != 0) {
+        return 0;
+    }
+
+    // We need to enumerate a copy of the backing array so that it doesn't
+    // reflect changes made during enumeration. This copy has to be autoreleased
+    // (since there's nowhere for us to store a strong reference), and uses
+    // RLMArrayHolder rather than an NSArray because NSArray doesn't guarantee
+    // that it'll use a single contiguous block of memory, and if it doesn't
+    // we'd need to forward multiple calls to this method to the same NSArray,
+    // which would require holding a reference to it somewhere.
+    __autoreleasing RLMArrayHolder *copy = [[RLMArrayHolder alloc] init];
+    copy->items = std::make_unique<id[]>(self.count);
+
+    NSUInteger i = 0;
+    for (id object in _backingArray) {
+        copy->items[i++] = object;
+    }
+
+    state->itemsPtr = (__unsafe_unretained id *)(void *)copy->items.get();
+    // needs to point to something valid, but the whole point of this is so
+    // that it can't be changed
+    state->mutationsPtr = state->extra;
+    state->state = i;
+
+    return i;
+}
+
+
+template<typename IndexSetFactory>
+static void changeArray(__unsafe_unretained RLMArray *const ar,
+                        NSKeyValueChange kind, dispatch_block_t f, IndexSetFactory&& is) {
+    if (!ar->_backingArray) {
+        ar->_backingArray = [NSMutableArray new];
+    }
+
+    if (RLMObjectBase *parent = ar->_parentObject) {
+        NSIndexSet *indexes = is();
+        [parent willChange:kind valuesAtIndexes:indexes forKey:ar->_key];
+        f();
+        [parent didChange:kind valuesAtIndexes:indexes forKey:ar->_key];
+    }
+    else {
+        f();
+    }
+}
+
+static void changeArray(__unsafe_unretained RLMArray *const ar, NSKeyValueChange kind,
+                        NSUInteger index, dispatch_block_t f) {
+    changeArray(ar, kind, f, [=] { return [NSIndexSet indexSetWithIndex:index]; });
+}
+
+static void changeArray(__unsafe_unretained RLMArray *const ar, NSKeyValueChange kind,
+                        NSRange range, dispatch_block_t f) {
+    changeArray(ar, kind, f, [=] { return [NSIndexSet indexSetWithIndexesInRange:range]; });
+}
+
+static void changeArray(__unsafe_unretained RLMArray *const ar, NSKeyValueChange kind,
+                        NSIndexSet *is, dispatch_block_t f) {
+    changeArray(ar, kind, f, [=] { return is; });
+}
+
+void RLMArrayValidateMatchingObjectType(__unsafe_unretained RLMArray *const array,
+                                        __unsafe_unretained id const value) {
+    if (!value && !array->_optional) {
+        @throw RLMException(@"Invalid nil value for array of '%@'.",
+                            array->_objectClassName ?: RLMTypeToString(array->_type));
+    }
+    if (array->_type != RLMPropertyTypeObject) {
+        if (!RLMValidateValue(value, array->_type, array->_optional, false, nil)) {
+            @throw RLMException(@"Invalid value '%@' of type '%@' for expected type '%@%s'.",
+                                value, [value class], RLMTypeToString(array->_type),
+                                array->_optional ? "?" : "");
+        }
+        return;
+    }
+
+    auto object = RLMDynamicCast<RLMObjectBase>(value);
+    if (!object) {
+        return;
+    }
+    if (!object->_objectSchema) {
+        @throw RLMException(@"Object cannot be inserted unless the schema is initialized. "
+                            "This can happen if you try to insert objects into a RLMArray / List from a default value or from an overriden unmanaged initializer (`init()`).");
+    }
+    if (![array->_objectClassName isEqualToString:object->_objectSchema.className]) {
+        @throw RLMException(@"Object of type '%@' does not match RLMArray type '%@'.",
+                            object->_objectSchema.className, array->_objectClassName);
+    }
+}
+
+static void validateArrayBounds(__unsafe_unretained RLMArray *const ar,
+                                   NSUInteger index, bool allowOnePastEnd=false) {
+    NSUInteger max = ar->_backingArray.count + allowOnePastEnd;
+    if (index >= max) {
+        @throw RLMException(@"Index %llu is out of bounds (must be less than %llu).",
+                            (unsigned long long)index, (unsigned long long)max);
+    }
+}
+
+- (void)addObjectsFromArray:(NSArray *)array {
+    for (id obj in array) {
+        RLMArrayValidateMatchingObjectType(self, obj);
+    }
+    changeArray(self, NSKeyValueChangeInsertion, NSMakeRange(_backingArray.count, array.count), ^{
+        [_backingArray addObjectsFromArray:array];
+    });
+}
+
+- (void)insertObject:(id)anObject atIndex:(NSUInteger)index {
+    RLMArrayValidateMatchingObjectType(self, anObject);
+    validateArrayBounds(self, index, true);
+    changeArray(self, NSKeyValueChangeInsertion, index, ^{
+        [_backingArray insertObject:anObject atIndex:index];
+    });
+}
+
+- (void)insertObjects:(id<NSFastEnumeration>)objects atIndexes:(NSIndexSet *)indexes {
+    changeArray(self, NSKeyValueChangeInsertion, indexes, ^{
+        NSUInteger currentIndex = [indexes firstIndex];
+        for (RLMObject *obj in objects) {
+            RLMArrayValidateMatchingObjectType(self, obj);
+            [_backingArray insertObject:obj atIndex:currentIndex];
+            currentIndex = [indexes indexGreaterThanIndex:currentIndex];
+        }
+    });
+}
+
+- (void)removeObjectAtIndex:(NSUInteger)index {
+    validateArrayBounds(self, index);
+    changeArray(self, NSKeyValueChangeRemoval, index, ^{
+        [_backingArray removeObjectAtIndex:index];
+    });
+}
+
+- (void)removeObjectsAtIndexes:(NSIndexSet *)indexes {
+    changeArray(self, NSKeyValueChangeRemoval, indexes, ^{
+        [_backingArray removeObjectsAtIndexes:indexes];
+    });
+}
+
+- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject {
+    RLMArrayValidateMatchingObjectType(self, anObject);
+    validateArrayBounds(self, index);
+    changeArray(self, NSKeyValueChangeReplacement, index, ^{
+        [_backingArray replaceObjectAtIndex:index withObject:anObject];
+    });
+}
+
+- (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex {
+    validateArrayBounds(self, sourceIndex);
+    validateArrayBounds(self, destinationIndex);
+    id original = _backingArray[sourceIndex];
+
+    auto start = std::min(sourceIndex, destinationIndex);
+    auto len = std::max(sourceIndex, destinationIndex) - start + 1;
+    changeArray(self, NSKeyValueChangeReplacement, {start, len}, ^{
+        [_backingArray removeObjectAtIndex:sourceIndex];
+        [_backingArray insertObject:original atIndex:destinationIndex];
+    });
+}
+
+- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2 {
+    validateArrayBounds(self, index1);
+    validateArrayBounds(self, index2);
+
+    changeArray(self, NSKeyValueChangeReplacement, ^{
+        [_backingArray exchangeObjectAtIndex:index1 withObjectAtIndex:index2];
+    }, [=] {
+        NSMutableIndexSet *set = [[NSMutableIndexSet alloc] initWithIndex:index1];
+        [set addIndex:index2];
+        return set;
+    });
+}
+
+- (NSUInteger)indexOfObject:(id)object {
+    RLMArrayValidateMatchingObjectType(self, object);
+    if (!_backingArray) {
+        return NSNotFound;
+    }
+    if (_type != RLMPropertyTypeObject) {
+        return [_backingArray indexOfObject:object];
+    }
+
+    NSUInteger index = 0;
+    for (RLMObjectBase *cmp in _backingArray) {
+        if (RLMObjectBaseAreEqual(object, cmp)) {
+            return index;
+        }
+        index++;
+    }
+    return NSNotFound;
+}
+
+- (void)removeAllObjects {
+    changeArray(self, NSKeyValueChangeRemoval, NSMakeRange(0, _backingArray.count), ^{
+        [_backingArray removeAllObjects];
+    });
+}
+
+- (RLMResults *)objectsWhere:(NSString *)predicateFormat, ... {
+    va_list args;
+    va_start(args, predicateFormat);
+    RLMResults *results = [self objectsWhere:predicateFormat args:args];
+    va_end(args);
+    return results;
+}
+
+- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args {
+    return [self objectsWithPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]];
+}
+
+static bool canAggregate(RLMPropertyType type, bool allowDate) {
+    switch (type) {
+        case RLMPropertyTypeInt:
+        case RLMPropertyTypeFloat:
+        case RLMPropertyTypeDouble:
+        case RLMPropertyTypeDecimal128:
+            return true;
+        case RLMPropertyTypeDate:
+            return allowDate;
+        default:
+            return false;
+    }
+}
+
+- (RLMPropertyType)typeForProperty:(NSString *)propertyName {
+    if ([propertyName isEqualToString:@"self"]) {
+        return _type;
+    }
+
+    RLMObjectSchema *objectSchema;
+    if (_backingArray.count) {
+        objectSchema = [_backingArray[0] objectSchema];
+    }
+    else {
+        objectSchema = [RLMSchema.partialPrivateSharedSchema schemaForClassName:_objectClassName];
+    }
+
+    return RLMValidatedProperty(objectSchema, propertyName).type;
+}
+
+- (id)aggregateProperty:(NSString *)key operation:(NSString *)op method:(SEL)sel {
+    // Although delegating to valueForKeyPath: here would allow to support
+    // nested key paths as well, limiting functionality gives consistency
+    // between unmanaged and managed arrays.
+    if ([key rangeOfString:@"."].location != NSNotFound) {
+        @throw RLMException(@"Nested key paths are not supported yet for KVC collection operators.");
+    }
+
+    bool allowDate = false;
+    bool sum = false;
+    if ([op isEqualToString:@"@min"] || [op isEqualToString:@"@max"]) {
+        allowDate = true;
+    }
+    else if ([op isEqualToString:@"@sum"]) {
+        sum = true;
+    }
+    else if (![op isEqualToString:@"@avg"]) {
+        // Just delegate to NSArray for all other operators
+        return [_backingArray valueForKeyPath:[op stringByAppendingPathExtension:key]];
+    }
+
+    RLMPropertyType type = [self typeForProperty:key];
+    if (!canAggregate(type, allowDate)) {
+        NSString *method = sel ? NSStringFromSelector(sel) : op;
+        if (_type == RLMPropertyTypeObject) {
+            @throw RLMException(@"%@: is not supported for %@ property '%@.%@'",
+                                method, RLMTypeToString(type), _objectClassName, key);
+        }
+        else {
+            @throw RLMException(@"%@ is not supported for %@%s array",
+                                method, RLMTypeToString(_type), _optional ? "?" : "");
+        }
+    }
+
+    NSArray *values = [key isEqualToString:@"self"] ? _backingArray : [_backingArray valueForKey:key];
+    if (_optional) {
+        // Filter out NSNull values to match our behavior on managed arrays
+        NSIndexSet *nonnull = [values indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger, BOOL *) {
+            return obj != NSNull.null;
+        }];
+        if (nonnull.count < values.count) {
+            values = [values objectsAtIndexes:nonnull];
+        }
+    }
+    id result = [values valueForKeyPath:[op stringByAppendingString:@".self"]];
+    return sum && !result ? @0 : result;
+}
+
+- (id)valueForKeyPath:(NSString *)keyPath {
+    if ([keyPath characterAtIndex:0] != '@') {
+        return _backingArray ? [_backingArray valueForKeyPath:keyPath] : [super valueForKeyPath:keyPath];
+    }
+
+    if (!_backingArray) {
+        _backingArray = [NSMutableArray new];
+    }
+
+    NSUInteger dot = [keyPath rangeOfString:@"."].location;
+    if (dot == NSNotFound) {
+        return [_backingArray valueForKeyPath:keyPath];
+    }
+
+    NSString *op = [keyPath substringToIndex:dot];
+    NSString *key = [keyPath substringFromIndex:dot + 1];
+    return [self aggregateProperty:key operation:op method:nil];
+}
+
+- (id)valueForKey:(NSString *)key {
+    if ([key isEqualToString:RLMInvalidatedKey]) {
+        return @NO; // Unmanaged arrays are never invalidated
+    }
+    if (!_backingArray) {
+        _backingArray = [NSMutableArray new];
+    }
+    return [_backingArray valueForKey:key];
+}
+
+- (void)setValue:(id)value forKey:(NSString *)key {
+    if ([key isEqualToString:@"self"]) {
+        RLMArrayValidateMatchingObjectType(self, value);
+        for (NSUInteger i = 0, count = _backingArray.count; i < count; ++i) {
+            _backingArray[i] = value;
+        }
+        return;
+    }
+    else if (_type == RLMPropertyTypeObject) {
+        [_backingArray setValue:value forKey:key];
+    }
+    else {
+        [self setValue:value forUndefinedKey:key];
+    }
+}
+
+- (id)minOfProperty:(NSString *)property {
+    return [self aggregateProperty:property operation:@"@min" method:_cmd];
+}
+
+- (id)maxOfProperty:(NSString *)property {
+    return [self aggregateProperty:property operation:@"@max" method:_cmd];
+}
+
+- (id)sumOfProperty:(NSString *)property {
+    return [self aggregateProperty:property operation:@"@sum" method:_cmd];
+}
+
+- (id)averageOfProperty:(NSString *)property {
+    return [self aggregateProperty:property operation:@"@avg" method:_cmd];
+}
+
+- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate {
+    if (!_backingArray) {
+        return NSNotFound;
+    }
+    return [_backingArray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger, BOOL *) {
+        return [predicate evaluateWithObject:obj];
+    }];
+}
+
+- (NSArray *)objectsAtIndexes:(NSIndexSet *)indexes {
+    if (!_backingArray) {
+        _backingArray = [NSMutableArray new];
+    }
+    return [_backingArray objectsAtIndexes:indexes];
+}
+
+- (BOOL)isEqual:(id)object {
+    if (auto array = RLMDynamicCast<RLMArray>(object)) {
+        return !array.realm
+        && ((_backingArray.count == 0 && array->_backingArray.count == 0)
+            || [_backingArray isEqual:array->_backingArray]);
+    }
+    return NO;
+}
+
+- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath
+            options:(NSKeyValueObservingOptions)options context:(void *)context {
+    RLMValidateArrayObservationKey(keyPath, self);
+    [super addObserver:observer forKeyPath:keyPath options:options context:context];
+}
+
+#pragma mark - Methods unsupported on unmanaged RLMArray instances
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunused-parameter"
+
+- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate {
+    @throw RLMException(@"This method may only be called on RLMArray instances retrieved from an RLMRealm");
+}
+
+- (RLMResults *)sortedResultsUsingDescriptors:(NSArray<RLMSortDescriptor *> *)properties {
+    @throw RLMException(@"This method may only be called on RLMArray instances retrieved from an RLMRealm");
+}
+
+- (RLMResults *)distinctResultsUsingKeyPaths:(NSArray<NSString *> *)keyPaths {
+    @throw RLMException(@"This method may only be called on RLMArray instances retrieved from an RLMRealm");
+}
+
+// The compiler complains about the method's argument type not matching due to
+// it not having the generic type attached, but it doesn't seem to be possible
+// to actually include the generic type
+// http://www.openradar.me/radar?id=6135653276319744
+#pragma clang diagnostic ignored "-Wmismatched-parameter-types"
+- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray *, RLMCollectionChange *, NSError *))block {
+    return [self addNotificationBlock:block queue:nil];
+}
+- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray *, RLMCollectionChange *, NSError *))block
+                                         queue:(nullable dispatch_queue_t)queue {
+    @throw RLMException(@"This method may only be called on RLMArray instances retrieved from an RLMRealm");
+}
+
+- (instancetype)freeze {
+    @throw RLMException(@"This method may only be called on RLMArray instances retrieved from an RLMRealm");
+}
+
+- (instancetype)thaw {
+    @throw RLMException(@"This method may only be called on RLMArray instances retrieved from an RLMRealm");
+}
+
+#pragma mark - Thread Confined Protocol Conformance
+
+- (realm::ThreadSafeReference)makeThreadSafeReference {
+    REALM_TERMINATE("Unexpected handover of unmanaged `RLMArray`");
+}
+
+- (id)objectiveCMetadata {
+    REALM_TERMINATE("Unexpected handover of unmanaged `RLMArray`");
+}
+
++ (instancetype)objectWithThreadSafeReference:(realm::ThreadSafeReference)reference
+                                     metadata:(id)metadata
+                                        realm:(RLMRealm *)realm {
+    REALM_TERMINATE("Unexpected handover of unmanaged `RLMArray`");
+}
+
+#pragma clang diagnostic pop // unused parameter warning
+
+#pragma mark - Superclass Overrides
+
+- (NSString *)description {
+    return [self descriptionWithMaxDepth:RLMDescriptionMaxDepth];
+}
+
+- (NSString *)descriptionWithMaxDepth:(NSUInteger)depth {
+    return RLMDescriptionWithMaxDepth(@"RLMArray", self, depth);
+}
+@end
+
+@implementation RLMSortDescriptor
+
++ (instancetype)sortDescriptorWithKeyPath:(NSString *)keyPath ascending:(BOOL)ascending {
+    RLMSortDescriptor *desc = [[RLMSortDescriptor alloc] init];
+    desc->_keyPath = keyPath;
+    desc->_ascending = ascending;
+    return desc;
+}
+
+- (instancetype)reversedSortDescriptor {
+    return [self.class sortDescriptorWithKeyPath:_keyPath ascending:!_ascending];
+}
+
+@end

+ 389 - 0
Example/Pods/Realm/Realm/RLMBSON.mm

@@ -0,0 +1,389 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMBSON_Private.hpp"
+
+#import "RLMDecimal128_Private.hpp"
+#import "RLMObjectId_Private.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/util/bson/bson.hpp>
+
+using namespace realm;
+using namespace bson;
+
+#pragma mark NSNull
+
+@implementation NSNull (RLMBSON)
+
+- (RLMBSONType)bsonType {
+    return RLMBSONTypeNull;
+}
+
+@end
+
+#pragma mark RLMObjectId
+
+@implementation RLMObjectId (RLMBSON)
+
+- (RLMBSONType)bsonType {
+    return RLMBSONTypeObjectId;
+}
+
+@end
+
+#pragma mark RLMDecimal128
+
+@implementation RLMDecimal128 (RLMBSON)
+
+- (RLMBSONType)bsonType {
+    return RLMBSONTypeDecimal128;
+}
+
+@end
+
+#pragma mark NSString
+
+@implementation NSString (RLMBSON)
+
+- (RLMBSONType)bsonType {
+    return RLMBSONTypeString;
+}
+
+@end
+
+#pragma mark NSNumber
+
+@implementation NSNumber (RLMBSON)
+
+- (RLMBSONType)bsonType {
+    char numberType = [self objCType][0];
+    
+    if (numberType == *@encode(bool) ||
+        numberType == *@encode(char)) {
+        return RLMBSONTypeBool;
+    } else if (numberType == *@encode(int) ||
+               numberType == *@encode(short) ||
+               numberType == *@encode(unsigned short) ||
+               numberType == *@encode(unsigned int)) {
+        return RLMBSONTypeInt32;
+    } else if (numberType == *@encode(long) ||
+               numberType == *@encode(long long) ||
+               numberType == *@encode(unsigned long) ||
+               numberType == *@encode(unsigned long long)) {
+        return RLMBSONTypeInt64;
+    } else {
+        return RLMBSONTypeDouble;
+    }
+}
+
+@end
+
+#pragma mark NSMutableArray
+
+@implementation NSMutableArray (RLMBSON)
+
+- (RLMBSONType)bsonType {
+    return RLMBSONTypeArray;
+}
+
+- (instancetype)initWithBsonArray:(BsonArray)bsonArray {
+
+    if ((self = [self init])) {
+        for (auto& entry : bsonArray) {
+            [self addObject:RLMConvertBsonToRLMBSON(entry)];
+        }
+
+        return self;
+    }
+
+    return nil;
+}
+
+@end
+
+@implementation NSArray (RLMBSON)
+
+- (BsonArray)bsonArrayValue {
+    BsonArray bsonArray;
+    for (id value in self) {
+        bsonArray.push_back(RLMConvertRLMBSONToBson(value));
+    }
+    return bsonArray;
+}
+
+- (RLMBSONType)bsonType {
+    return RLMBSONTypeArray;
+}
+
+@end
+
+#pragma mark NSDictionary
+
+@implementation NSMutableDictionary (RLMBSON)
+
+- (RLMBSONType)bsonType {
+    return RLMBSONTypeDocument;
+}
+
+- (BsonDocument)bsonDocumentValue {
+    BsonDocument bsonDocument;
+    for (NSString *value in self) {
+        bsonDocument[value.UTF8String] = RLMConvertRLMBSONToBson(self[value]);
+    }
+    return bsonDocument;
+}
+
+- (instancetype)initWithBsonDocument:(BsonDocument)bsonDocument {
+    if ((self = [self init])) {
+        for (auto it = bsonDocument.begin(); it != bsonDocument.end(); ++it) {
+            const auto& entry = (*it);
+            [self setObject:RLMConvertBsonToRLMBSON(entry.second) forKey:@(entry.first.data())];
+        }
+
+        return self;
+    }
+
+    return nil;
+}
+
+@end
+
+@implementation NSDictionary (RLMBSON)
+
+- (RLMBSONType)bsonType {
+    return RLMBSONTypeDocument;
+}
+
+- (BsonDocument)bsonDocumentValue {
+    BsonDocument bsonDocument;
+    for (NSString *value in self) {
+        bsonDocument[value.UTF8String] = RLMConvertRLMBSONToBson(self[value]);
+    }
+    return bsonDocument;
+}
+
+@end
+
+#pragma mark NSData
+
+@implementation NSData (RLMBSON)
+
+- (RLMBSONType)bsonType {
+    return RLMBSONTypeBinary;
+}
+
+- (instancetype)initWithBsonBinary:(std::vector<char>)bsonBinary {
+    if ((self = [NSData dataWithBytes:bsonBinary.data() length:bsonBinary.size()])) {
+        return self;
+    }
+
+    return nil;
+}
+
+@end
+
+#pragma mark NSDate
+
+@implementation NSDate (RLMBSON)
+
+- (RLMBSONType)bsonType {
+    return RLMBSONTypeDatetime;
+}
+
+@end
+
+#pragma mark NSRegularExpression
+
+@implementation NSRegularExpression (RLMBSON)
+
+- (RLMBSONType)bsonType {
+    return RLMBSONTypeRegularExpression;
+}
+
+- (RegularExpression)regularExpressionValue {
+    using Option = RegularExpression::Option;
+    std::string s;
+
+    if ((_options & NSRegularExpressionCaseInsensitive) != 0) s += 'i';
+    if ((_options & NSRegularExpressionUseUnixLineSeparators) != 0) s += 'm';
+    if ((_options & NSRegularExpressionDotMatchesLineSeparators) != 0) s += 's';
+    if ((_options & NSRegularExpressionUseUnicodeWordBoundaries) != 0) s += 'x';
+
+    return RegularExpression(_pattern.UTF8String, s);
+}
+
+- (instancetype)initWithRegularExpression:(RegularExpression)regularExpression {
+    if ((self = [self init])) {
+        _pattern = @(regularExpression.pattern().data());
+        switch (regularExpression.options()) {
+            case realm::bson::RegularExpression::Option::None:
+                _options = 0;
+                break;
+            case realm::bson::RegularExpression::Option::IgnoreCase:
+                _options = NSRegularExpressionCaseInsensitive;
+                break;
+            case realm::bson::RegularExpression::Option::Multiline:
+                _options = NSRegularExpressionUseUnixLineSeparators;
+                break;
+            case realm::bson::RegularExpression::Option::Dotall:
+                _options = NSRegularExpressionDotMatchesLineSeparators;
+                break;
+            case realm::bson::RegularExpression::Option::Extended:
+                _options = NSRegularExpressionUseUnicodeWordBoundaries;
+                break;
+        }
+        return self;
+    }
+
+    return nil;
+}
+
+@end
+
+#pragma mark RLMMaxKey
+
+@implementation RLMMaxKey
+
+- (BOOL)isEqual:(id)other {
+    return other == self || ([other class] == [self class]);
+}
+
+- (NSUInteger)hash {
+    return 0;
+}
+
+@end
+
+#pragma mark RLMMaxKey
+
+@implementation RLMMinKey
+
+- (BOOL)isEqual:(id)other {
+    return other == self || ([other class] == [self class]);
+}
+
+- (NSUInteger)hash {
+    return 0;
+}
+
+@end
+
+@implementation RLMMaxKey (RLMBSON)
+
+- (RLMBSONType)bsonType {
+    return RLMBSONTypeMaxKey;
+}
+
+@end
+
+@implementation RLMMinKey (RLMBSON)
+
+- (RLMBSONType)bsonType {
+    return RLMBSONTypeMinKey;
+}
+
+@end
+
+#pragma mark RLMBSONToBson
+
+Bson RLMConvertRLMBSONToBson(id<RLMBSON> b) {
+    switch ([b bsonType]) {
+        case RLMBSONTypeString:
+            return ((NSString *)b).UTF8String;
+        case RLMBSONTypeInt32:
+            return ((NSNumber *)b).intValue;
+        case RLMBSONTypeInt64:
+            return ((NSNumber *)b).longLongValue;
+        case RLMBSONTypeObjectId:
+            return [((RLMObjectId *)b) value];
+        case RLMBSONTypeNull:
+            return util::none;
+        case RLMBSONTypeBool:
+            return (bool)((NSNumber *)b).boolValue;
+        case RLMBSONTypeDouble:
+            return ((NSNumber *)b).doubleValue;
+        case RLMBSONTypeBinary:
+            return std::vector<char>((char*)((NSData *)b).bytes,
+                                     ((char*)((NSData *)b).bytes) + (int)((NSData *)b).length);
+        case RLMBSONTypeTimestamp:
+            // This represents a value of `Timestamp` in a MongoDB Collection.
+            return MongoTimestamp(((NSDate *)b).timeIntervalSince1970, 0);
+        case RLMBSONTypeDatetime:
+            // This represents a value of `Date` in a MongoDB Collection.
+            return RLMTimestampForNSDate((NSDate *)b);
+        case RLMBSONTypeDecimal128:
+            return [((RLMDecimal128 *)b) decimal128Value];
+        case RLMBSONTypeRegularExpression:
+            return [((NSRegularExpression *)b) regularExpressionValue];
+        case RLMBSONTypeMaxKey:
+            return max_key;
+        case RLMBSONTypeMinKey:
+            return min_key;
+        case RLMBSONTypeDocument:
+            return [((NSDictionary *)b) bsonDocumentValue];
+        case RLMBSONTypeArray:
+            return [((NSArray *)b) bsonArrayValue];
+    }
+}
+
+#pragma mark BsonToRLMBSON
+
+id<RLMBSON> RLMConvertBsonToRLMBSON(const Bson& b) {
+    switch (b.type()) {
+        case realm::bson::Bson::Type::Null:
+            return [NSNull null];
+        case realm::bson::Bson::Type::Int32:
+            return @(static_cast<int32_t>(b));
+        case realm::bson::Bson::Type::Int64:
+            return @(static_cast<int64_t>(b));
+        case realm::bson::Bson::Type::Bool:
+            return @(static_cast<bool>(b));
+        case realm::bson::Bson::Type::Double:
+            return @(static_cast<double>(b));
+        case realm::bson::Bson::Type::String:
+            return RLMStringDataToNSString(static_cast<std::string>(b).c_str());
+        case realm::bson::Bson::Type::Binary:
+            return [[NSData alloc] initWithBsonBinary:static_cast<std::vector<char>>(b)];
+        case realm::bson::Bson::Type::Timestamp:
+            return [[NSDate alloc] initWithTimeIntervalSince1970:static_cast<MongoTimestamp>(b).seconds];
+        case realm::bson::Bson::Type::Datetime:
+            return [[NSDate alloc] initWithTimeIntervalSince1970:static_cast<Timestamp>(b).get_seconds()];
+        case realm::bson::Bson::Type::ObjectId:
+            return [[RLMObjectId alloc] initWithValue:static_cast<ObjectId>(b)];
+        case realm::bson::Bson::Type::Decimal128:
+            return [[RLMDecimal128 alloc] initWithDecimal128:static_cast<Decimal128>(b)];
+        case realm::bson::Bson::Type::RegularExpression:
+            return [[NSRegularExpression alloc] initWithRegularExpression:static_cast<RegularExpression>(b)];
+        case realm::bson::Bson::Type::MaxKey:
+            return [RLMMaxKey new];
+        case realm::bson::Bson::Type::MinKey:
+            return [RLMMinKey new];
+        case realm::bson::Bson::Type::Document:
+            return [[NSMutableDictionary alloc] initWithBsonDocument:static_cast<BsonDocument>(b)];
+        case realm::bson::Bson::Type::Array:
+            return [[NSMutableArray alloc] initWithBsonArray:static_cast<BsonArray>(b)];
+        case realm::bson::Bson::Type::Uuid:
+            REALM_COMPILER_HINT_UNREACHABLE();
+    }
+    return nil;
+}
+
+id<RLMBSON> RLMConvertBsonDocumentToRLMBSON(realm::util::Optional<BsonDocument> b) {
+    return b ? RLMConvertBsonToRLMBSON(*b) : nil;
+}

+ 127 - 0
Example/Pods/Realm/Realm/RLMClassInfo.mm

@@ -0,0 +1,127 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2016 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMClassInfo.hpp"
+
+#import "RLMRealm_Private.hpp"
+#import "RLMObjectSchema_Private.h"
+#import "RLMSchema.h"
+#import "RLMProperty_Private.h"
+#import "RLMQueryUtil.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/object_schema.hpp>
+#import <realm/object-store/object_store.hpp>
+#import <realm/object-store/schema.hpp>
+#import <realm/object-store/shared_realm.hpp>
+#import <realm/table.hpp>
+
+using namespace realm;
+
+RLMClassInfo::RLMClassInfo(RLMRealm *realm, RLMObjectSchema *rlmObjectSchema,
+                           const realm::ObjectSchema *objectSchema)
+: realm(realm), rlmObjectSchema(rlmObjectSchema), objectSchema(objectSchema) { }
+
+realm::TableRef RLMClassInfo::table() const {
+    if (auto key = objectSchema->table_key) {
+        return realm.group.get_table(objectSchema->table_key);
+    }
+    return nullptr;
+}
+
+RLMProperty *RLMClassInfo::propertyForTableColumn(ColKey col) const noexcept {
+    auto const& props = objectSchema->persisted_properties;
+    for (size_t i = 0; i < props.size(); ++i) {
+        if (props[i].column_key == col) {
+            return rlmObjectSchema.properties[i];
+        }
+    }
+    return nil;
+}
+
+RLMProperty *RLMClassInfo::propertyForPrimaryKey() const noexcept {
+    return rlmObjectSchema.primaryKeyProperty;
+}
+
+realm::ColKey RLMClassInfo::tableColumn(NSString *propertyName) const {
+    return tableColumn(RLMValidatedProperty(rlmObjectSchema, propertyName));
+}
+
+realm::ColKey RLMClassInfo::tableColumn(RLMProperty *property) const {
+    return objectSchema->persisted_properties[property.index].column_key;
+}
+
+RLMClassInfo &RLMClassInfo::linkTargetType(size_t propertyIndex) {
+    return realm->_info[rlmObjectSchema.properties[propertyIndex].objectClassName];
+}
+
+RLMClassInfo &RLMClassInfo::linkTargetType(realm::Property const& property) {
+    REALM_ASSERT(property.type == PropertyType::Object);
+    return linkTargetType(&property - &objectSchema->persisted_properties[0]);
+}
+
+RLMClassInfo &RLMClassInfo::resolve(__unsafe_unretained RLMRealm *const realm) {
+    return realm->_info[rlmObjectSchema.className];
+}
+
+RLMSchemaInfo::impl::iterator RLMSchemaInfo::begin() noexcept { return m_objects.begin(); }
+RLMSchemaInfo::impl::iterator RLMSchemaInfo::end() noexcept { return m_objects.end(); }
+RLMSchemaInfo::impl::const_iterator RLMSchemaInfo::begin() const noexcept { return m_objects.begin(); }
+RLMSchemaInfo::impl::const_iterator RLMSchemaInfo::end() const noexcept { return m_objects.end(); }
+
+RLMClassInfo& RLMSchemaInfo::operator[](NSString *name) {
+    auto it = m_objects.find(name);
+    if (it == m_objects.end()) {
+        @throw RLMException(@"Object type '%@' is not managed by the Realm. "
+                            @"If using a custom `objectClasses` / `objectTypes` array in your configuration, "
+                            @"add `%@` to the list of `objectClasses` / `objectTypes`.",
+                            name, name);
+    }
+    return *&it->second;
+}
+
+RLMSchemaInfo::RLMSchemaInfo(RLMRealm *realm) {
+    RLMSchema *rlmSchema = realm.schema;
+    realm::Schema const& schema = realm->_realm->schema();
+    // rlmSchema can be larger due to multiple classes backed by one table
+    REALM_ASSERT(rlmSchema.objectSchema.count >= schema.size());
+
+    m_objects.reserve(schema.size());
+    for (RLMObjectSchema *rlmObjectSchema in rlmSchema.objectSchema) {
+        m_objects.emplace(std::piecewise_construct,
+                          std::forward_as_tuple(rlmObjectSchema.className),
+                          std::forward_as_tuple(realm, rlmObjectSchema,
+                                                &*schema.find(rlmObjectSchema.objectName.UTF8String)));
+    }
+}
+
+RLMSchemaInfo RLMSchemaInfo::clone(realm::Schema const& source_schema,
+                                   __unsafe_unretained RLMRealm *const target_realm) {
+    RLMSchemaInfo info;
+    info.m_objects.reserve(m_objects.size());
+
+    auto& schema = target_realm->_realm->schema();
+    for (auto& pair : m_objects) {
+        size_t idx = pair.second.objectSchema - &*source_schema.begin();
+        info.m_objects.emplace(std::piecewise_construct,
+                               std::forward_as_tuple(pair.first),
+                               std::forward_as_tuple(target_realm, pair.second.rlmObjectSchema,
+                                                     &*schema.begin() + idx));
+    }
+    return info;
+}

+ 460 - 0
Example/Pods/Realm/Realm/RLMCollection.mm

@@ -0,0 +1,460 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2016 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMCollection_Private.hpp"
+
+#import "RLMAccessor.hpp"
+#import "RLMArray_Private.hpp"
+#import "RLMListBase.h"
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMObjectStore.h"
+#import "RLMObject_Private.hpp"
+#import "RLMProperty_Private.h"
+
+#import <realm/object-store/collection_notifications.hpp>
+#import <realm/object-store/list.hpp>
+#import <realm/object-store/results.hpp>
+
+static const int RLMEnumerationBufferSize = 16;
+
+@implementation RLMFastEnumerator {
+    // The buffer supplied by fast enumeration does not retain the objects given
+    // to it, but because we create objects on-demand and don't want them
+    // autoreleased (a table can have more rows than the device has memory for
+    // accessor objects) we need a thing to retain them.
+    id _strongBuffer[RLMEnumerationBufferSize];
+
+    RLMRealm *_realm;
+    RLMClassInfo *_info;
+
+    // A pointer to either _snapshot or a Results from the source collection,
+    // to avoid having to copy the Results when not in a write transaction
+    realm::Results *_results;
+    realm::Results _snapshot;
+
+    // A strong reference to the collection being enumerated to ensure it stays
+    // alive when we're holding a pointer to a member in it
+    id _collection;
+}
+
+- (instancetype)initWithList:(realm::List&)list
+                  collection:(id)collection
+                   classInfo:(RLMClassInfo&)info
+{
+    self = [super init];
+    if (self) {
+        _info = &info;
+        _realm = _info->realm;
+        if (_realm.inWriteTransaction) {
+            _snapshot = list.snapshot();
+        }
+        else {
+            _snapshot = list.as_results();
+            _collection = collection;
+            [_realm registerEnumerator:self];
+        }
+        _results = &_snapshot;
+    }
+    return self;
+}
+
+- (instancetype)initWithResults:(realm::Results&)results
+                     collection:(id)collection
+                      classInfo:(RLMClassInfo&)info
+{
+    self = [super init];
+    if (self) {
+        _info = &info;
+        _realm = _info->realm;
+        if (_realm.inWriteTransaction) {
+            _snapshot = results.snapshot();
+            _results = &_snapshot;
+        }
+        else {
+            _results = &results;
+            _collection = collection;
+            [_realm registerEnumerator:self];
+        }
+    }
+    return self;
+}
+
+- (void)dealloc {
+    if (_collection) {
+        [_realm unregisterEnumerator:self];
+    }
+}
+
+- (void)detach {
+    _snapshot = _results->snapshot();
+    _results = &_snapshot;
+    _collection = nil;
+}
+
+- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
+                                    count:(NSUInteger)len {
+    [_realm verifyThread];
+    if (!_results->is_valid()) {
+        @throw RLMException(@"Collection is no longer valid");
+    }
+    // The fast enumeration buffer size is currently a hardcoded number in the
+    // compiler so this can't actually happen, but just in case it changes in
+    // the future...
+    if (len > RLMEnumerationBufferSize) {
+        len = RLMEnumerationBufferSize;
+    }
+
+    NSUInteger batchCount = 0, count = state->extra[1];
+
+    @autoreleasepool {
+        RLMAccessorContext ctx(*_info);
+        for (NSUInteger index = state->state; index < count && batchCount < len; ++index) {
+            _strongBuffer[batchCount] = _results->get(ctx, index);
+            batchCount++;
+        }
+    }
+
+    for (NSUInteger i = batchCount; i < len; ++i) {
+        _strongBuffer[i] = nil;
+    }
+
+    if (batchCount == 0) {
+        // Release our data if we're done, as we're autoreleased and so may
+        // stick around for a while
+        if (_collection) {
+            _collection = nil;
+            [_realm unregisterEnumerator:self];
+        }
+        _snapshot = {};
+    }
+
+    state->itemsPtr = (__unsafe_unretained id *)(void *)_strongBuffer;
+    state->state += batchCount;
+    state->mutationsPtr = state->extra+1;
+
+    return batchCount;
+}
+@end
+
+NSUInteger RLMFastEnumerate(NSFastEnumerationState *state, NSUInteger len, id<RLMFastEnumerable> collection) {
+    __autoreleasing RLMFastEnumerator *enumerator;
+    if (state->state == 0) {
+        enumerator = collection.fastEnumerator;
+        state->extra[0] = (long)enumerator;
+        state->extra[1] = collection.count;
+    }
+    else {
+        enumerator = (__bridge id)(void *)state->extra[0];
+    }
+
+    return [enumerator countByEnumeratingWithState:state count:len];
+}
+
+template<typename Collection>
+NSArray *RLMCollectionValueForKey(Collection& collection, NSString *key, RLMClassInfo& info) {
+    size_t count = collection.size();
+    if (count == 0) {
+        return @[];
+    }
+
+    NSMutableArray *array = [NSMutableArray arrayWithCapacity:count];
+    if ([key isEqualToString:@"self"]) {
+        RLMAccessorContext context(info);
+        for (size_t i = 0; i < count; ++i) {
+            [array addObject:collection.get(context, i) ?: NSNull.null];
+        }
+        return array;
+    }
+
+    if (collection.get_type() != realm::PropertyType::Object) {
+        RLMAccessorContext context(info);
+        for (size_t i = 0; i < count; ++i) {
+            [array addObject:[collection.get(context, i) valueForKey:key] ?: NSNull.null];
+        }
+        return array;
+    }
+
+    RLMObject *accessor = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, &info);
+
+    // List properties need to be handled specially since we need to create a
+    // new List each time
+    if (info.rlmObjectSchema.isSwiftClass) {
+        auto prop = info.rlmObjectSchema[key];
+        if (prop && prop.array && prop.swiftIvar) {
+            // Grab the actual class for the generic List from an instance of it
+            // so that we can make instances of the List without creating a new
+            // object accessor each time
+            Class cls = [object_getIvar(accessor, prop.swiftIvar) class];
+            RLMAccessorContext context(info);
+            for (size_t i = 0; i < count; ++i) {
+                RLMListBase *list = [[cls alloc] init];
+                list._rlmArray = [[RLMManagedArray alloc] initWithList:realm::List(info.realm->_realm,
+                                                                                   collection.get(i),
+                                                                                   info.tableColumn(prop))
+                                                            parentInfo:&info
+                                                              property:prop];
+                [array addObject:list];
+            }
+            return array;
+        }
+    }
+
+    for (size_t i = 0; i < count; i++) {
+        accessor->_row = collection.get(i);
+        RLMInitializeSwiftAccessorGenerics(accessor);
+        [array addObject:[accessor valueForKey:key] ?: NSNull.null];
+    }
+    return array;
+}
+
+template NSArray *RLMCollectionValueForKey(realm::Results&, NSString *, RLMClassInfo&);
+template NSArray *RLMCollectionValueForKey(realm::List&, NSString *, RLMClassInfo&);
+
+void RLMCollectionSetValueForKey(id<RLMFastEnumerable> collection, NSString *key, id value) {
+    realm::TableView tv = [collection tableView];
+    if (tv.size() == 0) {
+        return;
+    }
+
+    RLMClassInfo *info = collection.objectInfo;
+    RLMObject *accessor = RLMCreateManagedAccessor(info->rlmObjectSchema.accessorClass, info);
+    for (size_t i = 0; i < tv.size(); i++) {
+        accessor->_row = tv[i];
+        RLMInitializeSwiftAccessorGenerics(accessor);
+        [accessor setValue:value forKey:key];
+    }
+}
+
+NSString *RLMDescriptionWithMaxDepth(NSString *name,
+                                     id<RLMCollection> collection,
+                                     NSUInteger depth) {
+    if (depth == 0) {
+        return @"<Maximum depth exceeded>";
+    }
+
+    const NSUInteger maxObjects = 100;
+    auto str = [NSMutableString stringWithFormat:@"%@<%@> <%p> (\n", name,
+                [collection objectClassName] ?: RLMTypeToString([collection type]),
+                (void *)collection];
+    size_t index = 0, skipped = 0;
+    for (id obj in collection) {
+        NSString *sub;
+        if ([obj respondsToSelector:@selector(descriptionWithMaxDepth:)]) {
+            sub = [obj descriptionWithMaxDepth:depth - 1];
+        }
+        else {
+            sub = [obj description];
+        }
+
+        // Indent child objects
+        NSString *objDescription = [sub stringByReplacingOccurrencesOfString:@"\n"
+                                                                  withString:@"\n\t"];
+        [str appendFormat:@"\t[%zu] %@,\n", index++, objDescription];
+        if (index >= maxObjects) {
+            skipped = collection.count - maxObjects;
+            break;
+        }
+    }
+
+    // Remove last comma and newline characters
+    if (collection.count > 0) {
+        [str deleteCharactersInRange:NSMakeRange(str.length-2, 2)];
+    }
+    if (skipped) {
+        [str appendFormat:@"\n\t... %zu objects skipped.", skipped];
+    }
+    [str appendFormat:@"\n)"];
+    return str;
+}
+
+std::vector<std::pair<std::string, bool>> RLMSortDescriptorsToKeypathArray(NSArray<RLMSortDescriptor *> *properties) {
+    std::vector<std::pair<std::string, bool>> keypaths;
+    keypaths.reserve(properties.count);
+    for (RLMSortDescriptor *desc in properties) {
+        if ([desc.keyPath rangeOfString:@"@"].location != NSNotFound) {
+            @throw RLMException(@"Cannot sort on key path '%@': KVC collection operators are not supported.", desc.keyPath);
+        }
+        keypaths.push_back({desc.keyPath.UTF8String, desc.ascending});
+    }
+    return keypaths;
+}
+
+@implementation RLMCollectionChange {
+    realm::CollectionChangeSet _indices;
+}
+
+- (instancetype)initWithChanges:(realm::CollectionChangeSet)indices {
+    self = [super init];
+    if (self) {
+        _indices = std::move(indices);
+    }
+    return self;
+}
+
+static NSArray *toArray(realm::IndexSet const& set) {
+    NSMutableArray *ret = [NSMutableArray new];
+    for (auto index : set.as_indexes()) {
+        [ret addObject:@(index)];
+    }
+    return ret;
+}
+
+- (NSArray *)insertions {
+    return toArray(_indices.insertions);
+}
+
+- (NSArray *)deletions {
+    return toArray(_indices.deletions);
+}
+
+- (NSArray *)modifications {
+    return toArray(_indices.modifications);
+}
+
+static NSArray *toIndexPathArray(realm::IndexSet const& set, NSUInteger section) {
+    NSMutableArray *ret = [NSMutableArray new];
+    NSUInteger path[2] = {section, 0};
+    for (auto index : set.as_indexes()) {
+        path[1] = index;
+        [ret addObject:[NSIndexPath indexPathWithIndexes:path length:2]];
+    }
+    return ret;
+}
+
+- (NSArray<NSIndexPath *> *)deletionsInSection:(NSUInteger)section {
+    return toIndexPathArray(_indices.deletions, section);
+}
+
+- (NSArray<NSIndexPath *> *)insertionsInSection:(NSUInteger)section {
+    return toIndexPathArray(_indices.insertions, section);
+}
+
+- (NSArray<NSIndexPath *> *)modificationsInSection:(NSUInteger)section {
+    return toIndexPathArray(_indices.modifications, section);
+}
+
+- (NSString *)description {
+    return [NSString stringWithFormat:@"<RLMCollectionChange: %p> insertions: %@, deletions: %@, modifications: %@",
+            (__bridge void *)self, self.insertions, self.deletions, self.modifications];
+}
+
+@end
+
+namespace {
+struct CollectionCallbackWrapper {
+    void (^block)(id, RLMCollectionChange *, NSError *);
+    id collection;
+    bool ignoreChangesInInitialNotification;
+
+    void operator()(realm::CollectionChangeSet const& changes, std::exception_ptr err) {
+        if (err) {
+            try {
+                rethrow_exception(err);
+            }
+            catch (...) {
+                NSError *error = nil;
+                RLMRealmTranslateException(&error);
+                block(nil, nil, error);
+                return;
+            }
+        }
+
+        if (ignoreChangesInInitialNotification) {
+            ignoreChangesInInitialNotification = false;
+            block(collection, nil, nil);
+        }
+        else if (changes.empty()) {
+            block(collection, nil, nil);
+        }
+        else if (!changes.collection_root_was_deleted || !changes.deletions.empty()) {
+            block(collection, [[RLMCollectionChange alloc] initWithChanges:changes], nil);
+        }
+    }
+};
+} // anonymous namespace
+
+@interface RLMCancellationToken : RLMNotificationToken
+@end
+
+@implementation RLMCancellationToken {
+@public
+    __unsafe_unretained RLMRealm *_realm;
+    realm::NotificationToken _token;
+    std::mutex _mutex;
+}
+
+- (RLMRealm *)realm {
+    std::lock_guard<std::mutex> lock(_mutex);
+    return _realm;
+}
+
+- (void)suppressNextNotification {
+    std::lock_guard<std::mutex> lock(_mutex);
+    if (_realm) {
+        _token.suppress_next();
+    }
+}
+
+- (void)invalidate {
+    std::lock_guard<std::mutex> lock(_mutex);
+    _token = {};
+    _realm = nil;
+}
+
+template<typename RLMCollection>
+RLMNotificationToken *RLMAddNotificationBlock(RLMCollection *collection,
+                                              void (^block)(id, RLMCollectionChange *, NSError *),
+                                              dispatch_queue_t queue) {
+    RLMRealm *realm = collection.realm;
+    if (!realm) {
+        @throw RLMException(@"Linking objects notifications are only supported on managed objects.");
+    }
+    bool skipFirst = std::is_same_v<RLMCollection, RLMResults>;
+    auto token = [[RLMCancellationToken alloc] init];
+
+    if (!queue) {
+        [realm verifyNotificationsAreSupported:true];
+        token->_realm = realm;
+        token->_token = RLMGetBackingCollection(collection).add_notification_callback(CollectionCallbackWrapper{block, collection, skipFirst});
+        return token;
+    }
+
+    RLMThreadSafeReference *tsr = [RLMThreadSafeReference referenceWithThreadConfined:collection];
+    token->_realm = realm;
+    RLMRealmConfiguration *config = realm.configuration;
+    dispatch_async(queue, ^{
+        std::lock_guard<std::mutex> lock(token->_mutex);
+        if (!token->_realm) {
+            return;
+        }
+        NSError *error;
+        RLMRealm *realm = token->_realm = [RLMRealm realmWithConfiguration:config queue:queue error:&error];
+        if (!realm) {
+            block(nil, nil, error);
+            return;
+        }
+        RLMCollection *collection = [realm resolveThreadSafeReference:tsr];
+        token->_token = RLMGetBackingCollection(collection).add_notification_callback(CollectionCallbackWrapper{block, collection, skipFirst});
+    });
+    return token;
+}
+@end
+
+// Explicitly instantiate the templated function for the two types we'll use it on
+template RLMNotificationToken *RLMAddNotificationBlock<>(RLMManagedArray *, void (^)(id, RLMCollectionChange *, NSError *), dispatch_queue_t);
+template RLMNotificationToken *RLMAddNotificationBlock<>(RLMResults *, void (^)(id, RLMCollectionChange *, NSError *), dispatch_queue_t);

+ 36 - 0
Example/Pods/Realm/Realm/RLMConstants.m

@@ -0,0 +1,36 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import <Realm/RLMConstants.h>
+
+RLMNotification const RLMRealmRefreshRequiredNotification = @"RLMRealmRefreshRequiredNotification";
+RLMNotification const RLMRealmDidChangeNotification = @"RLMRealmDidChangeNotification";
+
+NSString * const RLMErrorDomain = @"io.realm";
+
+NSString * const RLMUnknownSystemErrorDomain = @"io.realm.unknown";
+
+NSString * const RLMExceptionName = @"RLMException";
+
+NSString * const RLMRealmVersionKey = @"RLMRealmVersion";
+
+NSString * const RLMRealmCoreVersionKey = @"RLMRealmCoreVersion";
+
+NSString * const RLMInvalidatedKey = @"invalidated";
+
+NSString * const RLMBackupRealmConfigurationErrorKey = @"RLMBackupRealmConfiguration";

+ 88 - 0
Example/Pods/Realm/Realm/RLMCredentials.mm

@@ -0,0 +1,88 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2016 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMCredentials_Private.hpp"
+
+#import "RLMBSON_Private.hpp"
+#import "RLMSyncUtil_Private.h"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/util/bson/bson.hpp>
+
+using namespace realm;
+
+@implementation RLMCredentials
+- (instancetype)initWithAppCredentials:(app::AppCredentials&&)credentials {
+    if (self = [super init]) {
+        _appCredentials = std::move(credentials);
+        self.provider = @(_appCredentials.provider_as_string().data());
+        return self;
+    }
+    return nil;
+}
+
++ (instancetype)credentialsWithFacebookToken:(RLMCredentialsToken)token {
+    return [[self alloc] initWithAppCredentials:app::AppCredentials::facebook(token.UTF8String)];
+}
+
++ (instancetype)credentialsWithGoogleAuthCode:(RLMCredentialsToken)token {
+    return [[self alloc] initWithAppCredentials:app::AppCredentials::google(app::AuthCode(token.UTF8String))];
+}
+
++ (instancetype)credentialsWithGoogleIdToken:(RLMCredentialsToken)token {
+    return [[self alloc] initWithAppCredentials:app::AppCredentials::google(app::IdToken(token.UTF8String))];
+}
+
++ (instancetype)credentialsWithAppleToken:(RLMCredentialsToken)token {
+    return [[self alloc] initWithAppCredentials:app::AppCredentials::apple(token.UTF8String)];
+}
+
++ (instancetype)credentialsWithEmail:(NSString *)username
+                            password:(NSString *)password {
+    return [[self alloc] initWithAppCredentials:app::AppCredentials::username_password(username.UTF8String,
+                                                                                       password.UTF8String)];
+}
+
++ (instancetype)credentialsWithJWT:(NSString *)token {
+    return [[self alloc] initWithAppCredentials:app::AppCredentials::custom(token.UTF8String)];
+}
+
++ (instancetype)credentialsWithFunctionPayload:(NSDictionary<NSString *, id<RLMBSON>> *)payload {
+    return [[self alloc] initWithAppCredentials:app::AppCredentials::function(static_cast<bson::BsonDocument>(RLMConvertRLMBSONToBson(payload)))];
+}
+
++ (instancetype)credentialsWithUserAPIKey:(NSString *)apiKey {
+    return [[self alloc] initWithAppCredentials:app::AppCredentials::user_api_key(apiKey.UTF8String)];
+}
+
++ (instancetype)credentialsWithServerAPIKey:(NSString *)apiKey {
+    return [[self alloc] initWithAppCredentials:app::AppCredentials::server_api_key(apiKey.UTF8String)];
+}
+
++ (instancetype)anonymousCredentials {
+    return [[self alloc] initWithAppCredentials:realm::app::AppCredentials::anonymous()];
+}
+
+- (BOOL)isEqual:(id)object {
+    if (auto that = RLMDynamicCast<RLMCredentials>(object)) {
+        return [self.provider isEqualToString:that.provider]
+            && self.appCredentials.serialize_as_json() == that.appCredentials.serialize_as_json();
+    }
+    return NO;
+}
+@end

+ 192 - 0
Example/Pods/Realm/Realm/RLMDecimal128.mm

@@ -0,0 +1,192 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMDecimal128_Private.hpp"
+
+#import "RLMUtil.hpp"
+
+#import <realm/decimal128.hpp>
+
+// Swift's obj-c bridging does not support making an obj-c defined class conform
+// to Decodable, so we need a Swift-defined subclass for that. This means that
+// when Realm Swift is being used, we need to produce objects of that type rather
+// than our obj-c defined type. objc_runtime_visible marks the type as being
+// visbile only to the obj-c runtime and not the linker, which means that it'll
+// be `nil` at runtime rather than being a linker error if it's not defined, and
+// valid if it happens to be defined by some other library (i.e. Realm Swift).
+//
+// At the point where the objects are being allocated we generally don't have
+// any good way of knowing whether or not it's going to end up being used by
+// Swift, so we just switch to the subclass unconditionally if the subclass
+// exists. This shouldn't have any impact on obj-c code other than a small
+// performance hit.
+[[clang::objc_runtime_visible]]
+@interface RealmSwiftDecimal128 : RLMDecimal128
+@end
+
+@implementation RLMDecimal128 {
+    realm::Decimal128 _value;
+}
+
+- (instancetype)init {
+    if (self = [super init]) {
+        if (auto cls = [RealmSwiftDecimal128 class]; cls && cls != self.class) {
+            object_setClass(self, cls);
+        }
+    }
+     return self;
+}
+
+- (instancetype)initWithDecimal128:(realm::Decimal128)value {
+    if ((self = [self init])) {
+        _value = value;
+    }
+    return self;
+}
+
+- (instancetype)initWithValue:(id)value {
+    if ((self = [self init])) {
+        _value = RLMObjcToDecimal128(value);
+    }
+    return self;
+}
+
+- (instancetype)initWithNumber:(NSNumber *)number {
+    if ((self = [self init])) {
+        _value = RLMObjcToDecimal128(number);
+    }
+    return self;
+}
+
+- (instancetype)initWithString:(NSString *)string error:(__unused NSError **)error {
+    if ((self = [self init])) {
+        _value = realm::Decimal128(string.UTF8String);
+    }
+    return self;
+}
+
++ (instancetype)decimalWithNumber:(NSNumber *)number {
+    return [[self alloc] initWithNumber:number];
+}
+
++ (instancetype)decimalWithNSDecimal:(NSDecimalNumber *)number {
+    return [[self alloc] initWithString:number.stringValue error:nil];
+}
+
+- (realm::Decimal128)decimal128Value {
+    return _value;
+}
+
+- (BOOL)isEqual:(id)object {
+    if (auto decimal128 = RLMDynamicCast<RLMDecimal128>(object)) {
+        return _value == decimal128->_value;
+    }
+    if (auto number = RLMDynamicCast<NSNumber>(object)) {
+        return _value == RLMObjcToDecimal128(number);
+    }
+    return NO;
+}
+
+- (NSUInteger)hash {
+    return std::hash<realm::Decimal128>()(_value);
+}
+
+- (NSString *)description {
+    return self.stringValue;
+}
+
+- (NSComparisonResult)compare:(RLMDecimal128 *)other {
+    return static_cast<NSComparisonResult>(_value.compare(other->_value));
+}
+
+- (double)doubleValue {
+    return [NSDecimalNumber decimalNumberWithDecimal:self.decimalValue].doubleValue;
+}
+
+- (NSDecimal)decimalValue {
+    NSDecimal ret;
+    [[[NSScanner alloc] initWithString:@(_value.to_string().c_str())] scanDecimal:&ret];
+    return ret;
+}
+
+- (NSString *)stringValue {
+    return @(_value.to_string().c_str());
+}
+
+- (BOOL)isNaN {
+    return _value.is_nan();
+}
+
+- (RLMDecimal128 *)magnitude {
+    auto result = realm::Decimal128(abs(self.doubleValue));
+    return [[RLMDecimal128 alloc] initWithDecimal128:result];
+}
+
+- (void)negate {
+    _value = realm::Decimal128(-self.doubleValue);
+}
+
++ (RLMDecimal128 *)minimumDecimalNumber {
+    return [[RLMDecimal128 alloc] initWithDecimal128:std::numeric_limits<realm::Decimal128>::lowest()];
+}
+
++ (RLMDecimal128 *)maximumDecimalNumber {
+    return [[RLMDecimal128 alloc] initWithDecimal128:std::numeric_limits<realm::Decimal128>::max()];
+}
+
+- (RLMDecimal128 *)decimalNumberByAdding:(RLMDecimal128 *)decimalNumber {
+    auto rhs = RLMObjcToDecimal128(decimalNumber);
+    return [[RLMDecimal128 alloc] initWithDecimal128:_value+rhs];
+}
+
+- (RLMDecimal128 *)decimalNumberByDividingBy:(RLMDecimal128 *)decimalNumber {
+    auto rhs = RLMObjcToDecimal128(decimalNumber);
+    return [[RLMDecimal128 alloc] initWithDecimal128:_value/rhs];
+}
+
+- (RLMDecimal128 *)decimalNumberBySubtracting:(RLMDecimal128 *)decimalNumber {
+    auto rhs = RLMObjcToDecimal128(decimalNumber);
+    return [[RLMDecimal128 alloc] initWithDecimal128:_value-rhs];
+}
+
+- (RLMDecimal128 *)decimalNumberByMultiplyingBy:(RLMDecimal128 *)decimalNumber {
+    auto rhs = RLMObjcToDecimal128(decimalNumber);
+    return [[RLMDecimal128 alloc] initWithDecimal128:_value*rhs];
+}
+
+- (BOOL)isGreaterThan:(RLMDecimal128 *)decimalNumber {
+    auto rhs = RLMObjcToDecimal128(decimalNumber);
+    return _value > rhs;
+}
+
+- (BOOL)isGreaterThanOrEqualTo:(RLMDecimal128 *)decimalNumber {
+    auto rhs = RLMObjcToDecimal128(decimalNumber);
+    return _value >= rhs;
+}
+
+- (BOOL)isLessThan:(RLMDecimal128 *)decimalNumber {
+    auto rhs = RLMObjcToDecimal128(decimalNumber);
+    return _value < rhs;
+}
+
+- (BOOL)isLessThanOrEqualTo:(RLMDecimal128 *)decimalNumber {
+    auto rhs = RLMObjcToDecimal128(decimalNumber);
+    return _value <= rhs;
+}
+
+@end

+ 84 - 0
Example/Pods/Realm/Realm/RLMEmailPasswordAuth.mm

@@ -0,0 +1,84 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMEmailPasswordAuth.h"
+
+#import "RLMApp_Private.hpp"
+#import "RLMBSON_Private.hpp"
+#import "RLMProviderClient_Private.hpp"
+
+#import <realm/object-store/sync/app.hpp>
+
+@implementation RLMEmailPasswordAuth
+
+- (realm::app::App::UsernamePasswordProviderClient)client {
+    return self.app._realmApp->provider_client<realm::app::App::UsernamePasswordProviderClient>();
+}
+
+- (void)registerUserWithEmail:(NSString *)email
+                     password:(NSString *)password
+                   completion:(RLMEmailPasswordAuthOptionalErrorBlock)completion {
+    self.client.register_email(email.UTF8String, password.UTF8String, ^(realm::util::Optional<realm::app::AppError> error) {
+        [self handleResponse:error completion:completion];
+    });
+}
+
+- (void)confirmUser:(NSString *)token
+            tokenId:(NSString *)tokenId
+         completion:(RLMEmailPasswordAuthOptionalErrorBlock)completion {
+    self.client.confirm_user(token.UTF8String, tokenId.UTF8String, ^(realm::util::Optional<realm::app::AppError> error) {
+        [self handleResponse:error completion:completion];
+    });
+}
+
+- (void)resendConfirmationEmail:(NSString *)email
+                     completion:(RLMEmailPasswordAuthOptionalErrorBlock)completion {
+    self.client.resend_confirmation_email(email.UTF8String, ^(realm::util::Optional<realm::app::AppError> error) {
+        [self handleResponse:error completion:completion];
+    });
+}
+
+- (void)sendResetPasswordEmail:(NSString *)email
+                    completion:(RLMEmailPasswordAuthOptionalErrorBlock)completion {
+    self.client.send_reset_password_email(email.UTF8String, ^(realm::util::Optional<realm::app::AppError> error) {
+        [self handleResponse:error completion:completion];
+    });
+}
+
+- (void)resetPasswordTo:(NSString *)password
+                  token:(NSString *)token
+                tokenId:(NSString *)tokenId
+             completion:(RLMEmailPasswordAuthOptionalErrorBlock)completion {
+    self.client.reset_password(password.UTF8String, token.UTF8String, tokenId.UTF8String, ^(realm::util::Optional<realm::app::AppError> error) {
+        [self handleResponse:error completion:completion];
+    });
+}
+
+- (void)callResetPasswordFunction:(NSString *)email
+                         password:(NSString *)password
+                             args:(NSArray<id<RLMBSON>> *)args
+                       completion:(RLMEmailPasswordAuthOptionalErrorBlock)completion {
+    self.client.call_reset_password_function(email.UTF8String,
+                                             password.UTF8String,
+                                             static_cast<realm::bson::BsonArray>(RLMConvertRLMBSONToBson(args)),
+                                                                                 ^(realm::util::Optional<realm::app::AppError> error) {
+        [self handleResponse:error completion:completion];
+    });
+}
+
+@end

+ 113 - 0
Example/Pods/Realm/Realm/RLMEmbeddedObject.mm

@@ -0,0 +1,113 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMEmbeddedObject.h"
+
+#import "RLMObject_Private.hpp"
+#import "RLMSchema_Private.h"
+
+@implementation RLMEmbeddedObject
+// synthesized in RLMObjectBase but redeclared here for documentation purposes
+@dynamic invalidated, realm, objectSchema;
+
+#pragma mark - Designated Initializers
+
+- (instancetype)init {
+    return [super init];
+}
+
+#pragma mark - Convenience Initializers
+
+- (instancetype)initWithValue:(id)value {
+    if (!(self = [self init])) {
+        return nil;
+    }
+    RLMInitializeWithValue(self, value, RLMSchema.partialPrivateSharedSchema);
+    return self;
+}
+
+#pragma mark - Subscripting
+
+- (id)objectForKeyedSubscript:(NSString *)key {
+    return RLMObjectBaseObjectForKeyedSubscript(self, key);
+}
+
+- (void)setObject:(id)obj forKeyedSubscript:(NSString *)key {
+    RLMObjectBaseSetObjectForKeyedSubscript(self, key, obj);
+}
+
+#pragma mark - Other Instance Methods
+
+- (BOOL)isEqualToObject:(RLMObjectBase *)object {
+    return [object isKindOfClass:RLMObjectBase.class] && RLMObjectBaseAreEqual(self, object);
+}
+
+- (instancetype)freeze {
+    return RLMObjectFreeze(self);
+}
+
+- (instancetype)thaw {
+    return RLMObjectThaw(self);
+}
+
+- (RLMNotificationToken *)addNotificationBlock:(RLMObjectChangeBlock)block {
+    return RLMObjectAddNotificationBlock(self, block, nil);
+}
+
+- (RLMNotificationToken *)addNotificationBlock:(RLMObjectChangeBlock)block queue:(dispatch_queue_t)queue {
+    return RLMObjectAddNotificationBlock(self, block, queue);
+}
+
++ (NSString *)className {
+    return [super className];
+}
+
+#pragma mark - Default values for schema definition
+
++ (NSString *)primaryKey {
+    return nil;
+}
+
++ (NSArray *)indexedProperties {
+    return @[];
+}
+
++ (NSDictionary *)linkingObjectsProperties {
+    return @{};
+}
+
++ (NSDictionary *)defaultPropertyValues {
+    return nil;
+}
+
++ (NSArray *)ignoredProperties {
+    return nil;
+}
+
++ (NSArray *)requiredProperties {
+    return @[];
+}
+
++ (bool)_realmIgnoreClass {
+    return false;
+}
+
++ (bool)isEmbedded {
+    return true;
+}
+@end

+ 88 - 0
Example/Pods/Realm/Realm/RLMFindOneAndModifyOptions.mm

@@ -0,0 +1,88 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMFindOneAndModifyOptions_Private.hpp"
+#import "RLMBSON_Private.hpp"
+
+@interface RLMFindOneAndModifyOptions() {
+    realm::app::MongoCollection::FindOneAndModifyOptions _options;
+};
+@end
+
+@implementation RLMFindOneAndModifyOptions
+
+- (instancetype)initWithProjection:(id<RLMBSON> _Nullable)projection
+                              sort:(id<RLMBSON> _Nullable)sort
+                            upsert:(BOOL)upsert
+           shouldReturnNewDocument:(BOOL)shouldReturnNewDocument {
+    if (self = [super init]) {
+        self.upsert = upsert;
+        self.shouldReturnNewDocument = shouldReturnNewDocument;
+        self.projection = projection;
+        self.sort = sort;
+    }
+    return self;
+}
+
+- (realm::app::MongoCollection::FindOneAndModifyOptions)_findOneAndModifyOptions {
+    return _options;
+}
+
+- (id<RLMBSON>)projection {
+    return RLMConvertBsonDocumentToRLMBSON(_options.projection_bson);
+}
+
+- (id<RLMBSON>)sort {
+    return RLMConvertBsonDocumentToRLMBSON(_options.sort_bson);
+}
+
+- (BOOL)upsert {
+    return _options.upsert;
+}
+
+- (BOOL)shouldReturnNewDocument {
+    return _options.return_new_document;
+}
+
+- (void)setProjection:(id<RLMBSON>)projection {
+    if (projection) {
+        auto bson = realm::bson::BsonDocument(RLMConvertRLMBSONToBson(projection));
+        _options.projection_bson = realm::util::Optional<realm::bson::BsonDocument>(bson);
+    } else {
+        _options.projection_bson = realm::util::none;
+    }
+}
+
+- (void)setSort:(id<RLMBSON>)sort {
+    if (sort) {
+        auto bson = realm::bson::BsonDocument(RLMConvertRLMBSONToBson(sort));
+        _options.sort_bson = realm::util::Optional<realm::bson::BsonDocument>(bson);
+    } else {
+        _options.sort_bson = realm::util::none;
+    }
+}
+
+- (void)setUpsert:(BOOL)upsert {
+    _options.upsert = upsert;
+}
+
+- (void)setShouldReturnNewDocument:(BOOL)returnNewDocument {
+    _options.return_new_document = returnNewDocument;
+}
+
+@end

+ 87 - 0
Example/Pods/Realm/Realm/RLMFindOptions.mm

@@ -0,0 +1,87 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMFindOptions_Private.hpp"
+#import "RLMBSON_Private.hpp"
+
+@interface RLMFindOptions() {
+    realm::app::MongoCollection::FindOptions _options;
+};
+@end
+
+@implementation RLMFindOptions
+
+- (instancetype)initWithLimit:(NSInteger)limit
+                   projection:(id<RLMBSON> _Nullable)projection
+                         sort:(id<RLMBSON> _Nullable)sort {
+    if (self = [super init]) {
+        self.projection = projection;
+        self.sort = sort;
+        self.limit = limit;
+    }
+    return self;
+}
+
+- (instancetype)initWithProjection:(id<RLMBSON> _Nullable)projection
+                              sort:(id<RLMBSON> _Nullable)sort {
+    if (self = [super init]) {
+        self.projection = projection;
+        self.sort = sort;
+    }
+    return self;
+}
+
+- (realm::app::MongoCollection::FindOptions)_findOptions {
+    return _options;
+}
+
+- (id<RLMBSON>)projection {
+    return RLMConvertBsonDocumentToRLMBSON(_options.projection_bson);
+}
+
+- (id<RLMBSON>)sort {
+    return RLMConvertBsonDocumentToRLMBSON(_options.sort_bson);
+}
+
+- (void)setProjection:(id<RLMBSON>)projection {
+    if (projection) {
+        auto bson = realm::bson::BsonDocument(RLMConvertRLMBSONToBson(projection));
+        _options.projection_bson = realm::util::Optional<realm::bson::BsonDocument>(bson);
+    } else {
+        _options.projection_bson = realm::util::none;
+    }
+}
+
+- (void)setSort:(id<RLMBSON>)sort {
+    if (sort) {
+        auto bson = realm::bson::BsonDocument(RLMConvertRLMBSONToBson(sort));
+        _options.sort_bson = realm::util::Optional<realm::bson::BsonDocument>(bson);
+    } else {
+        _options.sort_bson = realm::util::none;
+    }
+}
+
+- (NSInteger)limit {
+    return static_cast<NSInteger>(_options.limit.value_or(0));
+}
+
+- (void)setLimit:(NSInteger)limit {
+    _options.limit = realm::util::Optional<int64_t>(limit);
+}
+
+@end

+ 163 - 0
Example/Pods/Realm/Realm/RLMListBase.mm

@@ -0,0 +1,163 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2015 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMListBase.h"
+
+#import "RLMArray_Private.hpp"
+#import "RLMObjectSchema_Private.h"
+#import "RLMObject_Private.hpp"
+#import "RLMObservation.hpp"
+#import "RLMProperty_Private.h"
+#import "RLMRealm_Private.hpp"
+
+@interface RLMArray (KVO)
+- (NSArray *)objectsAtIndexes:(__unused NSIndexSet *)indexes;
+@end
+
+@implementation RLMListBase {
+    std::unique_ptr<RLMObservationInfo> _observationInfo;
+}
+
++ (RLMArray *)_unmanagedArray {
+    return nil;
+}
+
+- (instancetype)init {
+    return self = [super init];
+}
+
+- (instancetype)initWithArray:(RLMArray *)array {
+    self = [super init];
+    if (self) {
+        __rlmArray = array;
+    }
+    return self;
+}
+
+- (RLMArray *)_rlmArray {
+    if (!__rlmArray) {
+        __rlmArray = self.class._unmanagedArray;
+    }
+    return __rlmArray;
+}
+
+- (id)valueForKey:(NSString *)key {
+    return [self._rlmArray valueForKey:key];
+}
+
+- (id)valueForKeyPath:(NSString *)keyPath {
+    return [self._rlmArray valueForKeyPath:keyPath];
+}
+
+- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
+                                  objects:(id __unsafe_unretained [])buffer
+                                    count:(NSUInteger)len {
+    return [self._rlmArray countByEnumeratingWithState:state objects:buffer count:len];
+}
+
+- (NSArray *)objectsAtIndexes:(NSIndexSet *)indexes {
+    return [self._rlmArray objectsAtIndexes:indexes];
+}
+
+- (void)addObserver:(id)observer
+         forKeyPath:(NSString *)keyPath
+            options:(NSKeyValueObservingOptions)options
+            context:(void *)context {
+    RLMEnsureArrayObservationInfo(_observationInfo, keyPath, self._rlmArray, self);
+    [super addObserver:observer forKeyPath:keyPath options:options context:context];
+}
+
+- (BOOL)isEqual:(id)object {
+    if (auto array = RLMDynamicCast<RLMListBase>(object)) {
+        return !array._rlmArray.realm
+        && ((self._rlmArray.count == 0 && array._rlmArray.count == 0) ||
+            [self._rlmArray isEqual:array._rlmArray]);
+    }
+    return NO;
+}
+
+@end
+
+@implementation RLMLinkingObjectsHandle {
+    realm::TableKey _tableKey;
+    realm::ObjKey _objKey;
+    RLMClassInfo *_info;
+    RLMRealm *_realm;
+    RLMProperty *_property;
+
+    RLMResults *_results;
+}
+
+- (instancetype)initWithObject:(RLMObjectBase *)object property:(RLMProperty *)prop {
+    if (!(self = [super init])) {
+        return nil;
+    }
+    auto& obj = object->_row;
+    _tableKey = obj.get_table()->get_key();
+    _objKey = obj.get_key();
+    _info = object->_info;
+    _realm = object->_realm;
+    _property = prop;
+
+    return self;
+}
+
+- (instancetype)initWithLinkingObjects:(RLMResults *)linkingObjects {
+    if (!(self = [super init])) {
+        return nil;
+    }
+    _realm = linkingObjects.realm;
+    _results = linkingObjects;
+
+    return self;
+}
+
+- (instancetype)freeze {
+    RLMLinkingObjectsHandle *frozen = [[self.class alloc] init];
+    frozen->_results = [self.results freeze];
+    return frozen;
+}
+
+- (instancetype)thaw {
+    RLMLinkingObjectsHandle *thawed = [[self.class alloc] init];
+    thawed->_results = [self.results thaw];
+    return thawed;
+}
+
+- (RLMResults *)results {
+    if (_results) {
+        return _results;
+    }
+    [_realm verifyThread];
+
+    auto table = _realm.group.get_table(_tableKey);
+    if (!table->is_valid(_objKey)) {
+        @throw RLMException(@"Object has been deleted or invalidated.");
+    }
+
+    auto obj = _realm.group.get_table(_tableKey)->get_object(_objKey);
+    auto& objectInfo = _realm->_info[_property.objectClassName];
+    auto& linkOrigin = _info->objectSchema->computed_properties[_property.index].link_origin_property_name;
+    auto linkingProperty = objectInfo.objectSchema->property_for_name(linkOrigin);
+    realm::Results results(_realm->_realm, obj.get_backlink_view(objectInfo.table(), linkingProperty->column_key));
+    _results = [RLMLinkingObjects resultsWithObjectInfo:objectInfo results:std::move(results)];
+    _realm = nil;
+    return _results;
+}
+
+@end

+ 575 - 0
Example/Pods/Realm/Realm/RLMManagedArray.mm

@@ -0,0 +1,575 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMArray_Private.hpp"
+
+#import "RLMAccessor.hpp"
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMObjectStore.h"
+#import "RLMObject_Private.hpp"
+#import "RLMObservation.hpp"
+#import "RLMProperty_Private.h"
+#import "RLMQueryUtil.hpp"
+#import "RLMRealm_Private.hpp"
+#import "RLMRealmConfiguration_Private.hpp"
+#import "RLMSchema.h"
+#import "RLMThreadSafeReference_Private.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/list.hpp>
+#import <realm/object-store/results.hpp>
+#import <realm/object-store/shared_realm.hpp>
+#import <realm/table_view.hpp>
+
+#import <objc/runtime.h>
+
+@interface RLMManagedArrayHandoverMetadata : NSObject
+@property (nonatomic) NSString *parentClassName;
+@property (nonatomic) NSString *key;
+@end
+
+@implementation RLMManagedArrayHandoverMetadata
+@end
+
+@interface RLMManagedArray () <RLMThreadConfined_Private>
+@end
+
+//
+// RLMArray implementation
+//
+@implementation RLMManagedArray {
+@public
+    realm::List _backingList;
+    RLMRealm *_realm;
+    RLMClassInfo *_objectInfo;
+    RLMClassInfo *_ownerInfo;
+    std::unique_ptr<RLMObservationInfo> _observationInfo;
+}
+
+- (RLMManagedArray *)initWithList:(realm::List)list
+                       parentInfo:(RLMClassInfo *)parentInfo
+                         property:(__unsafe_unretained RLMProperty *const)property {
+    if (property.type == RLMPropertyTypeObject)
+        self = [self initWithObjectClassName:property.objectClassName];
+    else
+        self = [self initWithObjectType:property.type optional:property.optional];
+    if (self) {
+        _realm = parentInfo->realm;
+        REALM_ASSERT(list.get_realm() == _realm->_realm);
+        _backingList = std::move(list);
+        _ownerInfo = parentInfo;
+        if (property.type == RLMPropertyTypeObject)
+            _objectInfo = &parentInfo->linkTargetType(property.index);
+        else
+            _objectInfo = _ownerInfo;
+        _key = property.name;
+    }
+    return self;
+}
+
+- (RLMManagedArray *)initWithParent:(__unsafe_unretained RLMObjectBase *const)parentObject
+                           property:(__unsafe_unretained RLMProperty *const)property {
+    __unsafe_unretained RLMRealm *const realm = parentObject->_realm;
+    auto col = parentObject->_info->tableColumn(property);
+    return [self initWithList:realm::List(realm->_realm, parentObject->_row, col)
+                   parentInfo:parentObject->_info
+                     property:property];
+}
+
+void RLMValidateArrayObservationKey(__unsafe_unretained NSString *const keyPath,
+                                    __unsafe_unretained RLMArray *const array) {
+    if (![keyPath isEqualToString:RLMInvalidatedKey]) {
+        @throw RLMException(@"[<%@ %p> addObserver:forKeyPath:options:context:] is not supported. Key path: %@",
+                            [array class], array, keyPath);
+    }
+}
+
+void RLMEnsureArrayObservationInfo(std::unique_ptr<RLMObservationInfo>& info,
+                                   __unsafe_unretained NSString *const keyPath,
+                                   __unsafe_unretained RLMArray *const array,
+                                   __unsafe_unretained id const observed) {
+    RLMValidateArrayObservationKey(keyPath, array);
+    if (!info && array.class == [RLMManagedArray class]) {
+        auto lv = static_cast<RLMManagedArray *>(array);
+        info = std::make_unique<RLMObservationInfo>(*lv->_ownerInfo,
+                                                    lv->_backingList.get_parent_object_key(),
+                                                    observed);
+    }
+}
+
+//
+// validation helpers
+//
+[[gnu::noinline]]
+[[noreturn]]
+static void throwError(__unsafe_unretained RLMManagedArray *const ar, NSString *aggregateMethod) {
+    try {
+        throw;
+    }
+    catch (realm::InvalidTransactionException const&) {
+        @throw RLMException(@"Cannot modify managed RLMArray outside of a write transaction.");
+    }
+    catch (realm::IncorrectThreadException const&) {
+        @throw RLMException(@"Realm accessed from incorrect thread.");
+    }
+    catch (realm::List::InvalidatedException const&) {
+        @throw RLMException(@"RLMArray has been invalidated or the containing object has been deleted.");
+    }
+    catch (realm::List::OutOfBoundsIndexException const& e) {
+        @throw RLMException(@"Index %zu is out of bounds (must be less than %zu).",
+                            e.requested, e.valid_count);
+    }
+    catch (realm::Results::UnsupportedColumnTypeException const& e) {
+        if (ar->_backingList.get_type() == realm::PropertyType::Object) {
+            @throw RLMException(@"%@: is not supported for %s%s property '%s'.",
+                                aggregateMethod,
+                                string_for_property_type(e.property_type),
+                                is_nullable(e.property_type) ? "?" : "",
+                                e.column_name.data());
+        }
+        @throw RLMException(@"%@: is not supported for %s%s array '%@.%@'.",
+                            aggregateMethod,
+                            string_for_property_type(e.property_type),
+                            is_nullable(e.property_type) ? "?" : "",
+                            ar->_ownerInfo->rlmObjectSchema.className, ar->_key);
+    }
+    catch (std::logic_error const& e) {
+        @throw RLMException(e);
+    }
+}
+
+template<typename Function>
+static auto translateErrors(__unsafe_unretained RLMManagedArray *const ar,
+                            Function&& f, NSString *aggregateMethod=nil) {
+    try {
+        return f();
+    }
+    catch (...) {
+        throwError(ar, aggregateMethod);
+    }
+}
+
+template<typename Function>
+static auto translateErrors(Function&& f) {
+    try {
+        return f();
+    }
+    catch (...) {
+        throwError(nil, nil);
+    }
+}
+
+template<typename IndexSetFactory>
+static void changeArray(__unsafe_unretained RLMManagedArray *const ar,
+                        NSKeyValueChange kind, dispatch_block_t f, IndexSetFactory&& is) {
+    translateErrors([&] { ar->_backingList.verify_in_transaction(); });
+
+    RLMObservationTracker tracker(ar->_realm);
+    tracker.trackDeletions();
+    auto obsInfo = RLMGetObservationInfo(ar->_observationInfo.get(),
+                                         ar->_backingList.get_parent_object_key(),
+                                         *ar->_ownerInfo);
+    if (obsInfo) {
+        tracker.willChange(obsInfo, ar->_key, kind, is());
+    }
+
+    translateErrors(f);
+}
+
+static void changeArray(__unsafe_unretained RLMManagedArray *const ar, NSKeyValueChange kind, NSUInteger index, dispatch_block_t f) {
+    changeArray(ar, kind, f, [=] { return [NSIndexSet indexSetWithIndex:index]; });
+}
+
+static void changeArray(__unsafe_unretained RLMManagedArray *const ar, NSKeyValueChange kind, NSRange range, dispatch_block_t f) {
+    changeArray(ar, kind, f, [=] { return [NSIndexSet indexSetWithIndexesInRange:range]; });
+}
+
+static void changeArray(__unsafe_unretained RLMManagedArray *const ar, NSKeyValueChange kind, NSIndexSet *is, dispatch_block_t f) {
+    changeArray(ar, kind, f, [=] { return is; });
+}
+
+//
+// public method implementations
+//
+- (RLMRealm *)realm {
+    return _realm;
+}
+
+- (NSUInteger)count {
+    return translateErrors([&] { return _backingList.size(); });
+}
+
+- (BOOL)isInvalidated {
+    return translateErrors([&] { return !_backingList.is_valid(); });
+}
+
+- (RLMClassInfo *)objectInfo {
+    return _objectInfo;
+}
+
+
+- (bool)isBackedByList:(realm::List const&)list {
+    return _backingList == list;
+}
+
+- (BOOL)isEqual:(id)object {
+    return [object respondsToSelector:@selector(isBackedByList:)] && [object isBackedByList:_backingList];
+}
+
+- (NSUInteger)hash {
+    return std::hash<realm::List>()(_backingList);
+}
+
+- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
+                                  objects:(__unused __unsafe_unretained id [])buffer
+                                    count:(NSUInteger)len {
+    return RLMFastEnumerate(state, len, self);
+}
+
+- (id)objectAtIndex:(NSUInteger)index {
+    return translateErrors([&] {
+        RLMAccessorContext context(*_objectInfo);
+        return _backingList.get(context, index);
+    });
+}
+
+static void RLMInsertObject(RLMManagedArray *ar, id object, NSUInteger index) {
+    RLMArrayValidateMatchingObjectType(ar, object);
+    if (index == NSUIntegerMax) {
+        index = translateErrors([&] { return ar->_backingList.size(); });
+    }
+
+    changeArray(ar, NSKeyValueChangeInsertion, index, ^{
+        RLMAccessorContext context(*ar->_objectInfo);
+        ar->_backingList.insert(context, index, object);
+    });
+}
+
+- (void)addObject:(id)object {
+    RLMInsertObject(self, object, NSUIntegerMax);
+}
+
+- (void)insertObject:(id)object atIndex:(NSUInteger)index {
+    RLMInsertObject(self, object, index);
+}
+
+- (void)insertObjects:(id<NSFastEnumeration>)objects atIndexes:(NSIndexSet *)indexes {
+    changeArray(self, NSKeyValueChangeInsertion, indexes, ^{
+        NSUInteger index = [indexes firstIndex];
+        RLMAccessorContext context(*_objectInfo);
+        for (id obj in objects) {
+            RLMArrayValidateMatchingObjectType(self, obj);
+            _backingList.insert(context, index, obj);
+            index = [indexes indexGreaterThanIndex:index];
+        }
+    });
+}
+
+
+- (void)removeObjectAtIndex:(NSUInteger)index {
+    changeArray(self, NSKeyValueChangeRemoval, index, ^{
+        _backingList.remove(index);
+    });
+}
+
+- (void)removeObjectsAtIndexes:(NSIndexSet *)indexes {
+    changeArray(self, NSKeyValueChangeRemoval, indexes, ^{
+        [indexes enumerateIndexesWithOptions:NSEnumerationReverse usingBlock:^(NSUInteger idx, BOOL *) {
+            _backingList.remove(idx);
+        }];
+    });
+}
+
+- (void)addObjectsFromArray:(NSArray *)array {
+    changeArray(self, NSKeyValueChangeInsertion, NSMakeRange(self.count, array.count), ^{
+        RLMAccessorContext context(*_objectInfo);
+        for (id obj in array) {
+            RLMArrayValidateMatchingObjectType(self, obj);
+            _backingList.add(context, obj);
+        }
+    });
+}
+
+- (void)removeAllObjects {
+    changeArray(self, NSKeyValueChangeRemoval, NSMakeRange(0, self.count), ^{
+        _backingList.remove_all();
+    });
+}
+
+- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
+    RLMArrayValidateMatchingObjectType(self, object);
+    changeArray(self, NSKeyValueChangeReplacement, index, ^{
+        RLMAccessorContext context(*_objectInfo);
+        _backingList.set(context, index, object);
+    });
+}
+
+- (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex {
+    auto start = std::min(sourceIndex, destinationIndex);
+    auto len = std::max(sourceIndex, destinationIndex) - start + 1;
+    changeArray(self, NSKeyValueChangeReplacement, {start, len}, ^{
+        _backingList.move(sourceIndex, destinationIndex);
+    });
+}
+
+- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2 {
+    changeArray(self, NSKeyValueChangeReplacement, ^{
+        _backingList.swap(index1, index2);
+    }, [=] {
+        NSMutableIndexSet *set = [[NSMutableIndexSet alloc] initWithIndex:index1];
+        [set addIndex:index2];
+        return set;
+    });
+}
+
+- (NSUInteger)indexOfObject:(id)object {
+    RLMArrayValidateMatchingObjectType(self, object);
+    return translateErrors([&] {
+        RLMAccessorContext context(*_objectInfo);
+        return RLMConvertNotFound(_backingList.find(context, object));
+    });
+}
+
+- (id)valueForKeyPath:(NSString *)keyPath {
+    if ([keyPath hasPrefix:@"@"]) {
+        // Delegate KVC collection operators to RLMResults
+        return translateErrors([&] {
+            auto results = [RLMResults resultsWithObjectInfo:*_objectInfo results:_backingList.as_results()];
+            return [results valueForKeyPath:keyPath];
+        });
+    }
+    return [super valueForKeyPath:keyPath];
+}
+
+- (id)valueForKey:(NSString *)key {
+    // Ideally we'd use "@invalidated" for this so that "invalidated" would use
+    // normal array KVC semantics, but observing @things works very oddly (when
+    // it's part of a key path, it's triggered automatically when array index
+    // changes occur, and can't be sent explicitly, but works normally when it's
+    // the entire key path), and an RLMManagedArray *can't* have objects where
+    // invalidated is true, so we're not losing much.
+    return translateErrors([&]() -> id {
+        if ([key isEqualToString:RLMInvalidatedKey]) {
+            return @(!_backingList.is_valid());
+        }
+
+        _backingList.verify_attached();
+        return RLMCollectionValueForKey(_backingList, key, *_objectInfo);
+    });
+}
+
+- (void)setValue:(id)value forKey:(NSString *)key {
+    if ([key isEqualToString:@"self"]) {
+        RLMArrayValidateMatchingObjectType(self, value);
+        RLMAccessorContext context(*_objectInfo);
+        translateErrors([&] {
+            for (size_t i = 0, count = _backingList.size(); i < count; ++i) {
+                _backingList.set(context, i, value);
+            }
+        });
+        return;
+    }
+    else if (_type == RLMPropertyTypeObject) {
+        RLMArrayValidateMatchingObjectType(self, value);
+        translateErrors([&] { _backingList.verify_in_transaction(); });
+        RLMCollectionSetValueForKey(self, key, value);
+    }
+    else {
+        [self setValue:value forUndefinedKey:key];
+    }
+}
+
+- (realm::ColKey)columnForProperty:(NSString *)propertyName {
+    if (_backingList.get_type() == realm::PropertyType::Object) {
+        return _objectInfo->tableColumn(propertyName);
+    }
+    if (![propertyName isEqualToString:@"self"]) {
+        @throw RLMException(@"Arrays of '%@' can only be aggregated on \"self\"", RLMTypeToString(_type));
+    }
+    return {};
+}
+
+- (id)minOfProperty:(NSString *)property {
+    auto column = [self columnForProperty:property];
+    auto value = translateErrors(self, [&] { return _backingList.min(column); }, @"minOfProperty");
+    return value ? RLMMixedToObjc(*value) : nil;
+}
+
+- (id)maxOfProperty:(NSString *)property {
+    auto column = [self columnForProperty:property];
+    auto value = translateErrors(self, [&] { return _backingList.max(column); }, @"maxOfProperty");
+    return value ? RLMMixedToObjc(*value) : nil;
+}
+
+- (id)sumOfProperty:(NSString *)property {
+    auto column = [self columnForProperty:property];
+    return RLMMixedToObjc(translateErrors(self, [&] { return _backingList.sum(column); }, @"sumOfProperty"));
+}
+
+- (id)averageOfProperty:(NSString *)property {
+    auto column = [self columnForProperty:property];
+    auto value = translateErrors(self, [&] { return _backingList.average(column); }, @"averageOfProperty");
+    return value ? RLMMixedToObjc(*value) : nil;
+}
+
+- (void)deleteObjectsFromRealm {
+    if (_type != RLMPropertyTypeObject) {
+        @throw RLMException(@"Cannot delete objects from RLMArray<%@>: only RLMObjects can be deleted.", RLMTypeToString(_type));
+    }
+    // delete all target rows from the realm
+    RLMObservationTracker tracker(_realm, true);
+    translateErrors([&] { _backingList.delete_all(); });
+}
+
+- (RLMResults *)sortedResultsUsingDescriptors:(NSArray<RLMSortDescriptor *> *)properties {
+    return translateErrors([&] {
+        return [RLMResults resultsWithObjectInfo:*_objectInfo
+                                         results:_backingList.sort(RLMSortDescriptorsToKeypathArray(properties))];
+    });
+}
+
+- (RLMResults *)distinctResultsUsingKeyPaths:(NSArray<NSString *> *)keyPaths {
+    return translateErrors([&] {
+        auto results = [RLMResults resultsWithObjectInfo:*_objectInfo results:_backingList.as_results()];
+        return [results distinctResultsUsingKeyPaths:keyPaths];
+    });
+}
+
+- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate {
+    if (_type != RLMPropertyTypeObject) {
+        @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects");
+    }
+    auto query = RLMPredicateToQuery(predicate, _objectInfo->rlmObjectSchema, _realm.schema, _realm.group);
+    auto results = translateErrors([&] { return _backingList.filter(std::move(query)); });
+    return [RLMResults resultsWithObjectInfo:*_objectInfo results:std::move(results)];
+}
+
+- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate {
+    if (_type != RLMPropertyTypeObject) {
+        @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects");
+    }
+    realm::Query query = RLMPredicateToQuery(predicate, _objectInfo->rlmObjectSchema,
+                                             _realm.schema, _realm.group);
+
+    return translateErrors([&] {
+        return RLMConvertNotFound(_backingList.find(std::move(query)));
+    });
+}
+
+- (NSArray *)objectsAtIndexes:(__unused NSIndexSet *)indexes {
+    // FIXME: this is called by KVO when array changes are made. It's not clear
+    // why, and returning nil seems to work fine.
+    return nil;
+}
+
+- (void)addObserver:(id)observer
+         forKeyPath:(NSString *)keyPath
+            options:(NSKeyValueObservingOptions)options
+            context:(void *)context {
+    RLMEnsureArrayObservationInfo(_observationInfo, keyPath, self, self);
+    [super addObserver:observer forKeyPath:keyPath options:options context:context];
+}
+
+- (realm::TableView)tableView {
+    return translateErrors([&] { return _backingList.get_query(); }).find_all();
+}
+
+- (RLMFastEnumerator *)fastEnumerator {
+    return translateErrors([&] {
+        return [[RLMFastEnumerator alloc] initWithList:_backingList collection:self
+                                             classInfo:*_objectInfo];
+    });
+}
+
+- (BOOL)isFrozen {
+    return _realm.isFrozen;
+}
+
+- (instancetype)freeze {
+    if (self.frozen) {
+        return self;
+    }
+
+    RLMRealm *frozenRealm = [_realm freeze];
+    auto& parentInfo = _ownerInfo->resolve(frozenRealm);
+    return translateRLMResultsErrors([&] {
+        return [[self.class alloc] initWithList:_backingList.freeze(frozenRealm->_realm)
+                                     parentInfo:&parentInfo
+                                       property:parentInfo.rlmObjectSchema[_key]];
+    });
+}
+
+- (instancetype)thaw {
+    if (!self.frozen) {
+        return self;
+    }
+
+    RLMRealm *liveRealm = [_realm thaw];
+    auto& parentInfo = _ownerInfo->resolve(liveRealm);
+    return translateRLMResultsErrors([&] {
+        return [[self.class alloc] initWithList:_backingList.freeze(liveRealm->_realm)
+                                     parentInfo:&parentInfo
+                                       property:parentInfo.rlmObjectSchema[_key]];
+    });
+}
+
+// The compiler complains about the method's argument type not matching due to
+// it not having the generic type attached, but it doesn't seem to be possible
+// to actually include the generic type
+// http://www.openradar.me/radar?id=6135653276319744
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wmismatched-parameter-types"
+- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray *, RLMCollectionChange *, NSError *))block {
+    return RLMAddNotificationBlock(self, block, nil);
+}
+- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray *, RLMCollectionChange *, NSError *))block queue:(dispatch_queue_t)queue {
+    return RLMAddNotificationBlock(self, block, queue);
+}
+#pragma clang diagnostic pop
+
+realm::List& RLMGetBackingCollection(RLMManagedArray *self) {
+    return self->_backingList;
+}
+
+#pragma mark - Thread Confined Protocol Conformance
+
+- (realm::ThreadSafeReference)makeThreadSafeReference {
+    return _backingList;
+}
+
+- (RLMManagedArrayHandoverMetadata *)objectiveCMetadata {
+    RLMManagedArrayHandoverMetadata *metadata = [[RLMManagedArrayHandoverMetadata alloc] init];
+    metadata.parentClassName = _ownerInfo->rlmObjectSchema.className;
+    metadata.key = _key;
+    return metadata;
+}
+
++ (instancetype)objectWithThreadSafeReference:(realm::ThreadSafeReference)reference
+                                     metadata:(RLMManagedArrayHandoverMetadata *)metadata
+                                        realm:(RLMRealm *)realm {
+    auto list = reference.resolve<realm::List>(realm->_realm);
+    if (!list.is_valid()) {
+        return nil;
+    }
+    RLMClassInfo *parentInfo = &realm->_info[metadata.parentClassName];
+    return [[RLMManagedArray alloc] initWithList:std::move(list)
+                                       parentInfo:parentInfo
+                                         property:parentInfo->rlmObjectSchema[metadata.key]];
+}
+
+@end

+ 180 - 0
Example/Pods/Realm/Realm/RLMMigration.mm

@@ -0,0 +1,180 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMMigration_Private.h"
+
+#import "RLMAccessor.h"
+#import "RLMObject_Private.h"
+#import "RLMObject_Private.hpp"
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMObjectStore.h"
+#import "RLMProperty_Private.h"
+#import "RLMRealm_Dynamic.h"
+#import "RLMRealm_Private.hpp"
+#import "RLMResults_Private.hpp"
+#import "RLMSchema_Private.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/object_store.hpp>
+#import <realm/object-store/shared_realm.hpp>
+#import <realm/object-store/schema.hpp>
+#import <realm/table.hpp>
+
+using namespace realm;
+
+// The source realm for a migration has to use a SharedGroup to be able to share
+// the file with the destination realm, but we don't want to let the user call
+// beginWriteTransaction on it as that would make no sense.
+@interface RLMMigrationRealm : RLMRealm
+@end
+
+@implementation RLMMigrationRealm
+- (BOOL)readonly {
+    return YES;
+}
+
+- (void)beginWriteTransaction {
+    @throw RLMException(@"Cannot modify the source Realm in a migration");
+}
+@end
+
+@implementation RLMMigration {
+    realm::Schema *_schema;
+}
+
+- (instancetype)initWithRealm:(RLMRealm *)realm oldRealm:(RLMRealm *)oldRealm schema:(realm::Schema &)schema {
+    self = [super init];
+    if (self) {
+        _realm = realm;
+        _oldRealm = oldRealm;
+        _schema = &schema;
+        object_setClass(_oldRealm, RLMMigrationRealm.class);
+    }
+    return self;
+}
+
+- (RLMSchema *)oldSchema {
+    return self.oldRealm.schema;
+}
+
+- (RLMSchema *)newSchema {
+    return self.realm.schema;
+}
+
+- (void)enumerateObjects:(NSString *)className block:(__attribute__((noescape)) RLMObjectMigrationBlock)block {
+    RLMResults *objects = [_realm.schema schemaForClassName:className] ? [_realm allObjects:className] : nil;
+    RLMResults *oldObjects = [_oldRealm.schema schemaForClassName:className] ? [_oldRealm allObjects:className] : nil;
+
+    // For whatever reason if this is a newly added table we enumerate the
+    // objects in it, while in all other cases we enumerate only the existing
+    // objects. It's unclear how this could be useful, but changing it would
+    // also be a pointless breaking change and it's unlikely to be hurting anyone.
+    if (objects && !oldObjects) {
+        for (RLMObject *object in objects) {
+            @autoreleasepool {
+                block(nil, object);
+            }
+        }
+        return;
+    }
+    
+    // If a table will be deleted it can still be enumerated during the migration
+    // so that data can be saved or transfered to other tables if necessary.
+    if (!objects && oldObjects) {
+        for (RLMObject *oldObject in oldObjects) {
+            @autoreleasepool {
+                block(oldObject, nil);
+            }
+        }
+        return;
+    }
+    
+    if (oldObjects.count == 0 || objects.count == 0) {
+        return;
+    }
+
+    auto& info = _realm->_info[className];
+    for (RLMObject *oldObject in oldObjects) {
+        @autoreleasepool {
+            Obj newObj;
+            try {
+                newObj = info.table()->get_object(oldObject->_row.get_key());
+            }
+            catch (KeyNotFound const&) {
+                continue;
+            }
+            block(oldObject, (id)RLMCreateObjectAccessor(info, std::move(newObj)));
+        }
+    }
+}
+
+- (void)execute:(RLMMigrationBlock)block {
+    @autoreleasepool {
+        // disable all primary keys for migration and use DynamicObject for all types
+        for (RLMObjectSchema *objectSchema in _realm.schema.objectSchema) {
+            objectSchema.accessorClass = RLMDynamicObject.class;
+            objectSchema.primaryKeyProperty.isPrimary = NO;
+        }
+        for (RLMObjectSchema *objectSchema in _oldRealm.schema.objectSchema) {
+            objectSchema.accessorClass = RLMDynamicObject.class;
+        }
+
+        block(self, _oldRealm->_realm->schema_version());
+
+        _oldRealm = nil;
+        _realm = nil;
+    }
+}
+
+- (RLMObject *)createObject:(NSString *)className withValue:(id)value {
+    return [_realm createObject:className withValue:value];
+}
+
+- (RLMObject *)createObject:(NSString *)className withObject:(id)object {
+    return [self createObject:className withValue:object];
+}
+
+- (void)deleteObject:(RLMObject *)object {
+    [_realm deleteObject:object];
+}
+
+- (BOOL)deleteDataForClassName:(NSString *)name {
+    if (!name) {
+        return false;
+    }
+
+    TableRef table = ObjectStore::table_for_object_type(_realm.group, name.UTF8String);
+    if (!table) {
+        return false;
+    }
+    if ([_realm.schema schemaForClassName:name]) {
+        table->clear();
+    }
+    else {
+        _realm.group.remove_table(table->get_key());
+    }
+
+    return true;
+}
+
+- (void)renamePropertyForClass:(NSString *)className oldName:(NSString *)oldName newName:(NSString *)newName {
+    realm::ObjectStore::rename_property(_realm.group, *_schema, className.UTF8String,
+                                        oldName.UTF8String, newName.UTF8String);
+}
+
+@end

+ 67 - 0
Example/Pods/Realm/Realm/RLMMongoClient.mm

@@ -0,0 +1,67 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMMongoClient_Private.hpp"
+
+#import "RLMMongoDatabase_Private.hpp"
+#import "RLMMongoCollection_Private.hpp"
+#import "RLMApp_Private.hpp"
+
+#import <realm/object-store/sync/mongo_client.hpp>
+#import <realm/object-store/sync/mongo_database.hpp>
+#import <realm/util/optional.hpp>
+
+@implementation RLMMongoClient
+
+- (instancetype)initWithUser:(RLMUser *)user serviceName:(NSString *)serviceName {
+    if (self = [super init]) {
+        _user = user;
+        _name = serviceName;
+    }
+    return self;
+}
+
+- (RLMMongoDatabase *)databaseWithName:(NSString *)name {
+    return [[RLMMongoDatabase alloc] initWithUser:self.user
+                                      serviceName:self.name
+                                     databaseName:name];
+}
+
+@end
+
+@implementation RLMMongoDatabase
+
+- (instancetype)initWithUser:(RLMUser *)user
+                 serviceName:(NSString *)serviceName
+                databaseName:(NSString *)databaseName {
+    if (self = [super init]) {
+        _user = user;
+        _serviceName = serviceName;
+        _name = databaseName;
+    }
+    return self;
+}
+
+- (RLMMongoCollection *)collectionWithName:(NSString *)name {
+    return [[RLMMongoCollection alloc] initWithUser:self.user
+                                       serviceName:self.serviceName
+                                      databaseName:self.name
+                                    collectionName:name];
+}
+
+@end

+ 419 - 0
Example/Pods/Realm/Realm/RLMMongoCollection.mm

@@ -0,0 +1,419 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMMongoCollection_Private.hpp"
+
+#import "RLMApp_Private.hpp"
+#import "RLMBSON_Private.hpp"
+#import "RLMFindOneAndModifyOptions_Private.hpp"
+#import "RLMFindOptions_Private.hpp"
+#import "RLMNetworkTransport_Private.hpp"
+#import "RLMUpdateResult_Private.hpp"
+#import "RLMUser_Private.hpp"
+
+#import <realm/object-store/sync/mongo_client.hpp>
+#import <realm/object-store/sync/mongo_collection.hpp>
+#import <realm/object-store/sync/mongo_database.hpp>
+
+@implementation RLMChangeStream {
+    realm::app::WatchStream _watchStream;
+    id<RLMChangeEventDelegate> _subscriber;
+    __weak NSURLSession *_session;
+    _Nonnull dispatch_queue_t _queue;
+}
+
+- (instancetype)initWithChangeEventSubscriber:(id<RLMChangeEventDelegate>)subscriber
+                                delegateQueue:(nullable dispatch_queue_t)queue {
+    if (self = [super init]) {
+        _subscriber = subscriber;
+        _queue = queue ?: dispatch_get_main_queue();
+        return self;
+    }
+    return nil;
+}
+
+- (void)didCloseWithError:(NSError *)error {
+    dispatch_async(_queue, ^{
+        [_subscriber changeStreamDidCloseWithError:error];
+    });
+}
+
+- (void)didOpen {
+    dispatch_async(_queue, ^{
+        [_subscriber changeStreamDidOpen:self];
+    });
+}
+
+- (void)didReceiveError:(nonnull NSError *)error {
+    dispatch_async(_queue, ^{
+        [_subscriber changeStreamDidReceiveError:error];
+    });
+}
+
+- (void)didReceiveEvent:(nonnull NSData *)event {
+    std::string_view str = [[NSString alloc] initWithData:event encoding:NSUTF8StringEncoding].UTF8String;
+    if (!str.empty() && _watchStream.state() == realm::app::WatchStream::State::NEED_DATA) {
+        _watchStream.feed_buffer(str);
+    }
+
+    while (_watchStream.state() == realm::app::WatchStream::State::HAVE_EVENT) {
+        id<RLMBSON> event = RLMConvertBsonToRLMBSON(_watchStream.next_event());
+        dispatch_async(_queue, ^{
+            [_subscriber changeStreamDidReceiveChangeEvent:event];
+        });
+    }
+
+    if (_watchStream.state() == realm::app::WatchStream::State::HAVE_ERROR) {
+        [self didReceiveError:RLMAppErrorToNSError(_watchStream.error())];
+    }
+}
+
+- (void)attachURLSession:(NSURLSession *)urlSession {
+    _session = urlSession;
+}
+
+- (void)close {
+    [_session invalidateAndCancel];
+}
+
+@end
+
+@implementation RLMMongoCollection
+
+static realm::bson::BsonDocument toBsonDocument(id<RLMBSON> bson) {
+    return realm::bson::BsonDocument(RLMConvertRLMBSONToBson(bson));
+}
+static realm::bson::BsonArray toBsonArray(id<RLMBSON> bson) {
+    return realm::bson::BsonArray(RLMConvertRLMBSONToBson(bson));
+}
+
+- (instancetype)initWithUser:(RLMUser *)user
+                 serviceName:(NSString *)serviceName
+                databaseName:(NSString *)databaseName
+              collectionName:(NSString *)collectionName {
+    if (self = [super init]) {
+        _user = user;
+        _serviceName = serviceName;
+        _databaseName = databaseName;
+        _name = collectionName;
+    }
+    return self;
+}
+
+- (realm::app::MongoCollection)collection:(NSString *)name {
+    return _user._syncUser->mongo_client(self.serviceName.UTF8String)
+        .db(self.databaseName.UTF8String).collection(name.UTF8String);
+}
+
+- (realm::app::MongoCollection)collection {
+    return [self collection:self.name];
+}
+
+- (void)findWhere:(NSDictionary<NSString *, id<RLMBSON>> *)document
+          options:(RLMFindOptions *)options
+       completion:(RLMMongoFindBlock)completion {
+    self.collection.find(toBsonDocument(document), [options _findOptions],
+                         [completion](realm::util::Optional<realm::bson::BsonArray> documents,
+                                      realm::util::Optional<realm::app::AppError> error) {
+        if (error) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+        completion((NSArray<NSDictionary<NSString *, id<RLMBSON>> *> *)RLMConvertBsonToRLMBSON(*documents), nil);
+    });
+}
+
+- (void)findWhere:(NSDictionary<NSString *, id<RLMBSON>> *)document
+       completion:(RLMMongoFindBlock)completion {
+    [self findWhere:document options:[[RLMFindOptions alloc] init] completion:completion];
+}
+
+- (void)findOneDocumentWhere:(NSDictionary<NSString *, id<RLMBSON>> *)document
+                     options:(RLMFindOptions *)options
+                  completion:(RLMMongoFindOneBlock)completion {
+    self.collection.find_one(toBsonDocument(document), [options _findOptions],
+                             [completion](realm::util::Optional<realm::bson::BsonDocument> document,
+                                          realm::util::Optional<realm::app::AppError> error) {
+        if (error) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+        completion((NSDictionary<NSString *, id<RLMBSON>> *)RLMConvertBsonToRLMBSON(*document), nil);
+    });
+}
+
+- (void)findOneDocumentWhere:(NSDictionary<NSString *, id<RLMBSON>> *)document
+                  completion:(RLMMongoFindOneBlock)completion {
+    [self findOneDocumentWhere:document options:[[RLMFindOptions alloc] init] completion:completion];
+}
+
+- (void)insertOneDocument:(NSDictionary<NSString *, id<RLMBSON>> *)document
+               completion:(RLMMongoInsertBlock)completion {
+    self.collection.insert_one(toBsonDocument(document),
+                               [completion](realm::util::Optional<realm::bson::Bson> objectId,
+                                            realm::util::Optional<realm::app::AppError> error) {
+        if (error) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+        completion(RLMConvertBsonToRLMBSON(*objectId), nil);
+    });
+}
+
+- (void)insertManyDocuments:(NSArray<NSDictionary<NSString *, id<RLMBSON>> *> *)documents
+                 completion:(RLMMongoInsertManyBlock)completion {
+    self.collection.insert_many(toBsonArray(documents),
+                                [completion](std::vector<realm::bson::Bson> insertedIds,
+                                             realm::util::Optional<realm::app::AppError> error) {
+        if (error) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+        NSMutableArray *insertedArr = [[NSMutableArray alloc] initWithCapacity:insertedIds.size()];
+        for (auto& objectId : insertedIds) {
+            [insertedArr addObject:RLMConvertBsonToRLMBSON(objectId)];
+        }
+        completion(insertedArr, nil);
+    });
+}
+
+- (void)aggregateWithPipeline:(NSArray<NSDictionary<NSString *, id<RLMBSON>> *> *)pipeline
+                   completion:(RLMMongoFindBlock)completion {
+    self.collection.aggregate(toBsonArray(pipeline),
+                              [completion](realm::util::Optional<realm::bson::BsonArray> documents,
+                                           realm::util::Optional<realm::app::AppError> error) {
+        if (error) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+        completion((NSArray<id> *)RLMConvertBsonToRLMBSON(*documents), nil);
+    });
+}
+
+- (void)countWhere:(NSDictionary<NSString *, id<RLMBSON>> *)document
+             limit:(NSInteger)limit
+        completion:(RLMMongoCountBlock)completion {
+    self.collection.count(toBsonDocument(document), limit,
+                          [completion](uint64_t count,
+                                       realm::util::Optional<realm::app::AppError> error) {
+        if (error) {
+            return completion(0, RLMAppErrorToNSError(*error));
+        }
+        completion(static_cast<NSInteger>(count), nil);
+    });
+}
+
+- (void)countWhere:(NSDictionary<NSString *, id<RLMBSON>> *)document
+        completion:(RLMMongoCountBlock)completion {
+    [self countWhere:document limit:0 completion:completion];
+}
+
+- (void)deleteOneDocumentWhere:(NSDictionary<NSString *, id<RLMBSON>> *)document
+                    completion:(RLMMongoCountBlock)completion {
+    self.collection.delete_one(toBsonDocument(document),
+                               [completion](uint64_t count,
+                                            realm::util::Optional<realm::app::AppError> error) {
+        if (error) {
+            return completion(0, RLMAppErrorToNSError(*error));
+        }
+        completion(static_cast<NSInteger>(count), nil);
+    });
+}
+
+- (void)deleteManyDocumentsWhere:(NSDictionary<NSString *, id<RLMBSON>> *)document
+                      completion:(RLMMongoCountBlock)completion {
+    self.collection.delete_many(toBsonDocument(document),
+                                [completion](uint64_t count,
+                                             realm::util::Optional<realm::app::AppError> error) {
+        if (error) {
+            return completion(0, RLMAppErrorToNSError(*error));
+        }
+        completion(static_cast<NSInteger>(count), nil);
+    });
+}
+
+- (void)updateOneDocumentWhere:(NSDictionary<NSString *, id<RLMBSON>> *)filterDocument
+                updateDocument:(NSDictionary<NSString *, id<RLMBSON>> *)updateDocument
+                        upsert:(BOOL)upsert
+                    completion:(RLMMongoUpdateBlock)completion {
+    self.collection.update_one(toBsonDocument(filterDocument), toBsonDocument(updateDocument),
+                               upsert,
+                               [completion](realm::app::MongoCollection::UpdateResult result,
+                                            realm::util::Optional<realm::app::AppError> error) {
+        if (error) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+        completion([[RLMUpdateResult alloc] initWithUpdateResult:result], nil);
+    });
+}
+
+- (void)updateOneDocumentWhere:(NSDictionary<NSString *, id<RLMBSON>> *)filterDocument
+                updateDocument:(NSDictionary<NSString *, id<RLMBSON>> *)updateDocument
+                    completion:(RLMMongoUpdateBlock)completion {
+    [self updateOneDocumentWhere:filterDocument
+                  updateDocument:updateDocument
+                          upsert:NO
+                      completion:completion];
+}
+
+- (void)updateManyDocumentsWhere:(NSDictionary<NSString *, id<RLMBSON>> *)filterDocument
+                  updateDocument:(NSDictionary<NSString *, id<RLMBSON>> *)updateDocument
+                          upsert:(BOOL)upsert
+                      completion:(RLMMongoUpdateBlock)completion {
+    self.collection.update_many(toBsonDocument(filterDocument), toBsonDocument(updateDocument),
+                                upsert,
+                                [completion](realm::app::MongoCollection::UpdateResult result,
+                                             realm::util::Optional<realm::app::AppError> error) {
+        if (error) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+        completion([[RLMUpdateResult alloc] initWithUpdateResult:result], nil);
+    });
+}
+
+- (void)updateManyDocumentsWhere:(NSDictionary<NSString *, id<RLMBSON>> *)filterDocument
+                  updateDocument:(NSDictionary<NSString *, id<RLMBSON>> *)updateDocument
+                      completion:(RLMMongoUpdateBlock)completion {
+    [self updateManyDocumentsWhere:filterDocument
+                    updateDocument:updateDocument
+                            upsert:NO
+                        completion:completion];
+}
+
+- (void)findOneAndUpdateWhere:(NSDictionary<NSString *, id<RLMBSON>> *)filterDocument
+               updateDocument:(NSDictionary<NSString *, id<RLMBSON>> *)updateDocument
+                      options:(RLMFindOneAndModifyOptions *)options
+                   completion:(RLMMongoFindOneBlock)completion {
+    self.collection.find_one_and_update(toBsonDocument(filterDocument), toBsonDocument(updateDocument),
+                                        [options _findOneAndModifyOptions],
+                                        [completion](realm::util::Optional<realm::bson::BsonDocument> document,
+                                                     realm::util::Optional<realm::app::AppError> error) {
+        if (error) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+
+        return completion((NSDictionary *)RLMConvertBsonDocumentToRLMBSON(document), nil);
+    });
+}
+
+- (void)findOneAndUpdateWhere:(NSDictionary<NSString *, id<RLMBSON>> *)filterDocument
+               updateDocument:(NSDictionary<NSString *, id<RLMBSON>> *)updateDocument
+                   completion:(RLMMongoFindOneBlock)completion {
+    [self findOneAndUpdateWhere:filterDocument
+                 updateDocument:updateDocument
+                        options:[[RLMFindOneAndModifyOptions alloc] init]
+                     completion:completion];
+}
+
+- (void)findOneAndReplaceWhere:(NSDictionary<NSString *, id<RLMBSON>> *)filterDocument
+           replacementDocument:(NSDictionary<NSString *, id<RLMBSON>> *)replacementDocument
+                       options:(RLMFindOneAndModifyOptions *)options
+                    completion:(RLMMongoFindOneBlock)completion {
+    self.collection.find_one_and_replace(toBsonDocument(filterDocument), toBsonDocument(replacementDocument),
+                                         [options _findOneAndModifyOptions],
+                                         [completion](realm::util::Optional<realm::bson::BsonDocument> document,
+                                                      realm::util::Optional<realm::app::AppError> error) {
+        if (error) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+
+        return completion((NSDictionary *)RLMConvertBsonDocumentToRLMBSON(document), nil);
+    });
+}
+
+- (void)findOneAndReplaceWhere:(NSDictionary<NSString *, id<RLMBSON>> *)filterDocument
+           replacementDocument:(NSDictionary<NSString *, id<RLMBSON>> *)replacementDocument
+                    completion:(RLMMongoFindOneBlock)completion {
+    [self findOneAndReplaceWhere:filterDocument
+             replacementDocument:replacementDocument
+                         options:[[RLMFindOneAndModifyOptions alloc] init]
+                      completion:completion];
+}
+
+- (void)findOneAndDeleteWhere:(NSDictionary<NSString *, id<RLMBSON>> *)filterDocument
+                      options:(RLMFindOneAndModifyOptions *)options
+                   completion:(RLMMongoDeleteBlock)completion {
+    self.collection.find_one_and_delete(toBsonDocument(filterDocument),
+                                        [options _findOneAndModifyOptions],
+                                        [completion](realm::util::Optional<realm::bson::BsonDocument> document,
+                                                     realm::util::Optional<realm::app::AppError> error) {
+        if (error) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+
+        return completion((NSDictionary *)RLMConvertBsonDocumentToRLMBSON(document), nil);
+    });
+}
+
+- (void)findOneAndDeleteWhere:(NSDictionary<NSString *, id<RLMBSON>> *)filterDocument
+                   completion:(RLMMongoDeleteBlock)completion {
+    [self findOneAndDeleteWhere:filterDocument
+                        options:[[RLMFindOneAndModifyOptions alloc] init]
+                     completion:completion];
+}
+
+- (RLMChangeStream *)watchWithDelegate:(id<RLMChangeEventDelegate>)delegate
+                         delegateQueue:(nullable dispatch_queue_t)delegateQueue {
+    return [self watchWithMatchFilter:nil
+                             idFilter:nil
+                             delegate:delegate
+                        delegateQueue:delegateQueue];
+}
+
+- (RLMChangeStream *)watchWithFilterIds:(NSArray<RLMObjectId *> *)filterIds
+                               delegate:(id<RLMChangeEventDelegate>)delegate
+                          delegateQueue:(nullable dispatch_queue_t)delegateQueue {
+    return [self watchWithMatchFilter:nil
+                             idFilter:filterIds
+                             delegate:delegate
+                        delegateQueue:delegateQueue];
+}
+
+- (RLMChangeStream *)watchWithMatchFilter:(NSDictionary<NSString *, id<RLMBSON>> *)matchFilter
+                                 delegate:(id<RLMChangeEventDelegate>)delegate
+                            delegateQueue:(nullable dispatch_queue_t)delegateQueue {
+    return [self watchWithMatchFilter:matchFilter
+                             idFilter:nil
+                             delegate:delegate
+                        delegateQueue:delegateQueue];
+}
+
+- (RLMChangeStream *)watchWithMatchFilter:(nullable id<RLMBSON>)matchFilter
+                                 idFilter:(nullable id<RLMBSON>)idFilter
+                                 delegate:(id<RLMChangeEventDelegate>)delegate
+                            delegateQueue:(nullable dispatch_queue_t)queue {
+    realm::bson::BsonDocument baseArgs = {
+        {"database", self.databaseName.UTF8String},
+        {"collection", self.name.UTF8String}
+    };
+
+    if (matchFilter) {
+        baseArgs["filter"] = RLMConvertRLMBSONToBson(matchFilter);
+    }
+    if (idFilter) {
+        baseArgs["ids"] = RLMConvertRLMBSONToBson(idFilter);
+    }
+    auto args = realm::bson::BsonArray{baseArgs};
+    auto app = self.user.app._realmApp;
+    auto request = app->make_streaming_request(app->current_user(), "watch", args,
+                                               realm::util::Optional<std::string>(self.serviceName.UTF8String));
+    RLMChangeStream *changeStream = [[RLMChangeStream alloc] initWithChangeEventSubscriber:delegate delegateQueue:queue];
+    RLMNetworkTransport *transport = self.user.app.configuration.transport;
+    RLMRequest *rlmRequest = [transport RLMRequestFromRequest:request];
+    NSURLSession *watchSession = [transport doStreamRequest:rlmRequest
+                                            eventSubscriber:changeStream];
+    [changeStream attachURLSession:watchSession];
+    return changeStream;
+}
+
+@end

+ 229 - 0
Example/Pods/Realm/Realm/RLMNetworkTransport.mm

@@ -0,0 +1,229 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMNetworkTransport_Private.hpp"
+
+#import "RLMApp.h"
+#import "RLMRealmConfiguration.h"
+#import "RLMSyncUtil_Private.hpp"
+#import "RLMSyncManager_Private.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/sync/generic_network_transport.hpp>
+#import <realm/util/scope_exit.hpp>
+
+using namespace realm;
+
+static_assert((int)RLMHTTPMethodGET        == (int)app::HttpMethod::get);
+static_assert((int)RLMHTTPMethodPOST       == (int)app::HttpMethod::post);
+static_assert((int)RLMHTTPMethodPUT        == (int)app::HttpMethod::put);
+static_assert((int)RLMHTTPMethodPATCH      == (int)app::HttpMethod::patch);
+static_assert((int)RLMHTTPMethodDELETE     == (int)app::HttpMethod::del);
+
+#pragma mark RLMSessionDelegate
+
+@interface RLMSessionDelegate <NSURLSessionDelegate> : NSObject
++ (instancetype)delegateWithCompletion:(RLMNetworkTransportCompletionBlock)completion;
+@end
+
+NSString * const RLMHTTPMethodToNSString[] = {
+    [RLMHTTPMethodGET] = @"GET",
+    [RLMHTTPMethodPOST] = @"POST",
+    [RLMHTTPMethodPUT] = @"PUT",
+    [RLMHTTPMethodPATCH] = @"PATCH",
+    [RLMHTTPMethodDELETE] = @"DELETE"
+};
+
+@implementation RLMRequest
+@end
+
+@implementation RLMResponse
+@end
+
+@interface RLMEventSessionDelegate <NSURLSessionDelegate> : NSObject
++ (instancetype)delegateWithEventSubscriber:(RLMEventSubscriber *)subscriber;
+@end;
+
+@implementation RLMNetworkTransport
+
+- (void)sendRequestToServer:(RLMRequest *) request
+                 completion:(RLMNetworkTransportCompletionBlock)completionBlock; {
+    // Create the request
+    NSURL *requestURL = [[NSURL alloc] initWithString: request.url];
+    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:requestURL];
+    urlRequest.HTTPMethod = RLMHTTPMethodToNSString[request.method];
+    if (![urlRequest.HTTPMethod isEqualToString:@"GET"]) {
+        urlRequest.HTTPBody = [request.body dataUsingEncoding:NSUTF8StringEncoding];
+    }
+    urlRequest.timeoutInterval = request.timeout;
+
+    for (NSString *key in request.headers) {
+        [urlRequest addValue:request.headers[key] forHTTPHeaderField:key];
+    }
+    id delegate = [RLMSessionDelegate delegateWithCompletion:completionBlock];
+    auto session = [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration
+                                                 delegate:delegate delegateQueue:nil];
+
+    // Add the request to a task and start it
+    [[session dataTaskWithRequest:urlRequest] resume];
+    // Tell the session to destroy itself once it's done with the request
+    [session finishTasksAndInvalidate];
+}
+
+- (NSURLSession *)doStreamRequest:(nonnull RLMRequest *)request
+                  eventSubscriber:(nonnull id<RLMEventDelegate>)subscriber {
+    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
+    sessionConfig.timeoutIntervalForRequest = 30;
+    sessionConfig.timeoutIntervalForResource = INT_MAX;
+    sessionConfig.HTTPAdditionalHeaders = @{
+        @"Content-Type": @"text/event-stream",
+        @"Cache": @"no-cache",
+        @"Accept": @"text/event-stream"
+    };
+    id delegate = [RLMEventSessionDelegate delegateWithEventSubscriber:subscriber];
+    auto session = [NSURLSession sessionWithConfiguration:sessionConfig
+                                                 delegate:delegate
+                                            delegateQueue:nil];
+    NSURL *url = [[NSURL alloc] initWithString:request.url];
+    [[session dataTaskWithURL:url] resume];
+    return session;
+}
+
+- (RLMRequest *)RLMRequestFromRequest:(const realm::app::Request)request {
+    RLMRequest *rlmRequest = [RLMRequest new];
+    NSMutableDictionary<NSString *, NSString*> *headersDict = [NSMutableDictionary new];
+    for(auto &[key, value] : request.headers) {
+        [headersDict setValue:@(value.c_str()) forKey:@(key.c_str())];
+    }
+    rlmRequest.headers = headersDict;
+    rlmRequest.method = static_cast<RLMHTTPMethod>(request.method);
+    rlmRequest.timeout = request.timeout_ms;
+    rlmRequest.url = @(request.url.c_str());
+    rlmRequest.body = @(request.body.c_str());
+    return rlmRequest;
+}
+
+@end
+
+#pragma mark RLMSessionDelegate
+
+@implementation RLMSessionDelegate {
+    NSData *_data;
+    RLMNetworkTransportCompletionBlock _completionBlock;
+}
+
++ (instancetype)delegateWithCompletion:(RLMNetworkTransportCompletionBlock)completion {
+    RLMSessionDelegate *delegate = [RLMSessionDelegate new];
+    delegate->_completionBlock = completion;
+    return delegate;
+}
+
+- (void)URLSession:(__unused NSURLSession *)session
+          dataTask:(__unused NSURLSessionDataTask *)dataTask
+    didReceiveData:(NSData *)data {
+    if (!_data) {
+        _data = data;
+        return;
+    }
+    if (![_data respondsToSelector:@selector(appendData:)]) {
+        _data = [_data mutableCopy];
+    }
+    [(id)_data appendData:data];
+}
+
+- (void)URLSession:(__unused NSURLSession *)session
+              task:(NSURLSessionTask *)task
+didCompleteWithError:(NSError *)error
+{
+    RLMResponse *response = [RLMResponse new];
+    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) task.response;
+    response.headers = httpResponse.allHeaderFields;
+    response.httpStatusCode = httpResponse.statusCode;
+
+    if (error) {
+        response.body = error.localizedDescription;
+        response.customStatusCode = error.code;
+        return _completionBlock(response);
+    }
+
+    response.body = [[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding];
+
+    _completionBlock(response);
+}
+
+@end
+
+@implementation RLMEventSessionDelegate {
+    RLMEventSubscriber *_subscriber;
+    bool _hasOpened;
+}
+
++ (instancetype)delegateWithEventSubscriber:(RLMEventSubscriber *)subscriber {
+    RLMEventSessionDelegate *delegate = [RLMEventSessionDelegate new];
+    delegate->_subscriber = subscriber;
+    return delegate;
+}
+
+- (void)URLSession:(__unused NSURLSession *)session
+          dataTask:(__unused NSURLSessionDataTask *)dataTask
+    didReceiveData:(NSData *)data {
+    if (!_hasOpened) {
+        _hasOpened = true;
+        [_subscriber didOpen];
+    }
+
+    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) dataTask.response;
+    if (httpResponse.statusCode != 200) {
+        NSString *errorStatus = [NSString stringWithFormat:@"URLSession HTTP error code: %ld",
+                                 (long)httpResponse.statusCode];
+        NSError *error = [NSError errorWithDomain:RLMErrorDomain
+                                             code:0
+                                         userInfo:@{NSLocalizedDescriptionKey: errorStatus}];
+        return [_subscriber didCloseWithError:error];
+    }
+    [_subscriber didReceiveEvent:data];
+}
+
+- (void)URLSession:(__unused NSURLSession *)session
+              task:(NSURLSessionTask *)task
+didCompleteWithError:(NSError *)error
+{
+    RLMResponse *response = [RLMResponse new];
+    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) task.response;
+    response.headers = httpResponse.allHeaderFields;
+    response.httpStatusCode = httpResponse.statusCode;
+
+    // -999 indicates that the session was cancelled.
+    if (error && (error.code != -999)) {
+        response.body = [error localizedDescription];
+        return [_subscriber didCloseWithError:error];
+    } else if (error && (error.code == -999)) {
+        return [_subscriber didCloseWithError:nil];
+    }
+
+    if (response.httpStatusCode != 200) {
+        NSString *errorStatus = [NSString stringWithFormat:@"URLSession HTTP error code: %ld",
+                                 (long)httpResponse.statusCode];
+        NSError *error = [NSError errorWithDomain:RLMErrorDomain
+                                             code:0
+                                         userInfo:@{NSLocalizedDescriptionKey: errorStatus}];
+        return [_subscriber didCloseWithError:error];
+    }
+}
+
+@end

+ 242 - 0
Example/Pods/Realm/Realm/RLMObject.mm

@@ -0,0 +1,242 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMObject_Private.hpp"
+
+#import "RLMAccessor.h"
+#import "RLMArray.h"
+#import "RLMCollection_Private.hpp"
+#import "RLMObjectBase_Private.h"
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMObjectStore.h"
+#import "RLMProperty_Private.h"
+#import "RLMQueryUtil.hpp"
+#import "RLMRealm_Private.hpp"
+#import "RLMSchema_Private.h"
+
+#import <realm/object-store/object.hpp>
+
+// We declare things in RLMObject which are actually implemented in RLMObjectBase
+// for documentation's sake, which leads to -Wunimplemented-method warnings.
+// Other alternatives to this would be to disable -Wunimplemented-method for this
+// file (but then we could miss legitimately missing things), or declaring the
+// inherited things in a category (but they currently aren't nicely grouped for
+// that).
+@implementation RLMObject
+
+// synthesized in RLMObjectBase
+@dynamic invalidated, realm, objectSchema;
+
+#pragma mark - Designated Initializers
+
+- (instancetype)init {
+    return [super init];
+}
+
+#pragma mark - Convenience Initializers
+
+- (instancetype)initWithValue:(id)value {
+    if (!(self = [self init])) {
+        return nil;
+    }
+    RLMInitializeWithValue(self, value, RLMSchema.partialPrivateSharedSchema);
+    return self;
+}
+
+#pragma mark - Class-based Object Creation
+
++ (instancetype)createInDefaultRealmWithValue:(id)value {
+    return (RLMObject *)RLMCreateObjectInRealmWithValue([RLMRealm defaultRealm], [self className], value, RLMUpdatePolicyError);
+}
+
++ (instancetype)createInRealm:(RLMRealm *)realm withValue:(id)value {
+    return (RLMObject *)RLMCreateObjectInRealmWithValue(realm, [self className], value, RLMUpdatePolicyError);
+}
+
++ (instancetype)createOrUpdateInDefaultRealmWithValue:(id)value {
+    return [self createOrUpdateInRealm:[RLMRealm defaultRealm] withValue:value];
+}
+
++ (instancetype)createOrUpdateModifiedInDefaultRealmWithValue:(id)value {
+    return [self createOrUpdateModifiedInRealm:[RLMRealm defaultRealm] withValue:value];
+}
+
++ (instancetype)createOrUpdateInRealm:(RLMRealm *)realm withValue:(id)value {
+    RLMVerifyHasPrimaryKey(self);
+    return (RLMObject *)RLMCreateObjectInRealmWithValue(realm, [self className], value, RLMUpdatePolicyUpdateAll);
+}
+
++ (instancetype)createOrUpdateModifiedInRealm:(RLMRealm *)realm withValue:(id)value {
+    RLMVerifyHasPrimaryKey(self);
+    return (RLMObject *)RLMCreateObjectInRealmWithValue(realm, [self className], value, RLMUpdatePolicyUpdateChanged);
+}
+
+#pragma mark - Subscripting
+
+- (id)objectForKeyedSubscript:(NSString *)key {
+    return RLMObjectBaseObjectForKeyedSubscript(self, key);
+}
+
+- (void)setObject:(id)obj forKeyedSubscript:(NSString *)key {
+    RLMObjectBaseSetObjectForKeyedSubscript(self, key, obj);
+}
+
+#pragma mark - Getting & Querying
+
++ (RLMResults *)allObjects {
+    return RLMGetObjects(RLMRealm.defaultRealm, self.className, nil);
+}
+
++ (RLMResults *)allObjectsInRealm:(__unsafe_unretained RLMRealm *const)realm {
+    return RLMGetObjects(realm, self.className, nil);
+}
+
++ (RLMResults *)objectsWhere:(NSString *)predicateFormat, ... {
+    va_list args;
+    va_start(args, predicateFormat);
+    RLMResults *results = [self objectsWhere:predicateFormat args:args];
+    va_end(args);
+    return results;
+}
+
++ (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args {
+    return [self objectsWithPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]];
+}
+
++ (RLMResults *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat, ... {
+    va_list args;
+    va_start(args, predicateFormat);
+    RLMResults *results = [self objectsInRealm:realm where:predicateFormat args:args];
+    va_end(args);
+    return results;
+}
+
++ (RLMResults *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat args:(va_list)args {
+    return [self objectsInRealm:realm withPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]];
+}
+
++ (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate {
+    return RLMGetObjects(RLMRealm.defaultRealm, self.className, predicate);
+}
+
++ (RLMResults *)objectsInRealm:(RLMRealm *)realm withPredicate:(NSPredicate *)predicate {
+    return RLMGetObjects(realm, self.className, predicate);
+}
+
++ (instancetype)objectForPrimaryKey:(id)primaryKey {
+    return RLMGetObject(RLMRealm.defaultRealm, self.className, primaryKey);
+}
+
++ (instancetype)objectInRealm:(RLMRealm *)realm forPrimaryKey:(id)primaryKey {
+    return RLMGetObject(realm, self.className, primaryKey);
+}
+
+#pragma mark - Other Instance Methods
+
+- (BOOL)isEqualToObject:(RLMObject *)object {
+    return [object isKindOfClass:RLMObject.class] && RLMObjectBaseAreEqual(self, object);
+}
+
+- (instancetype)freeze {
+    return RLMObjectFreeze(self);
+}
+
+- (instancetype)thaw {
+    return RLMObjectThaw(self);
+}
+
+- (BOOL)isFrozen {
+    return _realm.isFrozen;
+}
+
+- (RLMNotificationToken *)addNotificationBlock:(RLMObjectChangeBlock)block {
+    return RLMObjectAddNotificationBlock(self, block, nil);
+}
+
+- (RLMNotificationToken *)addNotificationBlock:(RLMObjectChangeBlock)block
+                                         queue:(nonnull dispatch_queue_t)queue {
+    return RLMObjectAddNotificationBlock(self, block, queue);
+}
+
++ (NSString *)className {
+    return [super className];
+}
+
+#pragma mark - Default values for schema definition
+
++ (NSArray *)indexedProperties {
+    return @[];
+}
+
++ (NSDictionary *)linkingObjectsProperties {
+    return @{};
+}
+
++ (NSDictionary *)defaultPropertyValues {
+    return nil;
+}
+
++ (NSString *)primaryKey {
+    return nil;
+}
+
++ (NSArray *)ignoredProperties {
+    return nil;
+}
+
++ (NSArray *)requiredProperties {
+    return @[];
+}
+
++ (bool)_realmIgnoreClass {
+    return false;
+}
+
+@end
+
+@implementation RLMDynamicObject
+
++ (bool)_realmIgnoreClass {
+    return true;
+}
+
++ (BOOL)shouldIncludeInDefaultSchema {
+    return NO;
+}
+
+- (id)valueForUndefinedKey:(NSString *)key {
+    return RLMDynamicGetByName(self, key);
+}
+
+- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
+    RLMDynamicValidatedSet(self, key, value);
+}
+
++ (RLMObjectSchema *)sharedSchema {
+    return nil;
+}
+
+@end
+
+BOOL RLMIsObjectOrSubclass(Class klass) {
+    return RLMIsKindOfClass(klass, RLMObjectBase.class);
+}
+
+BOOL RLMIsObjectSubclass(Class klass) {
+    return RLMIsKindOfClass(class_getSuperclass(class_getSuperclass(klass)), RLMObjectBase.class);
+}

+ 747 - 0
Example/Pods/Realm/Realm/RLMObjectBase.mm

@@ -0,0 +1,747 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMObject_Private.hpp"
+
+#import "RLMAccessor.h"
+#import "RLMArray_Private.hpp"
+#import "RLMDecimal128.h"
+#import "RLMListBase.h"
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMObjectStore.h"
+#import "RLMObservation.hpp"
+#import "RLMOptionalBase.h"
+#import "RLMProperty_Private.h"
+#import "RLMRealm_Private.hpp"
+#import "RLMSchema_Private.h"
+#import "RLMSwiftSupport.h"
+#import "RLMThreadSafeReference_Private.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/object.hpp>
+#import <realm/object-store/object_schema.hpp>
+#import <realm/object-store/shared_realm.hpp>
+
+using namespace realm;
+
+const NSUInteger RLMDescriptionMaxDepth = 5;
+
+
+static bool isManagedAccessorClass(Class cls) {
+    const char *className = class_getName(cls);
+    const char accessorClassPrefix[] = "RLM:Managed";
+    return strncmp(className, accessorClassPrefix, sizeof(accessorClassPrefix) - 1) == 0;
+}
+
+static bool maybeInitObjectSchemaForUnmanaged(RLMObjectBase *obj) {
+    Class cls = obj.class;
+    if (isManagedAccessorClass(cls)) {
+        return false;
+    }
+
+    obj->_objectSchema = [cls sharedSchema];
+    if (!obj->_objectSchema) {
+        return false;
+    }
+
+    // set default values
+    if (!obj->_objectSchema.isSwiftClass) {
+        NSDictionary *dict = RLMDefaultValuesForObjectSchema(obj->_objectSchema);
+        for (NSString *key in dict) {
+            [obj setValue:dict[key] forKey:key];
+        }
+    }
+
+    // set unmanaged accessor class
+    object_setClass(obj, obj->_objectSchema.unmanagedClass);
+    return true;
+}
+
+@interface RLMObjectBase () <RLMThreadConfined, RLMThreadConfined_Private>
+@end
+
+@implementation RLMObjectBase
+// unmanaged init
+- (instancetype)init {
+    if ((self = [super init])) {
+        maybeInitObjectSchemaForUnmanaged(self);
+    }
+    return self;
+}
+
+- (void)dealloc {
+    // This can't be a unique_ptr because associated objects are removed
+    // *after* c++ members are destroyed and dealloc is called, and we need it
+    // to be in a validish state when that happens
+    delete _observationInfo;
+    _observationInfo = nullptr;
+}
+
+static id coerceToObjectType(id obj, Class cls, RLMSchema *schema) {
+    if ([obj isKindOfClass:cls]) {
+        return obj;
+    }
+    id value = [[cls alloc] init];
+    RLMInitializeWithValue(value, obj, schema);
+    return value;
+}
+
+static id validatedObjectForProperty(__unsafe_unretained id const obj,
+                                     __unsafe_unretained RLMObjectSchema *const objectSchema,
+                                     __unsafe_unretained RLMProperty *const prop,
+                                     __unsafe_unretained RLMSchema *const schema) {
+    RLMValidateValueForProperty(obj, objectSchema, prop);
+    if (!obj || obj == NSNull.null) {
+        return nil;
+    }
+    if (prop.type == RLMPropertyTypeObject) {
+        Class objectClass = schema[prop.objectClassName].objectClass;
+        if (prop.array) {
+            NSMutableArray *ret = [[NSMutableArray alloc] init];
+            for (id el in obj) {
+                [ret addObject:coerceToObjectType(el, objectClass, schema)];
+            }
+            return ret;
+        }
+        return coerceToObjectType(obj, objectClass, schema);
+    }
+    else if (prop.type == RLMPropertyTypeDecimal128 && !prop.array) {
+        return [[RLMDecimal128 alloc] initWithValue:obj];
+    }
+    return obj;
+}
+
+void RLMInitializeWithValue(RLMObjectBase *self, id value, RLMSchema *schema) {
+    if (!value || value == NSNull.null) {
+        @throw RLMException(@"Must provide a non-nil value.");
+    }
+
+    RLMObjectSchema *objectSchema = self->_objectSchema;
+    if (!objectSchema) {
+        // Will be nil if we're called during schema init, when we don't want
+        // to actually populate the object anyway
+        return;
+    }
+
+    NSArray *properties = objectSchema.properties;
+    if (NSArray *array = RLMDynamicCast<NSArray>(value)) {
+        if (array.count > properties.count) {
+            @throw RLMException(@"Invalid array input: more values (%llu) than properties (%llu).",
+                                (unsigned long long)array.count, (unsigned long long)properties.count);
+        }
+        NSUInteger i = 0;
+        for (id val in array) {
+            RLMProperty *prop = properties[i++];
+            [self setValue:validatedObjectForProperty(RLMCoerceToNil(val), objectSchema, prop, schema)
+                    forKey:prop.name];
+        }
+    }
+    else {
+        // assume our object is an NSDictionary or an object with kvc properties
+        for (RLMProperty *prop in properties) {
+            id obj = RLMValidatedValueForProperty(value, prop.name, objectSchema.className);
+
+            // don't set unspecified properties
+            if (!obj) {
+                continue;
+            }
+
+            [self setValue:validatedObjectForProperty(RLMCoerceToNil(obj), objectSchema, prop, schema)
+                    forKey:prop.name];
+        }
+    }
+}
+
+id RLMCreateManagedAccessor(Class cls, RLMClassInfo *info) {
+    RLMObjectBase *obj = [[cls alloc] init];
+    obj->_info = info;
+    obj->_realm = info->realm;
+    obj->_objectSchema = info->rlmObjectSchema;
+    return obj;
+}
+
+- (id)valueForKey:(NSString *)key {
+    if (_observationInfo) {
+        return _observationInfo->valueForKey(key);
+    }
+    return [super valueForKey:key];
+}
+
+// Generic Swift properties can't be dynamic, so KVO doesn't work for them by default
+- (id)valueForUndefinedKey:(NSString *)key {
+    RLMProperty *prop = _objectSchema[key];
+    if (Class accessor = prop.swiftAccessor) {
+        return [accessor get:(char *)(__bridge void *)self + ivar_getOffset(prop.swiftIvar)];
+    }
+    if (Ivar ivar = prop.swiftIvar) {
+        return RLMCoerceToNil(object_getIvar(self, ivar));
+    }
+    return [super valueForUndefinedKey:key];
+}
+
+- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
+    value = RLMCoerceToNil(value);
+    RLMProperty *property = _objectSchema[key];
+    if (Ivar ivar = property.swiftIvar) {
+        if (property.array) {
+            value = RLMAsFastEnumeration(value);
+            RLMArray *array = [object_getIvar(self, ivar) _rlmArray];
+            [array removeAllObjects];
+
+            if (value) {
+                [array addObjects:validatedObjectForProperty(value, _objectSchema, property,
+                                                             RLMSchema.partialPrivateSharedSchema)];
+            }
+        }
+        else if (property.optional) {
+            RLMSetOptional(object_getIvar(self, ivar), value);
+        }
+        return;
+    }
+    [super setValue:value forUndefinedKey:key];
+}
+
+// overridden at runtime per-class for performance
++ (NSString *)className {
+    NSString *className = NSStringFromClass(self);
+    if ([RLMSwiftSupport isSwiftClassName:className]) {
+        className = [RLMSwiftSupport demangleClassName:className];
+    }
+    return className;
+}
+
+// overridden at runtime per-class for performance
++ (RLMObjectSchema *)sharedSchema {
+    return [RLMSchema sharedSchemaForClass:self.class];
+}
+
++ (void)initializeLinkedObjectSchemas {
+    for (RLMProperty *prop in self.sharedSchema.properties) {
+        if (prop.type == RLMPropertyTypeObject && !RLMSchema.partialPrivateSharedSchema[prop.objectClassName]) {
+            [[RLMSchema classForString:prop.objectClassName] initializeLinkedObjectSchemas];
+        }
+    }
+}
+
++ (nullable NSArray<RLMProperty *> *)_getProperties {
+    return nil;
+}
+
+- (NSString *)description {
+    if (self.isInvalidated) {
+        return @"[invalid object]";
+    }
+
+    return [self descriptionWithMaxDepth:RLMDescriptionMaxDepth];
+}
+
+- (NSString *)descriptionWithMaxDepth:(NSUInteger)depth {
+    if (depth == 0) {
+        return @"<Maximum depth exceeded>";
+    }
+
+    NSString *baseClassName = _objectSchema.className;
+    NSMutableString *mString = [NSMutableString stringWithFormat:@"%@ {\n", baseClassName];
+
+    for (RLMProperty *property in _objectSchema.properties) {
+        id object = [(id)self objectForKeyedSubscript:property.name];
+        NSString *sub;
+        if ([object respondsToSelector:@selector(descriptionWithMaxDepth:)]) {
+            sub = [object descriptionWithMaxDepth:depth - 1];
+        }
+        else if (property.type == RLMPropertyTypeData) {
+            static NSUInteger maxPrintedDataLength = 24;
+            NSData *data = object;
+            NSUInteger length = data.length;
+            if (length > maxPrintedDataLength) {
+                data = [NSData dataWithBytes:data.bytes length:maxPrintedDataLength];
+            }
+            NSString *dataDescription = [data description];
+            sub = [NSString stringWithFormat:@"<%@ — %lu total bytes>", [dataDescription substringWithRange:NSMakeRange(1, dataDescription.length - 2)], (unsigned long)length];
+        }
+        else {
+            sub = [object description];
+        }
+        [mString appendFormat:@"\t%@ = %@;\n", property.name, [sub stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]];
+    }
+    [mString appendString:@"}"];
+
+    return [NSString stringWithString:mString];
+}
+
+- (RLMRealm *)realm {
+    return _realm;
+}
+
+- (RLMObjectSchema *)objectSchema {
+    return _objectSchema;
+}
+
+- (BOOL)isInvalidated {
+    // if not unmanaged and our accessor has been detached, we have been deleted
+    return self.class == _objectSchema.accessorClass && !_row.is_valid();
+}
+
+- (BOOL)isEqual:(id)object {
+    if (RLMObjectBase *other = RLMDynamicCast<RLMObjectBase>(object)) {
+        if (_objectSchema.primaryKeyProperty || _realm.isFrozen) {
+            return RLMObjectBaseAreEqual(self, other);
+        }
+    }
+    return [super isEqual:object];
+}
+
+- (NSUInteger)hash {
+    if (_objectSchema.primaryKeyProperty) {
+        // If we have a primary key property, that's an immutable value which we
+        // can use as the identity of the object.
+        id primaryProperty = [self valueForKey:_objectSchema.primaryKeyProperty.name];
+
+        // modify the hash of our primary key value to avoid potential (although unlikely) collisions
+        return [primaryProperty hash] ^ 1;
+    }
+    else if (_realm.isFrozen) {
+        // The object key can never change for frozen objects, so that's usable
+        // for objects without primary keys
+        return static_cast<NSUInteger>(_row.get_key().value);
+    }
+    else {
+        // Non-frozen objects without primary keys don't have any immutable
+        // concept of identity that we can hash so we have to fall back to
+        // pointer equality
+        return [super hash];
+    }
+}
+
++ (BOOL)shouldIncludeInDefaultSchema {
+    return RLMIsObjectSubclass(self);
+}
+
++ (NSString *)primaryKey {
+    return nil;
+}
+
++ (NSString *)_realmObjectName {
+    return nil;
+}
+
++ (NSDictionary *)_realmColumnNames {
+    return nil;
+}
+
++ (bool)_realmIgnoreClass {
+    return false;
+}
+
++ (bool)isEmbedded {
+    return false;
+}
+
+- (id)mutableArrayValueForKey:(NSString *)key {
+    id obj = [self valueForKey:key];
+    if ([obj isKindOfClass:[RLMArray class]]) {
+        return obj;
+    }
+    return [super mutableArrayValueForKey:key];
+}
+
+- (void)addObserver:(id)observer
+         forKeyPath:(NSString *)keyPath
+            options:(NSKeyValueObservingOptions)options
+            context:(void *)context {
+    if (!_observationInfo) {
+        _observationInfo = new RLMObservationInfo(self);
+    }
+    _observationInfo->recordObserver(_row, _info, _objectSchema, keyPath);
+
+    [super addObserver:observer forKeyPath:keyPath options:options context:context];
+}
+
+- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath {
+    [super removeObserver:observer forKeyPath:keyPath];
+    if (_observationInfo)
+        _observationInfo->removeObserver();
+}
+
++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
+    if (isManagedAccessorClass(self) && [class_getSuperclass(self.class) sharedSchema][key]) {
+        return NO;
+    }
+
+    return [super automaticallyNotifiesObserversForKey:key];
+}
+
+#pragma mark - Thread Confined Protocol Conformance
+
+- (realm::ThreadSafeReference)makeThreadSafeReference {
+    return Object(_realm->_realm, *_info->objectSchema, _row);
+}
+
+- (id)objectiveCMetadata {
+    return nil;
+}
+
++ (instancetype)objectWithThreadSafeReference:(realm::ThreadSafeReference)reference
+                                     metadata:(__unused id)metadata
+                                        realm:(RLMRealm *)realm {
+    Object object = reference.resolve<Object>(realm->_realm);
+    if (!object.is_valid()) {
+        return nil;
+    }
+    NSString *objectClassName = @(object.get_object_schema().name.c_str());
+    return RLMCreateObjectAccessor(realm->_info[objectClassName], object.obj());
+}
+
+@end
+
+RLMRealm *RLMObjectBaseRealm(__unsafe_unretained RLMObjectBase *object) {
+    return object ? object->_realm : nil;
+}
+
+RLMObjectSchema *RLMObjectBaseObjectSchema(__unsafe_unretained RLMObjectBase *object) {
+    return object ? object->_objectSchema : nil;
+}
+
+id RLMObjectBaseObjectForKeyedSubscript(RLMObjectBase *object, NSString *key) {
+    if (!object) {
+        return nil;
+    }
+
+    if (object->_realm) {
+        return RLMDynamicGetByName(object, key);
+    }
+    else {
+        return [object valueForKey:key];
+    }
+}
+
+void RLMObjectBaseSetObjectForKeyedSubscript(RLMObjectBase *object, NSString *key, id obj) {
+    if (!object) {
+        return;
+    }
+
+    if (object->_realm || object.class == object->_objectSchema.accessorClass) {
+        RLMDynamicValidatedSet(object, key, obj);
+    }
+    else {
+        [object setValue:obj forKey:key];
+    }
+}
+
+
+BOOL RLMObjectBaseAreEqual(RLMObjectBase *o1, RLMObjectBase *o2) {
+    // if not the correct types throw
+    if ((o1 && ![o1 isKindOfClass:RLMObjectBase.class]) || (o2 && ![o2 isKindOfClass:RLMObjectBase.class])) {
+        @throw RLMException(@"Can only compare objects of class RLMObjectBase");
+    }
+    // if identical object (or both are nil)
+    if (o1 == o2) {
+        return YES;
+    }
+    // if one is nil
+    if (o1 == nil || o2 == nil) {
+        return NO;
+    }
+    // if not in realm or differing realms
+    if (o1->_realm == nil || o1->_realm != o2->_realm) {
+        return NO;
+    }
+    // if either are detached
+    if (!o1->_row.is_valid() || !o2->_row.is_valid()) {
+        return NO;
+    }
+    // if table and index are the same
+    return o1->_row.get_table() == o2->_row.get_table()
+        && o1->_row.get_key() == o2->_row.get_key();
+}
+
+id RLMObjectFreeze(RLMObjectBase *obj) {
+    if (!obj->_realm && !obj.isInvalidated) {
+        @throw RLMException(@"Unmanaged objects cannot be frozen.");
+    }
+    RLMVerifyAttached(obj);
+    if (obj->_realm.frozen) {
+        return obj;
+    }
+    RLMRealm *frozenRealm = [obj->_realm freeze];
+    RLMObjectBase *frozen = RLMCreateManagedAccessor(obj.class, &frozenRealm->_info[obj->_info->rlmObjectSchema.className]);
+    frozen->_row = frozenRealm->_realm->import_copy_of(obj->_row);
+    if (!frozen->_row.is_valid()) {
+        @throw RLMException(@"Cannot freeze an object in the same write transaction as it was created in.");
+    }
+    RLMInitializeSwiftAccessorGenerics(frozen);
+    return frozen;
+}
+
+id RLMObjectThaw(RLMObjectBase *obj) {
+    if (!obj->_realm && !obj.isInvalidated) {
+        @throw RLMException(@"Unmanaged objects cannot be frozen.");
+    }
+    RLMVerifyAttached(obj);
+    if (!obj->_realm.frozen) {
+        return obj;
+    }
+    RLMRealm *liveRealm = [obj->_realm thaw];
+    RLMObjectBase *live = RLMCreateManagedAccessor(obj.class, &liveRealm->_info[obj->_info->rlmObjectSchema.className]);
+    live->_row = liveRealm->_realm->import_copy_of(obj->_row);
+    if (!live->_row.is_valid()) {
+        return nil;
+    }
+    RLMInitializeSwiftAccessorGenerics(live);
+    return live;
+}
+
+id RLMValidatedValueForProperty(id object, NSString *key, NSString *className) {
+    @try {
+        return [object valueForKey:key];
+    }
+    @catch (NSException *e) {
+        if ([e.name isEqualToString:NSUndefinedKeyException]) {
+            @throw RLMException(@"Invalid value '%@' to initialize object of type '%@': missing key '%@'",
+                                object, className, key);
+        }
+        @throw;
+    }
+}
+
+#pragma mark - Notifications
+
+namespace {
+struct ObjectChangeCallbackWrapper {
+    RLMObjectNotificationCallback block;
+    RLMObjectBase *object;
+
+    NSArray<NSString *> *propertyNames = nil;
+    NSArray *oldValues = nil;
+    bool deleted = false;
+
+    void populateProperties(realm::CollectionChangeSet const& c) {
+        if (propertyNames) {
+            return;
+        }
+        if (!c.deletions.empty()) {
+            deleted = true;
+            return;
+        }
+        if (c.columns.empty()) {
+            return;
+        }
+
+        auto properties = [NSMutableArray new];
+        for (RLMProperty *property in object->_info->rlmObjectSchema.properties) {
+            if (c.columns.count(object->_info->tableColumn(property).value)) {
+                [properties addObject:property.name];
+            }
+        }
+        if (properties.count) {
+            propertyNames = properties;
+        }
+    }
+
+    NSArray *readValues(realm::CollectionChangeSet const& c) {
+        if (c.empty()) {
+            return nil;
+        }
+        populateProperties(c);
+        if (!propertyNames) {
+            return nil;
+        }
+
+        auto values = [NSMutableArray arrayWithCapacity:propertyNames.count];
+        for (NSString *name in propertyNames) {
+            id value = [object valueForKey:name];
+            if (!value || [value isKindOfClass:[RLMArray class]]) {
+                [values addObject:NSNull.null];
+            }
+            else {
+                [values addObject:value];
+            }
+        }
+        return values;
+    }
+
+    void before(realm::CollectionChangeSet const& c) {
+        @autoreleasepool {
+            oldValues = readValues(c);
+        }
+    }
+
+    void after(realm::CollectionChangeSet const& c) {
+        @autoreleasepool {
+            auto newValues = readValues(c);
+            if (deleted) {
+                block(nil, nil, nil, nil, nil);
+            }
+            else if (newValues) {
+                block(object, propertyNames, oldValues, newValues, nil);
+            }
+            propertyNames = nil;
+            oldValues = nil;
+        }
+    }
+
+    void error(std::exception_ptr err) {
+        @autoreleasepool {
+            try {
+                rethrow_exception(err);
+            }
+            catch (...) {
+                NSError *error = nil;
+                RLMRealmTranslateException(&error);
+                block(nil, nil, nil, nil, error);
+            }
+        }
+    }
+};
+} // anonymous namespace
+
+@interface RLMPropertyChange ()
+@property (nonatomic, readwrite, strong) NSString *name;
+@property (nonatomic, readwrite, strong, nullable) id previousValue;
+@property (nonatomic, readwrite, strong, nullable) id value;
+@end
+
+@implementation RLMPropertyChange
+- (NSString *)description {
+    return [NSString stringWithFormat:@"<RLMPropertyChange: %p> %@ %@ -> %@",
+            (__bridge void *)self, _name, _previousValue, _value];
+}
+@end
+
+@interface RLMObjectNotificationToken : RLMNotificationToken
+@end
+
+@implementation RLMObjectNotificationToken {
+    std::mutex _mutex;
+    __unsafe_unretained RLMRealm *_realm;
+    realm::Object _object;
+    realm::NotificationToken _token;
+}
+
+- (RLMRealm *)realm {
+    return _realm;
+}
+
+- (void)suppressNextNotification {
+    std::lock_guard<std::mutex> lock(_mutex);
+    if (_object.is_valid()) {
+        _token.suppress_next();
+    }
+}
+
+- (void)invalidate {
+    std::lock_guard<std::mutex> lock(_mutex);
+    _realm = nil;
+    _token = {};
+    _object = {};
+}
+
+- (void)addNotificationBlock:(RLMObjectNotificationCallback)block
+         threadSafeReference:(RLMThreadSafeReference *)tsr
+                      config:(RLMRealmConfiguration *)config
+                       queue:(dispatch_queue_t)queue {
+    std::lock_guard<std::mutex> lock(_mutex);
+    if (!_realm) {
+        // Token was invalidated before we got this far
+        return;
+    }
+
+    NSError *error;
+    RLMRealm *realm = _realm = [RLMRealm realmWithConfiguration:config queue:queue error:&error];
+    if (!realm) {
+        block(nil, nil, nil, nil, error);
+        return;
+    }
+    RLMObjectBase *obj = [realm resolveThreadSafeReference:tsr];
+
+    _object = realm::Object(obj->_realm->_realm, *obj->_info->objectSchema, obj->_row);
+    _token = _object.add_notification_callback(ObjectChangeCallbackWrapper{block, obj});
+}
+
+- (void)addNotificationBlock:(RLMObjectNotificationCallback)block object:(RLMObjectBase *)obj {
+    _object = realm::Object(obj->_realm->_realm, *obj->_info->objectSchema, obj->_row);
+    _realm = obj->_realm;
+    _token = _object.add_notification_callback(ObjectChangeCallbackWrapper{block, obj});
+}
+
+RLMNotificationToken *RLMObjectBaseAddNotificationBlock(RLMObjectBase *obj, dispatch_queue_t queue,
+                                                        RLMObjectNotificationCallback block) {
+    if (!obj->_realm) {
+        @throw RLMException(@"Only objects which are managed by a Realm support change notifications");
+    }
+
+    if (!queue) {
+        [obj->_realm verifyNotificationsAreSupported:true];
+        auto token = [[RLMObjectNotificationToken alloc] init];
+        token->_realm = obj->_realm;
+        [token addNotificationBlock:block object:obj];
+        return token;
+    }
+
+    RLMThreadSafeReference *tsr = [RLMThreadSafeReference referenceWithThreadConfined:(id)obj];
+    auto token = [[RLMObjectNotificationToken alloc] init];
+    token->_realm = obj->_realm;
+    RLMRealmConfiguration *config = obj->_realm.configuration;
+    dispatch_async(queue, ^{
+        @autoreleasepool {
+            [token addNotificationBlock:block threadSafeReference:tsr config:config queue:queue];
+        }
+    });
+    return token;
+}
+
+@end
+
+RLMNotificationToken *RLMObjectAddNotificationBlock(RLMObjectBase *obj, RLMObjectChangeBlock block, dispatch_queue_t queue) {
+    return RLMObjectBaseAddNotificationBlock(obj, queue, ^(RLMObjectBase *, NSArray<NSString *> *propertyNames,
+                                                           NSArray *oldValues, NSArray *newValues, NSError *error) {
+        if (error) {
+            block(false, nil, error);
+        }
+        else if (!propertyNames) {
+            block(true, nil, nil);
+        }
+        else {
+            auto properties = [NSMutableArray arrayWithCapacity:propertyNames.count];
+            for (NSUInteger i = 0, count = propertyNames.count; i < count; ++i) {
+                auto prop = [RLMPropertyChange new];
+                prop.name = propertyNames[i];
+                prop.previousValue = RLMCoerceToNil(oldValues[i]);
+                prop.value = RLMCoerceToNil(newValues[i]);
+                [properties addObject:prop];
+            }
+            block(false, properties, nil);
+        }
+    });
+}
+
+uint64_t RLMObjectBaseGetCombineId(__unsafe_unretained RLMObjectBase *const obj) {
+    if (obj.invalidated) {
+        RLMVerifyAttached(obj);
+    }
+    if (obj->_realm) {
+        return obj->_row.get_key().value;
+    }
+    return reinterpret_cast<uint64_t>((__bridge void *)obj);
+}
+
+@implementation RealmSwiftObject
+@end
+
+@implementation RealmSwiftEmbeddedObject
+@end

+ 128 - 0
Example/Pods/Realm/Realm/RLMObjectId.mm

@@ -0,0 +1,128 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMObjectId_Private.hpp"
+
+#import "RLMUtil.hpp"
+
+#import <realm/object_id.hpp>
+
+// Swift's obj-c bridging does not support making an obj-c defined class conform
+// to Decodable, so we need a Swift-defined subclass for that. This means that
+// when Realm Swift is being used, we need to produce objects of that type rather
+// than our obj-c defined type. objc_runtime_visible marks the type as being
+// visbile only to the obj-c runtime and not the linker, which means that it'll
+// be `nil` at runtime rather than being a linker error if it's not defined, and
+// valid if it happens to be defined by some other library (i.e. Realm Swift).
+//
+// At the point where the objects are being allocated we generally don't have
+// any good way of knowing whether or not it's going to end up being used by
+// Swift, so we just switch to the subclass unconditionally if the subclass
+// exists. This shouldn't have any impact on obj-c code other than a small
+// performance hit.
+[[clang::objc_runtime_visible]]
+@interface RealmSwiftObjectId : RLMObjectId
+@end
+
+@implementation RLMObjectId
+- (instancetype)init {
+    if ((self = [super init])) {
+        if (auto cls = [RealmSwiftObjectId class]; cls && cls != self.class) {
+            object_setClass(self, cls);
+        }
+    }
+    return self;
+}
+
+- (instancetype)initWithString:(NSString *)string error:(NSError **)error {
+    if ((self = [self init])) {
+        const char *str = string.UTF8String;
+        if (!realm::ObjectId::is_valid_str(str)) {
+            if (error) {
+                NSString *msg = [NSString stringWithFormat:@"Invalid Object ID string '%@': must be 24 hex digits", string];
+                *error = [NSError errorWithDomain:RLMErrorDomain
+                                             code:RLMErrorInvalidInput
+                                         userInfo:@{NSLocalizedDescriptionKey: msg}];
+            }
+            return nil;
+        }
+        _value = realm::ObjectId(str);
+    }
+    return self;
+}
+
+- (instancetype)initWithTimestamp:(NSDate *)timestamp
+                machineIdentifier:(int)machineIdentifier
+                processIdentifier:(int)processIdentifier {
+    if ((self = [self init])) {
+        _value = realm::ObjectId(RLMTimestampForNSDate(timestamp), machineIdentifier, processIdentifier);
+    }
+    return self;
+}
+
+- (instancetype)initWithValue:(realm::ObjectId)value {
+    if ((self = [self init])) {
+        _value = value;
+    }
+    return self;
+}
+
++ (instancetype)objectId {
+    return [[RLMObjectId alloc] initWithValue:realm::ObjectId::gen()];
+}
+
+- (BOOL)isEqual:(id)object {
+    if (RLMObjectId *objectId = RLMDynamicCast<RLMObjectId>(object)) {
+        return objectId->_value == _value;
+    }
+    return NO;
+}
+
+- (BOOL)isGreaterThan:(nullable RLMObjectId *)objectId {
+    return _value > objectId.value;
+}
+
+- (BOOL)isGreaterThanOrEqualTo:(nullable RLMObjectId *)objectId {
+    return _value >= objectId.value;
+}
+
+- (BOOL)isLessThan:(nullable RLMObjectId *)objectId {
+    return _value < objectId.value;
+}
+
+- (BOOL)isLessThanOrEqualTo:(nullable RLMObjectId *)objectId {
+    return _value <= objectId.value;
+}
+
+- (NSUInteger)hash {
+    return _value.hash();
+}
+
+- (NSString *)description {
+    return self.stringValue;
+}
+
+- (NSString *)stringValue {
+    return @(_value.to_string().c_str());
+}
+
+- (NSDate *)timestamp {
+    return RLMTimestampToNSDate(_value.get_timestamp());
+}
+
+@end

+ 372 - 0
Example/Pods/Realm/Realm/RLMObjectSchema.mm

@@ -0,0 +1,372 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMObjectSchema_Private.hpp"
+
+#import "RLMArray.h"
+#import "RLMEmbeddedObject.h"
+#import "RLMListBase.h"
+#import "RLMObject_Private.h"
+#import "RLMProperty_Private.hpp"
+#import "RLMRealm_Dynamic.h"
+#import "RLMRealm_Private.hpp"
+#import "RLMSchema_Private.h"
+#import "RLMSwiftSupport.h"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/object_schema.hpp>
+#import <realm/object-store/object_store.hpp>
+
+using namespace realm;
+
+// private properties
+@interface RLMObjectSchema ()
+@property (nonatomic, readwrite) NSDictionary<id, RLMProperty *> *allPropertiesByName;
+@property (nonatomic, readwrite) NSString *className;
+@end
+
+@implementation RLMObjectSchema {
+    NSArray *_swiftGenericProperties;
+}
+
+- (instancetype)initWithClassName:(NSString *)objectClassName objectClass:(Class)objectClass properties:(NSArray *)properties {
+    self = [super init];
+    self.className = objectClassName;
+    self.properties = properties;
+    self.objectClass = objectClass;
+    self.accessorClass = objectClass;
+    self.unmanagedClass = objectClass;
+    return self;
+}
+
+// return properties by name
+- (RLMProperty *)objectForKeyedSubscript:(__unsafe_unretained NSString *const)key {
+    return _allPropertiesByName[key];
+}
+
+// create property map when setting property array
+- (void)setProperties:(NSArray *)properties {
+    _properties = properties;
+    [self _propertiesDidChange];
+}
+
+- (void)setComputedProperties:(NSArray *)computedProperties {
+    _computedProperties = computedProperties;
+    [self _propertiesDidChange];
+}
+
+- (void)_propertiesDidChange {
+    NSMutableDictionary *map = [NSMutableDictionary dictionaryWithCapacity:_properties.count + _computedProperties.count];
+    NSUInteger index = 0;
+    for (RLMProperty *prop in _properties) {
+        prop.index = index++;
+        map[prop.name] = prop;
+        if (prop.isPrimary) {
+            self.primaryKeyProperty = prop;
+        }
+    }
+    index = 0;
+    for (RLMProperty *prop in _computedProperties) {
+        prop.index = index++;
+        map[prop.name] = prop;
+    }
+    _allPropertiesByName = map;
+}
+
+
+- (void)setPrimaryKeyProperty:(RLMProperty *)primaryKeyProperty {
+    _primaryKeyProperty.isPrimary = NO;
+    primaryKeyProperty.isPrimary = YES;
+    _primaryKeyProperty = primaryKeyProperty;
+}
+
++ (instancetype)schemaForObjectClass:(Class)objectClass {
+    RLMObjectSchema *schema = [RLMObjectSchema new];
+
+    // determine classname from objectclass as className method has not yet been updated
+    NSString *className = NSStringFromClass(objectClass);
+    bool hasSwiftName = [RLMSwiftSupport isSwiftClassName:className];
+    if (hasSwiftName) {
+        className = [RLMSwiftSupport demangleClassName:className];
+    }
+
+    bool isSwift = hasSwiftName || RLMIsSwiftObjectClass(objectClass);
+
+    schema.className = className;
+    schema.objectClass = objectClass;
+    schema.accessorClass = objectClass;
+    schema.unmanagedClass = objectClass;
+    schema.isSwiftClass = isSwift;
+    schema.isEmbedded = [(id)objectClass isEmbedded];
+
+    // create array of RLMProperties, inserting properties of superclasses first
+    Class cls = objectClass;
+    Class superClass = class_getSuperclass(cls);
+    NSArray *allProperties = @[];
+    while (superClass && superClass != RLMObjectBase.class) {
+        allProperties = [[RLMObjectSchema propertiesForClass:cls isSwift:isSwift]
+                         arrayByAddingObjectsFromArray:allProperties];
+        cls = superClass;
+        superClass = class_getSuperclass(superClass);
+    }
+    NSArray *persistedProperties = [allProperties filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(RLMProperty *property, NSDictionary *) {
+        return !RLMPropertyTypeIsComputed(property.type);
+    }]];
+    schema.properties = persistedProperties;
+
+    NSArray *computedProperties = [allProperties filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(RLMProperty *property, NSDictionary *) {
+        return RLMPropertyTypeIsComputed(property.type);
+    }]];
+    schema.computedProperties = computedProperties;
+
+    // verify that we didn't add any properties twice due to inheritance
+    if (allProperties.count != [NSSet setWithArray:[allProperties valueForKey:@"name"]].count) {
+        NSCountedSet *countedPropertyNames = [NSCountedSet setWithArray:[allProperties valueForKey:@"name"]];
+        NSArray *duplicatePropertyNames = [countedPropertyNames filteredSetUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *) {
+            return [countedPropertyNames countForObject:object] > 1;
+        }]].allObjects;
+
+        if (duplicatePropertyNames.count == 1) {
+            @throw RLMException(@"Property '%@' is declared multiple times in the class hierarchy of '%@'", duplicatePropertyNames.firstObject, className);
+        } else {
+            @throw RLMException(@"Object '%@' has properties that are declared multiple times in its class hierarchy: '%@'", className, [duplicatePropertyNames componentsJoinedByString:@"', '"]);
+        }
+    }
+
+    if (NSString *primaryKey = [objectClass primaryKey]) {
+        for (RLMProperty *prop in schema.properties) {
+            if ([primaryKey isEqualToString:prop.name]) {
+                prop.indexed = YES;
+                schema.primaryKeyProperty = prop;
+                break;
+            }
+        }
+
+        if (!schema.primaryKeyProperty) {
+            @throw RLMException(@"Primary key property '%@' does not exist on object '%@'", primaryKey, className);
+        }
+        if (schema.primaryKeyProperty.type != RLMPropertyTypeInt && schema.primaryKeyProperty.type != RLMPropertyTypeString && schema.primaryKeyProperty.type != RLMPropertyTypeObjectId) {
+            @throw RLMException(@"Property '%@' cannot be made the primary key of '%@' because it is not a 'string', 'int', or 'objectId' property.",
+                                primaryKey, className);
+        }
+    }
+
+    for (RLMProperty *prop in schema.properties) {
+        if (prop.optional && prop.array && (prop.type == RLMPropertyTypeObject || prop.type == RLMPropertyTypeLinkingObjects)) {
+            // FIXME: message is awkward
+            @throw RLMException(@"Property '%@.%@' cannot be made optional because optional '%@' properties are not supported.",
+                                className, prop.name, RLMTypeToString(prop.type));
+        }
+    }
+
+    if ([objectClass shouldIncludeInDefaultSchema] && schema.isSwiftClass && schema.properties.count == 0) {
+        @throw RLMException(@"No properties are defined for '%@'. Did you remember to mark them with '@objc' in your model?", schema.className);
+    }
+    return schema;
+}
+
++ (NSArray *)propertiesForClass:(Class)objectClass isSwift:(bool)isSwiftClass {
+    if (NSArray<RLMProperty *> *props = [objectClass _getProperties]) {
+        return props;
+    }
+
+    // For Swift subclasses of RLMObject we need an instance of the object when parsing properties
+    id swiftObjectInstance = isSwiftClass ? [[objectClass alloc] init] : nil;
+
+    NSArray *ignoredProperties = [objectClass ignoredProperties];
+    NSDictionary *linkingObjectsProperties = [objectClass linkingObjectsProperties];
+    NSDictionary *columnNameMap = [objectClass _realmColumnNames];
+
+    unsigned int count;
+    std::unique_ptr<objc_property_t[], decltype(&free)> props(class_copyPropertyList(objectClass, &count), &free);
+    NSMutableArray<RLMProperty *> *propArray = [NSMutableArray arrayWithCapacity:count];
+    NSSet *indexed = [[NSSet alloc] initWithArray:[objectClass indexedProperties]];
+    for (unsigned int i = 0; i < count; i++) {
+        NSString *propertyName = @(property_getName(props[i]));
+        if ([ignoredProperties containsObject:propertyName]) {
+            continue;
+        }
+
+        RLMProperty *prop = nil;
+        if (isSwiftClass) {
+            prop = [[RLMProperty alloc] initSwiftPropertyWithName:propertyName
+                                                          indexed:[indexed containsObject:propertyName]
+                                           linkPropertyDescriptor:linkingObjectsProperties[propertyName]
+                                                         property:props[i]
+                                                         instance:swiftObjectInstance];
+        }
+        else {
+            prop = [[RLMProperty alloc] initWithName:propertyName
+                                             indexed:[indexed containsObject:propertyName]
+                              linkPropertyDescriptor:linkingObjectsProperties[propertyName]
+                                            property:props[i]];
+        }
+
+        if (prop) {
+            if (columnNameMap) {
+                prop.columnName = columnNameMap[prop.name];
+            }
+            [propArray addObject:prop];
+        }
+    }
+
+    if (auto requiredProperties = [objectClass requiredProperties]) {
+        for (RLMProperty *property in propArray) {
+            bool required = [requiredProperties containsObject:property.name];
+            if (required && property.type == RLMPropertyTypeObject && !property.array) {
+                @throw RLMException(@"Object properties cannot be made required, "
+                                    "but '+[%@ requiredProperties]' included '%@'", objectClass, property.name);
+            }
+            property.optional &= !required;
+        }
+    }
+
+    for (RLMProperty *property in propArray) {
+        if (!property.optional && property.type == RLMPropertyTypeObject && !property.array) {
+            @throw RLMException(@"The `%@.%@` property must be marked as being optional.",
+                                [objectClass className], property.name);
+        }
+    }
+
+    return propArray;
+}
+
+- (id)copyWithZone:(NSZone *)zone {
+    RLMObjectSchema *schema = [[RLMObjectSchema allocWithZone:zone] init];
+    schema->_objectClass = _objectClass;
+    schema->_className = _className;
+    schema->_objectClass = _objectClass;
+    schema->_accessorClass = _objectClass;
+    schema->_unmanagedClass = _unmanagedClass;
+    schema->_isSwiftClass = _isSwiftClass;
+    schema->_isEmbedded = _isEmbedded;
+
+    // call property setter to reset map and primary key
+    schema.properties = [[NSArray allocWithZone:zone] initWithArray:_properties copyItems:YES];
+    schema.computedProperties = [[NSArray allocWithZone:zone] initWithArray:_computedProperties copyItems:YES];
+
+    return schema;
+}
+
+- (BOOL)isEqualToObjectSchema:(RLMObjectSchema *)objectSchema {
+    if (objectSchema.properties.count != _properties.count) {
+        return NO;
+    }
+
+    if (![_properties isEqualToArray:objectSchema.properties]) {
+        return NO;
+    }
+    if (![_computedProperties isEqualToArray:objectSchema.computedProperties]) {
+        return NO;
+    }
+
+    return YES;
+}
+
+- (NSString *)description {
+    NSMutableString *propertiesString = [NSMutableString string];
+    for (RLMProperty *property in self.properties) {
+        [propertiesString appendFormat:@"\t%@\n", [property.description stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]];
+    }
+    for (RLMProperty *property in self.computedProperties) {
+        [propertiesString appendFormat:@"\t%@\n", [property.description stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]];
+    }
+    return [NSString stringWithFormat:@"%@ %@{\n%@}",
+            self.className, _isEmbedded ? @"(embedded) " : @"", propertiesString];
+}
+
+- (NSString *)objectName {
+    return [self.objectClass _realmObjectName] ?: _className;
+}
+
+- (realm::ObjectSchema)objectStoreCopy:(RLMSchema *)schema {
+    ObjectSchema objectSchema;
+    objectSchema.name = self.objectName.UTF8String;
+    objectSchema.primary_key = _primaryKeyProperty ? _primaryKeyProperty.columnName.UTF8String : "";
+    objectSchema.is_embedded = ObjectSchema::IsEmbedded(_isEmbedded);
+    for (RLMProperty *prop in _properties) {
+        Property p = [prop objectStoreCopy:schema];
+        p.is_primary = (prop == _primaryKeyProperty);
+        objectSchema.persisted_properties.push_back(std::move(p));
+    }
+    for (RLMProperty *prop in _computedProperties) {
+        objectSchema.computed_properties.push_back([prop objectStoreCopy:schema]);
+    }
+    return objectSchema;
+}
+
++ (instancetype)objectSchemaForObjectStoreSchema:(realm::ObjectSchema const&)objectSchema {
+    RLMObjectSchema *schema = [RLMObjectSchema new];
+    schema.className = @(objectSchema.name.c_str());
+    schema.isEmbedded = objectSchema.is_embedded;
+
+    // create array of RLMProperties
+    NSMutableArray *properties = [NSMutableArray arrayWithCapacity:objectSchema.persisted_properties.size()];
+    for (const Property &prop : objectSchema.persisted_properties) {
+        RLMProperty *property = [RLMProperty propertyForObjectStoreProperty:prop];
+        property.isPrimary = (prop.name == objectSchema.primary_key);
+        [properties addObject:property];
+    }
+    schema.properties = properties;
+
+    NSMutableArray *computedProperties = [NSMutableArray arrayWithCapacity:objectSchema.computed_properties.size()];
+    for (const Property &prop : objectSchema.computed_properties) {
+        [computedProperties addObject:[RLMProperty propertyForObjectStoreProperty:prop]];
+    }
+    schema.computedProperties = computedProperties;
+
+    // get primary key from realm metadata
+    if (objectSchema.primary_key.length()) {
+        NSString *primaryKeyString = [NSString stringWithUTF8String:objectSchema.primary_key.c_str()];
+        schema.primaryKeyProperty = schema[primaryKeyString];
+        if (!schema.primaryKeyProperty) {
+            @throw RLMException(@"No property matching primary key '%@'", primaryKeyString);
+        }
+    }
+
+    // for dynamic schema use vanilla RLMDynamicObject accessor classes
+    schema.objectClass = RLMObject.class;
+    schema.accessorClass = RLMDynamicObject.class;
+    schema.unmanagedClass = RLMObject.class;
+
+    return schema;
+}
+
+- (NSArray *)swiftGenericProperties {
+    if (_swiftGenericProperties) {
+        return _swiftGenericProperties;
+    }
+
+    // Check if it's a swift class using the obj-c API
+    if (!RLMIsSwiftObjectClass(_accessorClass)) {
+        return _swiftGenericProperties = @[];
+    }
+
+    NSMutableArray *genericProperties = [NSMutableArray new];
+    for (RLMProperty *prop in _properties) {
+        if (prop->_swiftIvar) {
+            [genericProperties addObject:prop];
+        }
+    }
+    // Currently all computed properties are Swift generics
+    [genericProperties addObjectsFromArray:_computedProperties];
+
+    return _swiftGenericProperties = genericProperties;
+}
+
+@end

+ 241 - 0
Example/Pods/Realm/Realm/RLMObjectStore.mm

@@ -0,0 +1,241 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMObjectStore.h"
+
+#import "RLMAccessor.hpp"
+#import "RLMArray_Private.hpp"
+#import "RLMListBase.h"
+#import "RLMObservation.hpp"
+#import "RLMObject_Private.hpp"
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMOptionalBase.h"
+#import "RLMProperty_Private.h"
+#import "RLMQueryUtil.hpp"
+#import "RLMRealm_Private.hpp"
+#import "RLMSchema_Private.h"
+#import "RLMSwiftSupport.h"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/object_store.hpp>
+#import <realm/object-store/results.hpp>
+#import <realm/object-store/shared_realm.hpp>
+#import <realm/group.hpp>
+
+#import <objc/message.h>
+
+using namespace realm;
+
+void RLMRealmCreateAccessors(RLMSchema *schema) {
+    const size_t bufferSize = sizeof("RLM:Managed  ") // includes null terminator
+                            + std::numeric_limits<unsigned long long>::digits10
+                            + realm::Group::max_table_name_length;
+
+    char className[bufferSize] = "RLM:Managed ";
+    char *const start = className + strlen(className);
+
+    for (RLMObjectSchema *objectSchema in schema.objectSchema) {
+        if (objectSchema.accessorClass != objectSchema.objectClass) {
+            continue;
+        }
+
+        static unsigned long long count = 0;
+        sprintf(start, "%llu %s", count++, objectSchema.className.UTF8String);
+        objectSchema.accessorClass = RLMManagedAccessorClassForObjectClass(objectSchema.objectClass, objectSchema, className);
+    }
+}
+
+static inline void RLMVerifyRealmRead(__unsafe_unretained RLMRealm *const realm) {
+    if (!realm) {
+        @throw RLMException(@"Realm must not be nil");
+    }
+    [realm verifyThread];
+    if (realm->_realm->is_closed()) {
+        // This message may seem overly specific, but frozen Realms are currently
+        // the only ones which we outright close.
+        @throw RLMException(@"Cannot read from a frozen Realm which has been invalidated.");
+    }
+}
+
+static inline void RLMVerifyInWriteTransaction(__unsafe_unretained RLMRealm *const realm) {
+    RLMVerifyRealmRead(realm);
+    // if realm is not writable throw
+    if (!realm.inWriteTransaction) {
+        @throw RLMException(@"Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first.");
+    }
+}
+
+void RLMInitializeSwiftAccessorGenerics(__unsafe_unretained RLMObjectBase *const object) {
+    if (!object || !object->_row || !object->_objectSchema->_isSwiftClass) {
+        return;
+    }
+    if (![object isKindOfClass:object->_objectSchema.objectClass]) {
+        // It can be a different class if it's a dynamic object, and those don't
+        // require any init here (and would crash since they don't have the ivars)
+        return;
+    }
+
+    for (RLMProperty *prop in object->_objectSchema.swiftGenericProperties) {
+        if (prop.type == RLMPropertyTypeLinkingObjects) {
+            [prop.swiftAccessor initializeObject:(char *)(__bridge void *)object + ivar_getOffset(prop.swiftIvar)
+                                          parent:object property:prop];
+        }
+        else if (prop.array) {
+            id ivar = object_getIvar(object, prop.swiftIvar);
+            RLMArray *array = [[RLMManagedArray alloc] initWithParent:object property:prop];
+            [ivar set_rlmArray:array];
+        }
+        else {
+            id ivar = object_getIvar(object, prop.swiftIvar);
+            RLMInitializeManagedOptional(ivar, object, prop);
+        }
+    }
+}
+
+void RLMVerifyHasPrimaryKey(Class cls) {
+    RLMObjectSchema *schema = [cls sharedSchema];
+    if (!schema.primaryKeyProperty) {
+        NSString *reason = [NSString stringWithFormat:@"'%@' does not have a primary key and can not be updated", schema.className];
+        @throw [NSException exceptionWithName:@"RLMException" reason:reason userInfo:nil];
+    }
+}
+
+static CreatePolicy updatePolicyToCreatePolicy(RLMUpdatePolicy policy) {
+    CreatePolicy createPolicy = {.create = true, .copy = false, .diff = false, .update = false};
+    switch (policy) {
+        case RLMUpdatePolicyError:
+            break;
+        case RLMUpdatePolicyUpdateChanged:
+            createPolicy.diff = true;
+            [[clang::fallthrough]];
+        case RLMUpdatePolicyUpdateAll:
+            createPolicy.update = true;
+            break;
+    }
+    return createPolicy;
+}
+
+void RLMAddObjectToRealm(__unsafe_unretained RLMObjectBase *const object,
+                         __unsafe_unretained RLMRealm *const realm,
+                         RLMUpdatePolicy updatePolicy) {
+    RLMVerifyInWriteTransaction(realm);
+
+    CreatePolicy createPolicy = updatePolicyToCreatePolicy(updatePolicy);
+    createPolicy.copy = false;
+    auto& info = realm->_info[object->_objectSchema.className];
+    RLMAccessorContext c{info};
+    c.createObject(object, createPolicy);
+}
+
+RLMObjectBase *RLMCreateObjectInRealmWithValue(RLMRealm *realm, NSString *className,
+                                               id value, RLMUpdatePolicy updatePolicy) {
+    RLMVerifyInWriteTransaction(realm);
+
+    CreatePolicy createPolicy = updatePolicyToCreatePolicy(updatePolicy);
+    createPolicy.copy = true;
+
+    auto& info = realm->_info[className];
+    RLMAccessorContext c{info};
+    RLMObjectBase *object = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, &info);
+    auto [obj, reuseExisting] = c.createObject(value, createPolicy, true);
+    if (reuseExisting) {
+        return value;
+    }
+    object->_row = std::move(obj);
+    RLMInitializeSwiftAccessorGenerics(object);
+    return object;
+}
+
+void RLMDeleteObjectFromRealm(__unsafe_unretained RLMObjectBase *const object,
+                              __unsafe_unretained RLMRealm *const realm) {
+    if (realm != object->_realm) {
+        @throw RLMException(@"Can only delete an object from the Realm it belongs to.");
+    }
+
+    RLMVerifyInWriteTransaction(object->_realm);
+
+    if (object->_row.is_valid()) {
+        RLMObservationTracker tracker(realm, true);
+        object->_row.remove();
+    }
+    object->_realm = nil;
+}
+
+void RLMDeleteAllObjectsFromRealm(RLMRealm *realm) {
+    RLMVerifyInWriteTransaction(realm);
+
+    // clear table for each object schema
+    for (auto& info : realm->_info) {
+        RLMClearTable(info.second);
+    }
+}
+
+RLMResults *RLMGetObjects(__unsafe_unretained RLMRealm *const realm,
+                          NSString *objectClassName,
+                          NSPredicate *predicate) {
+    RLMVerifyRealmRead(realm);
+
+    // create view from table and predicate
+    RLMClassInfo& info = realm->_info[objectClassName];
+    if (!info.table()) {
+        // read-only realms may be missing tables since we can't add any
+        // missing ones on init
+        return [RLMResults resultsWithObjectInfo:info results:{}];
+    }
+
+    if (predicate) {
+        realm::Query query = RLMPredicateToQuery(predicate, info.rlmObjectSchema, realm.schema, realm.group);
+        return [RLMResults resultsWithObjectInfo:info
+                                         results:realm::Results(realm->_realm, std::move(query))];
+    }
+
+    return [RLMResults resultsWithObjectInfo:info
+                                     results:realm::Results(realm->_realm, info.table())];
+}
+
+id RLMGetObject(RLMRealm *realm, NSString *objectClassName, id key) {
+    RLMVerifyRealmRead(realm);
+
+    auto& info = realm->_info[objectClassName];
+    if (RLMProperty *prop = info.propertyForPrimaryKey()) {
+        RLMValidateValueForProperty(key, info.rlmObjectSchema, prop);
+    }
+    try {
+        RLMAccessorContext c{info};
+        auto obj = realm::Object::get_for_primary_key(c, realm->_realm, *info.objectSchema,
+                                                      key ?: NSNull.null);
+        if (!obj.is_valid())
+            return nil;
+        return RLMCreateObjectAccessor(info, obj.obj());
+    }
+    catch (std::exception const& e) {
+        @throw RLMException(e);
+    }
+}
+
+RLMObjectBase *RLMCreateObjectAccessor(RLMClassInfo& info, int64_t key) {
+    return RLMCreateObjectAccessor(info, info.table()->get_object(realm::ObjKey(key)));
+}
+
+// Create accessor and register with realm
+RLMObjectBase *RLMCreateObjectAccessor(RLMClassInfo& info, realm::Obj&& obj) {
+    RLMObjectBase *accessor = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, &info);
+    accessor->_row = std::move(obj);
+    RLMInitializeSwiftAccessorGenerics(accessor);
+    return accessor;
+}

+ 555 - 0
Example/Pods/Realm/Realm/RLMObservation.mm

@@ -0,0 +1,555 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2015 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMObservation.hpp"
+
+#import "RLMAccessor.h"
+#import "RLMArray_Private.hpp"
+#import "RLMListBase.h"
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMObject_Private.hpp"
+#import "RLMProperty_Private.h"
+#import "RLMRealm_Private.hpp"
+
+#import <realm/group.hpp>
+
+using namespace realm;
+
+namespace {
+    template<typename Iterator>
+    struct IteratorPair {
+        Iterator first;
+        Iterator second;
+    };
+    template<typename Iterator>
+    Iterator begin(IteratorPair<Iterator> const& p) {
+        return p.first;
+    }
+    template<typename Iterator>
+    Iterator end(IteratorPair<Iterator> const& p) {
+        return p.second;
+    }
+
+    template<typename Container>
+    auto reverse(Container const& c) {
+        return IteratorPair<typename Container::const_reverse_iterator>{c.rbegin(), c.rend()};
+    }
+}
+
+RLMObservationInfo::RLMObservationInfo(RLMClassInfo &objectSchema, realm::ObjKey row, id object)
+: object(object)
+, objectSchema(&objectSchema)
+{
+    setRow(*objectSchema.table(), row);
+}
+
+RLMObservationInfo::RLMObservationInfo(id object)
+: object(object)
+{
+}
+
+RLMObservationInfo::~RLMObservationInfo() {
+    if (prev) {
+        // Not the head of the linked list, so just detach from the list
+        REALM_ASSERT_DEBUG(prev->next == this);
+        prev->next = next;
+        if (next) {
+            REALM_ASSERT_DEBUG(next->prev == this);
+            next->prev = prev;
+        }
+    }
+    else if (objectSchema) {
+        // The head of the list, so remove self from the object schema's array
+        // of observation info, either replacing self with the next info or
+        // removing entirely if there is no next
+        auto end = objectSchema->observedObjects.end();
+        auto it = find(objectSchema->observedObjects.begin(), end, this);
+        if (it != end) {
+            if (next) {
+                *it = next;
+                next->prev = nullptr;
+            }
+            else {
+                iter_swap(it, std::prev(end));
+                objectSchema->observedObjects.pop_back();
+            }
+        }
+    }
+    // Otherwise the observed object was unmanaged, so nothing to do
+
+#ifdef DEBUG
+    // ensure that incorrect cleanup fails noisily
+    object = (__bridge id)(void *)-1;
+    prev = (RLMObservationInfo *)-1;
+    next = (RLMObservationInfo *)-1;
+#endif
+}
+
+NSString *RLMObservationInfo::columnName(realm::ColKey col) const noexcept {
+    return objectSchema->propertyForTableColumn(col).name;
+}
+
+void RLMObservationInfo::willChange(NSString *key, NSKeyValueChange kind, NSIndexSet *indexes) const {
+    if (indexes) {
+        forEach([=](__unsafe_unretained auto o) {
+            [o willChange:kind valuesAtIndexes:indexes forKey:key];
+        });
+    }
+    else {
+        forEach([=](__unsafe_unretained auto o) {
+            [o willChangeValueForKey:key];
+        });
+    }
+}
+
+void RLMObservationInfo::didChange(NSString *key, NSKeyValueChange kind, NSIndexSet *indexes) const {
+    if (indexes) {
+        forEach([=](__unsafe_unretained auto o) {
+            [o didChange:kind valuesAtIndexes:indexes forKey:key];
+        });
+    }
+    else {
+        forEach([=](__unsafe_unretained auto o) {
+            [o didChangeValueForKey:key];
+        });
+    }
+}
+
+void RLMObservationInfo::prepareForInvalidation() {
+    REALM_ASSERT_DEBUG(objectSchema);
+    REALM_ASSERT_DEBUG(!prev);
+    for (auto info = this; info; info = info->next)
+        info->invalidated = true;
+}
+
+void RLMObservationInfo::setRow(realm::Table const& table, realm::ObjKey key) {
+    REALM_ASSERT_DEBUG(!row);
+    REALM_ASSERT_DEBUG(objectSchema);
+    row = table.get_object(key);
+    for (auto info : objectSchema->observedObjects) {
+        if (info->row && info->row.get_key() == key) {
+            prev = info;
+            next = info->next;
+            if (next)
+                next->prev = this;
+            info->next = this;
+            return;
+        }
+    }
+    objectSchema->observedObjects.push_back(this);
+}
+
+void RLMObservationInfo::recordObserver(realm::Obj& objectRow, RLMClassInfo *objectInfo,
+                                        __unsafe_unretained RLMObjectSchema *const objectSchema,
+                                        __unsafe_unretained NSString *const keyPath) {
+    ++observerCount;
+    if (row) {
+        return;
+    }
+
+    // add ourselves to the list of observed objects if this is the first time
+    // an observer is being added to a managed object
+    if (objectRow) {
+        this->objectSchema = objectInfo;
+        setRow(*objectRow.get_table(), objectRow.get_key());
+        return;
+    }
+
+    // Arrays need a reference to their containing object to avoid having to
+    // go through the awful proxy object from mutableArrayValueForKey.
+    // For managed objects we do this when the object is added or created
+    // (and have to to support notifications from modifying an object which
+    // was never observed), but for Swift classes (both RealmSwift and
+    // RLMObject) we can't do it then because we don't know what the parent
+    // object is.
+
+    NSUInteger sep = [keyPath rangeOfString:@"."].location;
+    NSString *key = sep == NSNotFound ? keyPath : [keyPath substringToIndex:sep];
+    RLMProperty *prop = objectSchema[key];
+    if (prop && prop.array) {
+        id value = valueForKey(key);
+        RLMArray *array = [value isKindOfClass:[RLMListBase class]] ? [value _rlmArray] : value;
+        array->_key = key;
+        array->_parentObject = object;
+    }
+    else if (auto swiftIvar = prop.swiftIvar) {
+        if (auto optional = RLMDynamicCast<RLMOptionalBase>(object_getIvar(object, swiftIvar))) {
+            RLMInitializeUnmanagedOptional(optional, object, prop);
+        }
+    }
+}
+
+void RLMObservationInfo::removeObserver() {
+    --observerCount;
+}
+
+id RLMObservationInfo::valueForKey(NSString *key) {
+    if (invalidated) {
+        if ([key isEqualToString:RLMInvalidatedKey]) {
+            return @YES;
+        }
+        return cachedObjects[key];
+    }
+
+    if (key != lastKey) {
+        lastKey = key;
+        lastProp = objectSchema ? objectSchema->rlmObjectSchema[key] : nil;
+    }
+
+    static auto superValueForKey = reinterpret_cast<id(*)(id, SEL, NSString *)>([NSObject methodForSelector:@selector(valueForKey:)]);
+    if (!lastProp) {
+        // Not a managed property, so use NSObject's implementation of valueForKey:
+        return RLMCoerceToNil(superValueForKey(object, @selector(valueForKey:), key));
+    }
+
+    auto getSuper = [&] {
+        return row ? RLMDynamicGet(object, lastProp) : RLMCoerceToNil(superValueForKey(object, @selector(valueForKey:), key));
+    };
+
+    // We need to return the same object each time for observing over keypaths
+    // to work, so we store a cache of them here. We can't just cache them on
+    // the object as that leads to retain cycles.
+    if (lastProp.array) {
+        RLMArray *value = cachedObjects[key];
+        if (!value) {
+            value = getSuper();
+            if (!cachedObjects) {
+                cachedObjects = [NSMutableDictionary new];
+            }
+            cachedObjects[key] = value;
+        }
+        return value;
+    }
+
+    if (lastProp.type == RLMPropertyTypeObject) {
+        auto col = row.get_table()->get_column_key(lastProp.name.UTF8String);
+        if (row.is_null(col)) {
+            [cachedObjects removeObjectForKey:key];
+            return nil;
+        }
+
+        RLMObjectBase *value = cachedObjects[key];
+        if (value && value->_row.get_key() == row.get<realm::ObjKey>(col)) {
+            return value;
+        }
+        value = getSuper();
+        if (!cachedObjects) {
+            cachedObjects = [NSMutableDictionary new];
+        }
+        cachedObjects[key] = value;
+        return value;
+    }
+
+    return getSuper();
+}
+
+RLMObservationInfo *RLMGetObservationInfo(RLMObservationInfo *info, realm::ObjKey row,
+                                          RLMClassInfo& objectSchema) {
+    if (info) {
+        return info;
+    }
+
+    for (RLMObservationInfo *info : objectSchema.observedObjects) {
+        if (info->isForRow(row)) {
+            return info;
+        }
+    }
+
+    return nullptr;
+}
+
+void RLMClearTable(RLMClassInfo &objectSchema) {
+    if (!objectSchema.table()) {
+        // Orphaned embedded object types are included in the schema but do not
+        // create a table at all, so we may not have a table here and just
+        // don't need to do anything
+        return;
+    }
+
+    for (auto info : objectSchema.observedObjects) {
+        info->willChange(RLMInvalidatedKey);
+    }
+
+    {
+        RLMObservationTracker tracker(objectSchema.realm, true);
+        Results(objectSchema.realm->_realm, objectSchema.table()).clear();
+
+        for (auto info : objectSchema.observedObjects) {
+            info->prepareForInvalidation();
+        }
+    }
+
+    for (auto info : reverse(objectSchema.observedObjects)) {
+        info->didChange(RLMInvalidatedKey);
+    }
+
+    objectSchema.observedObjects.clear();
+}
+
+RLMObservationTracker::RLMObservationTracker(__unsafe_unretained RLMRealm *const realm, bool trackDeletions)
+: _realm(realm)
+, _group(realm.group)
+{
+    if (trackDeletions) {
+        this->trackDeletions();
+    }
+}
+
+RLMObservationTracker::~RLMObservationTracker() {
+    didChange();
+}
+
+void RLMObservationTracker::willChange(RLMObservationInfo *info, NSString *key,
+                                       NSKeyValueChange kind, NSIndexSet *indexes) {
+    _key = key;
+    _kind = kind;
+    _indexes = indexes;
+    _info = info;
+    if (_info) {
+        _info->willChange(key, kind, indexes);
+    }
+}
+
+void RLMObservationTracker::trackDeletions() {
+    if (_group.has_cascade_notification_handler()) {
+        // We're nested inside another call which will handle any cascaded changes for us
+        return;
+    }
+
+    for (auto& info : _realm->_info) {
+        if (!info.second.observedObjects.empty()) {
+            _observedTables.push_back(&info.second.observedObjects);
+        }
+    }
+
+    // No need for change tracking if no objects are observed
+    if (_observedTables.empty()) {
+        return;
+    }
+
+    _group.set_cascade_notification_handler([=](realm::Group::CascadeNotification const& cs) {
+        cascadeNotification(cs);
+    });
+}
+
+template<typename CascadeNotification>
+void RLMObservationTracker::cascadeNotification(CascadeNotification const& cs) {
+    if (cs.rows.empty() && cs.links.empty()) {
+        return;
+    }
+
+    size_t invalidatedCount = _invalidated.size();
+    size_t changeCount = _changes.size();
+
+    auto tableKey = [](RLMObservationInfo *info) {
+        return info->getRow().get_table()->get_key();
+    };
+    std::sort(begin(_observedTables), end(_observedTables),
+              [=](auto a, auto b) { return tableKey(a->front()) < tableKey(b->front()); });
+    for (auto const& link : cs.links) {
+        auto table = std::find_if(_observedTables.begin(), _observedTables.end(), [&](auto table) {
+            return tableKey(table->front()) == link.origin_table;
+        });
+        if (table == _observedTables.end()) {
+            continue;
+        }
+
+        for (auto observer : **table) {
+            if (!observer->isForRow(link.origin_key)) {
+                continue;
+            }
+
+            NSString *name = observer->columnName(link.origin_col_key);
+            if (observer->getRow().get_table()->get_column_type(link.origin_col_key) != type_LinkList) {
+                _changes.push_back({observer, name});
+                continue;
+            }
+
+            auto c = find_if(begin(_changes), end(_changes), [&](auto const& c) {
+                return c.info == observer && c.property == name;
+            });
+            if (c == end(_changes)) {
+                _changes.push_back({observer, name, [NSMutableIndexSet new]});
+                c = prev(end(_changes));
+            }
+
+            // We know what row index is being removed from the LinkView,
+            // but what we actually want is the indexes in the LinkView that
+            // are going away
+            auto linkview = observer->getRow().get_linklist(link.origin_col_key);
+            linkview.find_all(link.old_target_key, [&](size_t index) {
+                [c->indexes addIndex:index];
+            });
+        }
+    }
+    if (!cs.rows.empty()) {
+        using Row = realm::Group::CascadeNotification::row;
+        auto begin = cs.rows.begin();
+        for (auto table : _observedTables) {
+            auto currentTableKey = tableKey(table->front());
+            if (begin->table_key < currentTableKey) {
+                // Find the first deleted object in or after this table
+                begin = std::lower_bound(begin, cs.rows.end(), Row{currentTableKey, realm::ObjKey(0)});
+            }
+            if (begin == cs.rows.end()) {
+                // No more deleted objects
+                break;
+            }
+            if (currentTableKey < begin->table_key) {
+                // Next deleted object is in a table after this one
+                continue;
+            }
+
+            // Find the end of the deletions in this table
+            auto end = std::lower_bound(begin, cs.rows.end(), Row{realm::TableKey(currentTableKey.value + 1), realm::ObjKey(0)});
+
+            // Check each observed object to see if it's in the deleted rows
+            for (auto info : *table) {
+                if (std::binary_search(begin, end, Row{currentTableKey, info->getRow().get_key()})) {
+                    _invalidated.push_back(info);
+                }
+            }
+
+            // Advance the begin iterator to the start of the next table
+            begin = end;
+            if (begin == cs.rows.end()) {
+                break;
+            }
+        }
+    }
+
+    // The relative order of these loops is very important
+    for (size_t i = invalidatedCount; i < _invalidated.size(); ++i) {
+        _invalidated[i]->willChange(RLMInvalidatedKey);
+    }
+    for (size_t i = changeCount; i < _changes.size(); ++i) {
+        auto const& change = _changes[i];
+        change.info->willChange(change.property, NSKeyValueChangeRemoval, change.indexes);
+    }
+    for (size_t i = invalidatedCount; i < _invalidated.size(); ++i) {
+        _invalidated[i]->prepareForInvalidation();
+    }
+}
+
+void RLMObservationTracker::didChange() {
+    if (_info) {
+        _info->didChange(_key, _kind, _indexes);
+        _info = nullptr;
+    }
+    if (_observedTables.empty()) {
+        return;
+    }
+    _group.set_cascade_notification_handler(nullptr);
+
+    for (auto const& change : reverse(_changes)) {
+        change.info->didChange(change.property, NSKeyValueChangeRemoval, change.indexes);
+    }
+    for (auto info : reverse(_invalidated)) {
+        info->didChange(RLMInvalidatedKey);
+    }
+    _observedTables.clear();
+    _changes.clear();
+    _invalidated.clear();
+}
+
+namespace {
+template<typename Func>
+void forEach(realm::BindingContext::ObserverState const& state, Func&& func) {
+    for (auto& change : state.changes) {
+        func(realm::ColKey(change.first), change.second, static_cast<RLMObservationInfo *>(state.info));
+    }
+}
+}
+
+std::vector<realm::BindingContext::ObserverState> RLMGetObservedRows(RLMSchemaInfo const& schema) {
+    std::vector<realm::BindingContext::ObserverState> observers;
+    for (auto& table : schema) {
+        for (auto info : table.second.observedObjects) {
+            auto const& row = info->getRow();
+            if (!row.is_valid())
+                continue;
+            observers.push_back({
+                row.get_table()->get_key(),
+                row.get_key().value,
+                info});
+        }
+    }
+    sort(begin(observers), end(observers));
+    return observers;
+}
+
+static NSKeyValueChange convert(realm::BindingContext::ColumnInfo::Kind kind) {
+    switch (kind) {
+        case realm::BindingContext::ColumnInfo::Kind::None:
+        case realm::BindingContext::ColumnInfo::Kind::SetAll:
+            return NSKeyValueChangeSetting;
+        case realm::BindingContext::ColumnInfo::Kind::Set:
+            return NSKeyValueChangeReplacement;
+        case realm::BindingContext::ColumnInfo::Kind::Insert:
+            return NSKeyValueChangeInsertion;
+        case realm::BindingContext::ColumnInfo::Kind::Remove:
+            return NSKeyValueChangeRemoval;
+    }
+}
+
+static NSIndexSet *convert(realm::IndexSet const& in, NSMutableIndexSet *out) {
+    if (in.empty()) {
+        return nil;
+    }
+
+    [out removeAllIndexes];
+    for (auto range : in) {
+        [out addIndexesInRange:{range.first, range.second - range.first}];
+    }
+    return out;
+}
+
+void RLMWillChange(std::vector<realm::BindingContext::ObserverState> const& observed,
+                   std::vector<void *> const& invalidated) {
+    for (auto info : invalidated) {
+        static_cast<RLMObservationInfo *>(info)->willChange(RLMInvalidatedKey);
+    }
+    if (!observed.empty()) {
+        NSMutableIndexSet *indexes = [NSMutableIndexSet new];
+        for (auto const& o : observed) {
+            forEach(o, [&](realm::ColKey colKey, auto const& change, RLMObservationInfo *info) {
+                info->willChange(info->columnName(colKey),
+                                 convert(change.kind), convert(change.indices, indexes));
+            });
+        }
+    }
+    for (auto info : invalidated) {
+        static_cast<RLMObservationInfo *>(info)->prepareForInvalidation();
+    }
+}
+
+void RLMDidChange(std::vector<realm::BindingContext::ObserverState> const& observed,
+                  std::vector<void *> const& invalidated) {
+    if (!observed.empty()) {
+        // Loop in reverse order to avoid O(N^2) behavior in Foundation
+        NSMutableIndexSet *indexes = [NSMutableIndexSet new];
+        for (auto const& o : reverse(observed)) {
+            forEach(o, [&](realm::ColKey col, auto const& change, RLMObservationInfo *info) {
+                info->didChange(info->columnName(col), convert(change.kind), convert(change.indices, indexes));
+            });
+        }
+    }
+    for (auto const& info : reverse(invalidated)) {
+        static_cast<RLMObservationInfo *>(info)->didChange(RLMInvalidatedKey);
+    }
+}

+ 164 - 0
Example/Pods/Realm/Realm/RLMOptionalBase.mm

@@ -0,0 +1,164 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2015 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMOptionalBase.h"
+
+#import "RLMAccessor.hpp"
+#import "RLMObject_Private.hpp"
+#import "RLMProperty.h"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/object.hpp>
+
+namespace {
+struct OptionalBase {
+    virtual id get() = 0;
+    virtual void set(id) = 0;
+    virtual ~OptionalBase() = default;
+};
+
+class UnmanagedOptional : public OptionalBase {
+public:
+    id get() override {
+        return _value;
+    }
+
+    void set(__unsafe_unretained const id newValue) override {
+        @autoreleasepool {
+            RLMObjectBase *object = _parent;
+            [object willChangeValueForKey:_property];
+            _value = newValue;
+            [object didChangeValueForKey:_property];
+        }
+    }
+
+    void attach(__unsafe_unretained RLMObjectBase *const obj, NSString *property) {
+        if (!_property) {
+            _property = property;
+            _parent = obj;
+        }
+    }
+
+private:
+    id _value;
+    NSString *_property;
+    __weak RLMObjectBase *_parent;
+
+};
+
+class ManagedOptional : public OptionalBase {
+public:
+    ManagedOptional(RLMObjectBase *obj, RLMProperty *prop)
+    : _realm(obj->_realm)
+    , _object(obj->_realm->_realm, *obj->_info->objectSchema, obj->_row)
+    , _propertyName(prop.name.UTF8String)
+    , _ctx(*obj->_info)
+    {
+    }
+
+    id get() override {
+        return _object.get_property_value<id>(_ctx, _propertyName);
+    }
+
+    void set(__unsafe_unretained id const value) override {
+        _object.set_property_value(_ctx, _propertyName, value ?: NSNull.null);
+    }
+
+private:
+    // We have to hold onto a strong reference to the Realm as
+    // RLMAccessorContext holds a non-retaining one.
+    __unused RLMRealm *_realm;
+    realm::Object _object;
+    std::string _propertyName;
+    RLMAccessorContext _ctx;
+};
+} // anonymous namespace
+
+@interface RLMOptionalBase () {
+    std::unique_ptr<OptionalBase> _impl;
+}
+@end
+
+@implementation RLMOptionalBase
+- (instancetype)init {
+    return self;
+}
+
+- (BOOL)isKindOfClass:(Class)aClass {
+    return [RLMGetOptional(self) isKindOfClass:aClass] || RLMIsKindOfClass(object_getClass(self), aClass);
+}
+
+- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
+    return [RLMGetOptional(self) methodSignatureForSelector:sel];
+}
+
+- (void)forwardInvocation:(NSInvocation *)invocation {
+    [invocation invokeWithTarget:RLMGetOptional(self)];
+}
+
+- (id)forwardingTargetForSelector:(__unused SEL)sel {
+    return RLMGetOptional(self);
+}
+
+- (BOOL)respondsToSelector:(SEL)aSelector {
+    return [RLMGetOptional(self) respondsToSelector:aSelector];
+}
+
+- (void)doesNotRecognizeSelector:(SEL)aSelector {
+    [RLMGetOptional(self) doesNotRecognizeSelector:aSelector];
+}
+
+id RLMGetOptional(__unsafe_unretained RLMOptionalBase *const self) {
+    try {
+        return self->_impl ? RLMCoerceToNil(self->_impl->get()) : nil;
+    }
+    catch (std::exception const& err) {
+        @throw RLMException(err);
+    }
+}
+
+void RLMSetOptional(__unsafe_unretained RLMOptionalBase *const self, __unsafe_unretained const id value) {
+    try {
+        if (!self->_impl && value) {
+            self->_impl.reset(new UnmanagedOptional);
+        }
+        if (self->_impl) {
+            self->_impl->set(value);
+        }
+    }
+    catch (std::exception const& err) {
+        @throw RLMException(err);
+    }
+}
+
+void RLMInitializeManagedOptional(__unsafe_unretained RLMOptionalBase *const self,
+                                  __unsafe_unretained RLMObjectBase *const parent,
+                                  __unsafe_unretained RLMProperty *const prop) {
+    REALM_ASSERT(parent->_realm);
+    self->_impl.reset(new ManagedOptional(parent, prop));
+}
+
+void RLMInitializeUnmanagedOptional(__unsafe_unretained RLMOptionalBase *const self,
+                                    __unsafe_unretained RLMObjectBase *const parent,
+                                    __unsafe_unretained RLMProperty *const prop) {
+    if (!self->_impl) {
+        self->_impl.reset(new UnmanagedOptional);
+    }
+    static_cast<UnmanagedOptional&>(*self->_impl).attach(parent, prop.name);
+}
+@end

+ 127 - 0
Example/Pods/Realm/Realm/RLMPredicateUtil.mm

@@ -0,0 +1,127 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2015 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#import "RLMPredicateUtil.hpp"
+
+#include <realm/util/assert.hpp>
+
+// NSConditionalExpressionType is new in OS X 10.11 and iOS 9.0
+#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+#define CONDITIONAL_EXPRESSION_DECLARED (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
+#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+#define CONDITIONAL_EXPRESSION_DECLARED (__IPHONE_OS_VERSION_MIN_REQUIRED >= 90000)
+#else
+#define CONDITIONAL_EXPRESSION_DECLARED 0
+#endif
+
+#if !CONDITIONAL_EXPRESSION_DECLARED
+
+#define NSConditionalExpressionType 20
+
+@interface NSExpression (NewIn1011And90)
++ (NSExpression *)expressionForConditional:(NSPredicate *)predicate trueExpression:(NSExpression *)trueExpression falseExpression:(NSExpression *)falseExpression;
+- (NSExpression *)trueExpression;
+- (NSExpression *)falseExpression;
+@end
+
+#endif
+
+namespace {
+
+struct PredicateExpressionTransformer {
+    PredicateExpressionTransformer(ExpressionVisitor visitor) : m_visitor(visitor) { }
+
+    NSExpression *visit(NSExpression *expression) const;
+    NSPredicate *visit(NSPredicate *predicate) const;
+
+    ExpressionVisitor m_visitor;
+};
+
+NSExpression *PredicateExpressionTransformer::visit(NSExpression *expression) const {
+    expression = m_visitor(expression);
+
+    switch (expression.expressionType) {
+        case NSFunctionExpressionType: {
+            NSMutableArray *arguments = [NSMutableArray array];
+            for (NSExpression *argument in expression.arguments) {
+                [arguments addObject:visit(argument)];
+            }
+            if (expression.operand) {
+                return [NSExpression expressionForFunction:visit(expression.operand) selectorName:expression.function arguments:arguments];
+            } else {
+                return [NSExpression expressionForFunction:expression.function arguments:arguments];
+            }
+        }
+
+        case NSUnionSetExpressionType:
+            return [NSExpression expressionForUnionSet:visit(expression.leftExpression) with:visit(expression.rightExpression)];
+        case NSIntersectSetExpressionType:
+            return [NSExpression expressionForIntersectSet:visit(expression.leftExpression) with:visit(expression.rightExpression)];
+        case NSMinusSetExpressionType:
+            return [NSExpression expressionForMinusSet:visit(expression.leftExpression) with:visit(expression.rightExpression)];
+
+        case NSSubqueryExpressionType: {
+            NSExpression *collection = expression.collection;
+            // NSExpression.collection is declared as id, but appears to always hold an NSExpression for subqueries.
+            REALM_ASSERT([collection isKindOfClass:[NSExpression class]]);
+            return [NSExpression expressionForSubquery:visit(collection) usingIteratorVariable:expression.variable predicate:visit(expression.predicate)];
+        }
+
+        case NSAggregateExpressionType: {
+            NSMutableArray *subexpressions = [NSMutableArray array];
+            for (NSExpression *subexpression in expression.collection) {
+                [subexpressions addObject:visit(subexpression)];
+            }
+            return [NSExpression expressionForAggregate:subexpressions];
+        }
+
+        case NSConditionalExpressionType:
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wpartial-availability"
+            return [NSExpression expressionForConditional:visit(expression.predicate) trueExpression:visit(expression.trueExpression) falseExpression:visit(expression.falseExpression)];
+#pragma clang diagnostic pop
+
+        default:
+            // The remaining expression types do not contain nested expressions or predicates.
+            return expression;
+    }
+}
+
+NSPredicate *PredicateExpressionTransformer::visit(NSPredicate *predicate) const {
+    if ([predicate isKindOfClass:[NSCompoundPredicate class]]) {
+        NSCompoundPredicate *compoundPredicate = (NSCompoundPredicate *)predicate;
+        NSMutableArray *subpredicates = [NSMutableArray array];
+        for (NSPredicate *subpredicate in compoundPredicate.subpredicates) {
+            [subpredicates addObject:visit(subpredicate)];
+        }
+        return [[NSCompoundPredicate alloc] initWithType:compoundPredicate.compoundPredicateType subpredicates:subpredicates];
+    }
+    if ([predicate isKindOfClass:[NSComparisonPredicate class]]) {
+        NSComparisonPredicate *comparisonPredicate = (NSComparisonPredicate *)predicate;
+        NSExpression *leftExpression = visit(comparisonPredicate.leftExpression);
+        NSExpression *rightExpression = visit(comparisonPredicate.rightExpression);
+        return [NSComparisonPredicate predicateWithLeftExpression:leftExpression rightExpression:rightExpression modifier:comparisonPredicate.comparisonPredicateModifier type:comparisonPredicate.predicateOperatorType options:comparisonPredicate.options];
+    }
+    return predicate;
+}
+
+} // anonymous namespace
+
+NSPredicate *transformPredicate(NSPredicate *predicate, ExpressionVisitor visitor) {
+    PredicateExpressionTransformer transformer(visitor);
+    return transformer.visit(predicate);
+}

+ 642 - 0
Example/Pods/Realm/Realm/RLMProperty.mm

@@ -0,0 +1,642 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMProperty_Private.hpp"
+
+#import "RLMArray_Private.hpp"
+#import "RLMListBase.h"
+#import "RLMObject.h"
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMObject_Private.h"
+#import "RLMSchema_Private.h"
+#import "RLMSwiftSupport.h"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/property.hpp>
+
+static_assert((int)RLMPropertyTypeInt        == (int)realm::PropertyType::Int);
+static_assert((int)RLMPropertyTypeBool       == (int)realm::PropertyType::Bool);
+static_assert((int)RLMPropertyTypeFloat      == (int)realm::PropertyType::Float);
+static_assert((int)RLMPropertyTypeDouble     == (int)realm::PropertyType::Double);
+static_assert((int)RLMPropertyTypeString     == (int)realm::PropertyType::String);
+static_assert((int)RLMPropertyTypeData       == (int)realm::PropertyType::Data);
+static_assert((int)RLMPropertyTypeDate       == (int)realm::PropertyType::Date);
+static_assert((int)RLMPropertyTypeObject     == (int)realm::PropertyType::Object);
+static_assert((int)RLMPropertyTypeObjectId   == (int)realm::PropertyType::ObjectId);
+static_assert((int)RLMPropertyTypeDecimal128 == (int)realm::PropertyType::Decimal);
+
+BOOL RLMPropertyTypeIsComputed(RLMPropertyType propertyType) {
+    return propertyType == RLMPropertyTypeLinkingObjects;
+}
+
+// Swift obeys the ARC naming conventions for method families (except for init)
+// but the end result doesn't really work (using KVC on a method returning a
+// retained value results in a leak, but not returning a retained value results
+// in crashes). Objective-C makes properties with naming fitting the method
+// families a compile error, so we just disallow them in Swift as well.
+// http://clang.llvm.org/docs/AutomaticReferenceCounting.html#arc-method-families
+void RLMValidateSwiftPropertyName(NSString *name) {
+    // To belong to a method family, the property name must begin with the family
+    // name followed by a non-lowercase letter (or nothing), with an optional
+    // leading underscore
+    const char *str = name.UTF8String;
+    if (str[0] == '_')
+        ++str;
+    auto nameSize = strlen(str);
+
+    // Note that "init" is deliberately not in this list because Swift does not
+    // infer family membership for it.
+    for (auto family : {"alloc", "new", "copy", "mutableCopy"}) {
+        auto familySize = strlen(family);
+        if (nameSize < familySize || !std::equal(str, str + familySize, family)) {
+            continue;
+        }
+        if (familySize == nameSize || !islower(str[familySize])) {
+            @throw RLMException(@"Property names beginning with '%s' are not "
+                                 "supported. Swift follows ARC's ownership "
+                                 "rules for methods based on their name, which "
+                                 "results in memory leaks when accessing "
+                                 "properties which return retained values via KVC.",
+                                family);
+        }
+        return;
+    }
+}
+
+static bool rawTypeShouldBeTreatedAsComputedProperty(NSString *rawType) {
+    return [rawType isEqualToString:@"@\"RLMLinkingObjects\""] || [rawType hasPrefix:@"@\"RLMLinkingObjects<"];
+}
+
+@implementation RLMProperty
+
++ (instancetype)propertyForObjectStoreProperty:(const realm::Property &)prop {
+    auto ret = [[RLMProperty alloc] initWithName:@(prop.name.c_str())
+                                            type:static_cast<RLMPropertyType>(prop.type & ~realm::PropertyType::Flags)
+                                 objectClassName:prop.object_type.length() ? @(prop.object_type.c_str()) : nil
+                          linkOriginPropertyName:prop.link_origin_property_name.length() ? @(prop.link_origin_property_name.c_str()) : nil
+                                         indexed:prop.is_indexed
+                                        optional:is_nullable(prop.type)];
+    if (is_array(prop.type)) {
+        ret->_array = true;
+    }
+    if (!prop.public_name.empty()) {
+        ret->_columnName = ret->_name;
+        ret->_name = @(prop.public_name.c_str());
+    }
+    return ret;
+}
+
+- (instancetype)initWithName:(NSString *)name
+                        type:(RLMPropertyType)type
+             objectClassName:(NSString *)objectClassName
+      linkOriginPropertyName:(NSString *)linkOriginPropertyName
+                     indexed:(BOOL)indexed
+                    optional:(BOOL)optional {
+    self = [super init];
+    if (self) {
+        _name = name;
+        _type = type;
+        _objectClassName = objectClassName;
+        _linkOriginPropertyName = linkOriginPropertyName;
+        _indexed = indexed;
+        _optional = optional;
+        [self updateAccessors];
+    }
+
+    return self;
+}
+
+- (void)setName:(NSString *)name {
+    _name = name;
+    [self updateAccessors];
+}
+
+- (void)updateAccessors {
+    // populate getter/setter names if generic
+    if (!_getterName) {
+        _getterName = _name;
+    }
+    if (!_setterName) {
+        // Objective-C setters only capitalize the first letter of the property name if it falls between 'a' and 'z'
+        int asciiCode = [_name characterAtIndex:0];
+        BOOL shouldUppercase = asciiCode >= 'a' && asciiCode <= 'z';
+        NSString *firstChar = [_name substringToIndex:1];
+        firstChar = shouldUppercase ? firstChar.uppercaseString : firstChar;
+        _setterName = [NSString stringWithFormat:@"set%@%@:", firstChar, [_name substringFromIndex:1]];
+    }
+
+    _getterSel = NSSelectorFromString(_getterName);
+    _setterSel = NSSelectorFromString(_setterName);
+}
+
+static realm::util::Optional<RLMPropertyType> typeFromProtocolString(const char *type) {
+    if (strncmp(type, "RLM", 3)) {
+        return realm::none;
+    }
+    type += 3;
+    if (strcmp(type, "Int>\"") == 0) {
+        return RLMPropertyTypeInt;
+    }
+    if (strcmp(type, "Float>\"") == 0) {
+        return RLMPropertyTypeFloat;
+    }
+    if (strcmp(type, "Double>\"") == 0) {
+        return RLMPropertyTypeDouble;
+    }
+    if (strcmp(type, "Bool>\"") == 0) {
+        return RLMPropertyTypeBool;
+    }
+    if (strcmp(type, "String>\"") == 0) {
+        return RLMPropertyTypeString;
+    }
+    if (strcmp(type, "Data>\"") == 0) {
+        return RLMPropertyTypeData;
+    }
+    if (strcmp(type, "Date>\"") == 0) {
+        return RLMPropertyTypeDate;
+    }
+    if (strcmp(type, "Decimal128>\"") == 0) {
+        return RLMPropertyTypeDecimal128;
+    }
+    if (strcmp(type, "ObjectId>\"") == 0) {
+        return RLMPropertyTypeObjectId;
+    }
+    return realm::none;
+}
+
+// determine RLMPropertyType from objc code - returns true if valid type was found/set
+- (BOOL)setTypeFromRawType:(NSString *)rawType {
+    const char *code = rawType.UTF8String;
+    switch (*code) {
+        case 's':   // short
+        case 'i':   // int
+        case 'l':   // long
+        case 'q':   // long long
+            _type = RLMPropertyTypeInt;
+            return YES;
+        case 'f':
+            _type = RLMPropertyTypeFloat;
+            return YES;
+        case 'd':
+            _type = RLMPropertyTypeDouble;
+            return YES;
+        case 'c':   // BOOL is stored as char - since rlm has no char type this is ok
+        case 'B':
+            _type = RLMPropertyTypeBool;
+            return YES;
+        case '@':
+            break;
+        default:
+            return NO;
+    }
+
+    _optional = true;
+    static const char arrayPrefix[] = "@\"RLMArray<";
+    static const int arrayPrefixLen = sizeof(arrayPrefix) - 1;
+
+    static const char numberPrefix[] = "@\"NSNumber<";
+    static const int numberPrefixLen = sizeof(numberPrefix) - 1;
+
+    static const char linkingObjectsPrefix[] = "@\"RLMLinkingObjects";
+    static const int linkingObjectsPrefixLen = sizeof(linkingObjectsPrefix) - 1;
+
+    if (strcmp(code, "@\"NSString\"") == 0) {
+        _type = RLMPropertyTypeString;
+    }
+    else if (strcmp(code, "@\"NSDate\"") == 0) {
+        _type = RLMPropertyTypeDate;
+    }
+    else if (strcmp(code, "@\"NSData\"") == 0) {
+        _type = RLMPropertyTypeData;
+    }
+    else if (strcmp(code, "@\"RLMDecimal128\"") == 0) {
+        _type = RLMPropertyTypeDecimal128;
+    }
+    else if (strcmp(code, "@\"RLMObjectId\"") == 0) {
+        _type = RLMPropertyTypeObjectId;
+    }
+    else if (strncmp(code, arrayPrefix, arrayPrefixLen) == 0) {
+        _array = true;
+        if (auto type = typeFromProtocolString(code + arrayPrefixLen)) {
+            _type = *type;
+            return YES;
+        }
+
+        // get object class from type string - @"RLMArray<objectClassName>"
+        _objectClassName = [[NSString alloc] initWithBytes:code + arrayPrefixLen
+                                                    length:strlen(code + arrayPrefixLen) - 2 // drop trailing >"
+                                                  encoding:NSUTF8StringEncoding];
+
+        if ([RLMSchema classForString:_objectClassName]) {
+            _optional = false;
+            _type = RLMPropertyTypeObject;
+            return YES;
+        }
+        @throw RLMException(@"Property '%@' is of type 'RLMArray<%@>' which is not a supported RLMArray object type. "
+                            @"RLMArrays can only contain instances of RLMObject subclasses. "
+                            @"See https://realm.io/docs/objc/latest/#to-many for more information.", _name, _objectClassName);
+    }
+    else if (strncmp(code, numberPrefix, numberPrefixLen) == 0) {
+        auto type = typeFromProtocolString(code + numberPrefixLen);
+        if (type && (*type == RLMPropertyTypeInt || *type == RLMPropertyTypeFloat || *type == RLMPropertyTypeDouble || *type == RLMPropertyTypeBool)) {
+            _type = *type;
+            return YES;
+        }
+        @throw RLMException(@"Property '%@' is of type %s which is not a supported NSNumber object type. "
+                            @"NSNumbers can only be RLMInt, RLMFloat, RLMDouble, and RLMBool at the moment. "
+                            @"See https://realm.io/docs/objc/latest for more information.", _name, code + 1);
+    }
+    else if (strncmp(code, linkingObjectsPrefix, linkingObjectsPrefixLen) == 0 &&
+             (code[linkingObjectsPrefixLen] == '"' || code[linkingObjectsPrefixLen] == '<')) {
+        _type = RLMPropertyTypeLinkingObjects;
+        _optional = false;
+        _array = true;
+
+        if (!_objectClassName || !_linkOriginPropertyName) {
+            @throw RLMException(@"Property '%@' is of type RLMLinkingObjects but +linkingObjectsProperties did not specify the class "
+                                "or property that is the origin of the link.", _name);
+        }
+
+        // If the property was declared with a protocol indicating the contained type, validate that it matches
+        // the class from the dictionary returned by +linkingObjectsProperties.
+        if (code[linkingObjectsPrefixLen] == '<') {
+            NSString *classNameFromProtocol = [[NSString alloc] initWithBytes:code + linkingObjectsPrefixLen + 1
+                                                                       length:strlen(code + linkingObjectsPrefixLen) - 3 // drop trailing >"
+                                                                     encoding:NSUTF8StringEncoding];
+            if (![_objectClassName isEqualToString:classNameFromProtocol]) {
+                @throw RLMException(@"Property '%@' was declared with type RLMLinkingObjects<%@>, but a conflicting "
+                                    "class name of '%@' was returned by +linkingObjectsProperties.", _name,
+                                    classNameFromProtocol, _objectClassName);
+            }
+        }
+    }
+    else if (strcmp(code, "@\"NSNumber\"") == 0) {
+        @throw RLMException(@"Property '%@' requires a protocol defining the contained type - example: NSNumber<RLMInt>.", _name);
+    }
+    else if (strcmp(code, "@\"RLMArray\"") == 0) {
+        @throw RLMException(@"Property '%@' requires a protocol defining the contained type - example: RLMArray<Person>.", _name);
+    }
+    else {
+        NSString *className;
+        Class cls = nil;
+        if (code[1] == '\0') {
+            className = @"id";
+        }
+        else {
+            // for objects strip the quotes and @
+            className = [rawType substringWithRange:NSMakeRange(2, rawType.length-3)];
+            cls = [RLMSchema classForString:className];
+        }
+
+        if (!cls) {
+            @throw RLMException(@"Property '%@' is declared as '%@', which is not a supported RLMObject property type. "
+                                @"All properties must be primitives, NSString, NSDate, NSData, NSNumber, RLMArray, RLMLinkingObjects, RLMDecimal128, RLMObjectId, or subclasses of RLMObject. "
+                                @"See https://realm.io/docs/objc/latest/api/Classes/RLMObject.html for more information.", _name, className);
+        }
+
+        _type = RLMPropertyTypeObject;
+        _optional = true;
+        _objectClassName = [cls className] ?: className;
+    }
+    return YES;
+}
+
+- (void)parseObjcProperty:(objc_property_t)property
+                 readOnly:(bool *)readOnly
+                 computed:(bool *)computed
+                  rawType:(NSString **)rawType {
+    unsigned int count;
+    objc_property_attribute_t *attrs = property_copyAttributeList(property, &count);
+
+    *computed = true;
+    for (size_t i = 0; i < count; ++i) {
+        switch (*attrs[i].name) {
+            case 'T':
+                *rawType = @(attrs[i].value);
+                break;
+            case 'R':
+                *readOnly = true;
+                break;
+            case 'G':
+                _getterName = @(attrs[i].value);
+                break;
+            case 'S':
+                _setterName = @(attrs[i].value);
+                break;
+            case 'V': // backing ivar name
+                *computed = false;
+                break;
+
+            case '&':
+                // retain/assign
+                break;
+            case 'C':
+                // copy
+                break;
+            case 'D':
+                // dynamic
+                break;
+            case 'N':
+                // nonatomic
+                break;
+            case 'P':
+                // GC'able
+                break;
+            case 'W':
+                // weak
+                break;
+            default:
+                break;
+        }
+    }
+    free(attrs);
+}
+
+- (instancetype)initSwiftPropertyWithName:(NSString *)name
+                                  indexed:(BOOL)indexed
+                   linkPropertyDescriptor:(RLMPropertyDescriptor *)linkPropertyDescriptor
+                                 property:(objc_property_t)property
+                                 instance:(RLMObject *)obj {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    RLMValidateSwiftPropertyName(name);
+
+    _name = name;
+    _indexed = indexed;
+
+    if (linkPropertyDescriptor) {
+        _objectClassName = [linkPropertyDescriptor.objectClass className];
+        _linkOriginPropertyName = linkPropertyDescriptor.propertyName;
+    }
+
+    NSString *rawType;
+    bool readOnly = false;
+    bool isComputed = false;
+    [self parseObjcProperty:property readOnly:&readOnly computed:&isComputed rawType:&rawType];
+
+    // Swift sometimes doesn't explicitly set the ivar name in the metadata, so check if
+    // there's an ivar with the same name as the property.
+    if (!readOnly && isComputed && class_getInstanceVariable([obj class], name.UTF8String)) {
+        isComputed = false;
+    }
+
+    // Check if there's a storage ivar for a lazy property in this name. We don't honor
+    // @lazy in managed objects, but allow it for unmanaged objects which are
+    // subclasses of RLMObject (but not RealmSwift.Object). It's unclear if there's a
+    // good reason for this difference.
+    if (!readOnly && isComputed) {
+        // Xcode 10 and earlier
+        NSString *backingPropertyName = [NSString stringWithFormat:@"%@.storage", name];
+        isComputed = !class_getInstanceVariable([obj class], backingPropertyName.UTF8String);
+    }
+    if (!readOnly && isComputed) {
+        // Xcode 11
+        NSString *backingPropertyName = [NSString stringWithFormat:@"$__lazy_storage_$_%@", name];
+        isComputed = !class_getInstanceVariable([obj class], backingPropertyName.UTF8String);
+    }
+
+    if (readOnly || isComputed) {
+        return nil;
+    }
+
+    id propertyValue = [obj valueForKey:_name];
+
+    // FIXME: temporarily workaround added since Objective-C generics used in Swift show up as `@`
+    //        * broken starting in Swift 3.0 Xcode 8 b1
+    //        * tested to still be broken in Swift 3.0 Xcode 8 b6
+    //        * if the Realm Objective-C Swift tests pass with this removed, it's been fixed
+    //        * once it has been fixed, remove this entire conditional block (contents included) entirely
+    //        * Bug Report: SR-2031 https://bugs.swift.org/browse/SR-2031
+    if ([rawType isEqualToString:@"@"]) {
+        if (propertyValue) {
+            rawType = [NSString stringWithFormat:@"@\"%@\"", [propertyValue class]];
+        } else if (linkPropertyDescriptor) {
+            // we're going to naively assume that the user used the correct type since we can't check it
+            rawType = @"@\"RLMLinkingObjects\"";
+        }
+    }
+
+    // convert array types to objc variant
+    if ([rawType isEqualToString:@"@\"RLMArray\""]) {
+        RLMArray *value = propertyValue;
+        _type = value.type;
+        _optional = value.optional;
+        _array = true;
+        _objectClassName = value.objectClassName;
+        if (_type == RLMPropertyTypeObject && ![RLMSchema classForString:_objectClassName]) {
+            @throw RLMException(@"Property '%@' is of type 'RLMArray<%@>' which is not a supported RLMArray object type. "
+                                @"RLMArrays can only contain instances of RLMObject subclasses. "
+                                @"See https://realm.io/docs/objc/latest/#to-many for more information.", _name, _objectClassName);
+        }
+    }
+    else if ([rawType isEqualToString:@"@\"NSNumber\""]) {
+        const char *numberType = [propertyValue objCType];
+        if (!numberType) {
+            @throw RLMException(@"Can't persist NSNumber without default value: use a Swift-native number type or provide a default value.");
+        }
+        _optional = true;
+        switch (*numberType) {
+            case 'i': case 'l': case 'q':
+                _type = RLMPropertyTypeInt;
+                break;
+            case 'f':
+                _type = RLMPropertyTypeFloat;
+                break;
+            case 'd':
+                _type = RLMPropertyTypeDouble;
+                break;
+            case 'B': case 'c':
+                _type = RLMPropertyTypeBool;
+                break;
+            default:
+                @throw RLMException(@"Can't persist NSNumber of type '%s': only integers, floats, doubles, and bools are currently supported.", numberType);
+        }
+    }
+    else if (![self setTypeFromRawType:rawType]) {
+        @throw RLMException(@"Can't persist property '%@' with incompatible type. "
+                            "Add to Object.ignoredProperties() class method to ignore.",
+                            self.name);
+    }
+
+    if ([rawType isEqualToString:@"c"]) {
+        // Check if it's a BOOL or Int8 by trying to set it to 2 and seeing if
+        // it actually sets it to 1.
+        [obj setValue:@2 forKey:name];
+        NSNumber *value = [obj valueForKey:name];
+        _type = value.intValue == 2 ? RLMPropertyTypeInt : RLMPropertyTypeBool;
+    }
+
+    // update getter/setter names
+    [self updateAccessors];
+
+    return self;
+}
+
+- (instancetype)initWithName:(NSString *)name
+                     indexed:(BOOL)indexed
+      linkPropertyDescriptor:(RLMPropertyDescriptor *)linkPropertyDescriptor
+                    property:(objc_property_t)property
+{
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    _name = name;
+    _indexed = indexed;
+
+    if (linkPropertyDescriptor) {
+        _objectClassName = [linkPropertyDescriptor.objectClass className];
+        _linkOriginPropertyName = linkPropertyDescriptor.propertyName;
+    }
+
+    NSString *rawType;
+    bool isReadOnly = false;
+    bool isComputed = false;
+    [self parseObjcProperty:property readOnly:&isReadOnly computed:&isComputed rawType:&rawType];
+    bool shouldBeTreatedAsComputedProperty = rawTypeShouldBeTreatedAsComputedProperty(rawType);
+    if ((isReadOnly || isComputed) && !shouldBeTreatedAsComputedProperty) {
+        return nil;
+    }
+
+    if (![self setTypeFromRawType:rawType]) {
+        @throw RLMException(@"Can't persist property '%@' with incompatible type. "
+                             "Add to ignoredPropertyNames: method to ignore.", self.name);
+    }
+
+    if (!isReadOnly && shouldBeTreatedAsComputedProperty) {
+        @throw RLMException(@"Property '%@' must be declared as readonly as %@ properties cannot be written to.",
+                            self.name, RLMTypeToString(_type));
+    }
+
+    // update getter/setter names
+    [self updateAccessors];
+
+    return self;
+}
+
+- (id)copyWithZone:(NSZone *)zone {
+    RLMProperty *prop = [[RLMProperty allocWithZone:zone] init];
+    prop->_name = _name;
+    prop->_columnName = _columnName;
+    prop->_type = _type;
+    prop->_objectClassName = _objectClassName;
+    prop->_array = _array;
+    prop->_indexed = _indexed;
+    prop->_getterName = _getterName;
+    prop->_setterName = _setterName;
+    prop->_getterSel = _getterSel;
+    prop->_setterSel = _setterSel;
+    prop->_isPrimary = _isPrimary;
+    prop->_swiftIvar = _swiftIvar;
+    prop->_optional = _optional;
+    prop->_linkOriginPropertyName = _linkOriginPropertyName;
+    return prop;
+}
+
+- (RLMProperty *)copyWithNewName:(NSString *)name {
+    RLMProperty *prop = [self copy];
+    prop.name = name;
+    return prop;
+}
+
+- (BOOL)isEqual:(id)object {
+    if (![object isKindOfClass:[RLMProperty class]]) {
+        return NO;
+    }
+
+    return [self isEqualToProperty:object];
+}
+
+- (BOOL)isEqualToProperty:(RLMProperty *)property {
+    return _type == property->_type
+        && _indexed == property->_indexed
+        && _isPrimary == property->_isPrimary
+        && _optional == property->_optional
+        && [_name isEqualToString:property->_name]
+        && (_objectClassName == property->_objectClassName  || [_objectClassName isEqualToString:property->_objectClassName])
+        && (_linkOriginPropertyName == property->_linkOriginPropertyName ||
+            [_linkOriginPropertyName isEqualToString:property->_linkOriginPropertyName]);
+}
+
+- (NSString *)description {
+    NSString *objectClassName = @"";
+    if (self.type == RLMPropertyTypeObject || self.type == RLMPropertyTypeLinkingObjects) {
+        objectClassName = [NSString stringWithFormat:
+                           @"\tobjectClassName = %@;\n"
+                           @"\tlinkOriginPropertyName = %@;\n",
+                           self.objectClassName, self.linkOriginPropertyName];
+    }
+    return [NSString stringWithFormat:
+            @"%@ {\n"
+             "\ttype = %@;\n"
+             "%@"
+             "\tindexed = %@;\n"
+             "\tisPrimary = %@;\n"
+             "\tarray = %@;\n"
+             "\toptional = %@;\n"
+             "}",
+            self.name, RLMTypeToString(self.type),
+            objectClassName,
+            self.indexed ? @"YES" : @"NO",
+            self.isPrimary ? @"YES" : @"NO",
+            self.array ? @"YES" : @"NO",
+            self.optional ? @"YES" : @"NO"];
+}
+
+- (NSString *)columnName {
+    return _columnName ?: _name;
+}
+
+- (realm::Property)objectStoreCopy:(RLMSchema *)schema {
+    realm::Property p;
+    p.name = self.columnName.UTF8String;
+    if (_objectClassName) {
+        RLMObjectSchema *targetSchema = schema[_objectClassName];
+        p.object_type = (targetSchema.objectName ?: _objectClassName).UTF8String;
+        if (_linkOriginPropertyName) {
+            p.link_origin_property_name = (targetSchema[_linkOriginPropertyName].columnName ?: _linkOriginPropertyName).UTF8String;
+        }
+    }
+    p.is_indexed = static_cast<bool>(_indexed);
+    p.type = static_cast<realm::PropertyType>(_type);
+    if (_array) {
+        p.type |= realm::PropertyType::Array;
+    }
+    if (_optional) {
+        p.type |= realm::PropertyType::Nullable;
+    }
+    return p;
+}
+
+@end
+
+@implementation RLMPropertyDescriptor
+
++ (instancetype)descriptorWithClass:(Class)objectClass propertyName:(NSString *)propertyName
+{
+    RLMPropertyDescriptor *descriptor = [[RLMPropertyDescriptor alloc] init];
+    descriptor->_objectClass = objectClass;
+    descriptor->_propertyName = propertyName;
+    return descriptor;
+}
+
+@end

+ 42 - 0
Example/Pods/Realm/Realm/RLMProviderClient.mm

@@ -0,0 +1,42 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMProviderClient_Private.hpp"
+
+#import "RLMApp_Private.hpp"
+
+#import <realm/object-store/sync/app.hpp>
+#import <realm/util/optional.hpp>
+
+@implementation RLMProviderClient
+- (instancetype)initWithApp:(RLMApp *)app {
+    self = [super init];
+    if (self) {
+        _app = app;
+    }
+    return self;
+}
+
+- (void)handleResponse:(realm::util::Optional<realm::app::AppError>)error
+            completion:(RLMProviderClientOptionalErrorBlock)completion {
+    if (error && error->error_code) {
+        return completion(RLMAppErrorToNSError(*error));
+    }
+    completion(nil);
+}
+@end

+ 59 - 0
Example/Pods/Realm/Realm/RLMPushClient.mm

@@ -0,0 +1,59 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMPushClient_Private.hpp"
+
+#import "RLMApp_Private.hpp"
+#import "RLMUser_Private.hpp"
+
+#import <realm/object-store/sync/push_client.hpp>
+
+using realm::util::Optional;
+
+@implementation RLMPushClient {
+    Optional<realm::app::PushClient> _pushClient;
+}
+
+- (instancetype)initWithPushClient:(realm::app::PushClient&&)pushClient {
+    if (self = [super init]) {
+        _pushClient = std::move(pushClient);
+        return self;
+    }
+    return nil;
+}
+
+- (void)registerDeviceWithToken:(NSString *)token user:(RLMUser *)user completion:(RLMOptionalErrorBlock)completion {
+    _pushClient->register_device(token.UTF8String, user._syncUser, ^(Optional<realm::app::AppError> error) {
+        if (error && error->error_code) {
+            return completion(RLMAppErrorToNSError(*error));
+        }
+        completion(nil);
+    });
+}
+
+
+- (void)deregisterDeviceForUser:(RLMUser *)user completion:(RLMOptionalErrorBlock)completion {
+    _pushClient->deregister_device(user._syncUser, ^(Optional<realm::app::AppError> error) {
+        if (error && error->error_code) {
+            return completion(RLMAppErrorToNSError(*error));
+        }
+        completion(nil);
+    });
+}
+
+@end

+ 1571 - 0
Example/Pods/Realm/Realm/RLMQueryUtil.mm

@@ -0,0 +1,1571 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMQueryUtil.hpp"
+
+#import "RLMArray.h"
+#import "RLMDecimal128_Private.hpp"
+#import "RLMObjectId_Private.hpp"
+#import "RLMObjectSchema_Private.h"
+#import "RLMObject_Private.hpp"
+#import "RLMPredicateUtil.hpp"
+#import "RLMProperty_Private.h"
+#import "RLMSchema.h"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/object_store.hpp>
+#import <realm/object-store/results.hpp>
+#import <realm/query_engine.hpp>
+#import <realm/query_expression.hpp>
+#import <realm/util/cf_ptr.hpp>
+#import <realm/util/overload.hpp>
+
+using namespace realm;
+
+NSString * const RLMPropertiesComparisonTypeMismatchException = @"RLMPropertiesComparisonTypeMismatchException";
+NSString * const RLMUnsupportedTypesFoundInPropertyComparisonException = @"RLMUnsupportedTypesFoundInPropertyComparisonException";
+
+NSString * const RLMPropertiesComparisonTypeMismatchReason = @"Property type mismatch between %@ and %@";
+NSString * const RLMUnsupportedTypesFoundInPropertyComparisonReason = @"Comparison between %@ and %@";
+
+namespace {
+
+// small helper to create the many exceptions thrown when parsing predicates
+[[gnu::cold]] [[noreturn]]
+void throwException(NSString *name, NSString *format, ...) {
+    va_list args;
+    va_start(args, format);
+    NSString *reason = [[NSString alloc] initWithFormat:format arguments:args];
+    va_end(args);
+
+    @throw [NSException exceptionWithName:name reason:reason userInfo:nil];
+}
+
+// check a precondition and throw an exception if it is not met
+// this should be used iff the condition being false indicates a bug in the caller
+// of the function checking its preconditions
+void RLMPrecondition(bool condition, NSString *name, NSString *format, ...) {
+    if (__builtin_expect(condition, 1)) {
+        return;
+    }
+
+    va_list args;
+    va_start(args, format);
+    NSString *reason = [[NSString alloc] initWithFormat:format arguments:args];
+    va_end(args);
+
+    @throw [NSException exceptionWithName:name reason:reason userInfo:nil];
+}
+
+BOOL propertyTypeIsNumeric(RLMPropertyType propertyType) {
+    switch (propertyType) {
+        case RLMPropertyTypeInt:
+        case RLMPropertyTypeFloat:
+        case RLMPropertyTypeDouble:
+        case RLMPropertyTypeDecimal128:
+        case RLMPropertyTypeDate:
+            return YES;
+        default:
+            return NO;
+    }
+}
+
+bool isObjectValidForProperty(id value, RLMProperty *prop) {
+    if (prop.array) {
+        if (prop.type == RLMPropertyTypeObject || prop.type == RLMPropertyTypeLinkingObjects) {
+            return [RLMObjectBaseObjectSchema(RLMDynamicCast<RLMObjectBase>(value)).className isEqualToString:prop.objectClassName];
+        }
+        return RLMValidateValue(value, prop.type, prop.optional, false, nil);
+    }
+    return RLMIsObjectValidForProperty(value, prop);
+}
+
+
+// Equal and ContainsSubstring are used by QueryBuilder::add_string_constraint as the comparator
+// for performing diacritic-insensitive comparisons.
+
+StringData get_string(Mixed const& m) {
+    if (m.is_null())
+        return StringData();
+    if (m.get_type() == type_String)
+        return m.get_string();
+    auto b = m.get_binary();
+    return StringData(b.data(), b.size());
+}
+
+bool equal(CFStringCompareFlags options, StringData v1, StringData v2)
+{
+    if (v1.is_null() || v2.is_null()) {
+        return v1.is_null() == v2.is_null();
+    }
+
+    auto s1 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v1.data(), v1.size(),
+                                                          kCFStringEncodingUTF8, false, kCFAllocatorNull));
+    auto s2 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v2.data(), v2.size(),
+                                                          kCFStringEncodingUTF8, false, kCFAllocatorNull));
+
+    return CFStringCompare(s1.get(), s2.get(), options) == kCFCompareEqualTo;
+}
+
+template <CFStringCompareFlags options>
+struct Equal {
+    using CaseSensitive = Equal<options & ~kCFCompareCaseInsensitive>;
+    using CaseInsensitive = Equal<options | kCFCompareCaseInsensitive>;
+
+    bool operator()(Mixed v1, Mixed v2) const
+    {
+        return equal(options, get_string(v1), get_string(v2));
+    }
+
+    static const char* description() { return options & kCFCompareCaseInsensitive ? "==[cd]" : "==[d]"; }
+};
+
+template <CFStringCompareFlags options>
+struct NotEqual {
+    using CaseSensitive = NotEqual<options & ~kCFCompareCaseInsensitive>;
+    using CaseInsensitive = NotEqual<options | kCFCompareCaseInsensitive>;
+
+    bool operator()(Mixed v1, Mixed v2) const
+    {
+        return !equal(options, get_string(v1), get_string(v2));
+    }
+
+    static const char* description() { return options & kCFCompareCaseInsensitive ? "!=[cd]" : "!=[d]"; }
+};
+
+bool contains_substring(CFStringCompareFlags options, StringData v1, StringData v2)
+{
+    if (v2.is_null()) {
+        // Everything contains NULL
+        return true;
+    }
+
+    if (v1.is_null()) {
+        // NULL contains nothing (except NULL, handled above)
+        return false;
+    }
+
+    if (v2.size() == 0) {
+        // Everything (except NULL, handled above) contains the empty string
+        return true;
+    }
+
+    auto s1 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v1.data(), v1.size(),
+                                                          kCFStringEncodingUTF8, false, kCFAllocatorNull));
+    auto s2 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v2.data(), v2.size(),
+                                                          kCFStringEncodingUTF8, false, kCFAllocatorNull));
+
+    return CFStringFind(s1.get(), s2.get(), options).location != kCFNotFound;
+}
+
+template <CFStringCompareFlags options>
+struct ContainsSubstring {
+    using CaseSensitive = ContainsSubstring<options & ~kCFCompareCaseInsensitive>;
+    using CaseInsensitive = ContainsSubstring<options | kCFCompareCaseInsensitive>;
+
+    bool operator()(Mixed v1, Mixed v2) const
+    {
+        return contains_substring(options, get_string(v1), get_string(v2));
+    }
+
+    static const char* description() { return options & kCFCompareCaseInsensitive ? "CONTAINS[cd]" : "CONTAINS[d]"; }
+};
+
+
+NSString *operatorName(NSPredicateOperatorType operatorType)
+{
+    switch (operatorType) {
+        case NSLessThanPredicateOperatorType:
+            return @"<";
+        case NSLessThanOrEqualToPredicateOperatorType:
+            return @"<=";
+        case NSGreaterThanPredicateOperatorType:
+            return @">";
+        case NSGreaterThanOrEqualToPredicateOperatorType:
+            return @">=";
+        case NSEqualToPredicateOperatorType:
+            return @"==";
+        case NSNotEqualToPredicateOperatorType:
+            return @"!=";
+        case NSMatchesPredicateOperatorType:
+            return @"MATCHES";
+        case NSLikePredicateOperatorType:
+            return @"LIKE";
+        case NSBeginsWithPredicateOperatorType:
+            return @"BEGINSWITH";
+        case NSEndsWithPredicateOperatorType:
+            return @"ENDSWITH";
+        case NSInPredicateOperatorType:
+            return @"IN";
+        case NSContainsPredicateOperatorType:
+            return @"CONTAINS";
+        case NSBetweenPredicateOperatorType:
+            return @"BETWEEN";
+        case NSCustomSelectorPredicateOperatorType:
+            return @"custom selector";
+    }
+
+    return [NSString stringWithFormat:@"unknown operator %lu", (unsigned long)operatorType];
+}
+
+[[gnu::cold]] [[noreturn]]
+void unsupportedOperator(RLMPropertyType datatype, NSPredicateOperatorType operatorType) {
+    throwException(@"Invalid operator type",
+                   @"Operator '%@' not supported for type '%@'",
+                   operatorName(operatorType), RLMTypeToString(datatype));
+}
+
+bool isNSNull(id value) {
+    return !value || value == NSNull.null;
+}
+
+template<typename T>
+bool isNSNull(T) {
+    return false;
+}
+
+Table& get_table(Group& group, RLMObjectSchema *objectSchema)
+{
+    return *ObjectStore::table_for_object_type(group, objectSchema.objectName.UTF8String);
+}
+
+// A reference to a column within a query. Can be resolved to a Columns<T> for use in query expressions.
+class ColumnReference {
+public:
+    ColumnReference(Query& query, Group& group, RLMSchema *schema, RLMProperty* property, const std::vector<RLMProperty*>& links = {})
+    : m_links(links), m_property(property), m_schema(schema), m_group(&group), m_query(&query), m_table(query.get_table())
+    {
+        auto& table = walk_link_chain([](Table const&, ColKey, RLMPropertyType) { });
+        m_col = table.get_column_key(m_property.columnName.UTF8String);
+    }
+
+    template <typename T, typename... SubQuery>
+    auto resolve(SubQuery&&... subquery) const
+    {
+        static_assert(sizeof...(SubQuery) < 2, "resolve() takes at most one subquery");
+        LinkChain lc = link_chain();
+
+        if (type() != RLMPropertyTypeLinkingObjects) {
+            return lc.column<T>(column(), std::forward<SubQuery>(subquery)...);
+        }
+
+        if constexpr (std::is_same_v<T, Link>) {
+            auto [table, col] = link_origin(m_property);
+            return lc.column<T>(table, col, std::forward<SubQuery>(subquery)...);
+        }
+
+        REALM_TERMINATE("LinkingObjects property did not have column type Link");
+    }
+
+    RLMProperty *property() const { return m_property; }
+    ColKey column() const { return m_col; }
+    RLMPropertyType type() const { return property().type; }
+    Group& group() const { return *m_group; }
+
+    RLMObjectSchema *link_target_object_schema() const
+    {
+        REALM_ASSERT(is_link());
+        return m_schema[property().objectClassName];
+    }
+
+    bool is_link() const noexcept {
+        return type() == RLMPropertyTypeLinkingObjects || type() == RLMPropertyTypeObject;
+    }
+
+    bool has_any_to_many_links() const {
+        return std::any_of(begin(m_links), end(m_links),
+                           [](RLMProperty *property) { return property.array; });
+    }
+
+    ColumnReference last_link_column() const {
+        REALM_ASSERT(!m_links.empty());
+        return {*m_query, *m_group, m_schema, m_links.back(), {m_links.begin(), m_links.end() - 1}};
+    }
+
+    ColumnReference column_ignoring_links(Query& query) const {
+        return {query, *m_group, m_schema, m_property};
+    }
+
+private:
+    template<typename Func>
+    Table const& walk_link_chain(Func&& func) const
+    {
+        auto table = m_query->get_table().unchecked_ptr();
+        for (const auto& link : m_links) {
+            if (link.type != RLMPropertyTypeLinkingObjects) {
+                auto index = table->get_column_key(link.columnName.UTF8String);
+                func(*table, index, link.type);
+                table = table->get_link_target(index).unchecked_ptr();
+            }
+            else {
+                auto [link_origin_table, link_origin_column] = link_origin(link);
+                func(link_origin_table, link_origin_column, link.type);
+                table = &link_origin_table;
+            }
+        }
+        return *table;
+    }
+
+    std::pair<Table&, ColKey> link_origin(RLMProperty *prop) const
+    {
+        RLMObjectSchema *link_origin_schema = m_schema[prop.objectClassName];
+        Table& link_origin_table = get_table(*m_group, link_origin_schema);
+        NSString *column_name = link_origin_schema[prop.linkOriginPropertyName].columnName;
+        auto link_origin_column = link_origin_table.get_column_key(column_name.UTF8String);
+        return {link_origin_table, link_origin_column};
+    }
+
+    LinkChain link_chain() const
+    {
+        LinkChain lc(m_table);
+        walk_link_chain([&](Table const& link_origin, ColKey col, RLMPropertyType type) {
+            if (type != RLMPropertyTypeLinkingObjects) {
+                lc.link(col);
+            }
+            else {
+                lc.backlink(link_origin, col);
+            }
+        });
+        return lc;
+    }
+
+    std::vector<RLMProperty*> m_links;
+    RLMProperty *m_property;
+    RLMSchema *m_schema;
+    Group *m_group;
+    Query *m_query;
+    ConstTableRef m_table;
+    ColKey m_col;
+};
+
+class CollectionOperation {
+public:
+    enum Type {
+        Count,
+        Minimum,
+        Maximum,
+        Sum,
+        Average,
+    };
+
+    CollectionOperation(Type type, ColumnReference link_column, util::Optional<ColumnReference> column)
+        : m_type(type)
+        , m_link_column(std::move(link_column))
+        , m_column(std::move(column))
+    {
+        RLMPrecondition(m_link_column.property().array,
+                        @"Invalid predicate", @"Collection operation can only be applied to a property of type RLMArray.");
+
+        switch (m_type) {
+            case Count:
+                RLMPrecondition(!m_column, @"Invalid predicate", @"Result of @count does not have any properties.");
+                break;
+            case Minimum:
+            case Maximum:
+            case Sum:
+            case Average: {
+                if (!m_link_column.is_link()) {
+                    m_column = m_link_column;
+                }
+                RLMPrecondition(m_column && propertyTypeIsNumeric(m_column->type()), @"Invalid predicate",
+                                @"%@ can only be applied to a numeric property.", name_for_type(m_type));
+                break;
+            }
+        }
+    }
+
+    CollectionOperation(NSString *operationName, ColumnReference link_column,
+                        util::Optional<ColumnReference> column = util::none)
+        : CollectionOperation(type_for_name(operationName), std::move(link_column), std::move(column))
+    {
+    }
+
+    Type type() const { return m_type; }
+    const ColumnReference& link_column() const { return m_link_column; }
+    const ColumnReference& column() const { return *m_column; }
+
+    void validate_comparison(id value) const {
+        bool valid = true;
+        switch (m_type) {
+            case Count:
+                RLMPrecondition([value isKindOfClass:[NSNumber class]], @"Invalid operand",
+                                @"%@ can only be compared with a numeric value.", name_for_type(m_type));
+                return;
+            case Average:
+            case Minimum:
+            case Maximum:
+                // Null on min/max/average matches arrays with no non-null values, including on non-nullable types
+                valid = isNSNull(value) || isObjectValidForProperty(value, m_column->property());
+                break;
+            case Sum:
+                // Sums are never null
+                valid = !isNSNull(value) && isObjectValidForProperty(value, m_column->property());
+                break;
+        }
+        RLMPrecondition(valid, @"Invalid operand",
+                        @"%@ on a property of type %@ cannot be compared with '%@'",
+                        name_for_type(m_type), RLMTypeToString(m_column->type()), value);
+    }
+
+    void validate_comparison(const ColumnReference& column) const {
+        switch (m_type) {
+            case Count:
+                RLMPrecondition(propertyTypeIsNumeric(column.type()), @"Invalid operand",
+                                @"%@ can only be compared with a numeric value.", name_for_type(m_type));
+                break;
+            case Average:
+            case Minimum:
+            case Maximum:
+            case Sum:
+                RLMPrecondition(propertyTypeIsNumeric(column.type()), @"Invalid operand",
+                                @"%@ on a property of type %@ cannot be compared with property of type '%@'",
+                                name_for_type(m_type), RLMTypeToString(m_column->type()), RLMTypeToString(column.type()));
+                break;
+        }
+    }
+
+private:
+    static Type type_for_name(NSString *name) {
+        if ([name isEqualToString:@"@count"]) {
+            return Count;
+        }
+        if ([name isEqualToString:@"@min"]) {
+            return Minimum;
+        }
+        if ([name isEqualToString:@"@max"]) {
+            return Maximum;
+        }
+        if ([name isEqualToString:@"@sum"]) {
+            return Sum;
+        }
+        if ([name isEqualToString:@"@avg"]) {
+            return Average;
+        }
+        throwException(@"Invalid predicate", @"Unsupported collection operation '%@'", name);
+    }
+
+    static NSString *name_for_type(Type type) {
+        switch (type) {
+            case Count: return @"@count";
+            case Minimum: return @"@min";
+            case Maximum: return @"@max";
+            case Sum: return @"@sum";
+            case Average: return @"@avg";
+        }
+    }
+
+    Type m_type;
+    ColumnReference m_link_column;
+    util::Optional<ColumnReference> m_column;
+};
+
+class QueryBuilder {
+public:
+    QueryBuilder(Query& query, Group& group, RLMSchema *schema)
+    : m_query(query), m_group(group), m_schema(schema) { }
+
+    void apply_predicate(NSPredicate *predicate, RLMObjectSchema *objectSchema);
+
+
+    void apply_collection_operator_expression(RLMObjectSchema *desc, NSString *keyPath, id value, NSComparisonPredicate *pred);
+    void apply_value_expression(RLMObjectSchema *desc, NSString *keyPath, id value, NSComparisonPredicate *pred);
+    void apply_column_expression(RLMObjectSchema *desc, NSString *leftKeyPath, NSString *rightKeyPath, NSComparisonPredicate *predicate);
+    void apply_function_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression,
+                                   NSPredicateOperatorType operatorType, NSExpression *right);
+
+
+    template <typename A, typename B>
+    void add_numeric_constraint(RLMPropertyType datatype,
+                                NSPredicateOperatorType operatorType,
+                                A&& lhs, B&& rhs);
+
+    template <typename A, typename B>
+    void add_bool_constraint(RLMPropertyType, NSPredicateOperatorType operatorType, A&& lhs, B&& rhs);
+
+    template<typename T>
+    void add_substring_constraint(const T& value, Query condition);
+    template<typename T>
+    void add_substring_constraint(const Columns<T>& value, Query condition);
+
+    template <typename C, typename T>
+    void add_string_constraint(NSPredicateOperatorType operatorType,
+                               NSComparisonPredicateOptions predicateOptions,
+                               Columns<C>&& column,
+                               T value);
+
+    template <typename C, typename T>
+    void add_diacritic_sensitive_string_constraint(NSPredicateOperatorType operatorType,
+                                                   NSComparisonPredicateOptions predicateOptions,
+                                                   Columns<C>&& column,
+                                                   T value);
+
+    template <typename R>
+    void add_constraint(NSPredicateOperatorType operatorType,
+                        NSComparisonPredicateOptions predicateOptions,
+                        ColumnReference const& column, R const& rhs);
+    template <template<typename> typename W, typename T>
+    void do_add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType,
+                           NSComparisonPredicateOptions predicateOptions, ColumnReference const& column, T&& value);
+
+    void add_between_constraint(const ColumnReference& column, id value);
+
+    void add_link_constraint(NSPredicateOperatorType operatorType, const Columns<Link>& column, RLMObjectBase *obj);
+    void add_link_constraint(NSPredicateOperatorType operatorType, const Columns<Link>& column, realm::null);
+    void add_link_constraint(NSPredicateOperatorType, const Columns<Link>&, const ColumnReference&);
+
+    template <CollectionOperation::Type Operation, bool IsLinkCollection, typename R>
+    void add_collection_operation_constraint(NSPredicateOperatorType operatorType,
+                                             const CollectionOperation& collectionOperation, R rhs);
+    template <CollectionOperation::Type Operation, typename R>
+    void add_collection_operation_constraint(NSPredicateOperatorType operatorType,
+                                             const CollectionOperation& collectionOperation, R rhs);
+    template <typename R>
+    void add_collection_operation_constraint(NSPredicateOperatorType operatorType,
+                                             const CollectionOperation& collectionOperation, R rhs);
+
+
+    CollectionOperation collection_operation_from_key_path(RLMObjectSchema *desc, NSString *keyPath);
+    ColumnReference column_reference_from_key_path(RLMObjectSchema *objectSchema, NSString *keyPath, bool isAggregate);
+
+private:
+    Query& m_query;
+    Group& m_group;
+    RLMSchema *m_schema;
+};
+
+// add a clause for numeric constraints based on operator type
+template <typename A, typename B>
+void QueryBuilder::add_numeric_constraint(RLMPropertyType datatype,
+                                          NSPredicateOperatorType operatorType,
+                                          A&& lhs, B&& rhs)
+{
+    switch (operatorType) {
+        case NSLessThanPredicateOperatorType:
+            m_query.and_query(lhs < rhs);
+            break;
+        case NSLessThanOrEqualToPredicateOperatorType:
+            m_query.and_query(lhs <= rhs);
+            break;
+        case NSGreaterThanPredicateOperatorType:
+            m_query.and_query(lhs > rhs);
+            break;
+        case NSGreaterThanOrEqualToPredicateOperatorType:
+            m_query.and_query(lhs >= rhs);
+            break;
+        case NSEqualToPredicateOperatorType:
+            m_query.and_query(lhs == rhs);
+            break;
+        case NSNotEqualToPredicateOperatorType:
+            m_query.and_query(lhs != rhs);
+            break;
+        default:
+            unsupportedOperator(datatype, operatorType);
+    }
+}
+
+template <typename A, typename B>
+void QueryBuilder::add_bool_constraint(RLMPropertyType datatype,
+                                       NSPredicateOperatorType operatorType,
+                                       A&& lhs, B&& rhs) {
+    switch (operatorType) {
+        case NSEqualToPredicateOperatorType:
+            m_query.and_query(lhs == rhs);
+            break;
+        case NSNotEqualToPredicateOperatorType:
+            m_query.and_query(lhs != rhs);
+            break;
+        default:
+            unsupportedOperator(datatype, operatorType);
+    }
+}
+
+template<typename T>
+void QueryBuilder::add_substring_constraint(const T& value, Query condition) {
+    // Foundation always returns false for substring operations with a RHS of null or "".
+    m_query.and_query(value.size()
+                      ? std::move(condition)
+                      : std::unique_ptr<Expression>(new FalseExpression));
+}
+
+template<typename T>
+void QueryBuilder::add_substring_constraint(const Columns<T>& value, Query condition) {
+    // Foundation always returns false for substring operations with a RHS of null or "".
+    // We don't need to concern ourselves with the possibility of value traversing a link list
+    // and producing multiple values per row as such expressions will have been rejected.
+    m_query.and_query(const_cast<Columns<T>&>(value).size() != 0 && std::move(condition));
+}
+
+template<typename Comparator>
+Query make_diacritic_insensitive_constraint(bool caseSensitive, std::unique_ptr<Subexpr> left, std::unique_ptr<Subexpr> right) {
+    using CompareCS = Compare<typename Comparator::CaseSensitive>;
+    using CompareCI = Compare<typename Comparator::CaseInsensitive>;
+    if (caseSensitive) {
+        return make_expression<CompareCS>(std::move(left), std::move(right));
+    }
+    else {
+        return make_expression<CompareCI>(std::move(left), std::move(right));
+    }
+};
+
+Query make_diacritic_insensitive_constraint(NSPredicateOperatorType operatorType, bool caseSensitive,
+                                            std::unique_ptr<Subexpr> left, std::unique_ptr<Subexpr> right) {
+    switch (operatorType) {
+        case NSBeginsWithPredicateOperatorType: {
+            constexpr auto flags = kCFCompareDiacriticInsensitive | kCFCompareAnchored;
+            return make_diacritic_insensitive_constraint<ContainsSubstring<flags>>(caseSensitive, std::move(left), std::move(right));
+        }
+        case NSEndsWithPredicateOperatorType: {
+            constexpr auto flags = kCFCompareDiacriticInsensitive | kCFCompareAnchored | kCFCompareBackwards;
+            return make_diacritic_insensitive_constraint<ContainsSubstring<flags>>(caseSensitive, std::move(left), std::move(right));
+        }
+        case NSContainsPredicateOperatorType: {
+            constexpr auto flags = kCFCompareDiacriticInsensitive;
+            return make_diacritic_insensitive_constraint<ContainsSubstring<flags>>(caseSensitive, std::move(left), std::move(right));
+        }
+        default:
+            REALM_COMPILER_HINT_UNREACHABLE();
+    }
+}
+
+template <typename C, typename T>
+void QueryBuilder::add_diacritic_sensitive_string_constraint(NSPredicateOperatorType operatorType,
+                                                             NSComparisonPredicateOptions predicateOptions,
+                                                             Columns<C>&& column,
+                                                             T value) {
+    bool caseSensitive = !(predicateOptions & NSCaseInsensitivePredicateOption);
+    switch (operatorType) {
+        case NSBeginsWithPredicateOperatorType:
+            add_substring_constraint(value, column.begins_with(value, caseSensitive));
+            break;
+        case NSEndsWithPredicateOperatorType:
+            add_substring_constraint(value, column.ends_with(value, caseSensitive));
+            break;
+        case NSContainsPredicateOperatorType:
+            add_substring_constraint(value, column.contains(value, caseSensitive));
+            break;
+        case NSEqualToPredicateOperatorType:
+            m_query.and_query(column.equal(value, caseSensitive));
+            break;
+        case NSNotEqualToPredicateOperatorType:
+            m_query.and_query(column.not_equal(value, caseSensitive));
+            break;
+        case NSLikePredicateOperatorType:
+            m_query.and_query(column.like(value, caseSensitive));
+            break;
+        default: {
+            constexpr auto propertyType = is_any_v<C, String, Lst<String>> ? RLMPropertyTypeString : RLMPropertyTypeData;
+            unsupportedOperator(propertyType, operatorType);
+        }
+    }
+}
+
+template <typename C, typename T>
+void QueryBuilder::add_string_constraint(NSPredicateOperatorType operatorType,
+                                         NSComparisonPredicateOptions predicateOptions,
+                                         Columns<C>&& column,
+                                         T value) {
+    if (!(predicateOptions & NSDiacriticInsensitivePredicateOption)) {
+        add_diacritic_sensitive_string_constraint(operatorType, predicateOptions, std::move(column), value);
+        return;
+    }
+
+    auto as_subexpr = util::overload{
+        [](StringData value) { return make_subexpr<ConstantStringValue>(value); },
+        [](const Columns<String>& c) { return c.clone(); },
+        [](const Columns<Lst<String>>& c) { return c.clone(); },
+        [](BinaryData value) { return make_subexpr<ConstantStringValue>(StringData(value.data(), value.size())); },
+        [](const Columns<BinaryData>& c) { return c.clone(); },
+        [](const Columns<Lst<BinaryData>>& c) { return c.clone(); }
+    };
+    auto left = as_subexpr(column);
+    auto right = as_subexpr(value);
+
+    bool caseSensitive = !(predicateOptions & NSCaseInsensitivePredicateOption);
+    constexpr auto flags = kCFCompareDiacriticInsensitive | kCFCompareAnchored;
+    switch (operatorType) {
+        case NSBeginsWithPredicateOperatorType:
+        case NSEndsWithPredicateOperatorType:
+        case NSContainsPredicateOperatorType:
+            add_substring_constraint(value, make_diacritic_insensitive_constraint(operatorType, caseSensitive, std::move(left), std::move(right)));
+            break;
+        case NSNotEqualToPredicateOperatorType:
+            m_query.and_query(make_diacritic_insensitive_constraint<NotEqual<flags>>(caseSensitive, std::move(left), std::move(right)));
+            break;
+        case NSEqualToPredicateOperatorType:
+            m_query.and_query(make_diacritic_insensitive_constraint<Equal<flags>>(caseSensitive, std::move(left), std::move(right)));
+            break;
+        case NSLikePredicateOperatorType:
+            throwException(@"Invalid operator type",
+                           @"Operator 'LIKE' not supported with diacritic-insensitive modifier.");
+        default:
+            unsupportedOperator(RLMPropertyTypeString, operatorType);
+    }
+}
+
+id value_from_constant_expression_or_value(id value) {
+    if (NSExpression *exp = RLMDynamicCast<NSExpression>(value)) {
+        RLMPrecondition(exp.expressionType == NSConstantValueExpressionType,
+                        @"Invalid value",
+                        @"Expressions within predicate aggregates must be constant values");
+        return exp.constantValue;
+    }
+    return value;
+}
+
+void validate_and_extract_between_range(id value, RLMProperty *prop, id *from, id *to) {
+    NSArray *array = RLMDynamicCast<NSArray>(value);
+    RLMPrecondition(array, @"Invalid value", @"object must be of type NSArray for BETWEEN operations");
+    RLMPrecondition(array.count == 2, @"Invalid value", @"NSArray object must contain exactly two objects for BETWEEN operations");
+
+    *from = value_from_constant_expression_or_value(array.firstObject);
+    *to = value_from_constant_expression_or_value(array.lastObject);
+    RLMPrecondition(isObjectValidForProperty(*from, prop) && isObjectValidForProperty(*to, prop),
+                    @"Invalid value",
+                    @"NSArray objects must be of type %@ for BETWEEN operations", RLMTypeToString(prop.type));
+}
+
+void QueryBuilder::add_between_constraint(const ColumnReference& column, id value) {
+    if (column.has_any_to_many_links()) {
+        auto link_column = column.last_link_column();
+        Query subquery = get_table(m_group, link_column.link_target_object_schema()).where();
+        QueryBuilder(subquery, m_group, m_schema).add_between_constraint(column.column_ignoring_links(subquery), value);
+
+        m_query.and_query(link_column.resolve<Link>(std::move(subquery)).count() > 0);
+        return;
+    }
+
+    id from, to;
+    validate_and_extract_between_range(value, column.property(), &from, &to);
+
+    if (!propertyTypeIsNumeric(column.type())) {
+        return unsupportedOperator(column.type(), NSBetweenPredicateOperatorType);
+    }
+
+    m_query.group();
+    add_constraint(NSGreaterThanOrEqualToPredicateOperatorType, 0, column, from);
+    add_constraint(NSLessThanOrEqualToPredicateOperatorType, 0, column, to);
+    m_query.end_group();
+}
+
+void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType,
+                                       const Columns<Link>& column, RLMObjectBase *obj) {
+    if (!obj->_row.is_valid()) {
+        // Unmanaged or deleted objects are not equal to any managed objects.
+        // For arrays this effectively checks if there are any objects in the
+        // array, while for links it's just always constant true or false
+        // (for != and = respectively).
+        if (!column.link_map().only_unary_links()) {
+            add_bool_constraint(RLMPropertyTypeObject, operatorType, column, null());
+        }
+        else if (operatorType == NSEqualToPredicateOperatorType) {
+            m_query.and_query(std::unique_ptr<Expression>(new FalseExpression));
+        }
+        else {
+            m_query.and_query(std::unique_ptr<Expression>(new TrueExpression));
+        }
+    }
+    else {
+        add_bool_constraint(RLMPropertyTypeObject, operatorType, column, obj->_row);
+    }
+}
+
+void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType,
+                                       const Columns<Link>& column,
+                                       realm::null) {
+    add_bool_constraint(RLMPropertyTypeObject, operatorType, column, null());
+}
+
+void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType,
+                                       const Columns<Link>& a, const ColumnReference& b) {
+    add_bool_constraint(RLMPropertyTypeObject, operatorType, a, b.resolve<Link>());
+}
+
+// iterate over an array of subpredicates, using @func to build a query from each
+// one and ORing them together
+template<typename Func>
+void process_or_group(Query &query, id array, Func&& func) {
+    array = RLMAsFastEnumeration(array);
+    RLMPrecondition(array, @"Invalid value", @"IN clause requires an array of items");
+
+    query.group();
+
+    bool first = true;
+    for (id item in array) {
+        if (!first) {
+            query.Or();
+        }
+        first = false;
+
+        func(item);
+    }
+
+    if (first) {
+        // Queries can't be empty, so if there's zero things in the OR group
+        // validation will fail. Work around this by adding an expression which
+        // will never find any rows in a table.
+        query.and_query(std::unique_ptr<Expression>(new FalseExpression));
+    }
+
+    query.end_group();
+}
+
+template <typename RequestedType>
+RequestedType convert(id value);
+
+template <>
+Timestamp convert<Timestamp>(id value) {
+    return RLMTimestampForNSDate(value);
+}
+
+template <>
+bool convert<bool>(id value) {
+    return [value boolValue];
+}
+
+template <>
+Double convert<Double>(id value) {
+    return [value doubleValue];
+}
+
+template <>
+Float convert<Float>(id value) {
+    return [value floatValue];
+}
+
+template <>
+Int convert<Int>(id value) {
+    return [value longLongValue];
+}
+
+template <>
+String convert<String>(id value) {
+    return isNSNull(value) ? StringData() : RLMStringDataWithNSString(value);
+}
+
+template <>
+Binary convert<Binary>(id value) {
+    return isNSNull(value) ? BinaryData() : RLMBinaryDataForNSData(value);
+}
+
+template <>
+Decimal128 convert<Decimal128>(id value) {
+    return RLMObjcToDecimal128(value);
+}
+
+template <>
+ObjectId convert<ObjectId>(id value) {
+    if (auto objectId = RLMDynamicCast<RLMObjectId>(value)) {
+        return objectId.value;
+    }
+    if (auto string = RLMDynamicCast<NSString>(value)) {
+        return ObjectId(string.UTF8String);
+    }
+    @throw RLMException(@"Cannot convert value '%@' of type '%@' to object id", value, [value class]);
+}
+
+template <typename>
+realm::null value_of_type(realm::null) {
+    return realm::null();
+}
+
+template <typename RequestedType>
+auto value_of_type(id value) {
+    return ::convert<RequestedType>(value);
+}
+
+template <typename RequestedType>
+auto value_of_type(const ColumnReference& column) {
+    return column.resolve<RequestedType>();
+}
+
+template <typename T, typename Fn>
+void convert_null(T&& value, Fn&& fn) {
+    if (isNSNull(value)) {
+        fn(null());
+    }
+    else {
+        fn(value);
+    }
+}
+
+template <template<typename> typename W, typename T>
+void QueryBuilder::do_add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType,
+                       NSComparisonPredicateOptions predicateOptions, ColumnReference const& column, T&& value)
+{
+    switch (type) {
+        case RLMPropertyTypeBool:
+            convert_null(value, [&](auto&& value) {
+                add_bool_constraint(type, operatorType, column.resolve<W<bool>>(), value_of_type<bool>(value));
+            });
+            break;
+        case RLMPropertyTypeObjectId:
+            convert_null(value, [&](auto&& value) {
+                add_bool_constraint(type, operatorType, column.resolve<W<ObjectId>>(),
+                                    value_of_type<ObjectId>(value));
+            });
+            break;
+        case RLMPropertyTypeDate:
+            convert_null(value, [&](auto&& value) {
+                add_numeric_constraint(type, operatorType, column.resolve<W<Timestamp>>(),
+                                       value_of_type<Timestamp>(value));
+            });
+            break;
+        case RLMPropertyTypeDouble:
+            convert_null(value, [&](auto&& value) {
+                add_numeric_constraint(type, operatorType, column.resolve<W<Double>>(),
+                                       value_of_type<Double>(value));
+            });
+            break;
+        case RLMPropertyTypeFloat:
+            convert_null(value, [&](auto&& value) {
+                add_numeric_constraint(type, operatorType, column.resolve<W<Float>>(),
+                                       value_of_type<Float>(value));
+            });
+            break;
+        case RLMPropertyTypeInt:
+            convert_null(value, [&](auto&& value) {
+                add_numeric_constraint(type, operatorType, column.resolve<W<Int>>(),
+                                       value_of_type<Int>(value));
+            });
+            break;
+        case RLMPropertyTypeDecimal128:
+            convert_null(value, [&](auto&& value) {
+                add_numeric_constraint(type, operatorType, column.resolve<W<Decimal128>>(),
+                                       value_of_type<Decimal128>(value));
+            });
+            break;
+        case RLMPropertyTypeString:
+            add_string_constraint(operatorType, predicateOptions, column.resolve<W<String>>(),
+                                  value_of_type<String>(value));
+            break;
+        case RLMPropertyTypeData:
+            add_string_constraint(operatorType, predicateOptions,
+                                  column.resolve<W<Binary>>(),
+                                  value_of_type<Binary>(value));
+            break;
+        case RLMPropertyTypeObject:
+        case RLMPropertyTypeLinkingObjects:
+            convert_null(value, [&](auto&& value) {
+                add_link_constraint(operatorType, column.resolve<Link>(), value);
+            });
+            break;
+        case RLMPropertyTypeAny:
+            throwException(@"Unsupported predicate value type",
+                           @"Object type '%@' not supported", RLMTypeToString(type));
+    }
+}
+
+template<typename T>
+using Identity = T;
+
+template <typename R>
+void QueryBuilder::add_constraint(NSPredicateOperatorType operatorType,
+                                  NSComparisonPredicateOptions predicateOptions, ColumnReference const& column, R const& rhs)
+{
+    auto type = column.type();
+    if (column.property().array) {
+        do_add_constraint<Lst>(type, operatorType, predicateOptions, column, rhs);
+    }
+    else {
+        do_add_constraint<Identity>(type, operatorType, predicateOptions, column, rhs);
+    }
+}
+
+struct KeyPath {
+    std::vector<RLMProperty *> links;
+    RLMProperty *property;
+    bool containsToManyRelationship;
+};
+
+KeyPath key_path_from_string(RLMSchema *schema, RLMObjectSchema *objectSchema, NSString *keyPath)
+{
+    RLMProperty *property;
+    std::vector<RLMProperty *> links;
+
+    bool keyPathContainsToManyRelationship = false;
+
+    NSUInteger start = 0, length = keyPath.length, end = NSNotFound;
+    do {
+        end = [keyPath rangeOfString:@"." options:0 range:{start, length - start}].location;
+        NSString *propertyName = [keyPath substringWithRange:{start, end == NSNotFound ? length - start : end - start}];
+        property = objectSchema[propertyName];
+        RLMPrecondition(property, @"Invalid property name",
+                        @"Property '%@' not found in object of type '%@'",
+                        propertyName, objectSchema.className);
+
+        if (property.array)
+            keyPathContainsToManyRelationship = true;
+
+        if (end != NSNotFound) {
+            RLMPrecondition(property.type == RLMPropertyTypeObject || property.type == RLMPropertyTypeLinkingObjects,
+                            @"Invalid value", @"Property '%@' is not a link in object of type '%@'",
+                            propertyName, objectSchema.className);
+
+            links.push_back(property);
+            REALM_ASSERT(property.objectClassName);
+            objectSchema = schema[property.objectClassName];
+        }
+
+        start = end + 1;
+    } while (end != NSNotFound);
+
+    return {std::move(links), property, keyPathContainsToManyRelationship};
+}
+
+ColumnReference QueryBuilder::column_reference_from_key_path(RLMObjectSchema *objectSchema,
+                                                             NSString *keyPathString, bool isAggregate)
+{
+    auto keyPath = key_path_from_string(m_schema, objectSchema, keyPathString);
+
+    if (isAggregate && !keyPath.containsToManyRelationship) {
+        throwException(@"Invalid predicate",
+                       @"Aggregate operations can only be used on key paths that include an array property");
+    } else if (!isAggregate && keyPath.containsToManyRelationship) {
+        throwException(@"Invalid predicate",
+                       @"Key paths that include an array property must use aggregate operations");
+    }
+
+    return ColumnReference(m_query, m_group, m_schema, keyPath.property, std::move(keyPath.links));
+}
+
+void validate_property_value(const ColumnReference& column,
+                             __unsafe_unretained id const value,
+                             __unsafe_unretained NSString *const err,
+                             __unsafe_unretained RLMObjectSchema *const objectSchema,
+                             __unsafe_unretained NSString *const keyPath) {
+    RLMProperty *prop = column.property();
+    RLMPrecondition(isObjectValidForProperty(value, prop),
+                    @"Invalid value", err, prop.objectClassName ?: RLMTypeToString(prop.type),
+                    keyPath, objectSchema.className, value);
+    if (RLMObjectBase *obj = RLMDynamicCast<RLMObjectBase>(value)) {
+        RLMPrecondition(!obj->_row.is_valid() || &column.group() == &obj->_realm.group,
+                        @"Invalid value origin", @"Object must be from the Realm being queried");
+    }
+}
+
+// static_assert is always evaluated even if it's inside a if constexpr
+// unless the value is derived from the template argument, in which case it's
+// only evaluated if that branch is active
+template <CollectionOperation::Type> struct AlwaysFalse : std::false_type {};
+
+template <CollectionOperation::Type OperationType, typename Column>
+auto collection_operation_expr_2(Column&& column) {
+    if constexpr (OperationType == CollectionOperation::Minimum) {
+        return column.min();
+    }
+    else if constexpr (OperationType == CollectionOperation::Maximum) {
+        return column.max();
+    }
+    else if constexpr (OperationType == CollectionOperation::Sum) {
+        return column.sum();
+    }
+    else if constexpr (OperationType == CollectionOperation::Average) {
+        return column.average();
+    }
+    else {
+        static_assert(AlwaysFalse<OperationType>::value, "invalid operation type");
+    }
+}
+
+template <typename Requested, CollectionOperation::Type OperationType, bool IsLinkCollection>
+auto collection_operation_expr(CollectionOperation operation) {
+    REALM_ASSERT(operation.type() == OperationType);
+
+    if constexpr (IsLinkCollection) {
+        auto&& resolved = operation.link_column().resolve<Link>();
+        auto col = operation.column().column();
+        return collection_operation_expr_2<OperationType>(resolved.template column<Requested>(col));
+    }
+    else {
+        return collection_operation_expr_2<OperationType>(operation.link_column().resolve<Lst<Requested>>());
+    }
+}
+
+template <CollectionOperation::Type Operation, bool IsLinkCollection, typename R>
+void QueryBuilder::add_collection_operation_constraint(NSPredicateOperatorType operatorType,
+                                                       CollectionOperation const& collectionOperation, R rhs)
+{
+    auto type = IsLinkCollection ? collectionOperation.column().type() : collectionOperation.link_column().type();
+    switch (type) {
+        case RLMPropertyTypeInt:
+            add_numeric_constraint(type, operatorType,
+                                   collection_operation_expr<Int, Operation, IsLinkCollection>(collectionOperation),
+                                   value_of_type<Int>(rhs));
+            break;
+        case RLMPropertyTypeFloat:
+            add_numeric_constraint(type, operatorType,
+                                   collection_operation_expr<Float, Operation, IsLinkCollection>(collectionOperation),
+                                   value_of_type<Float>(rhs));
+            break;
+        case RLMPropertyTypeDouble:
+            add_numeric_constraint(type, operatorType,
+                                   collection_operation_expr<Double, Operation, IsLinkCollection>(collectionOperation),
+                                   value_of_type<Double>(rhs));
+            break;
+        case RLMPropertyTypeDecimal128:
+            add_numeric_constraint(type, operatorType,
+                                   collection_operation_expr<Decimal128, Operation, IsLinkCollection>(collectionOperation),
+                                   value_of_type<Decimal128>(rhs));
+            break;
+        case RLMPropertyTypeDate:
+            if constexpr (Operation == CollectionOperation::Sum || Operation == CollectionOperation::Average) {
+                throwException(@"Unsupported predicate value type",
+                               @"Cannot sum or average date properties");
+            }
+            else {
+                add_numeric_constraint(type, operatorType,
+                                       collection_operation_expr<Timestamp, Operation, IsLinkCollection>(collectionOperation),
+                                       value_of_type<Timestamp>(rhs));
+            }
+            break;
+        default:
+            REALM_ASSERT(false && "Only numeric property types should hit this path.");
+    }
+}
+
+template <CollectionOperation::Type Operation, typename R>
+void QueryBuilder::add_collection_operation_constraint(NSPredicateOperatorType operatorType,
+                                                       CollectionOperation const& collectionOperation, R rhs)
+{
+    convert_null(rhs, [&](auto&& rhs) {
+        if (collectionOperation.link_column().is_link()) {
+            add_collection_operation_constraint<Operation, true>(operatorType, collectionOperation, rhs);
+        }
+        else {
+            add_collection_operation_constraint<Operation, false>(operatorType, collectionOperation, rhs);
+        }
+    });
+}
+
+template <typename R>
+void QueryBuilder::add_collection_operation_constraint(NSPredicateOperatorType operatorType,
+                                                       CollectionOperation const& collectionOperation, R rhs)
+{
+    switch (collectionOperation.type()) {
+        case CollectionOperation::Count: {
+            auto& column = collectionOperation.link_column();
+            RLMPropertyType type = column.type();
+            auto rhsValue = value_of_type<Int>(rhs);
+            switch (type) {
+                case RLMPropertyTypeBool:
+                    add_numeric_constraint(type, operatorType, column.resolve<Lst<Bool>>().size(), rhsValue);
+                    return;
+                case RLMPropertyTypeObjectId:
+                    add_numeric_constraint(type, operatorType, column.resolve<Lst<ObjectId>>().size(), rhsValue);
+                    return;
+                case RLMPropertyTypeDate:
+                    add_numeric_constraint(type, operatorType, column.resolve<Lst<Timestamp>>().size(), rhsValue);
+                    return;
+                case RLMPropertyTypeDouble:
+                    add_numeric_constraint(type, operatorType, column.resolve<Lst<Double>>().size(), rhsValue);
+                    return;
+                case RLMPropertyTypeFloat:
+                    add_numeric_constraint(type, operatorType, column.resolve<Lst<Float>>().size(), rhsValue);
+                    return;
+                case RLMPropertyTypeInt:
+                    add_numeric_constraint(type, operatorType, column.resolve<Lst<Int>>().size(), rhsValue);
+                    return;
+                case RLMPropertyTypeDecimal128:
+                    add_numeric_constraint(type, operatorType, column.resolve<Lst<Decimal128>>().size(), rhsValue);
+                    return;
+                case RLMPropertyTypeString:
+                    add_numeric_constraint(type, operatorType, column.resolve<Lst<String>>().size(), rhsValue);
+                    return;
+                case RLMPropertyTypeData:
+                    add_numeric_constraint(type, operatorType, column.resolve<Lst<Binary>>().size(), rhsValue);
+                    return;
+                case RLMPropertyTypeObject:
+                case RLMPropertyTypeLinkingObjects:
+                    add_numeric_constraint(type, operatorType, column.resolve<Link>().count(), rhsValue);
+                    return;
+                case RLMPropertyTypeAny:
+                    throwException(@"Unsupported predicate value type",
+                                   @"Object type %@ not supported", RLMTypeToString(type));
+            }
+        }
+        case CollectionOperation::Minimum:
+            add_collection_operation_constraint<CollectionOperation::Minimum>(operatorType, collectionOperation, rhs);
+            break;
+        case CollectionOperation::Maximum:
+            add_collection_operation_constraint<CollectionOperation::Maximum>(operatorType, collectionOperation, rhs);
+            break;
+        case CollectionOperation::Sum:
+            add_collection_operation_constraint<CollectionOperation::Sum>(operatorType, collectionOperation, rhs);
+            break;
+        case CollectionOperation::Average:
+            add_collection_operation_constraint<CollectionOperation::Average>(operatorType, collectionOperation, rhs);
+            break;
+    }
+}
+
+bool key_path_contains_collection_operator(NSString *keyPath) {
+    return [keyPath rangeOfString:@"@"].location != NSNotFound;
+}
+
+NSString *get_collection_operation_name_from_key_path(NSString *keyPath, NSString **leadingKeyPath,
+                                                      NSString **trailingKey) {
+    NSRange at = [keyPath rangeOfString:@"@"];
+    if (at.location == NSNotFound || at.location >= keyPath.length - 1) {
+        throwException(@"Invalid key path", @"'%@' is not a valid key path'", keyPath);
+    }
+
+    if (at.location == 0 || [keyPath characterAtIndex:at.location - 1] != '.') {
+        throwException(@"Invalid key path", @"'%@' is not a valid key path'", keyPath);
+    }
+
+    NSRange trailingKeyRange = [keyPath rangeOfString:@"." options:0 range:{at.location, keyPath.length - at.location} locale:nil];
+
+    *leadingKeyPath = [keyPath substringToIndex:at.location - 1];
+    if (trailingKeyRange.location == NSNotFound) {
+        *trailingKey = nil;
+        return [keyPath substringFromIndex:at.location];
+    } else {
+        *trailingKey = [keyPath substringFromIndex:trailingKeyRange.location + 1];
+        return [keyPath substringWithRange:{at.location, trailingKeyRange.location - at.location}];
+    }
+}
+
+CollectionOperation QueryBuilder::collection_operation_from_key_path(RLMObjectSchema *desc, NSString *keyPath) {
+    NSString *leadingKeyPath;
+    NSString *trailingKey;
+    NSString *collectionOperationName = get_collection_operation_name_from_key_path(keyPath, &leadingKeyPath, &trailingKey);
+
+    ColumnReference linkColumn = column_reference_from_key_path(desc, leadingKeyPath, true);
+    util::Optional<ColumnReference> column;
+    if (trailingKey) {
+        RLMPrecondition([trailingKey rangeOfString:@"."].location == NSNotFound, @"Invalid key path",
+                        @"Right side of collection operator may only have a single level key");
+        NSString *fullKeyPath = [leadingKeyPath stringByAppendingFormat:@".%@", trailingKey];
+        column = column_reference_from_key_path(desc, fullKeyPath, true);
+    }
+
+    return {collectionOperationName, std::move(linkColumn), std::move(column)};
+}
+
+NSPredicateOperatorType invert_comparison_operator(NSPredicateOperatorType type) {
+    switch (type) {
+        case NSLessThanPredicateOperatorType:
+            return NSGreaterThanPredicateOperatorType;
+        case NSLessThanOrEqualToPredicateOperatorType:
+            return NSGreaterThanOrEqualToPredicateOperatorType;
+        case NSGreaterThanPredicateOperatorType:
+            return NSLessThanPredicateOperatorType;
+        case NSGreaterThanOrEqualToPredicateOperatorType:
+            return NSLessThanOrEqualToPredicateOperatorType;
+        case NSBeginsWithPredicateOperatorType:
+        case NSEndsWithPredicateOperatorType:
+        case NSContainsPredicateOperatorType:
+        case NSLikePredicateOperatorType:
+            throwException(@"Unsupported predicate", @"Operator '%@' requires a keypath on the left side.", operatorName(type));
+        default:
+            return type;
+    }
+}
+
+void QueryBuilder::apply_collection_operator_expression(RLMObjectSchema *desc,
+                                                        NSString *keyPath, id value,
+                                                        NSComparisonPredicate *pred) {
+    CollectionOperation operation = collection_operation_from_key_path(desc, keyPath);
+    operation.validate_comparison(value);
+
+    auto type = pred.predicateOperatorType;
+    if (pred.leftExpression.expressionType != NSKeyPathExpressionType) {
+        // Turn "a > b" into "b < a" so that we can always put the column on the lhs
+        type = invert_comparison_operator(type);
+    }
+    add_collection_operation_constraint(type, operation, value);
+}
+
+void QueryBuilder::apply_value_expression(RLMObjectSchema *desc,
+                                          NSString *keyPath, id value,
+                                          NSComparisonPredicate *pred)
+{
+    if (key_path_contains_collection_operator(keyPath)) {
+        apply_collection_operator_expression(desc, keyPath, value, pred);
+        return;
+    }
+
+    bool isAny = pred.comparisonPredicateModifier == NSAnyPredicateModifier;
+    ColumnReference column = column_reference_from_key_path(desc, keyPath, isAny);
+
+    // check to see if this is a between query
+    if (pred.predicateOperatorType == NSBetweenPredicateOperatorType) {
+        add_between_constraint(std::move(column), value);
+        return;
+    }
+
+    // turn "key.path IN collection" into ored together ==. "collection IN key.path" is handled elsewhere.
+    if (pred.predicateOperatorType == NSInPredicateOperatorType) {
+        process_or_group(m_query, value, [&](id item) {
+            id normalized = value_from_constant_expression_or_value(item);
+            validate_property_value(column, normalized,
+                                    @"Expected object of type %@ in IN clause for property '%@' on object of type '%@', but received: %@", desc, keyPath);
+            add_constraint(NSEqualToPredicateOperatorType, pred.options, column, normalized);
+        });
+        return;
+    }
+
+    validate_property_value(column, value, @"Expected object of type %@ for property '%@' on object of type '%@', but received: %@", desc, keyPath);
+    if (pred.leftExpression.expressionType == NSKeyPathExpressionType) {
+        add_constraint(pred.predicateOperatorType, pred.options, std::move(column), value);
+    } else {
+        add_constraint(invert_comparison_operator(pred.predicateOperatorType), pred.options, std::move(column), value);
+    }
+}
+
+void QueryBuilder::apply_column_expression(RLMObjectSchema *desc,
+                                           NSString *leftKeyPath, NSString *rightKeyPath,
+                                           NSComparisonPredicate *predicate)
+{
+    bool left_key_path_contains_collection_operator = key_path_contains_collection_operator(leftKeyPath);
+    bool right_key_path_contains_collection_operator = key_path_contains_collection_operator(rightKeyPath);
+    if (left_key_path_contains_collection_operator && right_key_path_contains_collection_operator) {
+        throwException(@"Unsupported predicate", @"Key paths including aggregate operations cannot be compared with other aggregate operations.");
+    }
+
+    if (left_key_path_contains_collection_operator) {
+        CollectionOperation left = collection_operation_from_key_path(desc, leftKeyPath);
+        ColumnReference right = column_reference_from_key_path(desc, rightKeyPath, false);
+        left.validate_comparison(right);
+        add_collection_operation_constraint(predicate.predicateOperatorType, left, std::move(right));
+        return;
+    }
+    if (right_key_path_contains_collection_operator) {
+        ColumnReference left = column_reference_from_key_path(desc, leftKeyPath, false);
+        CollectionOperation right = collection_operation_from_key_path(desc, rightKeyPath);
+        right.validate_comparison(left);
+        add_collection_operation_constraint(invert_comparison_operator(predicate.predicateOperatorType),
+                                            right, std::move(left));
+        return;
+    }
+
+    bool isAny = false;
+    ColumnReference left = column_reference_from_key_path(desc, leftKeyPath, isAny);
+    ColumnReference right = column_reference_from_key_path(desc, rightKeyPath, isAny);
+
+    // NOTE: It's assumed that column type must match and no automatic type conversion is supported.
+    RLMPrecondition(left.type() == right.type(),
+                    RLMPropertiesComparisonTypeMismatchException,
+                    RLMPropertiesComparisonTypeMismatchReason,
+                    RLMTypeToString(left.type()),
+                    RLMTypeToString(right.type()));
+
+    // TODO: Should we handle special case where left row is the same as right row (tautology)
+    add_constraint(predicate.predicateOperatorType, predicate.options,
+                   std::move(left), std::move(right));
+}
+
+// Identify expressions of the form [SELF valueForKeyPath:]
+bool is_self_value_for_key_path_function_expression(NSExpression *expression)
+{
+    if (expression.expressionType != NSFunctionExpressionType)
+        return false;
+
+    if (expression.operand.expressionType != NSEvaluatedObjectExpressionType)
+        return false;
+
+    return [expression.function isEqualToString:@"valueForKeyPath:"];
+}
+
+// -[NSPredicate predicateWithSubtitutionVariables:] results in function expressions of the form [SELF valueForKeyPath:]
+// that apply_predicate cannot handle. Replace such expressions with equivalent NSKeyPathExpressionType expressions.
+NSExpression *simplify_self_value_for_key_path_function_expression(NSExpression *expression) {
+    if (is_self_value_for_key_path_function_expression(expression)) {
+        if (NSString *keyPath = [expression.arguments.firstObject keyPath]) {
+            return [NSExpression expressionForKeyPath:keyPath];
+        }
+    }
+    return expression;
+}
+
+void QueryBuilder::apply_function_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression,
+                                             NSPredicateOperatorType operatorType, NSExpression *right) {
+    RLMPrecondition(functionExpression.operand.expressionType == NSSubqueryExpressionType,
+                    @"Invalid predicate", @"The '%@' function is not supported.", functionExpression.function);
+    RLMPrecondition([functionExpression.function isEqualToString:@"valueForKeyPath:"] && functionExpression.arguments.count == 1,
+                    @"Invalid predicate", @"The '%@' function is not supported on the result of a SUBQUERY.", functionExpression.function);
+
+    NSExpression *keyPathExpression = functionExpression.arguments.firstObject;
+    RLMPrecondition([keyPathExpression.keyPath isEqualToString:@"@count"],
+                    @"Invalid predicate", @"SUBQUERY is only supported when immediately followed by .@count that is compared with a constant number.");
+    RLMPrecondition(right.expressionType == NSConstantValueExpressionType && [right.constantValue isKindOfClass:[NSNumber class]],
+                    @"Invalid predicate expression", @"SUBQUERY(…).@count is only supported when compared with a constant number.");
+
+    NSExpression *subqueryExpression = functionExpression.operand;
+    int64_t value = [right.constantValue integerValue];
+
+    ColumnReference collectionColumn = column_reference_from_key_path(objectSchema, [subqueryExpression.collection keyPath], true);
+    RLMObjectSchema *collectionMemberObjectSchema = m_schema[collectionColumn.property().objectClassName];
+
+    // Eliminate references to the iteration variable in the subquery.
+    NSPredicate *subqueryPredicate = [subqueryExpression.predicate predicateWithSubstitutionVariables:@{subqueryExpression.variable: [NSExpression expressionForEvaluatedObject]}];
+    subqueryPredicate = transformPredicate(subqueryPredicate, simplify_self_value_for_key_path_function_expression);
+
+    Query subquery = RLMPredicateToQuery(subqueryPredicate, collectionMemberObjectSchema, m_schema, m_group);
+    add_numeric_constraint(RLMPropertyTypeInt, operatorType,
+                           collectionColumn.resolve<Link>(std::move(subquery)).count(), value);
+}
+
+void QueryBuilder::apply_predicate(NSPredicate *predicate, RLMObjectSchema *objectSchema)
+{
+    // Compound predicates.
+    if ([predicate isMemberOfClass:[NSCompoundPredicate class]]) {
+        NSCompoundPredicate *comp = (NSCompoundPredicate *)predicate;
+
+        switch ([comp compoundPredicateType]) {
+            case NSAndPredicateType:
+                if (comp.subpredicates.count) {
+                    // Add all of the subpredicates.
+                    m_query.group();
+                    for (NSPredicate *subp in comp.subpredicates) {
+                        apply_predicate(subp, objectSchema);
+                    }
+                    m_query.end_group();
+                } else {
+                    // NSCompoundPredicate's documentation states that an AND predicate with no subpredicates evaluates to TRUE.
+                    m_query.and_query(std::unique_ptr<Expression>(new TrueExpression));
+                }
+                break;
+
+            case NSOrPredicateType: {
+                // Add all of the subpredicates with ors inbetween.
+                process_or_group(m_query, comp.subpredicates, [&](__unsafe_unretained NSPredicate *const subp) {
+                    apply_predicate(subp, objectSchema);
+                });
+                break;
+            }
+
+            case NSNotPredicateType:
+                // Add the negated subpredicate
+                m_query.Not();
+                apply_predicate(comp.subpredicates.firstObject, objectSchema);
+                break;
+
+            default:
+                // Not actually possible short of users making their own weird
+                // broken subclass of NSPredicate
+                throwException(@"Invalid compound predicate type",
+                               @"Only AND, OR, and NOT compound predicates are supported");
+        }
+    }
+    else if ([predicate isMemberOfClass:[NSComparisonPredicate class]]) {
+        NSComparisonPredicate *compp = (NSComparisonPredicate *)predicate;
+
+        RLMPrecondition(compp.comparisonPredicateModifier != NSAllPredicateModifier,
+                        @"Invalid predicate", @"ALL modifier not supported");
+
+        NSExpressionType exp1Type = compp.leftExpression.expressionType;
+        NSExpressionType exp2Type = compp.rightExpression.expressionType;
+
+        if (compp.comparisonPredicateModifier == NSAnyPredicateModifier) {
+            // for ANY queries
+            RLMPrecondition(exp1Type == NSKeyPathExpressionType && exp2Type == NSConstantValueExpressionType,
+                            @"Invalid predicate",
+                            @"Predicate with ANY modifier must compare a KeyPath with RLMArray with a value");
+        }
+
+        if (compp.predicateOperatorType == NSBetweenPredicateOperatorType || compp.predicateOperatorType == NSInPredicateOperatorType) {
+            // Inserting an array via %@ gives NSConstantValueExpressionType, but including it directly gives NSAggregateExpressionType
+            if (exp1Type == NSKeyPathExpressionType && (exp2Type == NSAggregateExpressionType || exp2Type == NSConstantValueExpressionType)) {
+                // "key.path IN %@", "key.path IN {…}", "key.path BETWEEN %@", or "key.path BETWEEN {…}".
+                exp2Type = NSConstantValueExpressionType;
+            }
+            else if (compp.predicateOperatorType == NSInPredicateOperatorType && exp1Type == NSConstantValueExpressionType && exp2Type == NSKeyPathExpressionType) {
+                // "%@ IN key.path" is equivalent to "ANY key.path IN %@". Rewrite the former into the latter.
+                compp = [NSComparisonPredicate predicateWithLeftExpression:compp.rightExpression rightExpression:compp.leftExpression
+                                                                  modifier:NSAnyPredicateModifier type:NSEqualToPredicateOperatorType options:0];
+                exp1Type = NSKeyPathExpressionType;
+                exp2Type = NSConstantValueExpressionType;
+            }
+            else {
+                if (compp.predicateOperatorType == NSBetweenPredicateOperatorType) {
+                    throwException(@"Invalid predicate",
+                                   @"Predicate with BETWEEN operator must compare a KeyPath with an aggregate with two values");
+                }
+                else if (compp.predicateOperatorType == NSInPredicateOperatorType) {
+                    throwException(@"Invalid predicate",
+                                   @"Predicate with IN operator must compare a KeyPath with an aggregate");
+                }
+            }
+        }
+
+        if (exp1Type == NSKeyPathExpressionType && exp2Type == NSKeyPathExpressionType) {
+            // both expression are KeyPaths
+            apply_column_expression(objectSchema, compp.leftExpression.keyPath, compp.rightExpression.keyPath, compp);
+        }
+        else if (exp1Type == NSKeyPathExpressionType && exp2Type == NSConstantValueExpressionType) {
+            // comparing keypath to value
+            apply_value_expression(objectSchema, compp.leftExpression.keyPath, compp.rightExpression.constantValue, compp);
+        }
+        else if (exp1Type == NSConstantValueExpressionType && exp2Type == NSKeyPathExpressionType) {
+            // comparing value to keypath
+            apply_value_expression(objectSchema, compp.rightExpression.keyPath, compp.leftExpression.constantValue, compp);
+        }
+        else if (exp1Type == NSFunctionExpressionType) {
+            apply_function_expression(objectSchema, compp.leftExpression, compp.predicateOperatorType, compp.rightExpression);
+        }
+        else if (exp1Type == NSSubqueryExpressionType) {
+            // The subquery expressions that we support are handled by the NSFunctionExpressionType case above.
+            throwException(@"Invalid predicate expression", @"SUBQUERY is only supported when immediately followed by .@count.");
+        }
+        else {
+            throwException(@"Invalid predicate expressions",
+                           @"Predicate expressions must compare a keypath and another keypath or a constant value");
+        }
+    }
+    else if ([predicate isEqual:[NSPredicate predicateWithValue:YES]]) {
+        m_query.and_query(std::unique_ptr<Expression>(new TrueExpression));
+    } else if ([predicate isEqual:[NSPredicate predicateWithValue:NO]]) {
+        m_query.and_query(std::unique_ptr<Expression>(new FalseExpression));
+    }
+    else {
+        // invalid predicate type
+        throwException(@"Invalid predicate",
+                       @"Only support compound, comparison, and constant predicates");
+    }
+}
+} // namespace
+
+realm::Query RLMPredicateToQuery(NSPredicate *predicate, RLMObjectSchema *objectSchema,
+                                 RLMSchema *schema, Group &group)
+{
+    auto query = get_table(group, objectSchema).where();
+
+    // passing a nil predicate is a no-op
+    if (!predicate) {
+        return query;
+    }
+
+    @autoreleasepool {
+        QueryBuilder(query, group, schema).apply_predicate(predicate, objectSchema);
+    }
+
+    // Test the constructed query in core
+    std::string validateMessage = query.validate();
+    RLMPrecondition(validateMessage.empty(), @"Invalid query", @"%.*s",
+                    (int)validateMessage.size(), validateMessage.c_str());
+    return query;
+}
+
+// return the property for a validated column name
+RLMProperty *RLMValidatedProperty(RLMObjectSchema *desc, NSString *columnName) {
+    RLMProperty *prop = desc[columnName];
+    RLMPrecondition(prop, @"Invalid property name",
+                    @"Property '%@' not found in object of type '%@'", columnName, desc.className);
+    return prop;
+}

+ 40 - 0
Example/Pods/Realm/Realm/RLMRealm+Sync.mm

@@ -0,0 +1,40 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2017 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMRealm+Sync.h"
+
+#import "RLMObjectBase.h"
+#import "RLMQueryUtil.hpp"
+#import "RLMObjectSchema.h"
+#import "RLMRealm_Private.hpp"
+#import "RLMResults_Private.hpp"
+#import "RLMSchema.h"
+#import "RLMSyncSession.h"
+
+#import <realm/object-store/results.hpp>
+#import <realm/object-store/shared_realm.hpp>
+
+using namespace realm;
+
+@implementation RLMRealm (Sync)
+
+- (RLMSyncSession *)syncSession {
+    return [RLMSyncSession sessionForRealm:self];
+}
+
+@end

+ 1003 - 0
Example/Pods/Realm/Realm/RLMRealm.mm

@@ -0,0 +1,1003 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMRealm_Private.hpp"
+
+#import "RLMAnalytics.hpp"
+#import "RLMArray_Private.hpp"
+#import "RLMMigration_Private.h"
+#import "RLMObject_Private.h"
+#import "RLMObject_Private.hpp"
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMObjectStore.h"
+#import "RLMObservation.hpp"
+#import "RLMProperty.h"
+#import "RLMProperty_Private.h"
+#import "RLMQueryUtil.hpp"
+#import "RLMRealmConfiguration+Sync.h"
+#import "RLMRealmConfiguration_Private.hpp"
+#import "RLMRealmUtil.hpp"
+#import "RLMSchema_Private.hpp"
+#import "RLMThreadSafeReference_Private.hpp"
+#import "RLMUpdateChecker.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/disable_sync_to_disk.hpp>
+#import <realm/object-store/impl/realm_coordinator.hpp>
+#import <realm/object-store/object_store.hpp>
+#import <realm/object-store/schema.hpp>
+#import <realm/object-store/shared_realm.hpp>
+#import <realm/object-store/thread_safe_reference.hpp>
+#import <realm/object-store/util/scheduler.hpp>
+#import <realm/util/scope_exit.hpp>
+#import <realm/version.hpp>
+
+#if REALM_ENABLE_SYNC
+#import "RLMSyncManager_Private.hpp"
+#import "RLMSyncSession_Private.hpp"
+#import "RLMSyncUtil_Private.hpp"
+
+#import <realm/object-store/sync/async_open_task.hpp>
+#import <realm/object-store/sync/sync_session.hpp>
+#endif
+
+using namespace realm;
+using util::File;
+
+@interface RLMRealmNotificationToken : RLMNotificationToken
+@property (nonatomic, strong) RLMRealm *realm;
+@property (nonatomic, copy) RLMNotificationBlock block;
+@end
+
+@interface RLMRealm ()
+@property (nonatomic, strong) NSHashTable<RLMRealmNotificationToken *> *notificationHandlers;
+- (void)sendNotifications:(RLMNotification)notification;
+@end
+
+void RLMDisableSyncToDisk() {
+    realm::disable_sync_to_disk();
+}
+
+static std::atomic<bool> s_set_skip_backup_attribute{true};
+void RLMSetSkipBackupAttribute(bool value) {
+    s_set_skip_backup_attribute = value;
+}
+
+static void RLMAddSkipBackupAttributeToItemAtPath(std::string_view path) {
+    [[NSURL fileURLWithPath:@(path.data())] setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
+}
+
+@implementation RLMRealmNotificationToken
+- (void)invalidate {
+    [_realm verifyThread];
+    [_realm.notificationHandlers removeObject:self];
+    _realm = nil;
+    _block = nil;
+}
+
+- (void)suppressNextNotification {
+    // Temporarily replace the block with one which restores the old block
+    // rather than producing a notification.
+
+    // This briefly creates a retain cycle but it's fine because the block will
+    // be synchronously called shortly after this method is called. Unlike with
+    // collection notifications, this does not have to go through the object
+    // store or do fancy things to handle transaction coalescing because it's
+    // called synchronously by the obj-c code and not by the object store.
+    auto notificationBlock = _block;
+    _block = ^(RLMNotification, RLMRealm *) {
+        _block = notificationBlock;
+    };
+}
+
+- (void)dealloc {
+    if (_realm || _block) {
+        NSLog(@"RLMNotificationToken released without unregistering a notification. You must hold "
+              @"on to the RLMNotificationToken returned from addNotificationBlock and call "
+              @"-[RLMNotificationToken invalidate] when you no longer wish to receive RLMRealm notifications.");
+    }
+}
+@end
+
+#if !REALM_ENABLE_SYNC
+@interface RLMAsyncOpenTask : NSObject
+@end
+@implementation RLMAsyncOpenTask
+@end
+#endif
+
+static bool shouldForciblyDisableEncryption() {
+    static bool disableEncryption = getenv("REALM_DISABLE_ENCRYPTION");
+    return disableEncryption;
+}
+
+NSData *RLMRealmValidatedEncryptionKey(NSData *key) {
+    if (shouldForciblyDisableEncryption()) {
+        return nil;
+    }
+
+    if (key && key.length != 64) {
+        @throw RLMException(@"Encryption key must be exactly 64 bytes long");
+    }
+
+    return key;
+}
+
+@implementation RLMRealm {
+    std::mutex _collectionEnumeratorMutex;
+    NSHashTable<RLMFastEnumerator *> *_collectionEnumerators;
+    bool _sendingNotifications;
+}
+
++ (void)initialize {
+    static bool initialized;
+    if (initialized) {
+        return;
+    }
+    initialized = true;
+
+    RLMCheckForUpdates();
+    RLMSendAnalytics();
+}
+
+- (instancetype)initPrivate {
+    self = [super init];
+    return self;
+}
+
+- (BOOL)isEmpty {
+    return realm::ObjectStore::is_empty(self.group);
+}
+
+- (void)verifyThread {
+    try {
+        _realm->verify_thread();
+    }
+    catch (std::exception const& e) {
+        @throw RLMException(e);
+    }
+}
+
+- (BOOL)inWriteTransaction {
+    return _realm->is_in_transaction();
+}
+
+- (realm::Group &)group {
+    return _realm->read_group();
+}
+
+- (BOOL)autorefresh {
+    return _realm->auto_refresh();
+}
+
+- (void)setAutorefresh:(BOOL)autorefresh {
+    try {
+        _realm->set_auto_refresh(autorefresh);
+    }
+    catch (std::exception const& e) {
+        @throw RLMException(e);
+    }
+}
+
++ (instancetype)defaultRealm {
+    return [RLMRealm realmWithConfiguration:[RLMRealmConfiguration rawDefaultConfiguration] error:nil];
+}
+
++ (instancetype)defaultRealmForQueue:(dispatch_queue_t)queue {
+    return [RLMRealm realmWithConfiguration:[RLMRealmConfiguration rawDefaultConfiguration] queue:queue error:nil];
+}
+
++ (instancetype)realmWithURL:(NSURL *)fileURL {
+    RLMRealmConfiguration *configuration = [RLMRealmConfiguration defaultConfiguration];
+    configuration.fileURL = fileURL;
+    return [RLMRealm realmWithConfiguration:configuration error:nil];
+}
+
+static dispatch_queue_t s_async_open_queue = dispatch_queue_create("io.realm.asyncOpenDispatchQueue",
+                                                                   DISPATCH_QUEUE_CONCURRENT);
+void RLMSetAsyncOpenQueue(dispatch_queue_t queue) {
+    s_async_open_queue = queue;
+}
+
++ (RLMAsyncOpenTask *)asyncOpenWithConfiguration:(RLMRealmConfiguration *)configuration
+                                   callbackQueue:(dispatch_queue_t)callbackQueue
+                                        callback:(RLMAsyncOpenRealmCallback)callback {
+    auto openCompletion = [=](ThreadSafeReference, std::exception_ptr err) {
+        @autoreleasepool {
+            if (err) {
+                try {
+                    std::rethrow_exception(err);
+                }
+                catch (...) {
+                    NSError *error;
+                    RLMRealmTranslateException(&error);
+                    dispatch_async(callbackQueue, ^{
+                        callback(nil, error);
+                    });
+                }
+                return;
+            }
+
+            dispatch_async(callbackQueue, ^{
+                @autoreleasepool {
+                    NSError *error;
+                    RLMRealm *localRealm = [RLMRealm realmWithConfiguration:configuration
+                                                                      queue:callbackQueue
+                                                                      error:&error];
+                    callback(localRealm, error);
+                }
+            });
+        }
+    };
+
+    RLMAsyncOpenTask *ret = [RLMAsyncOpenTask new];
+    dispatch_async(s_async_open_queue, ^{
+        @autoreleasepool {
+            Realm::Config& config = configuration.config;
+            if (config.sync_config) {
+#if REALM_ENABLE_SYNC
+                auto task = realm::Realm::get_synchronized_realm(config);
+                ret.task = task;
+                task->start(openCompletion);
+#else
+                @throw RLMException(@"Realm was not built with sync enabled");
+#endif
+            }
+            else {
+                try {
+                    openCompletion(realm::_impl::RealmCoordinator::get_coordinator(config)->get_unbound_realm(), nullptr);
+                }
+                catch (...) {
+                    openCompletion({}, std::current_exception());
+                }
+            }
+        }
+    });
+    return ret;
+}
+
+// ARC tries to eliminate calls to autorelease when the value is then immediately
+// returned, but this results in significantly different semantics between debug
+// and release builds for RLMRealm, so force it to always autorelease.
+static id RLMAutorelease(__unsafe_unretained id value) {
+    // +1 __bridge_retained, -1 CFAutorelease
+    return value ? (__bridge id)CFAutorelease((__bridge_retained CFTypeRef)value) : nil;
+}
+
++ (instancetype)realmWithSharedRealm:(SharedRealm)sharedRealm schema:(RLMSchema *)schema {
+    RLMRealm *realm = [[RLMRealm alloc] initPrivate];
+    realm->_realm = sharedRealm;
+    realm->_dynamic = YES;
+    realm->_schema = schema;
+    realm->_info = RLMSchemaInfo(realm);
+    return RLMAutorelease(realm);
+}
+
+REALM_NOINLINE void RLMRealmTranslateException(NSError **error) {
+    try {
+        throw;
+    }
+    catch (RealmFileException const& ex) {
+        switch (ex.kind()) {
+            case RealmFileException::Kind::PermissionDenied:
+                RLMSetErrorOrThrow(RLMMakeError(RLMErrorFilePermissionDenied, ex), error);
+                break;
+            case RealmFileException::Kind::IncompatibleLockFile: {
+                NSString *err = @"Realm file is currently open in another process "
+                                 "which cannot share access with this process. All "
+                                 "processes sharing a single file must be the same "
+                                 "architecture. For sharing files between the Realm "
+                                 "Browser and an iOS simulator, this means that you "
+                                 "must use a 64-bit simulator.";
+                RLMSetErrorOrThrow(RLMMakeError(RLMErrorIncompatibleLockFile,
+                                                File::PermissionDenied(err.UTF8String, ex.path())), error);
+                break;
+            }
+            case RealmFileException::Kind::NotFound:
+                RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileNotFound, ex), error);
+                break;
+            case RealmFileException::Kind::Exists:
+                RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileExists, ex), error);
+                break;
+            case RealmFileException::Kind::BadHistoryError: {
+                NSString *err = @"Realm file's history format is incompatible with the "
+                                 "settings in the configuration object being used to open "
+                                 "the Realm. Note that Realms configured for sync cannot be "
+                                 "opened as non-synced Realms, and vice versa. Otherwise, the "
+                                 "file may be corrupt.";
+                RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileAccess,
+                                                File::AccessError(err.UTF8String, ex.path())), error);
+                break;
+            }
+            case RealmFileException::Kind::AccessError:
+                RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileAccess, ex), error);
+                break;
+            case RealmFileException::Kind::FormatUpgradeRequired:
+                RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileFormatUpgradeRequired, ex), error);
+                break;
+            default:
+                RLMSetErrorOrThrow(RLMMakeError(RLMErrorFail, ex), error);
+                break;
+        }
+    }
+    catch (AddressSpaceExhausted const &ex) {
+        RLMSetErrorOrThrow(RLMMakeError(RLMErrorAddressSpaceExhausted, ex), error);
+    }
+    catch (SchemaMismatchException const& ex) {
+        RLMSetErrorOrThrow(RLMMakeError(RLMErrorSchemaMismatch, ex), error);
+    }
+    catch (std::system_error const& ex) {
+        RLMSetErrorOrThrow(RLMMakeError(ex), error);
+    }
+    catch (const std::exception &exp) {
+        RLMSetErrorOrThrow(RLMMakeError(RLMErrorFail, exp), error);
+    }
+}
+
+REALM_NOINLINE static void translateSharedGroupOpenException(NSError **error) {
+    try {
+        throw;
+    }
+    catch (...) {
+        RLMRealmTranslateException(error);
+    }
+}
+
+
++ (instancetype)realmWithConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error {
+    return [self realmWithConfiguration:configuration queue:nil error:error];
+}
+
++ (instancetype)realmWithConfiguration:(RLMRealmConfiguration *)configuration
+                                 queue:(dispatch_queue_t)queue
+                                 error:(NSError **)error {
+    bool dynamic = configuration.dynamic;
+    bool cache = configuration.cache;
+    bool readOnly = configuration.readOnly;
+
+    // The main thread and main queue share a cache key of 1 so that they give
+    // the same instance. Other Realms are keyed on either the thread or the queue.
+    // Note that despite being a void* the cache key is not actually a pointer;
+    // this is just an artifact of NSMapTable's strange API.
+    void *cacheKey = reinterpret_cast<void *>(1);
+    if (queue) {
+        if (queue != dispatch_get_main_queue()) {
+            cacheKey = (__bridge void *)queue;
+        }
+    }
+    else {
+        if (!pthread_main_np()) {
+            cacheKey = pthread_self();
+        }
+    }
+
+    {
+        Realm::Config const& config = configuration.config;
+
+        // try to reuse existing realm first
+        if (cache || dynamic) {
+            if (RLMRealm *realm = RLMGetThreadLocalCachedRealmForPath(config.path, cacheKey)) {
+                auto const& old_config = realm->_realm->config();
+                if (old_config.immutable() != config.immutable()
+                    || old_config.read_only_alternative() != config.read_only_alternative()) {
+                    @throw RLMException(@"Realm at path '%s' already opened with different read permissions", config.path.c_str());
+                }
+                if (old_config.in_memory != config.in_memory) {
+                    @throw RLMException(@"Realm at path '%s' already opened with different inMemory settings", config.path.c_str());
+                }
+                if (realm->_dynamic != dynamic) {
+                    @throw RLMException(@"Realm at path '%s' already opened with different dynamic settings", config.path.c_str());
+                }
+                if (old_config.encryption_key != config.encryption_key) {
+                    @throw RLMException(@"Realm at path '%s' already opened with different encryption key", config.path.c_str());
+                }
+                return RLMAutorelease(realm);
+            }
+        }
+    }
+
+    configuration = [configuration copy];
+    Realm::Config& config = configuration.config;
+
+    RLMRealm *realm = [[self alloc] initPrivate];
+    realm->_dynamic = dynamic;
+
+    // protects the realm cache and accessors cache
+    static std::mutex& initLock = *new std::mutex();
+    std::lock_guard<std::mutex> lock(initLock);
+
+    try {
+        if (queue) {
+            if (queue == dispatch_get_main_queue()) {
+                config.scheduler = realm::util::Scheduler::make_runloop(CFRunLoopGetMain());
+            }
+            else {
+                config.scheduler = realm::util::Scheduler::make_dispatch((__bridge void *)queue);
+            }
+            if (!config.scheduler->is_on_thread()) {
+                throw RLMException(@"Realm opened from incorrect dispatch queue.");
+            }
+        }
+        else {
+            // If the source config was read from a Realm it may already have a
+            // scheduler, and we don't want to reuse it.
+            config.scheduler = nullptr;
+        }
+        realm->_realm = Realm::get_shared_realm(config);
+    }
+    catch (...) {
+        translateSharedGroupOpenException(error);
+        return nil;
+    }
+
+    // if we have a cached realm on another thread we can skip a few steps and
+    // just grab its schema
+    @autoreleasepool {
+        // ensure that cachedRealm doesn't end up in this thread's autorelease pool
+        if (auto cachedRealm = RLMGetAnyCachedRealmForPath(config.path)) {
+            realm->_realm->set_schema_subset(cachedRealm->_realm->schema());
+            realm->_schema = cachedRealm.schema;
+            realm->_info = cachedRealm->_info.clone(cachedRealm->_realm->schema(), realm);
+        }
+    }
+
+    if (realm->_schema) { }
+    else if (dynamic) {
+        realm->_schema = [RLMSchema dynamicSchemaFromObjectStoreSchema:realm->_realm->schema()];
+        realm->_info = RLMSchemaInfo(realm);
+    }
+    else {
+        // set/align schema or perform migration if needed
+        RLMSchema *schema = configuration.customSchema ?: RLMSchema.sharedSchema;
+
+        Realm::MigrationFunction migrationFunction;
+        auto migrationBlock = configuration.migrationBlock;
+        if (migrationBlock && configuration.schemaVersion > 0) {
+            migrationFunction = [=](SharedRealm old_realm, SharedRealm realm, Schema& mutableSchema) {
+                RLMSchema *oldSchema = [RLMSchema dynamicSchemaFromObjectStoreSchema:old_realm->schema()];
+                RLMRealm *oldRealm = [RLMRealm realmWithSharedRealm:old_realm schema:oldSchema];
+
+                // The destination RLMRealm can't just use the schema from the
+                // SharedRealm because it doesn't have information about whether or
+                // not a class was defined in Swift, which effects how new objects
+                // are created
+                RLMRealm *newRealm = [RLMRealm realmWithSharedRealm:realm schema:schema.copy];
+
+                [[[RLMMigration alloc] initWithRealm:newRealm oldRealm:oldRealm schema:mutableSchema] execute:migrationBlock];
+
+                oldRealm->_realm = nullptr;
+                newRealm->_realm = nullptr;
+            };
+        }
+
+        try {
+            realm->_realm->update_schema(schema.objectStoreCopy, config.schema_version,
+                                         std::move(migrationFunction));
+        }
+        catch (...) {
+            RLMRealmTranslateException(error);
+            return nil;
+        }
+
+        realm->_schema = schema;
+        realm->_info = RLMSchemaInfo(realm);
+        RLMRealmCreateAccessors(realm.schema);
+
+        if (!readOnly) {
+            REALM_ASSERT(!realm->_realm->is_in_read_transaction());
+
+            if (s_set_skip_backup_attribute) {
+                RLMAddSkipBackupAttributeToItemAtPath(config.path + ".management");
+                RLMAddSkipBackupAttributeToItemAtPath(config.path + ".lock");
+                RLMAddSkipBackupAttributeToItemAtPath(config.path + ".note");
+            }
+        }
+    }
+
+    if (cache) {
+        RLMCacheRealm(config.path, cacheKey, realm);
+    }
+
+    if (!readOnly) {
+        realm->_realm->m_binding_context = RLMCreateBindingContext(realm);
+        realm->_realm->m_binding_context->realm = realm->_realm;
+    }
+
+    return RLMAutorelease(realm);
+}
+
++ (void)resetRealmState {
+    RLMClearRealmCache();
+    realm::_impl::RealmCoordinator::clear_cache();
+    [RLMRealmConfiguration resetRealmConfigurationState];
+}
+
+- (void)verifyNotificationsAreSupported:(bool)isCollection {
+    [self verifyThread];
+    if (_realm->config().immutable()) {
+        @throw RLMException(@"Read-only Realms do not change and do not have change notifications.");
+    }
+    if (_realm->is_frozen()) {
+        @throw RLMException(@"Frozen Realms do not change and do not have change notifications.");
+    }
+    if (!_realm->can_deliver_notifications()) {
+        @throw RLMException(@"Can only add notification blocks from within runloops.");
+    }
+    if (isCollection && _realm->is_in_transaction()) {
+        @throw RLMException(@"Cannot register notification blocks from within write transactions.");
+    }
+}
+
+- (RLMNotificationToken *)addNotificationBlock:(RLMNotificationBlock)block {
+    if (!block) {
+        @throw RLMException(@"The notification block should not be nil");
+    }
+    [self verifyNotificationsAreSupported:false];
+
+    _realm->read_group();
+
+    if (!_notificationHandlers) {
+        _notificationHandlers = [NSHashTable hashTableWithOptions:NSPointerFunctionsWeakMemory];
+    }
+
+    RLMRealmNotificationToken *token = [[RLMRealmNotificationToken alloc] init];
+    token.realm = self;
+    token.block = block;
+    [_notificationHandlers addObject:token];
+    return token;
+}
+
+- (void)sendNotifications:(RLMNotification)notification {
+    NSAssert(!_realm->config().immutable(), @"Read-only realms do not have notifications");
+    if (_sendingNotifications) {
+        return;
+    }
+    NSUInteger count = _notificationHandlers.count;
+    if (count == 0) {
+        return;
+    }
+
+    _sendingNotifications = true;
+    auto cleanup = realm::util::make_scope_exit([&]() noexcept {
+        _sendingNotifications = false;
+    });
+
+    // call this realm's notification blocks
+    if (count == 1) {
+        if (auto block = [_notificationHandlers.anyObject block]) {
+            block(notification, self);
+        }
+    }
+    else {
+        for (RLMRealmNotificationToken *token in _notificationHandlers.allObjects) {
+            if (auto block = token.block) {
+                block(notification, self);
+            }
+        }
+    }
+}
+
+- (RLMRealmConfiguration *)configuration {
+    RLMRealmConfiguration *configuration = [[RLMRealmConfiguration alloc] init];
+    configuration.config = _realm->config();
+    configuration.dynamic = _dynamic;
+    configuration.customSchema = _schema;
+    return configuration;
+}
+
+- (void)beginWriteTransaction {
+    [self beginWriteTransactionWithError:nil];
+}
+
+- (BOOL)beginWriteTransactionWithError:(NSError **)error {
+    try {
+        _realm->begin_transaction();
+        return YES;
+    }
+    catch (...) {
+        RLMRealmTranslateException(error);
+        return NO;
+    }
+}
+
+- (void)commitWriteTransaction {
+    [self commitWriteTransaction:nil];
+}
+
+- (BOOL)commitWriteTransaction:(NSError **)error {
+    return [self commitWriteTransactionWithoutNotifying:@[] error:error];
+}
+
+- (BOOL)commitWriteTransactionWithoutNotifying:(NSArray<RLMNotificationToken *> *)tokens error:(NSError **)error {
+    for (RLMNotificationToken *token in tokens) {
+        if (token.realm != self) {
+            @throw RLMException(@"Incorrect Realm: only notifications for the Realm being modified can be skipped.");
+        }
+        [token suppressNextNotification];
+    }
+
+    try {
+        _realm->commit_transaction();
+        return YES;
+    }
+    catch (...) {
+        RLMRealmTranslateException(error);
+        return NO;
+    }
+}
+
+- (void)transactionWithBlock:(__attribute__((noescape)) void(^)(void))block {
+    [self transactionWithBlock:block error:nil];
+}
+
+- (BOOL)transactionWithBlock:(__attribute__((noescape)) void(^)(void))block error:(NSError **)outError {
+    return [self transactionWithoutNotifying:@[] block:block error:outError];
+}
+
+- (void)transactionWithoutNotifying:(NSArray<RLMNotificationToken *> *)tokens block:(__attribute__((noescape)) void(^)(void))block {
+    [self transactionWithoutNotifying:tokens block:block error:nil];
+}
+
+- (BOOL)transactionWithoutNotifying:(NSArray<RLMNotificationToken *> *)tokens block:(__attribute__((noescape)) void(^)(void))block error:(NSError **)error {
+    [self beginWriteTransactionWithError:error];
+    block();
+    if (_realm->is_in_transaction()) {
+        return [self commitWriteTransactionWithoutNotifying:tokens error:error];
+    }
+    return YES;
+}
+
+- (void)cancelWriteTransaction {
+    try {
+        _realm->cancel_transaction();
+    }
+    catch (std::exception &ex) {
+        @throw RLMException(ex);
+    }
+}
+
+- (void)invalidate {
+    if (_realm->is_in_transaction()) {
+        NSLog(@"WARNING: An RLMRealm instance was invalidated during a write "
+              "transaction and all pending changes have been rolled back.");
+    }
+
+    [self detachAllEnumerators];
+
+    for (auto& objectInfo : _info) {
+        for (RLMObservationInfo *info : objectInfo.second.observedObjects) {
+            info->willChange(RLMInvalidatedKey);
+        }
+    }
+
+    _realm->invalidate();
+
+    for (auto& objectInfo : _info) {
+        for (RLMObservationInfo *info : objectInfo.second.observedObjects) {
+            info->didChange(RLMInvalidatedKey);
+        }
+    }
+
+    if (_realm->is_frozen()) {
+        _realm->close();
+    }
+}
+
+- (nullable id)resolveThreadSafeReference:(RLMThreadSafeReference *)reference {
+    return [reference resolveReferenceInRealm:self];
+}
+
+/**
+ Replaces all string columns in this Realm with a string enumeration column and compacts the
+ database file.
+
+ Cannot be called from a write transaction.
+
+ Compaction will not occur if other `RLMRealm` instances exist.
+
+ While compaction is in progress, attempts by other threads or processes to open the database will
+ wait.
+
+ Be warned that resource requirements for compaction is proportional to the amount of live data in
+ the database.
+
+ Compaction works by writing the database contents to a temporary database file and then replacing
+ the database with the temporary one. The name of the temporary file is formed by appending
+ `.tmp_compaction_space` to the name of the database.
+
+ @return YES if the compaction succeeded.
+ */
+- (BOOL)compact {
+    // compact() automatically ends the read transaction, but we need to clean
+    // up cached state and send invalidated notifications when that happens, so
+    // explicitly end it first unless we're in a write transaction (in which
+    // case compact() will throw an exception)
+    if (!_realm->is_in_transaction()) {
+        [self invalidate];
+    }
+
+    try {
+        return _realm->compact();
+    }
+    catch (std::exception const& ex) {
+        @throw RLMException(ex);
+    }
+}
+
+- (void)dealloc {
+    if (_realm) {
+        if (_realm->is_in_transaction()) {
+            [self cancelWriteTransaction];
+            NSLog(@"WARNING: An RLMRealm instance was deallocated during a write transaction and all "
+                  "pending changes have been rolled back. Make sure to retain a reference to the "
+                  "RLMRealm for the duration of the write transaction.");
+        }
+    }
+}
+
+- (BOOL)refresh {
+    if (_realm->config().immutable()) {
+        @throw RLMException(@"Read-only Realms do not change and cannot be refreshed.");
+    }
+    try {
+        return _realm->refresh();
+    }
+    catch (std::exception const& e) {
+        @throw RLMException(e);
+    }
+}
+
+- (void)addObject:(__unsafe_unretained RLMObject *const)object {
+    RLMAddObjectToRealm(object, self, RLMUpdatePolicyError);
+}
+
+- (void)addObjects:(id<NSFastEnumeration>)objects {
+    for (RLMObject *obj in objects) {
+        if (![obj isKindOfClass:RLMObjectBase.class]) {
+            @throw RLMException(@"Cannot insert objects of type %@ with addObjects:. Only RLMObjects are supported.",
+                                NSStringFromClass(obj.class));
+        }
+        [self addObject:obj];
+    }
+}
+
+- (void)addOrUpdateObject:(RLMObject *)object {
+    // verify primary key
+    if (!object.objectSchema.primaryKeyProperty) {
+        @throw RLMException(@"'%@' does not have a primary key and can not be updated", object.objectSchema.className);
+    }
+
+    RLMAddObjectToRealm(object, self, RLMUpdatePolicyUpdateAll);
+}
+
+- (void)addOrUpdateObjects:(id<NSFastEnumeration>)objects {
+    for (RLMObject *obj in objects) {
+        if (![obj isKindOfClass:RLMObjectBase.class]) {
+            @throw RLMException(@"Cannot add or update objects of type %@ with addOrUpdateObjects:. Only RLMObjects are"
+                                " supported.",
+                                NSStringFromClass(obj.class));
+        }
+        [self addOrUpdateObject:obj];
+    }
+}
+
+- (void)deleteObject:(RLMObject *)object {
+    RLMDeleteObjectFromRealm(object, self);
+}
+
+- (void)deleteObjects:(id<NSFastEnumeration>)objects {
+    id idObjects = objects;
+    if ([idObjects respondsToSelector:@selector(realm)]
+        && [idObjects respondsToSelector:@selector(deleteObjectsFromRealm)]) {
+        if (self != (RLMRealm *)[idObjects realm]) {
+            @throw RLMException(@"Can only delete objects from the Realm they belong to.");
+        }
+        [idObjects deleteObjectsFromRealm];
+        return;
+    }
+    if (auto array = RLMDynamicCast<RLMArray>(objects)) {
+        if (array.type != RLMPropertyTypeObject) {
+            @throw RLMException(@"Cannot delete objects from RLMArray<%@>: only RLMObjects can be deleted.",
+                                RLMTypeToString(array.type));
+        }
+    }
+    for (RLMObject *obj in objects) {
+        if (![obj isKindOfClass:RLMObjectBase.class]) {
+            @throw RLMException(@"Cannot delete objects of type %@ with deleteObjects:. Only RLMObjects can be deleted.",
+                                NSStringFromClass(obj.class));
+        }
+        RLMDeleteObjectFromRealm(obj, self);
+    }
+}
+
+- (void)deleteAllObjects {
+    RLMDeleteAllObjectsFromRealm(self);
+}
+
+- (RLMResults *)allObjects:(NSString *)objectClassName {
+    return RLMGetObjects(self, objectClassName, nil);
+}
+
+- (RLMResults *)objects:(NSString *)objectClassName where:(NSString *)predicateFormat, ... {
+    va_list args;
+    va_start(args, predicateFormat);
+    RLMResults *results = [self objects:objectClassName where:predicateFormat args:args];
+    va_end(args);
+    return results;
+}
+
+- (RLMResults *)objects:(NSString *)objectClassName where:(NSString *)predicateFormat args:(va_list)args {
+    return [self objects:objectClassName withPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]];
+}
+
+- (RLMResults *)objects:(NSString *)objectClassName withPredicate:(NSPredicate *)predicate {
+    return RLMGetObjects(self, objectClassName, predicate);
+}
+
+- (RLMObject *)objectWithClassName:(NSString *)className forPrimaryKey:(id)primaryKey {
+    return RLMGetObject(self, className, primaryKey);
+}
+
++ (uint64_t)schemaVersionAtURL:(NSURL *)fileURL encryptionKey:(NSData *)key error:(NSError **)error {
+    RLMRealmConfiguration *config = [[RLMRealmConfiguration alloc] init];
+    try {
+        config.fileURL = fileURL;
+        config.encryptionKey = RLMRealmValidatedEncryptionKey(key);
+
+        uint64_t version = Realm::get_schema_version(config.config);
+        if (version == realm::ObjectStore::NotVersioned) {
+            RLMSetErrorOrThrow([NSError errorWithDomain:RLMErrorDomain code:RLMErrorFail userInfo:@{NSLocalizedDescriptionKey:@"Cannot open an uninitialized realm in read-only mode"}], error);
+        }
+        return version;
+    }
+    catch (...) {
+        translateSharedGroupOpenException(error);
+        return RLMNotVersioned;
+    }
+}
+
++ (BOOL)performMigrationForConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error {
+    if (RLMGetAnyCachedRealmForPath(configuration.config.path)) {
+        @throw RLMException(@"Cannot migrate Realms that are already open.");
+    }
+
+    NSError *localError; // Prevents autorelease
+    BOOL success;
+    @autoreleasepool {
+        success = [RLMRealm realmWithConfiguration:configuration error:&localError] != nil;
+    }
+    if (!success && error) {
+        *error = localError; // Must set outside pool otherwise will free anyway
+    }
+    return success;
+}
+
+- (RLMObject *)createObject:(NSString *)className withValue:(id)value {
+    return (RLMObject *)RLMCreateObjectInRealmWithValue(self, className, value, RLMUpdatePolicyError);
+}
+
+- (BOOL)writeCopyToURL:(NSURL *)fileURL encryptionKey:(NSData *)key error:(NSError **)error {
+    key = RLMRealmValidatedEncryptionKey(key);
+    NSString *path = fileURL.path;
+
+    try {
+        _realm->write_copy(path.UTF8String, {static_cast<const char *>(key.bytes), key.length});
+        return YES;
+    }
+    catch (...) {
+        __autoreleasing NSError *dummyError;
+        if (!error) {
+            error = &dummyError;
+        }
+        RLMRealmTranslateException(error);
+        return NO;
+    }
+
+    return NO;
+}
+
++ (BOOL)fileExistsForConfiguration:(RLMRealmConfiguration *)config {
+    return [NSFileManager.defaultManager fileExistsAtPath:config.pathOnDisk];
+}
+
++ (BOOL)deleteFilesForConfiguration:(RLMRealmConfiguration *)config error:(NSError **)error {
+    auto& path = config.config.path;
+    bool anyDeleted = false;
+    NSError *localError;
+    bool didCall = DB::call_with_lock(path, [&](auto const& path) {
+        NSURL *url = [NSURL fileURLWithPath:@(path.c_str())];
+        NSFileManager *fm = NSFileManager.defaultManager;
+
+        anyDeleted = [fm removeItemAtURL:url error:&localError];
+        if (localError && localError.code != NSFileNoSuchFileError) {
+            return;
+        }
+
+        [fm removeItemAtURL:[url URLByAppendingPathExtension:@"management"] error:&localError];
+        if (localError && localError.code != NSFileNoSuchFileError) {
+            return;
+        }
+
+        [fm removeItemAtURL:[url URLByAppendingPathExtension:@"note"] error:&localError];
+    });
+    if (error && localError && localError.code != NSFileNoSuchFileError) {
+        *error = localError;
+    }
+    else if (!didCall) {
+        if (error) {
+            NSString *msg = [NSString stringWithFormat:@"Realm file at path %s cannot be deleted because it is currently opened.", path.c_str()];
+            *error = [NSError errorWithDomain:RLMErrorDomain
+                                         code:RLMErrorAlreadyOpen
+                                     userInfo:@{NSLocalizedDescriptionKey: msg}];
+        }
+    }
+    return anyDeleted;
+}
+
+- (BOOL)isFrozen {
+    return _realm->is_frozen();
+}
+
+- (RLMRealm *)freeze {
+    [self verifyThread];
+    return self.isFrozen ? self : RLMGetFrozenRealmForSourceRealm(self);
+}
+
+- (RLMRealm *)thaw {
+    [self verifyThread];
+    return self.isFrozen ? [RLMRealm realmWithConfiguration:self.configuration error:nil] : self;
+}
+
+- (RLMRealm *)frozenCopy {
+    try {
+        RLMRealm *realm = [[RLMRealm alloc] initPrivate];
+        realm->_realm = _realm->freeze();
+        realm->_realm->set_schema_subset(_realm->schema());
+        realm->_realm->read_group();
+        realm->_dynamic = _dynamic;
+        realm->_schema = _schema;
+        realm->_info = RLMSchemaInfo(realm);
+        return realm;
+    }
+    catch (std::exception const& e) {
+        @throw RLMException(e);
+    }
+}
+
+- (void)registerEnumerator:(RLMFastEnumerator *)enumerator {
+    std::lock_guard lock(_collectionEnumeratorMutex);
+    if (!_collectionEnumerators) {
+        _collectionEnumerators = [NSHashTable hashTableWithOptions:NSPointerFunctionsWeakMemory];
+    }
+    [_collectionEnumerators addObject:enumerator];
+}
+
+- (void)unregisterEnumerator:(RLMFastEnumerator *)enumerator {
+    std::lock_guard lock(_collectionEnumeratorMutex);
+    [_collectionEnumerators removeObject:enumerator];
+}
+
+- (void)detachAllEnumerators {
+    std::lock_guard lock(_collectionEnumeratorMutex);
+    for (RLMFastEnumerator *enumerator in _collectionEnumerators) {
+        [enumerator detach];
+    }
+    _collectionEnumerators = nil;
+}
+
+@end

+ 77 - 0
Example/Pods/Realm/Realm/RLMRealmConfiguration+Sync.mm

@@ -0,0 +1,77 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2016 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMRealmConfiguration+Sync.h"
+
+#import "RLMBSON_Private.hpp"
+#import "RLMRealmConfiguration_Private.hpp"
+#import "RLMSyncConfiguration_Private.hpp"
+#import "RLMUser_Private.hpp"
+#import "RLMSyncManager_Private.hpp"
+#import "RLMSyncUtil_Private.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/sync/sync_manager.hpp>
+#import <realm/object-store/util/bson/bson.hpp>
+#import <realm/sync/config.hpp>
+
+@implementation RLMRealmConfiguration (Sync)
+
+#pragma mark - API
+
+- (void)setSyncConfiguration:(RLMSyncConfiguration *)syncConfiguration {
+    if (syncConfiguration == nil) {
+        self.config.sync_config = nullptr;
+        return;
+    }
+    if (self.config.should_compact_on_launch_function) {
+        @throw RLMException(@"Cannot set `syncConfiguration` when `shouldCompactOnLaunch` is set.");
+    }
+    RLMUser *user = syncConfiguration.user;
+    if (user.state == RLMUserStateRemoved) {
+        @throw RLMException(@"Cannot set a sync configuration which has an errored-out user.");
+    }
+
+    NSAssert(user.identifier, @"Cannot call this method on a user that doesn't have an identifier.");
+    self.config.in_memory = false;
+    self.config.sync_config = std::make_shared<realm::SyncConfig>([syncConfiguration rawConfiguration]);
+
+    if (syncConfiguration.customFileURL) {
+        self.config.path = syncConfiguration.customFileURL.path.UTF8String;
+    } else {
+        self.config.path = [user pathForPartitionValue:self.config.sync_config->partition_value];
+    }
+
+    if (!self.config.encryption_key.empty()) {
+        auto& sync_encryption_key = self.config.sync_config->realm_encryption_key;
+        sync_encryption_key = std::array<char, 64>();
+        std::copy_n(self.config.encryption_key.begin(), 64, sync_encryption_key->begin());
+    }
+
+    [self updateSchemaMode];
+}
+
+- (RLMSyncConfiguration *)syncConfiguration {
+    if (!self.config.sync_config) {
+        return nil;
+    }
+    realm::SyncConfig& sync_config = *self.config.sync_config;
+    return [[RLMSyncConfiguration alloc] initWithRawConfig:sync_config];
+}
+
+@end

+ 345 - 0
Example/Pods/Realm/Realm/RLMRealmConfiguration.mm

@@ -0,0 +1,345 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2015 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMRealmConfiguration_Private.h"
+
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMRealm_Private.h"
+#import "RLMSchema_Private.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/schema.hpp>
+#import <realm/object-store/shared_realm.hpp>
+
+#if REALM_ENABLE_SYNC
+#import <realm/sync/config.hpp>
+#else
+@class RLMSyncConfiguration;
+#endif
+
+static NSString *const c_RLMRealmConfigurationProperties[] = {
+    @"fileURL",
+    @"inMemoryIdentifier",
+    @"encryptionKey",
+    @"readOnly",
+    @"schemaVersion",
+    @"migrationBlock",
+    @"deleteRealmIfMigrationNeeded",
+    @"shouldCompactOnLaunch",
+    @"dynamic",
+    @"customSchema",
+};
+
+static NSString *const c_defaultRealmFileName = @"default.realm";
+RLMRealmConfiguration *s_defaultConfiguration;
+
+NSString *RLMRealmPathForFileAndBundleIdentifier(NSString *fileName, NSString *bundleIdentifier) {
+    return [RLMDefaultDirectoryForBundleIdentifier(bundleIdentifier)
+            stringByAppendingPathComponent:fileName];
+}
+
+NSString *RLMRealmPathForFile(NSString *fileName) {
+    static NSString *directory = RLMDefaultDirectoryForBundleIdentifier(nil);
+    return [directory stringByAppendingPathComponent:fileName];
+}
+
+@implementation RLMRealmConfiguration {
+    realm::Realm::Config _config;
+}
+
+- (realm::Realm::Config&)config {
+    return _config;
+}
+
++ (instancetype)defaultConfiguration {
+    return [[self rawDefaultConfiguration] copy];
+}
+
++ (void)setDefaultConfiguration:(RLMRealmConfiguration *)configuration {
+    if (!configuration) {
+        @throw RLMException(@"Cannot set the default configuration to nil.");
+    }
+    @synchronized(c_defaultRealmFileName) {
+        s_defaultConfiguration = [configuration copy];
+    }
+}
+
++ (RLMRealmConfiguration *)rawDefaultConfiguration {
+    RLMRealmConfiguration *configuration;
+    @synchronized(c_defaultRealmFileName) {
+        if (!s_defaultConfiguration) {
+            s_defaultConfiguration = [[RLMRealmConfiguration alloc] init];
+        }
+        configuration = s_defaultConfiguration;
+    }
+    return configuration;
+}
+
++ (void)resetRealmConfigurationState {
+    @synchronized(c_defaultRealmFileName) {
+        s_defaultConfiguration = nil;
+    }
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (self) {
+        static NSURL *defaultRealmURL = [NSURL fileURLWithPath:RLMRealmPathForFile(c_defaultRealmFileName)];
+        self.fileURL = defaultRealmURL;
+        self.schemaVersion = 0;
+        self.cache = YES;
+    }
+
+    return self;
+}
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    RLMRealmConfiguration *configuration = [[[self class] allocWithZone:zone] init];
+    configuration->_config = _config;
+    configuration->_cache = _cache;
+    configuration->_dynamic = _dynamic;
+    configuration->_migrationBlock = _migrationBlock;
+    configuration->_shouldCompactOnLaunch = _shouldCompactOnLaunch;
+    configuration->_customSchema = _customSchema;
+    return configuration;
+}
+
+- (NSString *)description {
+    NSMutableString *string = [NSMutableString stringWithFormat:@"%@ {\n", self.class];
+    for (NSString *key : c_RLMRealmConfigurationProperties) {
+        NSString *description = [[self valueForKey:key] description];
+        description = [description stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"];
+
+        [string appendFormat:@"\t%@ = %@;\n", key, description];
+    }
+    return [string stringByAppendingString:@"}"];
+}
+
+- (NSURL *)fileURL {
+    if (_config.in_memory) {
+        return nil;
+    }
+    return [NSURL fileURLWithPath:@(_config.path.c_str())];
+}
+
+- (void)setFileURL:(NSURL *)fileURL {
+    NSString *path = fileURL.path;
+    if (path.length == 0) {
+        @throw RLMException(@"Realm path must not be empty");
+    }
+
+    RLMNSStringToStdString(_config.path, path);
+    _config.in_memory = false;
+}
+
+- (NSString *)inMemoryIdentifier {
+    if (!_config.in_memory) {
+        return nil;
+    }
+    return [@(_config.path.c_str()) lastPathComponent];
+}
+
+- (void)setInMemoryIdentifier:(NSString *)inMemoryIdentifier {
+    if (inMemoryIdentifier.length == 0) {
+        @throw RLMException(@"In-memory identifier must not be empty");
+    }
+    _config.sync_config = nullptr;
+
+    RLMNSStringToStdString(_config.path, [NSTemporaryDirectory() stringByAppendingPathComponent:inMemoryIdentifier]);
+    _config.in_memory = true;
+}
+
+- (NSData *)encryptionKey {
+    return _config.encryption_key.empty() ? nil : [NSData dataWithBytes:_config.encryption_key.data() length:_config.encryption_key.size()];
+}
+
+- (void)setEncryptionKey:(NSData * __nullable)encryptionKey {
+    if (NSData *key = RLMRealmValidatedEncryptionKey(encryptionKey)) {
+        auto bytes = static_cast<const char *>(key.bytes);
+        _config.encryption_key.assign(bytes, bytes + key.length);
+#if REALM_ENABLE_SYNC
+        if (_config.sync_config) {
+            auto& sync_encryption_key = self.config.sync_config->realm_encryption_key;
+            sync_encryption_key = std::array<char, 64>();
+            std::copy_n(_config.encryption_key.begin(), 64, sync_encryption_key->begin());
+        }
+#endif
+    }
+    else {
+        _config.encryption_key.clear();
+#if REALM_ENABLE_SYNC
+        if (_config.sync_config)
+            _config.sync_config->realm_encryption_key = realm::util::none;
+#endif
+    }
+}
+
+- (BOOL)readOnly {
+    return _config.immutable() || _config.read_only_alternative();
+}
+
+static bool isSync(realm::Realm::Config const& config) {
+#if REALM_ENABLE_SYNC
+    return !!config.sync_config;
+#endif
+    return false;
+}
+
+- (void)updateSchemaMode {
+    if (self.deleteRealmIfMigrationNeeded) {
+        if (isSync(_config)) {
+            @throw RLMException(@"Cannot set 'deleteRealmIfMigrationNeeded' when sync is enabled ('syncConfig' is set).");
+        }
+    }
+    else if (self.readOnly) {
+        _config.schema_mode = isSync(_config) ? realm::SchemaMode::ReadOnlyAlternative : realm::SchemaMode::Immutable;
+    }
+    else if (isSync(_config)) {
+        if (_customSchema) {
+            _config.schema_mode = realm::SchemaMode::AdditiveExplicit;
+        }
+        else {
+            _config.schema_mode = realm::SchemaMode::AdditiveDiscovered;
+        }
+    }
+    else {
+        _config.schema_mode = realm::SchemaMode::Automatic;
+    }
+}
+
+- (void)setReadOnly:(BOOL)readOnly {
+    if (readOnly) {
+        if (self.deleteRealmIfMigrationNeeded) {
+            @throw RLMException(@"Cannot set `readOnly` when `deleteRealmIfMigrationNeeded` is set.");
+        } else if (self.shouldCompactOnLaunch) {
+            @throw RLMException(@"Cannot set `readOnly` when `shouldCompactOnLaunch` is set.");
+        }
+        _config.schema_mode = isSync(_config) ? realm::SchemaMode::ReadOnlyAlternative : realm::SchemaMode::Immutable;
+    }
+    else if (self.readOnly) {
+        _config.schema_mode = realm::SchemaMode::Automatic;
+        [self updateSchemaMode];
+    }
+}
+
+- (uint64_t)schemaVersion {
+    return _config.schema_version;
+}
+
+- (void)setSchemaVersion:(uint64_t)schemaVersion {
+    if (schemaVersion == RLMNotVersioned) {
+        @throw RLMException(@"Cannot set schema version to %llu (RLMNotVersioned)", RLMNotVersioned);
+    }
+    _config.schema_version = schemaVersion;
+}
+
+- (BOOL)deleteRealmIfMigrationNeeded {
+    return _config.schema_mode == realm::SchemaMode::ResetFile;
+}
+
+- (void)setDeleteRealmIfMigrationNeeded:(BOOL)deleteRealmIfMigrationNeeded {
+    if (deleteRealmIfMigrationNeeded) {
+        if (self.readOnly) {
+            @throw RLMException(@"Cannot set `deleteRealmIfMigrationNeeded` when `readOnly` is set.");
+        }
+        if (isSync(_config)) {
+            @throw RLMException(@"Cannot set 'deleteRealmIfMigrationNeeded' when sync is enabled ('syncConfig' is set).");
+        }
+        _config.schema_mode = realm::SchemaMode::ResetFile;
+    }
+    else if (self.deleteRealmIfMigrationNeeded) {
+        _config.schema_mode = realm::SchemaMode::Automatic;
+    }
+}
+
+- (NSArray *)objectClasses {
+    return [_customSchema.objectSchema valueForKeyPath:@"objectClass"];
+}
+
+- (void)setObjectClasses:(NSArray *)objectClasses {
+    self.customSchema = objectClasses ? [RLMSchema schemaWithObjectClasses:objectClasses] : nil;
+    [self updateSchemaMode];
+}
+
+- (NSUInteger)maximumNumberOfActiveVersions {
+    if (_config.max_number_of_active_versions > std::numeric_limits<NSUInteger>::max()) {
+        return std::numeric_limits<NSUInteger>::max();
+    }
+    return static_cast<NSUInteger>(_config.max_number_of_active_versions);
+}
+
+- (void)setMaximumNumberOfActiveVersions:(NSUInteger)maximumNumberOfActiveVersions {
+    if (maximumNumberOfActiveVersions == 0) {
+        _config.max_number_of_active_versions = std::numeric_limits<uint_fast64_t>::max();
+    }
+    else {
+        _config.max_number_of_active_versions = maximumNumberOfActiveVersions;
+    }
+}
+
+- (void)setDynamic:(bool)dynamic {
+    _dynamic = dynamic;
+    self.cache = !dynamic;
+}
+
+- (bool)disableFormatUpgrade {
+    return _config.disable_format_upgrade;
+}
+
+- (void)setDisableFormatUpgrade:(bool)disableFormatUpgrade {
+    _config.disable_format_upgrade = disableFormatUpgrade;
+}
+
+- (realm::SchemaMode)schemaMode {
+    return _config.schema_mode;
+}
+
+- (void)setSchemaMode:(realm::SchemaMode)mode {
+    _config.schema_mode = mode;
+}
+
+- (NSString *)pathOnDisk {
+    return @(_config.path.c_str());
+}
+
+- (void)setShouldCompactOnLaunch:(RLMShouldCompactOnLaunchBlock)shouldCompactOnLaunch {
+    if (shouldCompactOnLaunch) {
+        if (_config.immutable()) {
+            @throw RLMException(@"Cannot set `shouldCompactOnLaunch` when `readOnly` is set.");
+        }
+        _config.should_compact_on_launch_function = [=](size_t totalBytes, size_t usedBytes) {
+            return shouldCompactOnLaunch(totalBytes, usedBytes);
+        };
+    }
+    else {
+        _config.should_compact_on_launch_function = nullptr;
+    }
+    _shouldCompactOnLaunch = shouldCompactOnLaunch;
+}
+
+- (void)setCustomSchemaWithoutCopying:(RLMSchema *)schema {
+    _customSchema = schema;
+}
+
+#if !REALM_ENABLE_SYNC
+- (RLMSyncConfiguration *)syncConfiguration {
+    return nil;
+}
+#endif
+
+@end

+ 157 - 0
Example/Pods/Realm/Realm/RLMRealmUtil.mm

@@ -0,0 +1,157 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMRealmUtil.hpp"
+
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMObservation.hpp"
+#import "RLMRealm_Private.hpp"
+#import "RLMUtil.hpp"
+
+#import <Realm/RLMConstants.h>
+#import <Realm/RLMSchema.h>
+
+#import <realm/obj.hpp>
+#import <realm/object-store/binding_context.hpp>
+#import <realm/object-store/shared_realm.hpp>
+#import <realm/object-store/util/scheduler.hpp>
+
+#import <map>
+#import <mutex>
+
+// Global realm state
+static auto& s_realmCacheMutex = *new std::mutex();
+static auto& s_realmsPerPath = *new std::map<std::string, NSMapTable *>();
+static auto& s_frozenRealms = *new std::map<std::string, NSMapTable *>();
+
+void RLMCacheRealm(std::string const& path, void *key, __unsafe_unretained RLMRealm *const realm) {
+    std::lock_guard<std::mutex> lock(s_realmCacheMutex);
+    NSMapTable *realms = s_realmsPerPath[path];
+    if (!realms) {
+        s_realmsPerPath[path] = realms = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsOpaquePersonality|NSPointerFunctionsOpaqueMemory
+                                                               valueOptions:NSPointerFunctionsWeakMemory];
+    }
+    [realms setObject:realm forKey:(__bridge id)key];
+}
+
+RLMRealm *RLMGetAnyCachedRealmForPath(std::string const& path) {
+    std::lock_guard<std::mutex> lock(s_realmCacheMutex);
+    return [s_realmsPerPath[path] objectEnumerator].nextObject;
+}
+
+RLMRealm *RLMGetThreadLocalCachedRealmForPath(std::string const& path, void *key) {
+    std::lock_guard<std::mutex> lock(s_realmCacheMutex);
+    RLMRealm *realm = [s_realmsPerPath[path] objectForKey:(__bridge id)key];
+    if (realm && !realm->_realm->scheduler()->is_on_thread()) {
+        // We can get here in two cases: if the user is trying to open a
+        // queue-bound Realm from the wrong queue, or if we have a stale cached
+        // Realm which is bound to a thread that no longer exists. In the first
+        // case we'll throw an error later on; in the second we'll just create
+        // a new RLMRealm and replace the cache entry with one bound to the
+        // thread that now exists.
+        realm = nil;
+    }
+    return realm;
+}
+
+void RLMClearRealmCache() {
+    std::lock_guard<std::mutex> lock(s_realmCacheMutex);
+    s_realmsPerPath.clear();
+    s_frozenRealms.clear();
+}
+
+RLMRealm *RLMGetFrozenRealmForSourceRealm(__unsafe_unretained RLMRealm *const sourceRealm) {
+    std::lock_guard<std::mutex> lock(s_realmCacheMutex);
+    auto& r = *sourceRealm->_realm;
+    auto& path = r.config().path;
+    NSMapTable *realms = s_realmsPerPath[path];
+    if (!realms) {
+        s_realmsPerPath[path] = realms = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsIntegerPersonality|NSPointerFunctionsOpaqueMemory
+                                                               valueOptions:NSPointerFunctionsWeakMemory];
+    }
+    r.read_group();
+    auto version = reinterpret_cast<void *>(r.read_transaction_version().version);
+    RLMRealm *realm = [realms objectForKey:(__bridge id)version];
+    if (!realm) {
+        realm = [sourceRealm frozenCopy];
+        [realms setObject:realm forKey:(__bridge id)version];
+    }
+    return realm;
+}
+
+namespace {
+class RLMNotificationHelper : public realm::BindingContext {
+public:
+    RLMNotificationHelper(RLMRealm *realm) : _realm(realm) { }
+
+    void changes_available() override {
+        @autoreleasepool {
+            auto realm = _realm;
+            if (realm && !realm.autorefresh) {
+                [realm sendNotifications:RLMRealmRefreshRequiredNotification];
+            }
+        }
+    }
+
+    std::vector<ObserverState> get_observed_rows() override {
+        @autoreleasepool {
+            if (auto realm = _realm) {
+                [realm detachAllEnumerators];
+                return RLMGetObservedRows(realm->_info);
+            }
+            return {};
+        }
+    }
+
+    void will_change(std::vector<ObserverState> const& observed, std::vector<void*> const& invalidated) override {
+        @autoreleasepool {
+            RLMWillChange(observed, invalidated);
+        }
+    }
+
+    void did_change(std::vector<ObserverState> const& observed, std::vector<void*> const& invalidated, bool version_changed) override {
+        try {
+            @autoreleasepool {
+                RLMDidChange(observed, invalidated);
+                if (version_changed) {
+                    [_realm sendNotifications:RLMRealmDidChangeNotification];
+                }
+            }
+        }
+        catch (...) {
+            // This can only be called during a write transaction if it was
+            // called due to the transaction beginning, so cancel it to ensure
+            // exceptions thrown here behave the same as exceptions thrown when
+            // actually beginning the write
+            if (_realm.inWriteTransaction) {
+                [_realm cancelWriteTransaction];
+            }
+            throw;
+        }
+    }
+
+private:
+    // This is owned by the realm, so it needs to not retain the realm
+    __weak RLMRealm *const _realm;
+};
+} // anonymous namespace
+
+
+std::unique_ptr<realm::BindingContext> RLMCreateBindingContext(__unsafe_unretained RLMRealm *const realm) {
+    return std::unique_ptr<realm::BindingContext>(new RLMNotificationHelper(realm));
+}

+ 572 - 0
Example/Pods/Realm/Realm/RLMResults.mm

@@ -0,0 +1,572 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMResults_Private.hpp"
+
+#import "RLMAccessor.hpp"
+#import "RLMArray_Private.hpp"
+#import "RLMCollection_Private.hpp"
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMObjectStore.h"
+#import "RLMObject_Private.hpp"
+#import "RLMObservation.hpp"
+#import "RLMProperty_Private.h"
+#import "RLMQueryUtil.hpp"
+#import "RLMRealm_Private.hpp"
+#import "RLMRealmConfiguration_Private.hpp"
+#import "RLMSchema_Private.h"
+#import "RLMThreadSafeReference_Private.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/results.hpp>
+#import <realm/object-store/shared_realm.hpp>
+#import <realm/table_view.hpp>
+
+#import <objc/message.h>
+
+using namespace realm;
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wincomplete-implementation"
+@implementation RLMNotificationToken
+@end
+#pragma clang diagnostic pop
+
+@interface RLMResults () <RLMThreadConfined_Private>
+@end
+
+//
+// RLMResults implementation
+//
+@implementation RLMResults {
+    RLMRealm *_realm;
+    RLMClassInfo *_info;
+}
+
+- (instancetype)initPrivate {
+    self = [super init];
+    return self;
+}
+
+- (instancetype)initWithResults:(Results)results {
+    if (self = [super init]) {
+        _results = std::move(results);
+    }
+    return self;
+}
+
+static void assertKeyPathIsNotNested(NSString *keyPath) {
+    if ([keyPath rangeOfString:@"."].location != NSNotFound) {
+        @throw RLMException(@"Nested key paths are not supported yet for KVC collection operators.");
+    }
+}
+
+void RLMThrowResultsError(NSString *aggregateMethod) {
+    try {
+        throw;
+    }
+    catch (realm::InvalidTransactionException const&) {
+        @throw RLMException(@"Cannot modify Results outside of a write transaction.");
+    }
+    catch (realm::IncorrectThreadException const&) {
+        @throw RLMException(@"Realm accessed from incorrect thread.");
+    }
+    catch (realm::Results::InvalidatedException const&) {
+        @throw RLMException(@"RLMResults has been invalidated.");
+    }
+    catch (realm::Results::DetatchedAccessorException const&) {
+        @throw RLMException(@"Object has been invalidated.");
+    }
+    catch (realm::Results::IncorrectTableException const& e) {
+        @throw RLMException(@"Object of type '%s' does not match RLMResults type '%s'.",
+                            e.actual.data(), e.expected.data());
+    }
+    catch (realm::Results::OutOfBoundsIndexException const& e) {
+        @throw RLMException(@"Index %zu is out of bounds (must be less than %zu).",
+                            e.requested, e.valid_count);
+    }
+    catch (realm::Results::UnsupportedColumnTypeException const& e) {
+        @throw RLMException(@"%@ is not supported for %s%s property '%s'.",
+                            aggregateMethod,
+                            string_for_property_type(e.property_type),
+                            is_nullable(e.property_type) ? "?" : "",
+                            e.column_name.data());
+    }
+    catch (std::exception const& e) {
+        @throw RLMException(e);
+    }
+}
+
+- (instancetype)initWithObjectInfo:(RLMClassInfo&)info
+                           results:(realm::Results&&)results {
+    if (self = [super init]) {
+        _results = std::move(results);
+        _realm = info.realm;
+        _info = &info;
+    }
+    return self;
+}
+
++ (instancetype)resultsWithObjectInfo:(RLMClassInfo&)info
+                              results:(realm::Results&&)results {
+    return [[self alloc] initWithObjectInfo:info results:std::move(results)];
+}
+
++ (instancetype)emptyDetachedResults {
+    return [[self alloc] initPrivate];
+}
+
+- (instancetype)subresultsWithResults:(realm::Results)results {
+    return [self.class resultsWithObjectInfo:*_info results:std::move(results)];
+}
+
+static inline void RLMResultsValidateInWriteTransaction(__unsafe_unretained RLMResults *const ar) {
+    ar->_realm->_realm->verify_thread();
+    ar->_realm->_realm->verify_in_write();
+}
+
+- (BOOL)isInvalidated {
+    return translateRLMResultsErrors([&] { return !_results.is_valid(); });
+}
+
+- (NSUInteger)count {
+    return translateRLMResultsErrors([&] { return _results.size(); });
+}
+
+- (RLMPropertyType)type {
+    return translateRLMResultsErrors([&] {
+        return static_cast<RLMPropertyType>(_results.get_type() & ~realm::PropertyType::Nullable);
+    });
+}
+
+- (BOOL)isOptional {
+    return translateRLMResultsErrors([&] {
+        return is_nullable(_results.get_type());
+    });
+}
+
+- (NSString *)objectClassName {
+    return translateRLMResultsErrors([&] {
+        if (_info && _results.get_type() == realm::PropertyType::Object) {
+            return _info->rlmObjectSchema.className;
+        }
+        return (NSString *)nil;
+    });
+}
+
+- (RLMClassInfo *)objectInfo {
+    return _info;
+}
+
+- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
+                                  objects:(__unused __unsafe_unretained id [])buffer
+                                    count:(NSUInteger)len {
+    if (!_info) {
+        return 0;
+    }
+    if (state->state == 0) {
+        translateRLMResultsErrors([&] {
+            _results.evaluate_query_if_needed();
+        });
+    }
+    return RLMFastEnumerate(state, len, self);
+}
+
+- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ... {
+    va_list args;
+    va_start(args, predicateFormat);
+    NSUInteger index = [self indexOfObjectWhere:predicateFormat args:args];
+    va_end(args);
+    return index;
+}
+
+- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args {
+    return [self indexOfObjectWithPredicate:[NSPredicate predicateWithFormat:predicateFormat
+                                                                   arguments:args]];
+}
+
+- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate {
+    if (_results.get_mode() == Results::Mode::Empty) {
+        return NSNotFound;
+    }
+
+    return translateRLMResultsErrors([&] {
+        if (_results.get_type() != realm::PropertyType::Object) {
+            @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects");
+        }
+        return RLMConvertNotFound(_results.index_of(RLMPredicateToQuery(predicate, _info->rlmObjectSchema, _realm.schema, _realm.group)));
+    });
+}
+
+- (id)objectAtIndex:(NSUInteger)index {
+    RLMAccessorContext ctx(*_info);
+    return translateRLMResultsErrors([&] {
+        return _results.get(ctx, index);
+    });
+}
+
+- (id)firstObject {
+    if (!_info) {
+        return nil;
+    }
+    RLMAccessorContext ctx(*_info);
+    return translateRLMResultsErrors([&] {
+        return _results.first(ctx);
+    });
+}
+
+- (id)lastObject {
+    if (!_info) {
+        return nil;
+    }
+    RLMAccessorContext ctx(*_info);
+    return translateRLMResultsErrors([&] {
+        return _results.last(ctx);
+    });
+}
+
+- (NSUInteger)indexOfObject:(id)object {
+    if (!_info || !object) {
+        return NSNotFound;
+    }
+    if (RLMObjectBase *obj = RLMDynamicCast<RLMObjectBase>(object)) {
+        // Unmanaged objects are considered not equal to all managed objects
+        if (!obj->_realm && !obj.invalidated) {
+            return NSNotFound;
+        }
+    }
+    RLMAccessorContext ctx(*_info);
+    return translateRLMResultsErrors([&] {
+        return RLMConvertNotFound(_results.index_of(ctx, object));
+    });
+}
+
+- (id)valueForKeyPath:(NSString *)keyPath {
+    if ([keyPath characterAtIndex:0] != '@') {
+        return [super valueForKeyPath:keyPath];
+    }
+    if ([keyPath isEqualToString:@"@count"]) {
+        return @(self.count);
+    }
+
+    NSRange operatorRange = [keyPath rangeOfString:@"." options:NSLiteralSearch];
+    NSUInteger keyPathLength = keyPath.length;
+    NSUInteger separatorIndex = operatorRange.location != NSNotFound ? operatorRange.location : keyPathLength;
+    NSString *operatorName = [keyPath substringWithRange:NSMakeRange(1, separatorIndex - 1)];
+    SEL opSelector = NSSelectorFromString([NSString stringWithFormat:@"_%@ForKeyPath:", operatorName]);
+    if (![self respondsToSelector:opSelector]) {
+        @throw RLMException(@"Unsupported KVC collection operator found in key path '%@'", keyPath);
+    }
+    if (separatorIndex >= keyPathLength - 1) {
+        @throw RLMException(@"Missing key path for KVC collection operator %@ in key path '%@'",
+                            operatorName, keyPath);
+    }
+    NSString *operatorKeyPath = [keyPath substringFromIndex:separatorIndex + 1];
+    return ((id(*)(id, SEL, id))objc_msgSend)(self, opSelector, operatorKeyPath);
+}
+
+- (id)valueForKey:(NSString *)key {
+    if (!_info) {
+        return @[];
+    }
+    return translateRLMResultsErrors([&] {
+        return RLMCollectionValueForKey(_results, key, *_info);
+    });
+}
+
+- (void)setValue:(id)value forKey:(NSString *)key {
+    translateRLMResultsErrors([&] { RLMResultsValidateInWriteTransaction(self); });
+    RLMCollectionSetValueForKey(self, key, value);
+}
+
+- (NSNumber *)_aggregateForKeyPath:(NSString *)keyPath
+                            method:(util::Optional<Mixed> (Results::*)(ColKey))method
+                        methodName:(NSString *)methodName returnNilForEmpty:(BOOL)returnNilForEmpty {
+    assertKeyPathIsNotNested(keyPath);
+    return [self aggregate:keyPath method:method methodName:methodName returnNilForEmpty:returnNilForEmpty];
+}
+
+- (NSNumber *)_minForKeyPath:(NSString *)keyPath {
+    return [self _aggregateForKeyPath:keyPath method:&Results::min methodName:@"@min" returnNilForEmpty:YES];
+}
+
+- (NSNumber *)_maxForKeyPath:(NSString *)keyPath {
+    return [self _aggregateForKeyPath:keyPath method:&Results::max methodName:@"@max" returnNilForEmpty:YES];
+}
+
+- (NSNumber *)_sumForKeyPath:(NSString *)keyPath {
+    return [self _aggregateForKeyPath:keyPath method:&Results::sum methodName:@"@sum" returnNilForEmpty:NO];
+}
+
+- (NSNumber *)_avgForKeyPath:(NSString *)keyPath {
+    assertKeyPathIsNotNested(keyPath);
+    return [self averageOfProperty:keyPath];
+}
+
+- (NSArray *)_unionOfObjectsForKeyPath:(NSString *)keyPath {
+    assertKeyPathIsNotNested(keyPath);
+    return translateRLMResultsErrors([&] {
+        return RLMCollectionValueForKey(_results, keyPath, *_info);
+    });
+}
+
+- (NSArray *)_distinctUnionOfObjectsForKeyPath:(NSString *)keyPath {
+    return [NSSet setWithArray:[self _unionOfObjectsForKeyPath:keyPath]].allObjects;
+}
+
+- (NSArray *)_unionOfArraysForKeyPath:(NSString *)keyPath {
+    assertKeyPathIsNotNested(keyPath);
+    if ([keyPath isEqualToString:@"self"]) {
+        @throw RLMException(@"self is not a valid key-path for a KVC array collection operator as 'unionOfArrays'.");
+    }
+
+    return translateRLMResultsErrors([&] {
+        NSMutableArray *flatArray = [NSMutableArray new];
+        for (id<NSFastEnumeration> array in RLMCollectionValueForKey(_results, keyPath, *_info)) {
+            for (id value in array) {
+                [flatArray addObject:value];
+            }
+        }
+        return flatArray;
+    });
+}
+
+- (NSArray *)_distinctUnionOfArraysForKeyPath:(__unused NSString *)keyPath {
+    return [NSSet setWithArray:[self _unionOfArraysForKeyPath:keyPath]].allObjects;
+}
+
+- (RLMResults *)objectsWhere:(NSString *)predicateFormat, ... {
+    va_list args;
+    va_start(args, predicateFormat);
+    RLMResults *results = [self objectsWhere:predicateFormat args:args];
+    va_end(args);
+    return results;
+}
+
+- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args {
+    return [self objectsWithPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]];
+}
+
+- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate {
+    return translateRLMResultsErrors([&] {
+        if (_results.get_mode() == Results::Mode::Empty) {
+            return self;
+        }
+        if (_results.get_type() != realm::PropertyType::Object) {
+            @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects");
+        }
+        auto query = RLMPredicateToQuery(predicate, _info->rlmObjectSchema, _realm.schema, _realm.group);
+        return [self subresultsWithResults:_results.filter(std::move(query))];
+    });
+}
+
+- (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending {
+    return [self sortedResultsUsingDescriptors:@[[RLMSortDescriptor sortDescriptorWithKeyPath:keyPath ascending:ascending]]];
+}
+
+- (RLMResults *)sortedResultsUsingDescriptors:(NSArray<RLMSortDescriptor *> *)properties {
+    if (properties.count == 0) {
+        return self;
+    }
+    return translateRLMResultsErrors([&] {
+        if (_results.get_mode() == Results::Mode::Empty) {
+            return self;
+        }
+        return [self subresultsWithResults:_results.sort(RLMSortDescriptorsToKeypathArray(properties))];
+    });
+}
+
+- (RLMResults *)distinctResultsUsingKeyPaths:(NSArray<NSString *> *)keyPaths {
+    for (NSString *keyPath in keyPaths) {
+        if ([keyPath rangeOfString:@"@"].location != NSNotFound) {
+            @throw RLMException(@"Cannot distinct on keypath '%@': KVC collection operators are not supported.", keyPath);
+        }
+    }
+    
+    return translateRLMResultsErrors([&] {
+        if (_results.get_mode() == Results::Mode::Empty) {
+            return self;
+        }
+        
+        std::vector<std::string> keyPathsVector;
+        for (NSString *keyPath in keyPaths) {
+            keyPathsVector.push_back(keyPath.UTF8String);
+        }
+        
+        return [self subresultsWithResults:_results.distinct(keyPathsVector)];
+    });
+}
+
+- (id)objectAtIndexedSubscript:(NSUInteger)index {
+    return [self objectAtIndex:index];
+}
+
+- (id)aggregate:(NSString *)property method:(util::Optional<Mixed> (Results::*)(ColKey))method
+     methodName:(NSString *)methodName returnNilForEmpty:(BOOL)returnNilForEmpty {
+    if (_results.get_mode() == Results::Mode::Empty) {
+        return returnNilForEmpty ? nil : @0;
+    }
+    ColKey column;
+    if (self.type == RLMPropertyTypeObject || ![property isEqualToString:@"self"]) {
+        column = _info->tableColumn(property);
+    }
+
+    auto value = translateRLMResultsErrors([&] { return (_results.*method)(column); }, methodName);
+    return value ? RLMMixedToObjc(*value) : nil;
+}
+
+- (id)minOfProperty:(NSString *)property {
+    return [self aggregate:property method:&Results::min
+                methodName:@"minOfProperty" returnNilForEmpty:YES];
+}
+
+- (id)maxOfProperty:(NSString *)property {
+    return [self aggregate:property method:&Results::max
+                methodName:@"maxOfProperty" returnNilForEmpty:YES];
+}
+
+- (id)sumOfProperty:(NSString *)property {
+    return [self aggregate:property method:&Results::sum
+                methodName:@"sumOfProperty" returnNilForEmpty:NO];
+}
+
+- (id)averageOfProperty:(NSString *)property {
+    if (_results.get_mode() == Results::Mode::Empty) {
+        return nil;
+    }
+    ColKey column;
+    if (self.type == RLMPropertyTypeObject || ![property isEqualToString:@"self"]) {
+        column = _info->tableColumn(property);
+    }
+    auto value = translateRLMResultsErrors([&] { return _results.average(column); }, @"averageOfProperty");
+    return value ? RLMMixedToObjc(*value) : nil;
+}
+
+- (void)deleteObjectsFromRealm {
+    if (self.type != RLMPropertyTypeObject) {
+        @throw RLMException(@"Cannot delete objects from RLMResults<%@>: only RLMObjects can be deleted.",
+                            RLMTypeToString(self.type));
+    }
+    return translateRLMResultsErrors([&] {
+        if (_results.get_mode() == Results::Mode::Table) {
+            RLMResultsValidateInWriteTransaction(self);
+            RLMClearTable(*_info);
+        }
+        else {
+            RLMObservationTracker tracker(_realm, true);
+            _results.clear();
+        }
+    });
+}
+
+- (NSString *)description {
+    return RLMDescriptionWithMaxDepth(@"RLMResults", self, RLMDescriptionMaxDepth);
+}
+
+- (realm::TableView)tableView {
+    return translateRLMResultsErrors([&] { return _results.get_tableview(); });
+}
+
+- (RLMFastEnumerator *)fastEnumerator {
+    return translateRLMResultsErrors([&] {
+        return [[RLMFastEnumerator alloc] initWithResults:_results collection:self
+                                                classInfo:*_info];
+    });
+}
+
+- (RLMResults *)snapshot {
+    return translateRLMResultsErrors([&] {
+        return [self subresultsWithResults:_results.snapshot()];
+    });
+}
+
+- (instancetype)freeze {
+    if (self.frozen) {
+        return self;
+    }
+
+    RLMRealm *frozenRealm = [_realm freeze];
+    return translateRLMResultsErrors([&] {
+        return [self.class resultsWithObjectInfo:_info->resolve(frozenRealm)
+                                         results:_results.freeze(frozenRealm->_realm)];
+    });
+}
+
+- (BOOL)isFrozen {
+    return _realm.frozen;
+}
+
+- (instancetype)thaw {
+    if (!self.frozen) {
+        return self;
+    }
+
+    RLMRealm *liveRealm = [_realm thaw];
+    return translateRLMResultsErrors([&] {
+        return [self.class resultsWithObjectInfo:_info->resolve(liveRealm)
+                                         results:_results.freeze(liveRealm->_realm)];
+    });
+}
+
+// The compiler complains about the method's argument type not matching due to
+// it not having the generic type attached, but it doesn't seem to be possible
+// to actually include the generic type
+// http://www.openradar.me/radar?id=6135653276319744
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wmismatched-parameter-types"
+- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMResults *, RLMCollectionChange *, NSError *))block {
+    return RLMAddNotificationBlock(self, block, nil);
+}
+- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMResults *, RLMCollectionChange *, NSError *))block queue:(dispatch_queue_t)queue {
+    return RLMAddNotificationBlock(self, block, queue);
+}
+#pragma clang diagnostic pop
+
+realm::Results& RLMGetBackingCollection(RLMResults *self) {
+    return self->_results;
+}
+
+- (BOOL)isAttached {
+    return !!_realm;
+}
+
+#pragma mark - Thread Confined Protocol Conformance
+
+- (realm::ThreadSafeReference)makeThreadSafeReference {
+    return _results;
+}
+
+- (id)objectiveCMetadata {
+    return nil;
+}
+
++ (instancetype)objectWithThreadSafeReference:(realm::ThreadSafeReference)reference
+                                     metadata:(__unused id)metadata
+                                        realm:(RLMRealm *)realm {
+    auto results = reference.resolve<Results>(realm->_realm);
+    return [RLMResults resultsWithObjectInfo:realm->_info[RLMStringDataToNSString(results.get_object_type())]
+                                     results:std::move(results)];
+}
+
+@end
+
+@implementation RLMLinkingObjects
+- (NSString *)description {
+    return RLMDescriptionWithMaxDepth(@"RLMLinkingObjects", self, RLMDescriptionMaxDepth);
+}
+@end

+ 377 - 0
Example/Pods/Realm/Realm/RLMSchema.mm

@@ -0,0 +1,377 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMSchema_Private.h"
+
+#import "RLMAccessor.h"
+#import "RLMObjectBase_Private.h"
+#import "RLMObject_Private.hpp"
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMProperty_Private.h"
+#import "RLMRealm_Private.hpp"
+#import "RLMSwiftSupport.h"
+#import "RLMUtil.hpp"
+
+#import <realm/group.hpp>
+#import <realm/object-store/object_schema.hpp>
+#import <realm/object-store/object_store.hpp>
+#import <realm/object-store/schema.hpp>
+
+#import <mutex>
+#import <objc/runtime.h>
+
+using namespace realm;
+
+const uint64_t RLMNotVersioned = realm::ObjectStore::NotVersioned;
+
+// RLMSchema private properties
+@interface RLMSchema ()
+@property (nonatomic, readwrite) NSMutableDictionary *objectSchemaByName;
+@end
+
+// Private RLMSchema subclass that skips class registration on lookup
+@interface RLMPrivateSchema : RLMSchema
+@end
+@implementation RLMPrivateSchema
+- (RLMObjectSchema *)schemaForClassName:(NSString *)className {
+    return self.objectSchemaByName[className];
+}
+
+- (RLMObjectSchema *)objectForKeyedSubscript:(__unsafe_unretained NSString *const)className {
+    return [self schemaForClassName:className];
+}
+@end
+
+static RLMSchema *s_sharedSchema = [[RLMSchema alloc] init];
+static NSMutableDictionary *s_localNameToClass = [[NSMutableDictionary alloc] init];
+static RLMSchema *s_privateSharedSchema = [[RLMPrivateSchema alloc] init];
+
+static enum class SharedSchemaState {
+    Uninitialized,
+    Initializing,
+    Initialized
+} s_sharedSchemaState = SharedSchemaState::Uninitialized;
+
+@implementation RLMSchema {
+    NSArray *_objectSchema;
+    realm::Schema _objectStoreSchema;
+}
+
+// Caller must @synchronize on s_localNameToClass
+static RLMObjectSchema *RLMRegisterClass(Class cls) {
+    if (RLMObjectSchema *schema = s_privateSharedSchema[[cls className]]) {
+        return schema;
+    }
+
+    auto prevState = s_sharedSchemaState;
+    s_sharedSchemaState = SharedSchemaState::Initializing;
+    RLMObjectSchema *schema = [RLMObjectSchema schemaForObjectClass:cls];
+    s_sharedSchemaState = prevState;
+
+    // set unmanaged class on shared shema for unmanaged object creation
+    schema.unmanagedClass = RLMUnmanagedAccessorClassForObjectClass(schema.objectClass, schema);
+
+    // override sharedSchema class methods for performance
+    RLMReplaceSharedSchemaMethod(cls, schema);
+
+    s_privateSharedSchema.objectSchemaByName[schema.className] = schema;
+    if ([cls shouldIncludeInDefaultSchema] && prevState != SharedSchemaState::Initialized) {
+        s_sharedSchema.objectSchemaByName[schema.className] = schema;
+    }
+
+    return schema;
+}
+
+// Caller must @synchronize on s_localNameToClass
+static void RLMRegisterClassLocalNames(Class *classes, NSUInteger count) {
+    for (NSUInteger i = 0; i < count; i++) {
+        Class cls = classes[i];
+        if (!RLMIsObjectSubclass(cls)) {
+            continue;
+        }
+        if ([cls _realmIgnoreClass]) {
+            continue;
+        }
+
+        NSString *className = NSStringFromClass(cls);
+        if ([className hasPrefix:@"RLM:"] || [className hasPrefix:@"NSKVONotifying"]) {
+            continue;
+        }
+
+        if ([RLMSwiftSupport isSwiftClassName:className]) {
+            className = [RLMSwiftSupport demangleClassName:className];
+        }
+        // NSStringFromClass demangles the names for top-level Swift classes
+        // but not for nested classes. _T indicates it's a Swift symbol, t
+        // indicates it's a type, and C indicates it's a class.
+        else if ([className hasPrefix:@"_TtC"]) {
+            @throw RLMException(@"RLMObject subclasses cannot be nested within other declarations. Please move %@ to global scope.", className);
+        }
+
+        if (Class existingClass = s_localNameToClass[className]) {
+            if (existingClass != cls) {
+                @throw RLMException(@"RLMObject subclasses with the same name cannot be included twice in the same target. "
+                                    @"Please make sure '%@' is only linked once to your current target.", className);
+            }
+            continue;
+        }
+
+        s_localNameToClass[className] = cls;
+        RLMReplaceClassNameMethod(cls, className);
+    }
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (self) {
+        _objectSchemaByName = [[NSMutableDictionary alloc] init];
+    }
+    return self;
+}
+
+- (NSArray *)objectSchema {
+    if (!_objectSchema) {
+        _objectSchema = [_objectSchemaByName allValues];
+    }
+    return _objectSchema;
+}
+
+- (void)setObjectSchema:(NSArray *)objectSchema {
+    _objectSchema = objectSchema;
+    _objectSchemaByName = [NSMutableDictionary dictionaryWithCapacity:objectSchema.count];
+    for (RLMObjectSchema *object in objectSchema) {
+        [_objectSchemaByName setObject:object forKey:object.className];
+    }
+}
+
+- (RLMObjectSchema *)schemaForClassName:(NSString *)className {
+    if (RLMObjectSchema *schema = _objectSchemaByName[className]) {
+        return schema; // fast path for already-initialized schemas
+    } else if (Class cls = [RLMSchema classForString:className]) {
+        [cls sharedSchema];                    // initialize the schema
+        return _objectSchemaByName[className]; // try again
+    } else {
+        return nil;
+    }
+}
+
+- (RLMObjectSchema *)objectForKeyedSubscript:(__unsafe_unretained NSString *const)className {
+    RLMObjectSchema *schema = [self schemaForClassName:className];
+    if (!schema) {
+        @throw RLMException(@"Object type '%@' not managed by the Realm", className);
+    }
+    return schema;
+}
+
++ (instancetype)schemaWithObjectClasses:(NSArray *)classes {
+    NSUInteger count = classes.count;
+    auto classArray = std::make_unique<__unsafe_unretained Class[]>(count);
+    [classes getObjects:classArray.get() range:NSMakeRange(0, count)];
+
+    RLMSchema *schema = [[self alloc] init];
+    @synchronized(s_localNameToClass) {
+        RLMRegisterClassLocalNames(classArray.get(), count);
+
+        schema->_objectSchemaByName = [NSMutableDictionary dictionaryWithCapacity:count];
+        for (Class cls in classes) {
+            if (!RLMIsObjectSubclass(cls)) {
+                @throw RLMException(@"Can't add non-Object type '%@' to a schema.", cls);
+            }
+            schema->_objectSchemaByName[[cls className]] = RLMRegisterClass(cls);
+        }
+    }
+
+    NSMutableArray *errors = [NSMutableArray new];
+    // Verify that all of the targets of links are included in the class list
+    [schema->_objectSchemaByName enumerateKeysAndObjectsUsingBlock:^(id, RLMObjectSchema *objectSchema, BOOL *) {
+        for (RLMProperty *prop in objectSchema.properties) {
+            if (prop.type != RLMPropertyTypeObject) {
+                continue;
+            }
+            if (!schema->_objectSchemaByName[prop.objectClassName]) {
+                [errors addObject:[NSString stringWithFormat:@"- '%@.%@' links to class '%@', which is missing from the list of classes managed by the Realm", objectSchema.className, prop.name, prop.objectClassName]];
+            }
+        }
+    }];
+    if (errors.count) {
+        @throw RLMException(@"Invalid class subset list:\n%@", [errors componentsJoinedByString:@"\n"]);
+    }
+
+    return schema;
+}
+
++ (RLMObjectSchema *)sharedSchemaForClass:(Class)cls {
+    @synchronized(s_localNameToClass) {
+        // We create instances of Swift objects during schema init, and they
+        // obviously need to not also try to initialize the schema
+        if (s_sharedSchemaState == SharedSchemaState::Initializing) {
+            return nil;
+        }
+
+        RLMRegisterClassLocalNames(&cls, 1);
+        RLMObjectSchema *objectSchema = RLMRegisterClass(cls);
+        [cls initializeLinkedObjectSchemas];
+        return objectSchema;
+    }
+}
+
++ (instancetype)partialSharedSchema {
+    return s_sharedSchema;
+}
+
++ (instancetype)partialPrivateSharedSchema {
+    return s_privateSharedSchema;
+}
+
+// schema based on runtime objects
++ (instancetype)sharedSchema {
+    @synchronized(s_localNameToClass) {
+        // We replace this method with one which just returns s_sharedSchema
+        // once initialization is complete, but we still need to check if it's
+        // already complete because it may have been done by another thread
+        // while we were waiting for the lock
+        if (s_sharedSchemaState == SharedSchemaState::Initialized) {
+            return s_sharedSchema;
+        }
+
+        if (s_sharedSchemaState == SharedSchemaState::Initializing) {
+            @throw RLMException(@"Illegal recursive call of +[%@ %@]. Note: Properties of Swift `Object` classes must not be prepopulated with queried results from a Realm.", self, NSStringFromSelector(_cmd));
+        }
+
+        s_sharedSchemaState = SharedSchemaState::Initializing;
+        try {
+            // Make sure we've discovered all classes
+            {
+                unsigned int numClasses;
+                using malloc_ptr = std::unique_ptr<__unsafe_unretained Class[], decltype(&free)>;
+                malloc_ptr classes(objc_copyClassList(&numClasses), &free);
+                RLMRegisterClassLocalNames(classes.get(), numClasses);
+            }
+
+            [s_localNameToClass enumerateKeysAndObjectsUsingBlock:^(NSString *, Class cls, BOOL *) {
+                RLMRegisterClass(cls);
+            }];
+        }
+        catch (...) {
+            s_sharedSchemaState = SharedSchemaState::Uninitialized;
+            throw;
+        }
+
+        // Replace this method with one that doesn't need to acquire a lock
+        Class metaClass = objc_getMetaClass(class_getName(self));
+        IMP imp = imp_implementationWithBlock(^{ return s_sharedSchema; });
+        class_replaceMethod(metaClass, @selector(sharedSchema), imp, "@@:");
+
+        s_sharedSchemaState = SharedSchemaState::Initialized;
+    }
+
+    return s_sharedSchema;
+}
+
+// schema based on tables in a realm
++ (instancetype)dynamicSchemaFromObjectStoreSchema:(Schema const&)objectStoreSchema {
+    // cache descriptors for all subclasses of RLMObject
+    NSMutableArray *schemaArray = [NSMutableArray arrayWithCapacity:objectStoreSchema.size()];
+    for (auto &objectSchema : objectStoreSchema) {
+        RLMObjectSchema *schema = [RLMObjectSchema objectSchemaForObjectStoreSchema:objectSchema];
+        [schemaArray addObject:schema];
+    }
+
+    // set class array and mapping
+    RLMSchema *schema = [RLMSchema new];
+    schema.objectSchema = schemaArray;
+    return schema;
+}
+
++ (Class)classForString:(NSString *)className {
+    if (Class cls = s_localNameToClass[className]) {
+        return cls;
+    }
+
+    if (Class cls = NSClassFromString(className)) {
+        return RLMIsObjectSubclass(cls) ? cls : nil;
+    }
+
+    // className might be the local name of a Swift class we haven't registered
+    // yet, so scan them all then recheck
+    {
+        unsigned int numClasses;
+        std::unique_ptr<__unsafe_unretained Class[], decltype(&free)> classes(objc_copyClassList(&numClasses), &free);
+        RLMRegisterClassLocalNames(classes.get(), numClasses);
+    }
+
+    return s_localNameToClass[className];
+}
+
+- (id)copyWithZone:(NSZone *)zone {
+    RLMSchema *schema = [[RLMSchema allocWithZone:zone] init];
+    schema->_objectSchemaByName = [[NSMutableDictionary allocWithZone:zone]
+                                   initWithDictionary:_objectSchemaByName copyItems:YES];
+    return schema;
+}
+
+- (BOOL)isEqualToSchema:(RLMSchema *)schema {
+    if (_objectSchemaByName.count != schema->_objectSchemaByName.count) {
+        return NO;
+    }
+    __block BOOL matches = YES;
+    [_objectSchemaByName enumerateKeysAndObjectsUsingBlock:^(NSString *name, RLMObjectSchema *objectSchema, BOOL *stop) {
+        if (![schema->_objectSchemaByName[name] isEqualToObjectSchema:objectSchema]) {
+            *stop = YES;
+            matches = NO;
+        }
+    }];
+    return matches;
+}
+
+- (NSString *)description {
+    NSMutableString *objectSchemaString = [NSMutableString string];
+    NSArray *sort = @[[NSSortDescriptor sortDescriptorWithKey:@"className" ascending:YES]];
+    for (RLMObjectSchema *objectSchema in [self.objectSchema sortedArrayUsingDescriptors:sort]) {
+        [objectSchemaString appendFormat:@"\t%@\n",
+         [objectSchema.description stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]];
+    }
+    return [NSString stringWithFormat:@"Schema {\n%@}", objectSchemaString];
+}
+
+- (Schema)objectStoreCopy {
+    if (_objectStoreSchema.size() == 0) {
+        std::vector<realm::ObjectSchema> schema;
+        schema.reserve(_objectSchemaByName.count);
+        [_objectSchemaByName enumerateKeysAndObjectsUsingBlock:[&](NSString *, RLMObjectSchema *objectSchema, BOOL *) {
+            schema.push_back([objectSchema objectStoreCopy:self]);
+        }];
+
+        // Having both obj-c and Swift classes for the same tables results in
+        // duplicate ObjectSchemas that we need to filter out
+        std::sort(begin(schema), end(schema), [](auto&& a, auto&& b) { return a.name < b.name; });
+        schema.erase(std::unique(begin(schema), end(schema), [](auto&& a, auto&& b) {
+            if (a.name == b.name) {
+                // If we make _realmObjectName public this needs to be turned into an exception
+                REALM_ASSERT_DEBUG(a.persisted_properties == b.persisted_properties);
+                return true;
+            }
+            return false;
+        }), end(schema));
+
+        _objectStoreSchema = std::move(schema);
+    }
+    return _objectStoreSchema;
+}
+
+@end

+ 31 - 0
Example/Pods/Realm/Realm/RLMSwiftSupport.m

@@ -0,0 +1,31 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMSwiftSupport.h"
+
+@implementation RLMSwiftSupport
+
++ (BOOL)isSwiftClassName:(NSString *)className {
+    return [className rangeOfString:@"."].location != NSNotFound;
+}
+
++ (NSString *)demangleClassName:(NSString *)className {
+    return [className substringFromIndex:[className rangeOfString:@"."].location + 1];
+}
+
+@end

+ 215 - 0
Example/Pods/Realm/Realm/RLMSyncConfiguration.mm

@@ -0,0 +1,215 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2016 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMSyncConfiguration_Private.hpp"
+
+#import "RLMApp_Private.hpp"
+#import "RLMBSON_Private.hpp"
+#import "RLMRealmConfiguration+Sync.h"
+#import "RLMSyncManager_Private.hpp"
+#import "RLMSyncSession_Private.hpp"
+#import "RLMSyncUtil_Private.hpp"
+#import "RLMUser_Private.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/sync/sync_manager.hpp>
+#import <realm/object-store/sync/sync_session.hpp>
+#import <realm/sync/config.hpp>
+#import <realm/sync/protocol.hpp>
+
+using namespace realm;
+
+namespace {
+using ProtocolError = realm::sync::ProtocolError;
+
+RLMSyncSystemErrorKind errorKindForSyncError(SyncError error) {
+    if (error.is_client_reset_requested()) {
+        return RLMSyncSystemErrorKindClientReset;
+    } else if (error.error_code == ProtocolError::permission_denied) {
+        return RLMSyncSystemErrorKindPermissionDenied;
+    } else if (error.error_code == ProtocolError::bad_authentication) {
+        return RLMSyncSystemErrorKindUser;
+    } else if (error.is_session_level_protocol_error()) {
+        return RLMSyncSystemErrorKindSession;
+    } else if (error.is_connection_level_protocol_error()) {
+        return RLMSyncSystemErrorKindConnection;
+    } else if (error.is_client_error()) {
+        return RLMSyncSystemErrorKindClient;
+    } else {
+        return RLMSyncSystemErrorKindUnknown;
+    }
+}
+}
+
+@interface RLMSyncConfiguration () {
+    std::unique_ptr<realm::SyncConfig> _config;
+}
+
+@end
+
+@implementation RLMSyncConfiguration
+
+@dynamic stopPolicy;
+
+- (instancetype)initWithRawConfig:(realm::SyncConfig)config {
+    if (self = [super init]) {
+        _config = std::make_unique<realm::SyncConfig>(std::move(config));
+    }
+    return self;
+}
+
+- (BOOL)isEqual:(id)object {
+    if (![object isKindOfClass:[RLMSyncConfiguration class]]) {
+        return NO;
+    }
+    RLMSyncConfiguration *that = (RLMSyncConfiguration *)object;
+    return [self.partitionValue isEqual:that.partitionValue]
+    && [self.user isEqual:that.user]
+    && self.stopPolicy == that.stopPolicy;
+}
+
+- (realm::SyncConfig&)rawConfiguration {
+    return *_config;
+}
+
+- (RLMUser *)user {
+    RLMApp *app = [RLMApp appWithId:@(_config->user->sync_manager()->app().lock()->config().app_id.data())];
+    return [[RLMUser alloc] initWithUser:_config->user app:app];
+}
+
+- (RLMSyncStopPolicy)stopPolicy {
+    return translateStopPolicy(_config->stop_policy);
+}
+
+- (void)setStopPolicy:(RLMSyncStopPolicy)stopPolicy {
+    _config->stop_policy = translateStopPolicy(stopPolicy);
+}
+
+- (id<RLMBSON>)partitionValue {
+    if (!_config->partition_value.empty()) {
+        return RLMConvertBsonToRLMBSON(realm::bson::parse(_config->partition_value.c_str()));
+    }
+    return nil;
+}
+
+- (bool)cancelAsyncOpenOnNonFatalErrors {
+    return _config->cancel_waits_on_nonfatal_error;
+}
+
+- (void)setCancelAsyncOpenOnNonFatalErrors:(bool)cancelAsyncOpenOnNonFatalErrors {
+    _config->cancel_waits_on_nonfatal_error = cancelAsyncOpenOnNonFatalErrors;
+}
+
+- (instancetype)initWithUser:(RLMUser *)user
+              partitionValue:(nullable id<RLMBSON>)partitionValue {
+    return [self initWithUser:user
+               partitionValue:partitionValue
+                customFileURL:nil
+                   stopPolicy:RLMSyncStopPolicyAfterChangesUploaded];
+}
+
+- (instancetype)initWithUser:(RLMUser *)user
+              partitionValue:(nullable id<RLMBSON>)partitionValue
+                  stopPolicy:(RLMSyncStopPolicy)stopPolicy{
+    auto config = [self initWithUser:user
+                      partitionValue:partitionValue
+                       customFileURL:nil
+                          stopPolicy:stopPolicy];
+    return config;
+}
+
+- (instancetype)initWithUser:(RLMUser *)user
+              partitionValue:(id<RLMBSON>)partitionValue
+               customFileURL:(nullable NSURL *)customFileURL
+                  stopPolicy:(RLMSyncStopPolicy)stopPolicy {
+    if (self = [super init]) {
+        std::stringstream s;
+        s << RLMConvertRLMBSONToBson(partitionValue);
+        _config = std::make_unique<SyncConfig>(
+            [user _syncUser],
+            s.str()
+        );
+        _config->stop_policy = translateStopPolicy(stopPolicy);
+        RLMApp *app = user.app;
+        _config->error_handler = [app](std::shared_ptr<SyncSession> errored_session, SyncError error) {
+            NSString *recoveryPath;
+            RLMSyncErrorActionToken *token;
+            for (auto& pair : error.user_info) {
+                if (pair.first == realm::SyncError::c_original_file_path_key) {
+                    token = [[RLMSyncErrorActionToken alloc] initWithOriginalPath:pair.second];
+                }
+                else if (pair.first == realm::SyncError::c_recovery_file_path_key) {
+                    recoveryPath = @(pair.second.c_str());
+                }
+            }
+
+            BOOL shouldMakeError = YES;
+            NSDictionary *custom = nil;
+            // Note that certain types of errors are 'interactive'; users have several options
+            // as to how to proceed after the error is reported.
+            auto errorClass = errorKindForSyncError(error);
+            switch (errorClass) {
+                case RLMSyncSystemErrorKindClientReset: {
+                    custom = @{kRLMSyncPathOfRealmBackupCopyKey: recoveryPath, kRLMSyncErrorActionTokenKey: token};
+                    break;
+                }
+                case RLMSyncSystemErrorKindPermissionDenied: {
+                    custom = @{kRLMSyncErrorActionTokenKey: token};
+                    break;
+                }
+                case RLMSyncSystemErrorKindUser:
+                case RLMSyncSystemErrorKindSession:
+                    break;
+                case RLMSyncSystemErrorKindConnection:
+                case RLMSyncSystemErrorKindClient:
+                case RLMSyncSystemErrorKindUnknown:
+                    // Report the error. There's nothing the user can do about it, though.
+                    shouldMakeError = error.is_fatal;
+                    break;
+            }
+
+            RLMSyncManager *manager = [app syncManager];
+            auto errorHandler = manager.errorHandler;
+            if (!shouldMakeError || !errorHandler) {
+                return;
+            }
+            NSError *nsError = make_sync_error(errorClass, @(error.message.c_str()), error.error_code.value(), custom);
+            RLMSyncSession *session = [[RLMSyncSession alloc] initWithSyncSession:errored_session];
+            dispatch_async(dispatch_get_main_queue(), ^{
+                errorHandler(nsError, session);
+            });
+        };
+        _config->client_resync_mode = realm::ClientResyncMode::Manual;
+
+        RLMSyncManager *manager = [user.app syncManager];
+        if (NSString *authorizationHeaderName = manager.authorizationHeaderName) {
+            _config->authorization_header_name.emplace(authorizationHeaderName.UTF8String);
+        }
+        if (NSDictionary<NSString *, NSString *> *customRequestHeaders = manager.customRequestHeaders) {
+            for (NSString *key in customRequestHeaders) {
+                _config->custom_http_headers.emplace(key.UTF8String, customRequestHeaders[key].UTF8String);
+            }
+        }
+
+        self.customFileURL = customFileURL;
+        return self;
+    }
+    return nil;
+}
+
+@end

+ 275 - 0
Example/Pods/Realm/Realm/RLMSyncManager.mm

@@ -0,0 +1,275 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2016 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMSyncManager_Private.hpp"
+
+#import "RLMApp_Private.hpp"
+#import "RLMRealmConfiguration+Sync.h"
+#import "RLMSyncConfiguration_Private.hpp"
+#import "RLMSyncSession_Private.hpp"
+#import "RLMUser_Private.hpp"
+#import "RLMSyncUtil_Private.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/sync/config.hpp>
+#import <realm/object-store/sync/sync_manager.hpp>
+#import <realm/object-store/sync/sync_session.hpp>
+
+#if !defined(REALM_COCOA_VERSION)
+#import "RLMVersion.h"
+#endif
+
+using namespace realm;
+
+using Level = realm::util::Logger::Level;
+
+namespace {
+
+Level levelForSyncLogLevel(RLMSyncLogLevel logLevel) {
+    switch (logLevel) {
+        case RLMSyncLogLevelOff:    return Level::off;
+        case RLMSyncLogLevelFatal:  return Level::fatal;
+        case RLMSyncLogLevelError:  return Level::error;
+        case RLMSyncLogLevelWarn:   return Level::warn;
+        case RLMSyncLogLevelInfo:   return Level::info;
+        case RLMSyncLogLevelDetail: return Level::detail;
+        case RLMSyncLogLevelDebug:  return Level::debug;
+        case RLMSyncLogLevelTrace:  return Level::trace;
+        case RLMSyncLogLevelAll:    return Level::all;
+    }
+    REALM_UNREACHABLE();    // Unrecognized log level.
+}
+
+RLMSyncLogLevel logLevelForLevel(Level logLevel) {
+    switch (logLevel) {
+        case Level::off:    return RLMSyncLogLevelOff;
+        case Level::fatal:  return RLMSyncLogLevelFatal;
+        case Level::error:  return RLMSyncLogLevelError;
+        case Level::warn:   return RLMSyncLogLevelWarn;
+        case Level::info:   return RLMSyncLogLevelInfo;
+        case Level::detail: return RLMSyncLogLevelDetail;
+        case Level::debug:  return RLMSyncLogLevelDebug;
+        case Level::trace:  return RLMSyncLogLevelTrace;
+        case Level::all:    return RLMSyncLogLevelAll;
+    }
+    REALM_UNREACHABLE();    // Unrecognized log level.
+}
+
+#pragma mark - Loggers
+
+struct CocoaSyncLogger : public realm::util::RootLogger {
+    void do_log(Level, std::string message) override {
+        NSLog(@"Sync: %@", RLMStringDataToNSString(message));
+    }
+};
+
+struct CocoaSyncLoggerFactory : public realm::SyncLoggerFactory {
+    std::unique_ptr<realm::util::Logger> make_logger(realm::util::Logger::Level level) override {
+        auto logger = std::make_unique<CocoaSyncLogger>();
+        logger->set_level_threshold(level);
+        return std::move(logger);
+    }
+} s_syncLoggerFactory;
+
+struct CallbackLogger : public realm::util::RootLogger {
+    RLMSyncLogFunction logFn;
+    void do_log(Level level, std::string message) override {
+        @autoreleasepool {
+            logFn(logLevelForLevel(level), RLMStringDataToNSString(message));
+        }
+    }
+};
+struct CallbackLoggerFactory : public realm::SyncLoggerFactory {
+    RLMSyncLogFunction logFn;
+    std::unique_ptr<realm::util::Logger> make_logger(realm::util::Logger::Level level) override {
+        auto logger = std::make_unique<CallbackLogger>();
+        logger->logFn = logFn;
+        logger->set_level_threshold(level);
+        return std::move(logger); // not a redundant move because it's a different type
+    }
+
+    CallbackLoggerFactory(RLMSyncLogFunction logFn) : logFn(logFn) { }
+};
+
+} // anonymous namespace
+
+#pragma mark - RLMSyncManager
+
+@interface RLMSyncTimeoutOptions () {
+    @public
+    realm::SyncClientTimeouts _options;
+}
+@end
+
+@implementation RLMSyncManager {
+    std::unique_ptr<CallbackLoggerFactory> _loggerFactory;
+    std::shared_ptr<SyncManager> _syncManager;
+}
+
+- (instancetype)initWithSyncManager:(std::shared_ptr<realm::SyncManager>)syncManager {
+    if (self = [super init]) {
+        [RLMUser _setUpBindingContextFactory];
+        _syncManager = syncManager;
+        return self;
+    }
+    return nil;
+}
+
++ (SyncClientConfig)configurationWithRootDirectory:(NSURL *)rootDirectory appId:(NSString *)appId {
+    SyncClientConfig config;
+    bool should_encrypt = !getenv("REALM_DISABLE_METADATA_ENCRYPTION") && !RLMIsRunningInPlayground();
+    config.logger_factory = &s_syncLoggerFactory;
+    config.metadata_mode = should_encrypt ? SyncManager::MetadataMode::Encryption
+                                          : SyncManager::MetadataMode::NoEncryption;
+    @autoreleasepool {
+        rootDirectory = rootDirectory ?: [NSURL fileURLWithPath:RLMDefaultDirectoryForBundleIdentifier(nil)];
+        config.base_file_path = rootDirectory.path.UTF8String;
+
+        bool isSwift = !!NSClassFromString(@"RealmSwiftObjectUtil");
+        config.user_agent_binding_info =
+            util::format("Realm%1/%2", isSwift ? "Swift" : "ObjectiveC",
+                         RLMStringDataWithNSString(REALM_COCOA_VERSION));
+        config.user_agent_application_info = RLMStringDataWithNSString(appId);
+    }
+
+    return config;
+}
+
+- (std::weak_ptr<realm::app::App>)app {
+    return _syncManager->app();
+}
+
+- (NSString *)appID {
+    if (!_appID) {
+        _appID = [[NSBundle mainBundle] bundleIdentifier] ?: @"(none)";
+    }
+    return _appID;
+}
+
+- (void)setUserAgent:(NSString *)userAgent {
+    _syncManager->set_user_agent(RLMStringDataWithNSString(userAgent));
+    _userAgent = userAgent;
+}
+
+- (void)setCustomRequestHeaders:(NSDictionary<NSString *,NSString *> *)customRequestHeaders {
+    _customRequestHeaders = customRequestHeaders.copy;
+
+    for (auto&& user : _syncManager->all_users()) {
+        for (auto&& session : user->all_sessions()) {
+            auto config = session->config();
+            config.custom_http_headers.clear();
+            for (NSString *key in customRequestHeaders) {
+                config.custom_http_headers.emplace(key.UTF8String, customRequestHeaders[key].UTF8String);
+            }
+            session->update_configuration(std::move(config));
+        }
+    }
+}
+
+- (void)setLogger:(RLMSyncLogFunction)logFn {
+    _logger = logFn;
+    if (_logger) {
+        _loggerFactory = std::make_unique<CallbackLoggerFactory>(logFn);
+        _syncManager->set_logger_factory(*_loggerFactory);
+    }
+    else {
+        _loggerFactory = nullptr;
+        _syncManager->set_logger_factory(s_syncLoggerFactory);
+    }
+}
+
+- (void)setTimeoutOptions:(RLMSyncTimeoutOptions *)timeoutOptions {
+    _timeoutOptions = timeoutOptions;
+    _syncManager->set_timeouts(timeoutOptions->_options);
+}
+
+#pragma mark - Passthrough properties
+
+- (RLMSyncLogLevel)logLevel {
+    return logLevelForLevel(_syncManager->log_level());
+}
+
+- (void)setLogLevel:(RLMSyncLogLevel)logLevel {
+    _syncManager->set_log_level(levelForSyncLogLevel(logLevel));
+}
+
+#pragma mark - Private API
+
+- (void)_fireError:(NSError *)error {
+    dispatch_async(dispatch_get_main_queue(), ^{
+        if (self.errorHandler) {
+            self.errorHandler(error, nil);
+        }
+    });
+}
+
+- (void)resetForTesting {
+    _errorHandler = nil;
+    _appID = nil;
+    _userAgent = nil;
+    _logger = nil;
+    _authorizationHeaderName = nil;
+    _customRequestHeaders = nil;
+    _timeoutOptions = nil;
+    _syncManager->reset_for_testing();
+}
+
+- (std::shared_ptr<realm::SyncManager>)syncManager {
+    return _syncManager;
+}
+@end
+
+#pragma mark - RLMSyncTimeoutOptions
+
+@implementation RLMSyncTimeoutOptions
+- (NSUInteger)connectTimeout {
+    return static_cast<NSUInteger>(_options.connect_timeout);
+}
+- (void)setConnectTimeout:(NSUInteger)connectTimeout {
+    _options.connect_timeout = connectTimeout;
+}
+
+- (NSUInteger)connectLingerTime {
+    return static_cast<NSUInteger>(_options.connection_linger_time);
+}
+- (void)setConnectionLingerTime:(NSUInteger)connectionLingerTime {
+    _options.connection_linger_time = connectionLingerTime;
+}
+
+- (NSUInteger)pingKeepalivePeriod {
+    return static_cast<NSUInteger>(_options.ping_keepalive_period);
+}
+- (void)setPingKeepalivePeriod:(NSUInteger)pingKeepalivePeriod {
+    _options.ping_keepalive_period = pingKeepalivePeriod;
+}
+
+- (NSUInteger)pongKeepaliveTimeout {
+    return static_cast<NSUInteger>(_options.pong_keepalive_timeout);
+}
+- (void)setPongKeepaliveTimeout:(NSUInteger)pongKeepaliveTimeout {
+    _options.pong_keepalive_timeout = pongKeepaliveTimeout;
+}
+
+- (NSUInteger)fastReconnectLimit {
+    return static_cast<NSUInteger>(_options.fast_reconnect_limit);
+}
+- (void)setFastReconnectLimit:(NSUInteger)fastReconnectLimit {
+    _options.fast_reconnect_limit = fastReconnectLimit;
+}
+
+@end

+ 327 - 0
Example/Pods/Realm/Realm/RLMSyncSession.mm

@@ -0,0 +1,327 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2016 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMSyncSession_Private.hpp"
+
+#import "RLMApp.h"
+#import "RLMRealm_Private.hpp"
+#import "RLMSyncConfiguration_Private.hpp"
+#import "RLMUser_Private.hpp"
+#import "RLMSyncManager_Private.hpp"
+#import "RLMSyncUtil_Private.hpp"
+
+#import <realm/object-store/sync/async_open_task.hpp>
+#import <realm/object-store/sync/sync_session.hpp>
+
+using namespace realm;
+
+@interface RLMSyncErrorActionToken () {
+@public
+    std::string _originalPath;
+    BOOL _isValid;
+}
+@end
+
+@interface RLMProgressNotificationToken() {
+    uint64_t _token;
+    std::weak_ptr<SyncSession> _session;
+}
+@end
+
+@implementation RLMProgressNotificationToken
+
+- (void)suppressNextNotification {
+    // No-op, but implemented in case this token is passed to
+    // `-[RLMRealm commitWriteTransactionWithoutNotifying:]`.
+}
+
+- (void)invalidate {
+    if (auto session = _session.lock()) {
+        session->unregister_progress_notifier(_token);
+        _session.reset();
+        _token = 0;
+    }
+}
+
+- (void)dealloc {
+    if (_token != 0) {
+        NSLog(@"RLMProgressNotificationToken released without unregistering a notification. "
+              @"You must hold on to the RLMProgressNotificationToken and call "
+              @"-[RLMProgressNotificationToken invalidate] when you no longer wish to receive "
+              @"progress update notifications.");
+    }
+}
+
+- (nullable instancetype)initWithTokenValue:(uint64_t)token
+                                    session:(std::shared_ptr<SyncSession>)session {
+    if (token == 0) {
+        return nil;
+    }
+    if (self = [super init]) {
+        _token = token;
+        _session = session;
+        return self;
+    }
+    return nil;
+}
+
+@end
+
+@interface RLMSyncSession ()
+@property (class, nonatomic, readonly) dispatch_queue_t notificationsQueue;
+@property (atomic, readwrite) RLMSyncConnectionState connectionState;
+@end
+
+@implementation RLMSyncSession
+
++ (dispatch_queue_t)notificationsQueue {
+    static dispatch_queue_t queue;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        queue = dispatch_queue_create("io.realm.sync.sessionsNotificationQueue", DISPATCH_QUEUE_SERIAL);
+    });
+    return queue;
+}
+
+static RLMSyncConnectionState convertConnectionState(SyncSession::ConnectionState state) {
+    switch (state) {
+        case SyncSession::ConnectionState::Disconnected: return RLMSyncConnectionStateDisconnected;
+        case SyncSession::ConnectionState::Connecting:   return RLMSyncConnectionStateConnecting;
+        case SyncSession::ConnectionState::Connected:    return RLMSyncConnectionStateConnected;
+    }
+}
+
+- (instancetype)initWithSyncSession:(std::shared_ptr<SyncSession> const&)session {
+    if (self = [super init]) {
+        _session = session;
+        _connectionState = convertConnectionState(session->connection_state());
+        // No need to save the token as RLMSyncSession always outlives the
+        // underlying SyncSession
+        session->register_connection_change_callback([=](auto, auto newState) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+                self.connectionState = convertConnectionState(newState);
+            });
+        });
+        return self;
+    }
+    return nil;
+}
+
+- (RLMSyncConfiguration *)configuration {
+    if (auto session = _session.lock()) {
+        return [[RLMSyncConfiguration alloc] initWithRawConfig:session->config()];
+    }
+    return nil;
+}
+
+- (NSURL *)realmURL {
+    if (auto session = _session.lock()) {
+        if (auto url = session->full_realm_url()) {
+            return [NSURL URLWithString:@(url->c_str())];
+        }
+    }
+    return nil;
+}
+
+- (RLMUser *)parentUser {
+    if (auto session = _session.lock()) {
+        if (auto app = session->user()->sync_manager()->app().lock()) {
+            auto rlmApp = [RLMApp appWithId:@(app->config().app_id.data())];
+            return [[RLMUser alloc] initWithUser:session->user() app:rlmApp];
+        }
+    }
+    return nil;
+}
+
+- (RLMSyncSessionState)state {
+    if (auto session = _session.lock()) {
+        if (session->state() == SyncSession::PublicState::Inactive) {
+            return RLMSyncSessionStateInactive;
+        }
+        return RLMSyncSessionStateActive;
+    }
+    return RLMSyncSessionStateInvalid;
+}
+
+- (void)suspend {
+    if (auto session = _session.lock()) {
+        session->log_out();
+    }
+}
+
+- (void)resume {
+    if (auto session = _session.lock()) {
+        session->revive_if_needed();
+    }
+}
+
+- (BOOL)waitForUploadCompletionOnQueue:(dispatch_queue_t)queue callback:(void(^)(NSError *))callback {
+    if (auto session = _session.lock()) {
+        queue = queue ?: dispatch_get_main_queue();
+        session->wait_for_upload_completion([=](std::error_code err) {
+            NSError *error = (err == std::error_code{}) ? nil : make_sync_error(err);
+            dispatch_async(queue, ^{
+                callback(error);
+            });
+        });
+        return YES;
+    }
+    return NO;
+}
+
+- (BOOL)waitForDownloadCompletionOnQueue:(dispatch_queue_t)queue callback:(void(^)(NSError *))callback {
+    if (auto session = _session.lock()) {
+        queue = queue ?: dispatch_get_main_queue();
+        session->wait_for_download_completion([=](std::error_code err) {
+            NSError *error = (err == std::error_code{}) ? nil : make_sync_error(err);
+            dispatch_async(queue, ^{
+                callback(error);
+            });
+        });
+        return YES;
+    }
+    return NO;
+}
+
+- (RLMProgressNotificationToken *)addProgressNotificationForDirection:(RLMSyncProgressDirection)direction
+                                                                 mode:(RLMSyncProgressMode)mode
+                                                                block:(RLMProgressNotificationBlock)block {
+    if (auto session = _session.lock()) {
+        dispatch_queue_t queue = RLMSyncSession.notificationsQueue;
+        auto notifier_direction = (direction == RLMSyncProgressDirectionUpload
+                                   ? SyncSession::NotifierType::upload
+                                   : SyncSession::NotifierType::download);
+        bool is_streaming = (mode == RLMSyncProgressModeReportIndefinitely);
+        uint64_t token = session->register_progress_notifier([=](uint64_t transferred, uint64_t transferrable) {
+            dispatch_async(queue, ^{
+                block((NSUInteger)transferred, (NSUInteger)transferrable);
+            });
+        }, notifier_direction, is_streaming);
+        return [[RLMProgressNotificationToken alloc] initWithTokenValue:token session:std::move(session)];
+    }
+    return nil;
+}
+
++ (void)immediatelyHandleError:(RLMSyncErrorActionToken *)token syncManager:(RLMSyncManager *)syncManager {
+    if (!token->_isValid) {
+        return;
+    }
+    token->_isValid = NO;
+
+    [syncManager syncManager]->immediately_run_file_actions(std::move(token->_originalPath));
+}
+
++ (nullable RLMSyncSession *)sessionForRealm:(RLMRealm *)realm {
+    auto& config = realm->_realm->config().sync_config;
+    if (!config) {
+        return nil;
+    }
+    if (auto session = config->user->session_for_on_disk_path(realm->_realm->config().path)) {
+        return [[RLMSyncSession alloc] initWithSyncSession:session];
+    }
+    return nil;
+}
+
+- (NSString *)description {
+    return [NSString stringWithFormat:
+            @"<RLMSyncSession: %p> {\n"
+            "\tstate = %d;\n"
+            "\tconnectionState = %d;\n"
+            "\trealmURL = %@;\n"
+            "\tuser = %@;\n"
+            "}",
+            (__bridge void *)self,
+            static_cast<int>(self.state),
+            static_cast<int>(self.connectionState),
+            self.realmURL,
+            self.parentUser.identifier];
+}
+
+@end
+
+// MARK: - Error action token
+
+@implementation RLMSyncErrorActionToken
+
+- (instancetype)initWithOriginalPath:(std::string)originalPath {
+    if (self = [super init]) {
+        _isValid = YES;
+        _originalPath = std::move(originalPath);
+        return self;
+    }
+    return nil;
+}
+
+@end
+
+@implementation RLMAsyncOpenTask {
+    bool _cancel;
+    NSMutableArray<RLMProgressNotificationBlock> *_blocks;
+}
+
+- (void)addProgressNotificationOnQueue:(dispatch_queue_t)queue block:(RLMProgressNotificationBlock)block {
+    auto wrappedBlock = ^(NSUInteger transferred_bytes, NSUInteger transferrable_bytes) {
+        dispatch_async(queue, ^{
+            @autoreleasepool {
+                block(transferred_bytes, transferrable_bytes);
+            }
+        });
+    };
+
+    @synchronized (self) {
+        if (_task) {
+            _task->register_download_progress_notifier(wrappedBlock);
+        }
+        else if (!_cancel) {
+            if (!_blocks) {
+                _blocks = [NSMutableArray new];
+            }
+            [_blocks addObject:wrappedBlock];
+        }
+    }
+}
+
+- (void)addProgressNotificationBlock:(RLMProgressNotificationBlock)block {
+    [self addProgressNotificationOnQueue:dispatch_get_main_queue() block:block];
+}
+
+- (void)cancel {
+    @synchronized (self) {
+        if (_task) {
+            _task->cancel();
+        }
+        else {
+            _cancel = true;
+            _blocks = nil;
+        }
+    }
+}
+
+- (void)setTask:(std::shared_ptr<realm::AsyncOpenTask>)task {
+    @synchronized (self) {
+        _task = task;
+        if (_cancel) {
+            _task->cancel();
+        }
+        for (RLMProgressNotificationBlock block in _blocks) {
+            _task->register_download_progress_notifier(block);
+        }
+        _blocks = nil;
+    }
+}
+@end

+ 126 - 0
Example/Pods/Realm/Realm/RLMSyncUtil.mm

@@ -0,0 +1,126 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2016 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMSyncUtil_Private.hpp"
+
+#import "RLMObject_Private.hpp"
+#import "RLMRealmConfiguration+Sync.h"
+#import "RLMRealmConfiguration_Private.hpp"
+#import "RLMRealm_Private.hpp"
+#import "RLMSyncConfiguration_Private.hpp"
+#import "RLMUser_Private.hpp"
+#import "RLMUtil.hpp"
+
+#import <realm/object-store/shared_realm.hpp>
+#import <realm/object-store/sync/sync_user.hpp>
+#import <realm/sync/config.hpp>
+
+NSString *const RLMSyncErrorDomain = @"io.realm.sync";
+NSString *const RLMSyncAuthErrorDomain = @"io.realm.sync.auth";
+NSString *const RLMAppErrorDomain = @"io.realm.app";
+
+NSString *const kRLMSyncPathOfRealmBackupCopyKey            = @"recovered_realm_location_path";
+NSString *const kRLMSyncErrorActionTokenKey                 = @"error_action_token";
+
+NSString *const kRLMSyncErrorStatusCodeKey      = @"statusCode";
+NSString *const kRLMSyncUnderlyingErrorKey      = @"underlying_error";
+
+#pragma mark - C++ APIs
+
+using namespace realm;
+
+SyncSessionStopPolicy translateStopPolicy(RLMSyncStopPolicy stopPolicy) {
+    switch (stopPolicy) {
+        case RLMSyncStopPolicyImmediately:              return SyncSessionStopPolicy::Immediately;
+        case RLMSyncStopPolicyLiveIndefinitely:         return SyncSessionStopPolicy::LiveIndefinitely;
+        case RLMSyncStopPolicyAfterChangesUploaded:     return SyncSessionStopPolicy::AfterChangesUploaded;
+    }
+    REALM_UNREACHABLE();    // Unrecognized stop policy.
+}
+
+RLMSyncStopPolicy translateStopPolicy(SyncSessionStopPolicy stop_policy) {
+    switch (stop_policy) {
+        case SyncSessionStopPolicy::Immediately:            return RLMSyncStopPolicyImmediately;
+        case SyncSessionStopPolicy::LiveIndefinitely:       return RLMSyncStopPolicyLiveIndefinitely;
+        case SyncSessionStopPolicy::AfterChangesUploaded:   return RLMSyncStopPolicyAfterChangesUploaded;
+    }
+    REALM_UNREACHABLE();
+}
+
+std::shared_ptr<SyncSession> sync_session_for_realm(RLMRealm *realm) {
+    Realm::Config realmConfig = realm.configuration.config;
+    if (auto config = realmConfig.sync_config) {
+        std::shared_ptr<SyncUser> user = config->user;
+        if (user && user->state() != SyncUser::State::Removed) {
+            return user->session_for_on_disk_path(realmConfig.path);
+        }
+    }
+    return nullptr;
+}
+
+CocoaSyncUserContext& context_for(const std::shared_ptr<realm::SyncUser>& user)
+{
+    return *std::static_pointer_cast<CocoaSyncUserContext>(user->binding_context());
+}
+
+NSError *make_sync_error(RLMSyncSystemErrorKind kind, NSString *description, NSInteger code, NSDictionary *custom) {
+    NSMutableDictionary *buffer = [custom ?: @{} mutableCopy];
+    buffer[NSLocalizedDescriptionKey] = description;
+    if (code != NSNotFound) {
+        buffer[kRLMSyncErrorStatusCodeKey] = @(code);
+    }
+
+    RLMSyncError errorCode;
+    switch (kind) {
+        case RLMSyncSystemErrorKindClientReset:
+            errorCode = RLMSyncErrorClientResetError;
+            break;
+        case RLMSyncSystemErrorKindPermissionDenied:
+            errorCode = RLMSyncErrorPermissionDeniedError;
+            break;
+        case RLMSyncSystemErrorKindUser:
+            errorCode = RLMSyncErrorClientUserError;
+            break;
+        case RLMSyncSystemErrorKindSession:
+            errorCode = RLMSyncErrorClientSessionError;
+            break;
+        case RLMSyncSystemErrorKindConnection:
+        case RLMSyncSystemErrorKindClient:
+        case RLMSyncSystemErrorKindUnknown:
+            errorCode = RLMSyncErrorClientInternalError;
+            break;
+    }
+    return [NSError errorWithDomain:RLMSyncErrorDomain
+                               code:errorCode
+                           userInfo:[buffer copy]];
+}
+
+NSError *make_sync_error(NSError *wrapped_auth_error) {
+    return [NSError errorWithDomain:RLMSyncErrorDomain
+                               code:RLMSyncErrorUnderlyingAuthError
+                           userInfo:@{kRLMSyncUnderlyingErrorKey: wrapped_auth_error}];
+}
+
+NSError *make_sync_error(std::error_code sync_error, RLMSyncSystemErrorKind kind) {
+    return [NSError errorWithDomain:RLMSyncErrorDomain
+                               code:kind
+                           userInfo:@{
+                                      NSLocalizedDescriptionKey: @(sync_error.message().c_str()),
+                                      kRLMSyncErrorStatusCodeKey: @(sync_error.value())
+                                      }];
+}

+ 69 - 0
Example/Pods/Realm/Realm/RLMThreadSafeReference.mm

@@ -0,0 +1,69 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2016 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMThreadSafeReference_Private.hpp"
+#import "RLMUtil.hpp"
+
+@implementation RLMThreadSafeReference {
+    realm::ThreadSafeReference _reference;
+    id _metadata;
+    Class _type;
+}
+
+- (instancetype)initWithThreadConfined:(id<RLMThreadConfined>)threadConfined {
+    if (!(self = [super init])) {
+        return nil;
+    }
+
+    REALM_ASSERT_DEBUG([threadConfined conformsToProtocol:@protocol(RLMThreadConfined)]);
+    if (![threadConfined conformsToProtocol:@protocol(RLMThreadConfined_Private)]) {
+        @throw RLMException(@"Illegal custom conformance to `RLMThreadConfined` by `%@`", threadConfined.class);
+    } else if (threadConfined.invalidated) {
+        @throw RLMException(@"Cannot construct reference to invalidated object");
+    } else if (!threadConfined.realm) {
+        @throw RLMException(@"Cannot construct reference to unmanaged object, "
+                            "which can be passed across threads directly");
+    }
+
+    RLMTranslateError([&] {
+        _reference = [(id<RLMThreadConfined_Private>)threadConfined makeThreadSafeReference];
+        _metadata = ((id<RLMThreadConfined_Private>)threadConfined).objectiveCMetadata;
+    });
+    _type = threadConfined.class;
+
+    return self;
+}
+
++ (instancetype)referenceWithThreadConfined:(id<RLMThreadConfined>)threadConfined {
+    return [[self alloc] initWithThreadConfined:threadConfined];
+}
+
+- (id<RLMThreadConfined>)resolveReferenceInRealm:(RLMRealm *)realm {
+    if (!_reference) {
+        @throw RLMException(@"Can only resolve a thread safe reference once.");
+    }
+    return RLMTranslateError([&] {
+        return [_type objectWithThreadSafeReference:std::move(_reference) metadata:_metadata realm:realm];
+    });
+}
+
+- (BOOL)isInvalidated {
+    return !_reference;
+}
+
+@end

+ 60 - 0
Example/Pods/Realm/Realm/RLMUpdateChecker.mm

@@ -0,0 +1,60 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMUpdateChecker.hpp"
+
+#import "RLMRealm.h"
+#import "RLMUtil.hpp"
+
+#if TARGET_IPHONE_SIMULATOR && !defined(REALM_COCOA_VERSION)
+#import "RLMVersion.h"
+#endif
+
+void RLMCheckForUpdates() {
+#if TARGET_IPHONE_SIMULATOR
+    if (getenv("REALM_DISABLE_UPDATE_CHECKER") || RLMIsRunningInPlayground()) {
+        return;
+    }
+
+    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"alpha|beta|rc"
+                                                                           options:(NSRegularExpressionOptions)0
+                                                                             error:nil];
+    NSUInteger numberOfMatches = [regex numberOfMatchesInString:REALM_COCOA_VERSION
+                                                        options:(NSMatchingOptions)0
+                                                          range:NSMakeRange(0, REALM_COCOA_VERSION.length)];
+
+    if (numberOfMatches > 0) {
+        // pre-release version, skip update checking
+        return;
+    }
+
+    auto handler = ^(NSData *data, NSURLResponse *response, NSError *error) {
+        if (error || ((NSHTTPURLResponse *)response).statusCode != 200) {
+            return;
+        }
+
+        NSString *latestVersion = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
+        if (![REALM_COCOA_VERSION isEqualToString:latestVersion]) {
+            NSLog(@"Version %@ of Realm is now available: https://github.com/realm/realm-cocoa/blob/v%@/CHANGELOG.md", latestVersion, latestVersion);
+        }
+    };
+
+    NSString *url = [NSString stringWithFormat:@"https://static.realm.io/update/cocoa?%@", REALM_COCOA_VERSION];
+    [[NSURLSession.sharedSession dataTaskWithURL:[NSURL URLWithString:url] completionHandler:handler] resume];
+#endif
+}

+ 35 - 0
Example/Pods/Realm/Realm/RLMUpdateResult.mm

@@ -0,0 +1,35 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMUpdateResult_Private.hpp"
+#import "RLMObjectId_Private.hpp"
+
+@implementation RLMUpdateResult
+
+- (instancetype)initWithUpdateResult:(realm::app::MongoCollection::UpdateResult)UpdateResult {
+    if (self = [super init]) {
+        _matchedCount = UpdateResult.matched_count;
+        _modifiedCount = UpdateResult.modified_count;
+        if (UpdateResult.upserted_id) {
+            _objectId = [[RLMObjectId alloc] initWithValue:*UpdateResult.upserted_id];
+        }
+    }
+    return self;
+}
+
+@end

+ 325 - 0
Example/Pods/Realm/Realm/RLMUser.mm

@@ -0,0 +1,325 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2016 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMUser_Private.hpp"
+
+#import "RLMAPIKeyAuth.h"
+#import "RLMApp_Private.hpp"
+#import "RLMBSON_Private.hpp"
+#import "RLMCredentials_Private.hpp"
+#import "RLMMongoClient_Private.hpp"
+#import "RLMRealmConfiguration+Sync.h"
+#import "RLMSyncConfiguration_Private.hpp"
+#import "RLMSyncSession_Private.hpp"
+
+#import <realm/object-store/sync/sync_manager.hpp>
+#import <realm/object-store/sync/sync_session.hpp>
+#import <realm/object-store/sync/sync_user.hpp>
+#import <realm/object-store/util/bson/bson.hpp>
+
+using namespace realm;
+
+@interface RLMUser () {
+    std::shared_ptr<SyncUser> _user;
+}
+@end
+
+@implementation RLMUserSubscriptionToken {
+@public
+    std::unique_ptr<realm::Subscribable<SyncUser>::Token> _token;
+}
+
+- (instancetype)initWithToken:(realm::Subscribable<SyncUser>::Token&&)token {
+    if (self = [super init]) {
+        _token = std::make_unique<realm::Subscribable<SyncUser>::Token>(std::move(token));
+        return self;
+    }
+
+    return nil;
+}
+
+- (NSUInteger)value {
+    return _token->value();
+}
+
+@end
+
+@implementation RLMUser
+
+#pragma mark - API
+
+- (instancetype)initWithUser:(std::shared_ptr<SyncUser>)user
+                         app:(RLMApp *)app {
+    if (self = [super init]) {
+        _user = user;
+        _app = app;
+        return self;
+    }
+    return nil;
+}
+
+- (BOOL)isEqual:(id)object {
+    if (![object isKindOfClass:[RLMUser class]]) {
+        return NO;
+    }
+    return _user == ((RLMUser *)object)->_user;
+}
+
+- (RLMRealmConfiguration *)configurationWithPartitionValue:(nullable id<RLMBSON>)partitionValue {
+    auto syncConfig = [[RLMSyncConfiguration alloc] initWithUser:self
+                                                  partitionValue:partitionValue
+                                                   customFileURL:nil
+                                                      stopPolicy:RLMSyncStopPolicyAfterChangesUploaded];
+    RLMRealmConfiguration *config = [[RLMRealmConfiguration alloc] init];
+    config.syncConfiguration = syncConfig;
+    return config;
+}
+
+- (void)logOut {
+    if (!_user) {
+        return;
+    }
+    _user->log_out();
+}
+
+- (BOOL)isLoggedIn {
+    return _user->is_logged_in();
+}
+
+- (void)invalidate {
+    if (!_user) {
+        return;
+    }
+    _user = nullptr;
+}
+
+- (std::string)pathForPartitionValue:(std::string const&)partitionValue {
+    if (!_user) {
+        return "";
+    }
+
+    auto path = _user->sync_manager()->path_for_realm(*_user, partitionValue);
+    if ([NSFileManager.defaultManager fileExistsAtPath:@(path.c_str())]) {
+        return path;
+    }
+
+    // Previous versions converted the partition value to a path *twice*,
+    // so if the file resulting from that exists open it instead
+    NSString *encodedPartitionValue = [@(partitionValue.data())
+                                       stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];
+    NSString *overEncodedRealmName = [[NSString alloc] initWithFormat:@"%@/%@", self.identifier, encodedPartitionValue];
+    auto legacyPath = _user->sync_manager()->path_for_realm(*_user, overEncodedRealmName.UTF8String);
+    if ([NSFileManager.defaultManager fileExistsAtPath:@(legacyPath.c_str())]) {
+        return legacyPath;
+    }
+
+    return path;
+}
+
+- (nullable RLMSyncSession *)sessionForPartitionValue:(id<RLMBSON>)partitionValue {
+    if (!_user) {
+        return nil;
+    }
+
+    std::stringstream s;
+    s << RLMConvertRLMBSONToBson(partitionValue);
+    auto path = [self pathForPartitionValue:s.str()];
+    if (auto session = _user->session_for_on_disk_path(path)) {
+        return [[RLMSyncSession alloc] initWithSyncSession:session];
+    }
+    return nil;
+}
+
+- (NSArray<RLMSyncSession *> *)allSessions {
+    if (!_user) {
+        return @[];
+    }
+    NSMutableArray<RLMSyncSession *> *buffer = [NSMutableArray array];
+    auto sessions = _user->all_sessions();
+    for (auto session : sessions) {
+        [buffer addObject:[[RLMSyncSession alloc] initWithSyncSession:std::move(session)]];
+    }
+    return [buffer copy];
+}
+
+- (NSString *)identifier {
+    if (!_user) {
+        return @"";
+    }
+    return @(_user->identity().c_str());
+}
+
+- (NSArray<RLMUserIdentity *> *)identities {
+    if (!_user) {
+        return @[];
+    }
+    NSMutableArray<RLMUserIdentity *> *buffer = [NSMutableArray array];
+    auto identities = _user->identities();
+    for (auto& identity : identities) {
+        [buffer addObject: [[RLMUserIdentity alloc] initUserIdentityWithProviderType:@(identity.provider_type.c_str())
+                                                                          identifier:@(identity.id.c_str())]];
+    }
+
+    return [buffer copy];
+}
+
+- (RLMUserState)state {
+    if (!_user) {
+        return RLMUserStateRemoved;
+    }
+    switch (_user->state()) {
+        case SyncUser::State::LoggedIn:
+            return RLMUserStateLoggedIn;
+        case SyncUser::State::LoggedOut:
+            return RLMUserStateLoggedOut;
+        case SyncUser::State::Removed:
+            return RLMUserStateRemoved;
+    }
+}
+
+- (void)refreshCustomDataWithCompletion:(RLMUserCustomDataBlock)completion {
+    _user->refresh_custom_data([completion, self](util::Optional<app::AppError> error) {
+        if (!error) {
+            return completion([self customData], nil);
+        }
+
+        completion(nil, RLMAppErrorToNSError(*error));
+    });
+}
+
+- (void)linkUserWithCredentials:(RLMCredentials *)credentials
+                     completion:(RLMOptionalUserBlock)completion {
+    _app._realmApp->link_user(_user, credentials.appCredentials,
+                   ^(std::shared_ptr<SyncUser> user, util::Optional<app::AppError> error) {
+        if (error && error->error_code) {
+            return completion(nil, RLMAppErrorToNSError(*error));
+        }
+
+        completion([[RLMUser alloc] initWithUser:user app:_app], nil);
+    });
+}
+
+- (void)removeWithCompletion:(RLMOptionalErrorBlock)completion {
+    _app._realmApp->remove_user(_user, ^(realm::util::Optional<app::AppError> error) {
+        [self handleResponse:error completion:completion];
+    });
+}
+
+- (void)logOutWithCompletion:(RLMOptionalErrorBlock)completion {
+    _app._realmApp->log_out(_user, ^(realm::util::Optional<app::AppError> error) {
+        [self handleResponse:error completion:completion];
+    });
+}
+
+- (RLMAPIKeyAuth *)apiKeysAuth {
+    return [[RLMAPIKeyAuth alloc] initWithApp: _app];
+}
+
+- (RLMMongoClient *)mongoClientWithServiceName:(NSString *)serviceName {
+    return [[RLMMongoClient alloc] initWithUser:self serviceName:serviceName];
+}
+
+- (void)callFunctionNamed:(NSString *)name
+                arguments:(NSArray<id<RLMBSON>> *)arguments
+          completionBlock:(RLMCallFunctionCompletionBlock)completionBlock {
+    bson::BsonArray args;
+
+    for (id<RLMBSON> argument in arguments) {
+        args.push_back(RLMConvertRLMBSONToBson(argument));
+    }
+
+    _app._realmApp->call_function(_user,
+                        std::string(name.UTF8String),
+                        args, [completionBlock](util::Optional<app::AppError> error,
+                                                util::Optional<bson::Bson> response) {
+        if (error) {
+            return completionBlock(nil, RLMAppErrorToNSError(*error));
+        }
+
+        completionBlock(RLMConvertBsonToRLMBSON(*response), nil);
+    });
+}
+
+- (void)handleResponse:(realm::util::Optional<realm::app::AppError>)error
+            completion:(RLMOptionalErrorBlock)completion {
+    if (error && error->error_code) {
+        return completion(RLMAppErrorToNSError(*error));
+    }
+    completion(nil);
+}
+
+#pragma mark - Private API
+
++ (void)_setUpBindingContextFactory {
+    SyncUser::set_binding_context_factory([] {
+        return std::make_shared<CocoaSyncUserContext>();
+    });
+}
+
+- (NSString *)refreshToken {
+    if (!_user || _user->refresh_token().empty()) {
+        return nil;
+    }
+    return @(_user->refresh_token().c_str());
+}
+
+- (NSString *)accessToken {
+    if (!_user || _user->access_token().empty()) {
+        return nil;
+    }
+    return @(_user->access_token().c_str());
+}
+
+- (NSDictionary *)customData {
+    if (!_user || !_user->custom_data()) {
+        return @{};
+    }
+
+    return (NSDictionary *)RLMConvertBsonToRLMBSON(*_user->custom_data());
+}
+
+- (std::shared_ptr<SyncUser>)_syncUser {
+    return _user;
+}
+
+- (RLMUserSubscriptionToken *)subscribe:(RLMUserNotificationBlock) block {
+    return [[RLMUserSubscriptionToken alloc] initWithToken:_user->subscribe([block, self] (auto&) {
+        block(self);
+    })];
+}
+
+- (void)unsubscribe:(RLMUserSubscriptionToken *)token {
+    _user->unsubscribe(*token->_token);
+}
+
+@end
+
+#pragma mark - RLMUserIdentity
+
+@implementation RLMUserIdentity
+
+- (instancetype)initUserIdentityWithProviderType:(NSString *)providerType
+                                      identifier:(NSString *)identifier {
+    if (self = [super init]) {
+        _providerType = providerType;
+        _identifier = identifier;
+    }
+    return self;
+}
+
+@end

+ 68 - 0
Example/Pods/Realm/Realm/RLMUserAPIKey.mm

@@ -0,0 +1,68 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2020 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMUserAPIKey.h"
+#import "RLMUserAPIKey_Private.hpp"
+#import "RLMUtil.hpp"
+#import "RLMObjectId_Private.hpp"
+
+@interface RLMUserAPIKey() {
+    realm::app::App::UserAPIKey _userAPIKey;
+}
+@end
+
+@implementation RLMUserAPIKey
+
+- (instancetype)initWithUserAPIKey:(realm::app::App::UserAPIKey)userAPIKey {
+    if (self = [super init]) {
+        _userAPIKey = userAPIKey;
+        return self;
+    }
+    
+    return nil;
+}
+
+// Indicates if the API key is disabled or not
+- (BOOL)disabled {
+    return _userAPIKey.disabled;
+}
+
+// The name of the key.
+- (NSString *)name {
+    return @(_userAPIKey.name.c_str());
+}
+
+// The actual key. Will only be included in
+// the response when an API key is first created.
+- (NSString *)key {
+    if (_userAPIKey.key) {
+        return @(_userAPIKey.name.c_str());
+    }
+    
+    return nil;
+}
+
+- (RLMObjectId *)objectId {
+    return [[RLMObjectId alloc] initWithValue:_userAPIKey.id];
+}
+
+- (realm::app::App::UserAPIKey)_apiKey {
+    return _userAPIKey;
+}
+
+@end

+ 510 - 0
Example/Pods/Realm/Realm/RLMUtil.mm

@@ -0,0 +1,510 @@
+////////////////////////////////////////////////////////////////////////////
+//
+// Copyright 2014 Realm Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#import "RLMUtil.hpp"
+
+#import "RLMArray_Private.hpp"
+#import "RLMDecimal128_Private.hpp"
+#import "RLMListBase.h"
+#import "RLMObjectId_Private.hpp"
+#import "RLMObjectSchema_Private.hpp"
+#import "RLMObjectStore.h"
+#import "RLMObject_Private.hpp"
+#import "RLMProperty_Private.h"
+#import "RLMSchema_Private.h"
+#import "RLMSwiftSupport.h"
+
+#import <realm/mixed.hpp>
+#import <realm/object-store/shared_realm.hpp>
+#import <realm/table_view.hpp>
+
+#if REALM_ENABLE_SYNC
+#import "RLMSyncUtil.h"
+#import <realm/sync/client.hpp>
+#endif
+
+#include <sys/sysctl.h>
+#include <sys/types.h>
+
+#if !defined(REALM_COCOA_VERSION)
+#import "RLMVersion.h"
+#endif
+
+static inline bool numberIsInteger(__unsafe_unretained NSNumber *const obj) {
+    char data_type = [obj objCType][0];
+    return data_type == *@encode(bool) ||
+           data_type == *@encode(char) ||
+           data_type == *@encode(short) ||
+           data_type == *@encode(int) ||
+           data_type == *@encode(long) ||
+           data_type == *@encode(long long) ||
+           data_type == *@encode(unsigned short) ||
+           data_type == *@encode(unsigned int) ||
+           data_type == *@encode(unsigned long) ||
+           data_type == *@encode(unsigned long long);
+}
+
+static inline bool numberIsBool(__unsafe_unretained NSNumber *const obj) {
+    // @encode(BOOL) is 'B' on iOS 64 and 'c'
+    // objcType is always 'c'. Therefore compare to "c".
+    if ([obj objCType][0] == 'c') {
+        return true;
+    }
+
+    if (numberIsInteger(obj)) {
+        int value = [obj intValue];
+        return value == 0 || value == 1;
+    }
+
+    return false;
+}
+
+static inline bool numberIsFloat(__unsafe_unretained NSNumber *const obj) {
+    char data_type = [obj objCType][0];
+    return data_type == *@encode(float) ||
+           data_type == *@encode(short) ||
+           data_type == *@encode(int) ||
+           data_type == *@encode(long) ||
+           data_type == *@encode(long long) ||
+           data_type == *@encode(unsigned short) ||
+           data_type == *@encode(unsigned int) ||
+           data_type == *@encode(unsigned long) ||
+           data_type == *@encode(unsigned long long) ||
+           // A double is like float if it fits within float bounds or is NaN.
+           (data_type == *@encode(double) && (ABS([obj doubleValue]) <= FLT_MAX || isnan([obj doubleValue])));
+}
+
+static inline bool numberIsDouble(__unsafe_unretained NSNumber *const obj) {
+    char data_type = [obj objCType][0];
+    return data_type == *@encode(double) ||
+           data_type == *@encode(float) ||
+           data_type == *@encode(short) ||
+           data_type == *@encode(int) ||
+           data_type == *@encode(long) ||
+           data_type == *@encode(long long) ||
+           data_type == *@encode(unsigned short) ||
+           data_type == *@encode(unsigned int) ||
+           data_type == *@encode(unsigned long) ||
+           data_type == *@encode(unsigned long long);
+}
+
+static inline RLMArray *asRLMArray(__unsafe_unretained id const value) {
+    return RLMDynamicCast<RLMArray>(value) ?: RLMDynamicCast<RLMListBase>(value)._rlmArray;
+}
+
+static inline bool checkArrayType(__unsafe_unretained RLMArray *const array,
+                                  RLMPropertyType type, bool optional,
+                                  __unsafe_unretained NSString *const objectClassName) {
+    return array.type == type && array.optional == optional
+        && (type != RLMPropertyTypeObject || [array.objectClassName isEqualToString:objectClassName]);
+}
+
+id (*RLMSwiftAsFastEnumeration)(id);
+id<NSFastEnumeration> RLMAsFastEnumeration(__unsafe_unretained id obj) {
+    if (!obj) {
+        return nil;
+    }
+    if ([obj conformsToProtocol:@protocol(NSFastEnumeration)]) {
+        return obj;
+    }
+    if (RLMSwiftAsFastEnumeration) {
+        return RLMSwiftAsFastEnumeration(obj);
+    }
+    return nil;
+}
+
+bool RLMIsSwiftObjectClass(Class cls) {
+    static Class s_swiftObjectClass = NSClassFromString(@"RealmSwiftObject");
+    static Class s_swiftEmbeddedObjectClass = NSClassFromString(@"RealmSwiftEmbeddedObject");
+    return [cls isSubclassOfClass:s_swiftObjectClass] || [cls isSubclassOfClass:s_swiftEmbeddedObjectClass];
+}
+
+BOOL RLMValidateValue(__unsafe_unretained id const value,
+                      RLMPropertyType type, bool optional, bool array,
+                      __unsafe_unretained NSString *const objectClassName) {
+    if (optional && !RLMCoerceToNil(value)) {
+        return YES;
+    }
+    if (array) {
+        if (auto rlmArray = asRLMArray(value)) {
+            return checkArrayType(rlmArray, type, optional, objectClassName);
+        }
+        if (id enumeration = RLMAsFastEnumeration(value)) {
+            // check each element for compliance
+            for (id el in enumeration) {
+                if (!RLMValidateValue(el, type, optional, false, objectClassName)) {
+                    return NO;
+                }
+            }
+            return YES;
+        }
+        if (!value || value == NSNull.null) {
+            return YES;
+        }
+        return NO;
+    }
+
+    switch (type) {
+        case RLMPropertyTypeString:
+            return [value isKindOfClass:[NSString class]];
+        case RLMPropertyTypeBool:
+            if ([value isKindOfClass:[NSNumber class]]) {
+                return numberIsBool(value);
+            }
+            return NO;
+        case RLMPropertyTypeDate:
+            return [value isKindOfClass:[NSDate class]];
+        case RLMPropertyTypeInt:
+            if (NSNumber *number = RLMDynamicCast<NSNumber>(value)) {
+                return numberIsInteger(number);
+            }
+            return NO;
+        case RLMPropertyTypeFloat:
+            if (NSNumber *number = RLMDynamicCast<NSNumber>(value)) {
+                return numberIsFloat(number);
+            }
+            return NO;
+        case RLMPropertyTypeDouble:
+            if (NSNumber *number = RLMDynamicCast<NSNumber>(value)) {
+                return numberIsDouble(number);
+            }
+            return NO;
+        case RLMPropertyTypeData:
+            return [value isKindOfClass:[NSData class]];
+        case RLMPropertyTypeAny:
+            return NO;
+        case RLMPropertyTypeLinkingObjects:
+            return YES;
+        case RLMPropertyTypeObject: {
+            // only NSNull, nil, or objects which derive from RLMObject and match the given
+            // object class are valid
+            RLMObjectBase *objBase = RLMDynamicCast<RLMObjectBase>(value);
+            return objBase && [objBase->_objectSchema.className isEqualToString:objectClassName];
+        }
+        case RLMPropertyTypeObjectId:
+            return [value isKindOfClass:[RLMObjectId class]];
+        case RLMPropertyTypeDecimal128:
+            return [value isKindOfClass:[NSNumber class]]
+                || [value isKindOfClass:[RLMDecimal128 class]]
+                || ([value isKindOfClass:[NSString class]] && realm::Decimal128::is_valid_str([value UTF8String]));
+    }
+    @throw RLMException(@"Invalid RLMPropertyType specified");
+}
+
+void RLMThrowTypeError(__unsafe_unretained id const obj,
+                       __unsafe_unretained RLMObjectSchema *const objectSchema,
+                       __unsafe_unretained RLMProperty *const prop) {
+    @throw RLMException(@"Invalid value '%@' of type '%@' for '%@%s'%s property '%@.%@'.",
+                        obj, [obj class],
+                        prop.objectClassName ?: RLMTypeToString(prop.type), prop.optional ? "?" : "",
+                        prop.array ? " array" : "", objectSchema.className, prop.name);
+}
+
+void RLMValidateValueForProperty(__unsafe_unretained id const obj,
+                                 __unsafe_unretained RLMObjectSchema *const objectSchema,
+                                 __unsafe_unretained RLMProperty *const prop,
+                                 bool validateObjects) {
+    // This duplicates a lot of the checks in RLMIsObjectValidForProperty()
+    // for the sake of more specific error messages
+    if (prop.array) {
+        // nil is considered equivalent to an empty array for historical reasons
+        // since we don't support null arrays (only arrays containing null),
+        // it's not worth the BC break to change this
+        if (!obj || obj == NSNull.null) {
+            return;
+        }
+        id enumeration = RLMAsFastEnumeration(obj);
+        if (!enumeration) {
+            @throw RLMException(@"Invalid value (%@) for '%@%s' array property '%@.%@': value is not enumerable.",
+                                obj, prop.objectClassName ?: RLMTypeToString(prop.type), prop.optional ? "?" : "",
+                                objectSchema.className, prop.name);
+        }
+        if (!validateObjects && prop.type == RLMPropertyTypeObject) {
+            return;
+        }
+
+        if (RLMArray *array = asRLMArray(obj)) {
+            if (!checkArrayType(array, prop.type, prop.optional, prop.objectClassName)) {
+                @throw RLMException(@"RLMArray<%@%s> does not match expected type '%@%s' for property '%@.%@'.",
+                                    array.objectClassName ?: RLMTypeToString(array.type), array.optional ? "?" : "",
+                                    prop.objectClassName ?: RLMTypeToString(prop.type), prop.optional ? "?" : "",
+                                    objectSchema.className, prop.name);
+            }
+            return;
+        }
+
+        for (id value in enumeration) {
+            if (!RLMValidateValue(value, prop.type, prop.optional, false, prop.objectClassName)) {
+                RLMThrowTypeError(value, objectSchema, prop);
+            }
+        }
+        return;
+    }
+
+    // For create() we want to skip the validation logic for objects because
+    // we allow much fuzzier matching (any KVC-compatible object with at least
+    // all the non-defaulted fields), and all the logic for that lives in the
+    // object store rather than here
+    if (prop.type == RLMPropertyTypeObject && !validateObjects) {
+        return;
+    }
+    if (RLMIsObjectValidForProperty(obj, prop)) {
+        return;
+    }
+
+    RLMThrowTypeError(obj, objectSchema, prop);
+}
+
+BOOL RLMIsObjectValidForProperty(__unsafe_unretained id const obj,
+                                 __unsafe_unretained RLMProperty *const property) {
+    return RLMValidateValue(obj, property.type, property.optional, property.array, property.objectClassName);
+}
+
+NSDictionary *RLMDefaultValuesForObjectSchema(__unsafe_unretained RLMObjectSchema *const objectSchema) {
+    if (!objectSchema.isSwiftClass) {
+        return [objectSchema.objectClass defaultPropertyValues];
+    }
+
+    NSMutableDictionary *defaults = nil;
+    if ([objectSchema.objectClass isSubclassOfClass:RLMObject.class]) {
+        defaults = [NSMutableDictionary dictionaryWithDictionary:[objectSchema.objectClass defaultPropertyValues]];
+    }
+    else {
+        defaults = [NSMutableDictionary dictionary];
+    }
+    RLMObject *defaultObject = [[objectSchema.objectClass alloc] init];
+    for (RLMProperty *prop in objectSchema.properties) {
+        if (!defaults[prop.name] && defaultObject[prop.name]) {
+            defaults[prop.name] = defaultObject[prop.name];
+        }
+    }
+    return defaults;
+}
+
+static NSException *RLMException(NSString *reason, NSDictionary *additionalUserInfo) {
+    NSMutableDictionary *userInfo = @{RLMRealmVersionKey: REALM_COCOA_VERSION,
+                                      RLMRealmCoreVersionKey: @REALM_VERSION}.mutableCopy;
+    if (additionalUserInfo != nil) {
+        [userInfo addEntriesFromDictionary:additionalUserInfo];
+    }
+    NSException *e = [NSException exceptionWithName:RLMExceptionName
+                                             reason:reason
+                                           userInfo:userInfo];
+    return e;
+}
+
+NSException *RLMException(NSString *fmt, ...) {
+    va_list args;
+    va_start(args, fmt);
+    NSException *e = RLMException([[NSString alloc] initWithFormat:fmt arguments:args], @{});
+    va_end(args);
+    return e;
+}
+
+NSException *RLMException(std::exception const& exception) {
+    return RLMException(@"%s", exception.what());
+}
+
+NSError *RLMMakeError(RLMError code, std::exception const& exception) {
+    return [NSError errorWithDomain:RLMErrorDomain
+                               code:code
+                           userInfo:@{NSLocalizedDescriptionKey: @(exception.what()),
+                                      @"Error Code": @(code)}];
+}
+
+NSError *RLMMakeError(RLMError code, const realm::util::File::AccessError& exception) {
+    return [NSError errorWithDomain:RLMErrorDomain
+                               code:code
+                           userInfo:@{NSLocalizedDescriptionKey: @(exception.what()),
+                                      NSFilePathErrorKey: @(exception.get_path().c_str()),
+                                      @"Error Code": @(code)}];
+}
+
+NSError *RLMMakeError(RLMError code, const realm::RealmFileException& exception) {
+    NSString *underlying = @(exception.underlying().c_str());
+    return [NSError errorWithDomain:RLMErrorDomain
+                               code:code
+                           userInfo:@{NSLocalizedDescriptionKey: @(exception.what()),
+                                      NSFilePathErrorKey: @(exception.path().c_str()),
+                                      @"Error Code": @(code),
+                                      @"Underlying": underlying.length == 0 ? @"n/a" : underlying}];
+}
+
+NSError *RLMMakeError(std::system_error const& exception) {
+    int code = exception.code().value();
+    BOOL isGenericCategoryError = (exception.code().category() == std::generic_category());
+    NSString *category = @(exception.code().category().name());
+    NSString *errorDomain = isGenericCategoryError ? NSPOSIXErrorDomain : RLMUnknownSystemErrorDomain;
+#if REALM_ENABLE_SYNC
+    if (exception.code().category() == realm::sync::client_error_category()) {
+        if (exception.code().value() == static_cast<int>(realm::sync::Client::Error::connect_timeout)) {
+            errorDomain = NSPOSIXErrorDomain;
+            code = ETIMEDOUT;
+        }
+        else {
+            errorDomain = RLMSyncErrorDomain;
+        }
+    }
+#endif
+
+    return [NSError errorWithDomain:errorDomain code:code
+                           userInfo:@{NSLocalizedDescriptionKey: @(exception.what()),
+                                      @"Error Code": @(exception.code().value()),
+                                      @"Category": category}];
+}
+
+void RLMSetErrorOrThrow(NSError *error, NSError **outError) {
+    if (outError) {
+        *outError = error;
+    }
+    else {
+        NSString *msg = error.localizedDescription;
+        if (error.userInfo[NSFilePathErrorKey]) {
+            msg = [NSString stringWithFormat:@"%@: %@", error.userInfo[NSFilePathErrorKey], error.localizedDescription];
+        }
+        @throw RLMException(msg, @{NSUnderlyingErrorKey: error});
+    }
+}
+
+BOOL RLMIsDebuggerAttached()
+{
+    int name[] = {
+        CTL_KERN,
+        KERN_PROC,
+        KERN_PROC_PID,
+        getpid()
+    };
+
+    struct kinfo_proc info;
+    size_t info_size = sizeof(info);
+    if (sysctl(name, sizeof(name)/sizeof(name[0]), &info, &info_size, NULL, 0) == -1) {
+        NSLog(@"sysctl() failed: %s", strerror(errno));
+        return false;
+    }
+
+    return (info.kp_proc.p_flag & P_TRACED) != 0;
+}
+
+BOOL RLMIsRunningInPlayground() {
+    return [[NSBundle mainBundle].bundleIdentifier hasPrefix:@"com.apple.dt.playground."];
+}
+
+id RLMMixedToObjc(realm::Mixed const& mixed) {
+    switch (mixed.get_type()) {
+        case realm::type_String:
+            return RLMStringDataToNSString(mixed.get_string());
+        case realm::type_Int:
+            return @(mixed.get_int());
+        case realm::type_Float:
+            return @(mixed.get_float());
+        case realm::type_Double:
+            return @(mixed.get_double());
+        case realm::type_Bool:
+            return @(mixed.get_bool());
+        case realm::type_Timestamp:
+            return RLMTimestampToNSDate(mixed.get_timestamp());
+        case realm::type_Binary:
+            return RLMBinaryDataToNSData(mixed.get<realm::BinaryData>());
+        case realm::type_Decimal:
+            return [[RLMDecimal128 alloc] initWithDecimal128:mixed.get<realm::Decimal128>()];
+        case realm::type_ObjectId:
+            return [[RLMObjectId alloc] initWithValue:mixed.get<realm::ObjectId>()];
+        case realm::type_Link:
+        case realm::type_LinkList:
+            REALM_UNREACHABLE();
+        default:
+            @throw RLMException(@"Invalid data type for RLMPropertyTypeAny property.");
+    }
+}
+
+realm::Decimal128 RLMObjcToDecimal128(__unsafe_unretained id const value) {
+    try {
+        if (!value || value == NSNull.null) {
+            return realm::Decimal128(realm::null());
+        }
+        if (auto decimal = RLMDynamicCast<RLMDecimal128>(value)) {
+            return decimal.decimal128Value;
+        }
+        if (auto string = RLMDynamicCast<NSString>(value)) {
+            return realm::Decimal128(string.UTF8String);
+        }
+        if (auto decimal = RLMDynamicCast<NSDecimalNumber>(value)) {
+            return realm::Decimal128(decimal.stringValue.UTF8String);
+        }
+        if (auto number = RLMDynamicCast<NSNumber>(value)) {
+            auto type = number.objCType[0];
+            if (type == *@encode(double) || type == *@encode(float)) {
+                return realm::Decimal128(number.doubleValue);
+            }
+            else if (std::isupper(type)) {
+                return realm::Decimal128(number.unsignedLongLongValue);
+            }
+            else {
+                return realm::Decimal128(number.longLongValue);
+            }
+        }
+    }
+    catch (std::exception const& e) {
+        @throw RLMException(@"Cannot convert value '%@' of type '%@' to decimal128: %s",
+                            value, [value class], e.what());
+    }
+    @throw RLMException(@"Cannot convert value '%@' of type '%@' to decimal128", value, [value class]);
+}
+
+NSString *RLMDefaultDirectoryForBundleIdentifier(NSString *bundleIdentifier) {
+#if TARGET_OS_TV
+    (void)bundleIdentifier;
+    // tvOS prohibits writing to the Documents directory, so we use the Library/Caches directory instead.
+    return NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
+#elif TARGET_OS_IPHONE && !TARGET_OS_MACCATALYST
+    (void)bundleIdentifier;
+    // On iOS the Documents directory isn't user-visible, so put files there
+    return NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
+#else
+    // On OS X it is, so put files in Application Support. If we aren't running
+    // in a sandbox, put it in a subdirectory based on the bundle identifier
+    // to avoid accidentally sharing files between applications
+    NSString *path = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES)[0];
+    if (![[NSProcessInfo processInfo] environment][@"APP_SANDBOX_CONTAINER_ID"]) {
+        if (!bundleIdentifier) {
+            bundleIdentifier = [NSBundle mainBundle].bundleIdentifier;
+        }
+        if (!bundleIdentifier) {
+            bundleIdentifier = [NSBundle mainBundle].executablePath.lastPathComponent;
+        }
+
+        path = [path stringByAppendingPathComponent:bundleIdentifier];
+
+        // create directory
+        [[NSFileManager defaultManager] createDirectoryAtPath:path
+                                  withIntermediateDirectories:YES
+                                                   attributes:nil
+                                                        error:nil];
+    }
+    return path;
+#endif
+}
+
+NSDateFormatter *RLMISO8601Formatter() {
+    // note: NSISO8601DateFormatter can't be used as it doesn't support milliseconds
+    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
+    dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
+    dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
+    dateFormatter.calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
+    return dateFormatter;
+}

+ 33 - 0
Example/Pods/Realm/Realm/Realm.modulemap

@@ -0,0 +1,33 @@
+framework module Realm {
+    umbrella header "Realm.h"
+
+    export *
+    module * { export * }
+
+    explicit module Private {
+        header "RLMAccessor.h"
+        header "RLMApp_Private.h"
+        header "RLMArray_Private.h"
+        header "RLMCollection_Private.h"
+        header "RLMListBase.h"
+        header "RLMObject_Private.h"
+        header "RLMObjectBase_Dynamic.h"
+        header "RLMObjectBase_Private.h"
+        header "RLMObjectSchema_Private.h"
+        header "RLMObjectStore.h"
+        header "RLMOptionalBase.h"
+        header "RLMProperty_Private.h"
+        header "RLMRealm_Private.h"
+        header "RLMRealmConfiguration_Private.h"
+        header "RLMResults_Private.h"
+        header "RLMSchema_Private.h"
+        header "RLMSyncConfiguration_Private.h"
+        header "RLMSyncUtil_Private.h"
+        header "RLMUser_Private.h"
+    }
+
+    explicit module Dynamic {
+        header "RLMRealm_Dynamic.h"
+        header "RLMObjectBase_Dynamic.h"
+    }
+}

+ 1386 - 0
Example/Pods/Realm/build.sh

@@ -0,0 +1,1386 @@
+#!/bin/bash
+
+##################################################################################
+# Custom build tool for Realm Objective-C binding.
+#
+# (C) Copyright 2011-2015 by realm.io.
+##################################################################################
+
+# Warning: pipefail is not a POSIX compatible option, but on macOS it works just fine.
+#          macOS uses a POSIX complain version of bash as /bin/sh, but apparently it does
+#          not strip away this feature. Also, this will fail if somebody forces the script
+#          to be run with zsh.
+set -o pipefail
+set -e
+
+readonly source_root="$(dirname "$0")"
+
+# You can override the version of the core library
+: "${REALM_BASE_URL:="https://static.realm.io/downloads"}" # set it if you need to use a remote repo
+
+: "${REALM_CORE_VERSION:=$(sed -n 's/^REALM_CORE_VERSION=\(.*\)$/\1/p' "${source_root}/dependencies.list")}" # set to "current" to always use the current build
+
+# You can override the xcmode used
+: "${XCMODE:=xcodebuild}" # must be one of: xcodebuild (default), xcpretty, xctool
+
+# Provide a fallback value for TMPDIR, relevant for Xcode Bots
+: "${TMPDIR:=$(getconf DARWIN_USER_TEMP_DIR)}"
+
+PATH=/usr/libexec:$PATH
+
+if [ -n "${JENKINS_HOME}" ]; then
+    XCPRETTY_PARAMS=(--no-utf --report junit --output build/reports/junit.xml)
+    CODESIGN_PARAMS=(CODE_SIGN_IDENTITY='' CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO)
+fi
+
+usage() {
+cat <<EOF
+Usage: sh $0 command [argument]
+
+command:
+  clean:                clean up/remove all generated files
+  download-core:        downloads core library (binary version)
+  build:                builds all iOS and macOS frameworks
+  ios-static:           builds fat iOS static framework
+  ios-dynamic:          builds iOS dynamic frameworks
+  ios-swift:            builds RealmSwift frameworks for iOS
+  watchos:              builds watchOS framwork
+  watchos-swift:        builds RealmSwift framework for watchOS
+  tvos:                 builds tvOS framework
+  tvos-swift:           builds RealmSwift framework for tvOS
+  osx:                  builds macOS framework
+  osx-swift:            builds RealmSwift framework for macOS
+  xcframework [plats]:  builds xcframeworks for Realm and RealmSwift for given platforms
+  analyze-osx:          analyzes macOS framework
+  test:                 tests all iOS and macOS frameworks
+  test-all:             tests all iOS and macOS frameworks in both Debug and Release configurations
+  test-ios-static:      tests static iOS framework on 32-bit and 64-bit simulators
+  test-ios-dynamic:     tests dynamic iOS framework on 32-bit and 64-bit simulators
+  test-ios-swift:       tests RealmSwift iOS framework on 32-bit and 64-bit simulators
+  test-ios-devices:     tests ObjC & Swift iOS frameworks on all attached iOS devices
+  test-ios-devices-objc:  tests ObjC iOS framework on all attached iOS devices
+  test-ios-devices-swift: tests Swift iOS framework on all attached iOS devices
+  test-tvos:            tests tvOS framework
+  test-tvos-swift:      tests RealmSwift tvOS framework
+  test-tvos-devices:    tests ObjC & Swift tvOS frameworks on all attached tvOS devices
+  test-osx:             tests macOS framework
+  test-osx-swift:       tests RealmSwift macOS framework
+  test-catalyst:        tests Mac Catalyst framework
+  test-catalyst-swift:  tests RealmSwift Mac Catalyst framework
+  test-swiftpm:         tests ObjC and Swift macOS frameworks via SwiftPM
+  test-swiftui-ios:         tests SwiftUI framework UI tests
+  verify:               verifies docs, osx, osx-swift, ios-static, ios-dynamic, ios-swift, ios-device, swiftui-ios in both Debug and Release configurations, swiftlint
+  verify-osx-object-server:  downloads the Realm Object Server and runs the Objective-C and Swift integration tests
+  docs:                 builds docs in docs/output
+  examples:             builds all examples
+  examples-ios:         builds all static iOS examples
+  examples-ios-swift:   builds all Swift iOS examples
+  examples-osx:         builds all macOS examples
+  get-version:          get the current version
+  set-version version:  set the version
+  cocoapods-setup:      download realm-core and create a stub RLMPlatform.h file to enable building via CocoaPods
+
+
+argument:
+  version: version in the x.y.z format
+
+environment variables:
+  XCMODE: xcodebuild (default), xcpretty or xctool
+  CONFIGURATION: Debug or Release (default)
+  REALM_CORE_VERSION: version in x.y.z format or "current" to use local build
+  REALM_EXTRA_BUILD_ARGUMENTS: additional arguments to pass to the build tool
+  REALM_XCODE_VERSION: the version number of Xcode to use (e.g.: 8.1)
+EOF
+}
+
+######################################
+# Xcode Helpers
+######################################
+
+xcode_version_major() {
+    echo "${REALM_XCODE_VERSION%%.*}"
+}
+
+xcode() {
+    mkdir -p build/DerivedData
+    CMD="xcodebuild -IDECustomDerivedDataLocation=build/DerivedData"
+    echo "Building with command: $CMD $*"
+    xcodebuild -IDECustomDerivedDataLocation=build/DerivedData "$@"
+}
+
+xc() {
+    # Logs xcodebuild output in realtime
+    : "${NSUnbufferedIO:=YES}"
+    args=("SWIFT_VERSION=$REALM_SWIFT_VERSION" $REALM_EXTRA_BUILD_ARGUMENTS)
+    if [[ "$XCMODE" == "xcodebuild" ]]; then
+        xcode "$@" "${args[@]}"
+    elif [[ "$XCMODE" == "xcpretty" ]]; then
+        mkdir -p build
+        xcode "$@" "${args[@]}" | tee build/build.log | xcpretty -c "${XCPRETTY_PARAMS[@]}" || {
+            echo "The raw xcodebuild output is available in build/build.log"
+            exit 1
+        }
+    elif [[ "$XCMODE" == "xctool" ]]; then
+        xctool "$@" "${args[@]}"
+    fi
+}
+
+xctest() {
+  local scheme="$1"
+  local test_plan="$(echo $1 | tr -d ' ')"
+  if (( $(xcode_version_major) < 12 )); then
+    test_plan="${test_plan}Xcode11"
+  fi
+  xc -scheme "$scheme" -testPlan "$test_plan" "${@:2}" build-for-testing
+  xc -scheme "$scheme" -testPlan "$test_plan" "${@:2}" test-without-building
+}
+
+build_combined() {
+    local scheme="$1"
+    local module_name="$2"
+    local os="$3"
+    local simulator="$4"
+    local scope_suffix="$5"
+    local version_suffix="$6"
+    local config="$CONFIGURATION"
+
+    local os_name=""
+    if [[ "$os" == "iphoneos" ]]; then
+        os_name="ios"
+    elif [[ "$os" == "watchos"  ]]; then
+        os_name="$os"
+    elif [[ "$os" == "appletvos"  ]]; then
+        os_name="tvos"
+    fi
+
+    # Derive build paths
+    local build_products_path="build/DerivedData/Realm/Build/Products"
+    local product_name="$module_name.framework"
+    local os_path="$build_products_path/$config-$os$scope_suffix/$product_name"
+    local simulator_path="$build_products_path/$config-$simulator$scope_suffix/$product_name"
+    local out_path="build/$os_name$scope_suffix$version_suffix"
+    local xcframework_path="$out_path/$module_name.xcframework"
+
+    # Build for each platform
+    xc -scheme "$scheme" -configuration "$config" -sdk "$os" build
+    xc -scheme "$scheme" -configuration "$config" -sdk "$simulator" build ONLY_ACTIVE_ARCH=NO
+
+    # Create the xcframework
+    rm -rf "$xcframework_path"
+    xcodebuild -create-xcframework -allow-internal-distribution -output "$xcframework_path" \
+        -framework "$os_path" -framework "$simulator_path"
+}
+
+copy_realm_framework() {
+    local platform="$1"
+    rm -rf "build/$platform/swift-$REALM_XCODE_VERSION/Realm.xcframework"
+    cp -R "build/$platform/Realm.xcframework" "build/$platform/swift-$REALM_XCODE_VERSION"
+}
+
+clean_retrieve() {
+  mkdir -p "$2"
+  rm -rf "$2/$3"
+  cp -R "$1" "$2"
+}
+
+move_to_clean_dir() {
+    rm -rf "$2"
+    mkdir -p "$2"
+    mv "$1" "$2"
+}
+
+test_ios_static() {
+    xctest 'Realm iOS static' -configuration "$CONFIGURATION" -sdk iphonesimulator -destination "$1"
+}
+
+plist_get() {
+    /usr/libexec/PlistBuddy -c "Print :$2" "$1" 2> /dev/null
+}
+
+######################################
+# Device Test Helper
+######################################
+
+test_devices() {
+    local serial_numbers=()
+    local awk_script="
+    /^ +Vendor ID: / { is_apple = 0; }
+    /^ +Vendor ID: 0x05[aA][cC] / { is_apple = 1; }
+    /^ +Serial Number: / {
+        if (is_apple) {
+            match(\$0, /^ +Serial Number: /);
+            print substr(\$0, RLENGTH + 1);
+        }
+    }
+    "
+    local serial_numbers_text=$(/usr/sbin/system_profiler SPUSBDataType | /usr/bin/awk "$awk_script")
+    while read -r number; do
+        if [[ "$number" != "" ]]; then
+            serial_numbers+=("$number")
+        fi
+    done <<< "$serial_numbers_text"
+    if [[ ${#serial_numbers[@]} == 0 ]]; then
+        echo "At least one iOS/tvOS device must be connected to this computer to run device tests"
+        if [ -z "${JENKINS_HOME}" ]; then
+            # Don't fail if running locally and there's no device
+            exit 0
+        fi
+        exit 1
+    fi
+    local sdk="$1"
+    local scheme="$2"
+    local configuration="$3"
+    local failed=0
+    for device in "${serial_numbers[@]}"; do
+        xc -scheme "$scheme" -configuration "$configuration" -destination "id=$device" -sdk "$sdk" test || failed=1
+    done
+    return $failed
+}
+
+######################################
+# Docs
+######################################
+
+build_docs() {
+    local language="$1"
+    local version=$(sh build.sh get-version)
+
+    local xcodebuild_arguments="--objc,Realm/Realm.h,--,-x,objective-c,-isysroot,$(xcrun --show-sdk-path),-I,$(pwd)"
+    local module="Realm"
+    local objc="--objc"
+
+    if [[ "$language" == "swift" ]]; then
+        xcodebuild_arguments="-scheme,RealmSwift"
+        module="RealmSwift"
+        objc=""
+    fi
+
+    touch Realm/RLMPlatform.h # jazzy will fail if it can't find all public header files
+    jazzy \
+      "${objc}" \
+      --clean \
+      --author Realm \
+      --author_url https://realm.io \
+      --github_url https://github.com/realm/realm-cocoa \
+      --github-file-prefix "https://github.com/realm/realm-cocoa/tree/v${version}" \
+      --module-version "${version}" \
+      --xcodebuild-arguments "${xcodebuild_arguments}" \
+      --module "${module}" \
+      --root-url "https://realm.io/docs/${language}/${version}/api/" \
+      --output "docs/${language}_output" \
+      --head "$(cat docs/custom_head.html)"
+
+    rm Realm/RLMPlatform.h
+}
+
+######################################
+# Input Validation
+######################################
+
+if [ "$#" -eq 0 ] || [ "$#" -gt 3 ]; then
+    usage
+    exit 1
+fi
+
+######################################
+# Downloading
+######################################
+
+copy_core() {
+    local src="$1"
+    rm -rf core
+    mkdir core
+    ditto "$src" core
+
+    # XCFramework processing only copies the "realm" headers, so put the third-party ones in a known location
+    mkdir -p core/include
+    find "$src" -name external -exec ditto "{}" core/include/external \; -quit
+}
+
+download_common() {
+    local tries_left=3 version url error suffix
+    suffix='-xcframework'
+
+    version=$REALM_CORE_VERSION
+    url="${REALM_BASE_URL}/core/realm-monorepo-xcframework-v${version}.tar.xz"
+
+    # First check if we need to do anything
+    if [ -e core ]; then
+        if [ -e core/version.txt ]; then
+            if [ "$(cat core/version.txt)" == "$version" ]; then
+                echo "Version ${version} already present"
+                exit 0
+            else
+                echo "Switching from version $(cat core/version.txt) to ${version}"
+            fi
+        else
+            if [ "$(find core -name librealm-monorepo.a)" ]; then
+                echo 'Using existing custom core build without checking version'
+                exit 0
+            fi
+        fi
+    fi
+
+    # We may already have this version downloaded and just need to set it as
+    # the active one
+    local versioned_dir="realm-core-${version}${suffix}"
+    if [ -e "$versioned_dir/version.txt" ]; then
+        echo "Setting ${version} as the active version"
+        copy_core "$versioned_dir"
+        exit 0
+    fi
+
+    echo "Downloading dependency: ${version} from ${url}"
+
+    if [ -z "$TMPDIR" ]; then
+        TMPDIR='/tmp'
+    fi
+    local temp_dir=$(dirname "$TMPDIR/waste")/realm-core-tmp
+    mkdir -p "$temp_dir"
+    local tar_path="${temp_dir}/${versioned_dir}.tar.xz"
+    local temp_path="${tar_path}.tmp"
+
+    while [ 0 -lt $tries_left ] && [ ! -f "$tar_path" ]; do
+        if ! error=$(/usr/bin/curl --fail --silent --show-error --location "$url" --output "$temp_path" 2>&1); then
+            tries_left=$((tries_left-1))
+        else
+            mv "$temp_path" "$tar_path"
+        fi
+    done
+
+    if [ ! -f "$tar_path" ]; then
+        printf "Downloading core failed:\n\t%s\n\t%s\n" "$url" "$error"
+        exit 1
+    fi
+
+    (
+        cd "$temp_dir"
+        rm -rf core
+        tar xf "$tar_path" --xz
+        if [ ! -f core/version.txt ]; then
+            printf %s "${version}" > core/version.txt
+        fi
+
+        # Xcode 11 dsymutil crashes when given debugging symbols created by
+        # Xcode 12. Check if this breaks, and strip them if so.
+        local test_lib=core/realm-monorepo.xcframework/ios-*-simulator/librealm-monorepo.a
+        xcrun clang++ -Wl,-all_load -g -arch x86_64 -shared -target ios13.0 \
+          -isysroot $(xcrun --sdk iphonesimulator --show-sdk-path) -o tmp.dylib \
+          $test_lib -lz -framework Security
+        if ! dsymutil tmp.dylib -o tmp.dSYM 2> /dev/null; then
+            find core -name '*.a' -exec strip -x "{}" \; 2> /dev/null
+        fi
+        rm -r tmp.dylib tmp.dSYM
+
+        mv core "${versioned_dir}"
+    )
+
+    rm -rf "${versioned_dir}"
+    mv "${temp_dir}/${versioned_dir}" .
+    copy_core "$versioned_dir"
+}
+
+######################################
+# Variables
+######################################
+
+COMMAND="$1"
+
+# Use Debug config if command ends with -debug, otherwise default to Release
+case "$COMMAND" in
+    *-debug)
+        COMMAND="${COMMAND%-debug}"
+        CONFIGURATION="Debug"
+        ;;
+esac
+export CONFIGURATION=${CONFIGURATION:-Release}
+
+# Pre-choose Xcode and Swift versions for those operations that do not set them
+REALM_XCODE_VERSION=${xcode_version:-$REALM_XCODE_VERSION}
+REALM_SWIFT_VERSION=${swift_version:-$REALM_SWIFT_VERSION}
+source "${source_root}/scripts/swift-version.sh"
+set_xcode_and_swift_versions
+
+######################################
+# Commands
+######################################
+
+case "$COMMAND" in
+
+    ######################################
+    # Clean
+    ######################################
+    "clean")
+        find . -type d -name build -exec rm -r "{}" +
+        exit 0
+        ;;
+
+    ######################################
+    # Dependencies
+    ######################################
+    "download-core")
+        download_common
+        exit 0
+        ;;
+
+    "setup-baas")
+        ruby Realm/ObjectServerTests/setup_baas.rb
+        exit 0
+        ;;
+
+    "prelaunch-simulator")
+        if [ -z "$REALM_SKIP_PRELAUNCH" ]; then
+            sh "${source_root}/scripts/reset-simulators.sh" "$1"
+        fi
+        ;;
+
+    ######################################
+    # Building
+    ######################################
+    "build")
+        sh build.sh ios-static
+        sh build.sh ios-dynamic
+        sh build.sh ios-swift
+        sh build.sh watchos
+        sh build.sh watchos-swift
+        sh build.sh tvos
+        sh build.sh tvos-swift
+        sh build.sh osx
+        sh build.sh osx-swift
+        exit 0
+        ;;
+
+    "ios-static")
+        build_combined 'Realm iOS static' Realm iphoneos iphonesimulator "-static"
+        exit 0
+        ;;
+
+    "ios-dynamic")
+        build_combined Realm Realm iphoneos iphonesimulator
+        exit 0
+        ;;
+
+    "ios-swift")
+        sh build.sh ios-dynamic
+        build_combined RealmSwift RealmSwift iphoneos iphonesimulator '' "/swift-$REALM_XCODE_VERSION"
+        copy_realm_framework ios
+        exit 0
+        ;;
+
+    "watchos")
+        build_combined Realm Realm watchos watchsimulator
+        exit 0
+        ;;
+
+    "watchos-swift")
+        sh build.sh watchos
+        build_combined RealmSwift RealmSwift watchos watchsimulator '' "/swift-$REALM_XCODE_VERSION"
+        copy_realm_framework watchos
+        exit 0
+        ;;
+
+    "tvos")
+        build_combined Realm Realm appletvos appletvsimulator
+        exit 0
+        ;;
+
+    "tvos-swift")
+        sh build.sh tvos
+        build_combined RealmSwift RealmSwift appletvos appletvsimulator '' "/swift-$REALM_XCODE_VERSION"
+        copy_realm_framework tvos
+        exit 0
+        ;;
+
+    "osx")
+        xc -scheme Realm -configuration "$CONFIGURATION"
+        clean_retrieve "build/DerivedData/Realm/Build/Products/$CONFIGURATION/Realm.framework" "build/osx" "Realm.framework"
+        exit 0
+        ;;
+
+    "osx-swift")
+        sh build.sh osx
+        xc -scheme RealmSwift -configuration "$CONFIGURATION" build
+        destination="build/osx/swift-$REALM_XCODE_VERSION"
+        clean_retrieve "build/DerivedData/Realm/Build/Products/$CONFIGURATION/RealmSwift.framework" "$destination" "RealmSwift.framework"
+        clean_retrieve "build/osx/Realm.framework" "$destination" "Realm.framework"
+        exit 0
+        ;;
+
+    "swiftui")
+        xc -scheme SwiftUITestHost -configuration $CONFIGURATION -sdk iphonesimulator build
+        ;;
+
+    "catalyst")
+        export REALM_SDKROOT=iphoneos
+        xc -scheme Realm -configuration "$CONFIGURATION" -destination variant='Mac Catalyst'
+        clean_retrieve "build/DerivedData/Realm/Build/Products/$CONFIGURATION-maccatalyst/Realm.framework" "build/catalyst" "Realm.framework"
+        ;;
+
+    "catalyst-swift")
+        sh build.sh catalyst
+        export REALM_SDKROOT=iphoneos
+        xc -scheme 'RealmSwift' -configuration "$CONFIGURATION" -destination variant='Mac Catalyst' build
+        destination="build/catalyst/swift-$REALM_XCODE_VERSION"
+        clean_retrieve "build/DerivedData/Realm/Build/Products/$CONFIGURATION-maccatalyst/RealmSwift.framework" "$destination" "RealmSwift.framework"
+        clean_retrieve "build/catalyst/Realm.framework" "$destination" "Realm.framework"
+        ;;
+
+    "xcframework")
+        # Build all of the requested frameworks
+        shift
+        PLATFORMS="${*:-osx ios watchos tvos catalyst}"
+        for platform in $PLATFORMS; do
+            sh build.sh "$platform-swift"
+        done
+
+        # Assemble them into xcframeworks
+        rm -rf build/*.xcframework
+        find build/DerivedData/Realm/Build/Products -name 'Realm.framework' \
+            | grep -v '\-static' \
+            | sed 's/.*/-framework &/' \
+            | xargs xcodebuild -create-xcframework -allow-internal-distribution -output build/Realm.xcframework
+        find build/DerivedData/Realm/Build/Products -name 'RealmSwift.framework' \
+            | sed 's/.*/-framework &/' \
+            | xargs xcodebuild -create-xcframework -allow-internal-distribution -output build/RealmSwift.xcframework
+
+        exit 0
+        ;;
+
+    ######################################
+    # Analysis
+    ######################################
+
+    "analyze-osx")
+        xc -scheme Realm -configuration "$CONFIGURATION" analyze
+        exit 0
+        ;;
+
+    ######################################
+    # Testing
+    ######################################
+    "test")
+        set +e # Run both sets of tests even if the first fails
+        failed=0
+        sh build.sh test-ios-static || failed=1
+        sh build.sh test-ios-dynamic || failed=1
+        sh build.sh test-ios-swift || failed=1
+        sh build.sh test-ios-devices || failed=1
+        sh build.sh test-tvos-devices || failed=1
+        sh build.sh test-osx || failed=1
+        sh build.sh test-osx-swift || failed=1
+        sh build.sh test-catalyst || failed=1
+        sh build.sh test-catalyst-swift || failed=1
+        exit $failed
+        ;;
+
+    "test-all")
+        set +e
+        failed=0
+        sh build.sh test || failed=1
+        sh build.sh test-debug || failed=1
+        exit $failed
+        ;;
+
+    "test-ios-static")
+        test_ios_static "name=iPhone 8"
+        exit 0
+        ;;
+
+    "test-ios-dynamic")
+        xctest Realm -configuration "$CONFIGURATION" -sdk iphonesimulator -destination 'name=iPhone 8'
+        exit 0
+        ;;
+
+    "test-ios-swift")
+        xctest RealmSwift -configuration "$CONFIGURATION" -sdk iphonesimulator -destination 'name=iPhone 8'
+        exit 0
+        ;;
+
+    "test-ios-devices")
+        failed=0
+        trap "failed=1" ERR
+        sh build.sh test-ios-devices-objc
+        sh build.sh test-ios-devices-swift
+        exit $failed
+        ;;
+
+    "test-ios-devices-objc")
+        test_devices iphoneos "Realm" "$CONFIGURATION"
+        exit $?
+        ;;
+
+    "test-ios-devices-swift")
+        test_devices iphoneos "RealmSwift" "$CONFIGURATION"
+        exit $?
+        ;;
+
+    "test-tvos")
+        destination="Apple TV"
+        xctest Realm -configuration "$CONFIGURATION" -sdk appletvsimulator -destination "name=$destination"
+        exit $?
+        ;;
+
+    "test-tvos-swift")
+        destination="Apple TV"
+        xctest RealmSwift -configuration "$CONFIGURATION" -sdk appletvsimulator -destination "name=$destination"
+        exit $?
+        ;;
+
+    "test-tvos-devices")
+        test_devices appletvos TestHost "$CONFIGURATION"
+        ;;
+
+    "test-osx")
+        COVERAGE_PARAMS=()
+        if [[ "$CONFIGURATION" == "Debug" ]]; then
+            COVERAGE_PARAMS=(GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES)
+        fi
+        xctest Realm -configuration "$CONFIGURATION" "${COVERAGE_PARAMS[@]}"
+        exit 0
+        ;;
+
+    "test-osx-swift")
+        xctest RealmSwift -configuration $CONFIGURATION
+        exit 0
+        ;;
+
+    "test-osx-object-server")
+        xctest 'Object Server Tests' -configuration "$CONFIGURATION" -sdk macosx
+        exit 0
+        ;;
+
+    test-swiftpm-ios)
+        cd examples/installation
+        sh build.sh test-ios-swift-spm
+        exit 0
+        ;;
+
+    test-swiftpm*)
+        SANITIZER=$(echo "$COMMAND" | cut -d - -f 3)
+        if [ -n "$SANITIZER" ]; then
+            SANITIZER="--sanitize $SANITIZER"
+            export ASAN_OPTIONS='check_initialization_order=true:detect_stack_use_after_return=true'
+        fi
+        xcrun swift package resolve
+        find .build -name views.cpp -delete
+        xcrun swift test --configuration "$(echo "$CONFIGURATION" | tr "[:upper:]" "[:lower:]")" $SANITIZER
+        exit 0
+        ;;
+
+    "test-swiftui-ios")
+        xctest 'SwiftUITestHost' -configuration "$CONFIGURATION" -sdk iphonesimulator -destination 'name=iPhone 8'
+        exit 0
+        ;;
+
+    "test-catalyst")
+        export REALM_SDKROOT=iphoneos
+        xctest Realm -configuration "$CONFIGURATION" -destination 'platform=macOS,variant=Mac Catalyst' CODE_SIGN_IDENTITY=''
+        exit 0
+        ;;
+
+    "test-catalyst-swift")
+        export REALM_SDKROOT=iphoneos
+        xctest RealmSwift -configuration "$CONFIGURATION" -destination 'platform=macOS,variant=Mac Catalyst' CODE_SIGN_IDENTITY=''
+        exit 0
+        ;;
+
+    ######################################
+    # Full verification
+    ######################################
+    "verify")
+        sh build.sh verify-cocoapods
+        sh build.sh verify-docs
+        sh build.sh verify-osx
+        sh build.sh verify-osx-debug
+        sh build.sh verify-osx-swift
+        sh build.sh verify-osx-swift-debug
+        sh build.sh verify-ios-static
+        sh build.sh verify-ios-static-debug
+        sh build.sh verify-ios-dynamic
+        sh build.sh verify-ios-dynamic-debug
+        sh build.sh verify-ios-swift
+        sh build.sh verify-ios-swift-debug
+        sh build.sh verify-ios-device-objc
+        sh build.sh verify-ios-device-swift
+        sh build.sh verify-watchos
+        sh build.sh verify-tvos
+        sh build.sh verify-tvos-debug
+        sh build.sh verify-tvos-device
+        sh build.sh verify-swiftlint
+        sh build.sh verify-swiftpm
+        sh build.sh verify-osx-object-server
+        sh build.sh verify-catalyst
+        sh build.sh verify-catalyst-swift
+        sh build.sh verify-swiftui-ios
+        ;;
+
+    "verify-cocoapods")
+        if [[ -d .git ]]; then
+          # Verify the current branch, unless one was already specified in the sha environment variable.
+          if [[ -z $sha ]]; then
+            export sha=$(git rev-parse --abbrev-ref HEAD)
+          fi
+
+          if [[ $(git log -1 '@{push}..') != "" ]] || ! git diff-index --quiet HEAD; then
+            echo "WARNING: verify-cocoapods will test the latest revision of $sha found on GitHub."
+            echo "         Any unpushed local changes will not be tested."
+            echo ""
+            sleep 1
+          fi
+        fi
+
+        sh build.sh verify-cocoapods-ios
+        sh build.sh verify-cocoapods-ios-dynamic
+        sh build.sh verify-cocoapods-osx
+        sh build.sh verify-cocoapods-watchos
+
+        # https://github.com/CocoaPods/CocoaPods/issues/7708
+        export EXPANDED_CODE_SIGN_IDENTITY=''
+        cd examples/installation
+        sh build.sh test-ios-objc-cocoapods
+        sh build.sh test-ios-objc-cocoapods-dynamic
+        sh build.sh test-ios-swift-cocoapods
+        sh build.sh test-osx-objc-cocoapods
+        sh build.sh test-osx-swift-cocoapods
+        sh build.sh test-catalyst-objc-cocoapods
+        sh build.sh test-catalyst-objc-cocoapods-dynamic
+        sh build.sh test-catalyst-swift-cocoapods
+        sh build.sh test-watchos-objc-cocoapods
+        sh build.sh test-watchos-swift-cocoapods
+        ;;
+
+    verify-cocoapods-ios-dynamic)
+        PLATFORM=$(echo "$COMMAND" | cut -d - -f 3)
+        # https://github.com/CocoaPods/CocoaPods/issues/7708
+        export EXPANDED_CODE_SIGN_IDENTITY=''
+        cd examples/installation
+        sh build.sh test-ios-objc-cocoapods-dynamic
+        ;;
+
+    verify-cocoapods-*)
+        PLATFORM=$(echo "$COMMAND" | cut -d - -f 3)
+        # https://github.com/CocoaPods/CocoaPods/issues/7708
+        export EXPANDED_CODE_SIGN_IDENTITY=''
+        cd examples/installation
+        sh build.sh "test-$PLATFORM-swift-cocoapods"
+        ;;
+
+    "verify-osx-encryption")
+        REALM_ENCRYPT_ALL=YES sh build.sh test-osx
+        exit 0
+        ;;
+
+    "verify-osx")
+        REALM_EXTRA_BUILD_ARGUMENTS="$REALM_EXTRA_BUILD_ARGUMENTS -workspace examples/osx/objc/RealmExamples.xcworkspace" \
+            sh build.sh test-osx
+        sh build.sh examples-osx
+
+        (
+            cd examples/osx/objc/build/DerivedData/RealmExamples/Build/Products/$CONFIGURATION
+            DYLD_FRAMEWORK_PATH=. ./JSONImport >/dev/null
+        )
+        exit 0
+        ;;
+
+    "verify-osx-swift")
+        sh build.sh test-osx-swift
+        exit 0
+        ;;
+
+    "verify-swiftui-ios")
+        sh build.sh test-swiftui-ios
+        exit 0
+        ;;
+
+    "verify-osx-swift-evolution")
+        export REALM_EXTRA_BUILD_ARGUMENTS="$REALM_EXTRA_BUILD_ARGUMENTS REALM_BUILD_LIBRARY_FOR_DISTRIBUTION=YES"
+        sh build.sh test-osx-swift
+        exit 0
+        ;;
+
+    "verify-ios-static")
+        REALM_EXTRA_BUILD_ARGUMENTS="$REALM_EXTRA_BUILD_ARGUMENTS -workspace examples/ios/objc/RealmExamples.xcworkspace" \
+            sh build.sh test-ios-static
+        sh build.sh examples-ios
+        ;;
+
+    "verify-ios-dynamic")
+        sh build.sh test-ios-dynamic
+        ;;
+
+    "verify-ios-swift")
+        REALM_EXTRA_BUILD_ARGUMENTS="$REALM_EXTRA_BUILD_ARGUMENTS -workspace examples/ios/swift/RealmExamples.xcworkspace" \
+            sh build.sh test-ios-swift
+        sh build.sh examples-ios-swift
+        ;;
+
+    "verify-ios-swift-evolution")
+        export REALM_EXTRA_BUILD_ARGUMENTS="$REALM_EXTRA_BUILD_ARGUMENTS REALM_BUILD_LIBRARY_FOR_DISTRIBUTION=YES"
+        sh build.sh test-ios-swift
+        exit 0
+        ;;
+
+    "verify-ios-device-objc")
+        sh build.sh test-ios-devices-objc
+        exit 0
+        ;;
+
+    "verify-ios-device-swift")
+        sh build.sh test-ios-devices-swift
+        exit 0
+        ;;
+
+    "verify-docs")
+        sh build.sh docs
+        for lang in swift objc; do
+            undocumented="docs/${lang}_output/undocumented.json"
+            if ruby -rjson -e "j = JSON.parse(File.read('docs/${lang}_output/undocumented.json')); exit j['warnings'].length != 0"; then
+              echo "Undocumented Realm $lang declarations:"
+              cat "$undocumented"
+              exit 1
+            fi
+        done
+        exit 0
+        ;;
+
+    "verify-watchos")
+        sh build.sh watchos-swift
+        exit 0
+        ;;
+
+    "verify-tvos")
+        REALM_EXTRA_BUILD_ARGUMENTS="$REALM_EXTRA_BUILD_ARGUMENTS -workspace examples/tvos/objc/RealmExamples.xcworkspace" \
+            sh build.sh test-tvos
+        sh build.sh examples-tvos
+        exit 0
+        ;;
+
+    "verify-tvos-swift")
+        REALM_EXTRA_BUILD_ARGUMENTS="$REALM_EXTRA_BUILD_ARGUMENTS -workspace examples/tvos/swift/RealmExamples.xcworkspace" \
+            sh build.sh test-tvos-swift
+        sh build.sh examples-tvos-swift
+        exit 0
+        ;;
+
+    "verify-tvos-swift-evolution")
+        export REALM_EXTRA_BUILD_ARGUMENTS="$REALM_EXTRA_BUILD_ARGUMENTS REALM_BUILD_LIBRARY_FOR_DISTRIBUTION=YES"
+        sh build.sh test-tvos-swift
+        exit 0
+        ;;
+
+    "verify-tvos-device")
+        sh build.sh test-tvos-devices
+        exit 0
+        ;;
+
+    "verify-swiftlint")
+        swiftlint lint --strict
+        exit 0
+        ;;
+
+    verify-swiftpm*)
+        sh build.sh "test-$(echo "$COMMAND" | cut -d - -f 2-)"
+        exit 0
+        ;;
+
+    "verify-osx-object-server")
+        sh build.sh test-osx-object-server
+        exit 0
+        ;;
+
+    "verify-catalyst")
+        sh build.sh test-catalyst
+        exit 0
+        ;;
+
+    "verify-catalyst-swift")
+        sh build.sh test-catalyst-swift
+        exit 0
+        ;;
+
+    "verify-xcframework")
+        sh build.sh xcframework
+        exit 0
+        ;;
+
+    ######################################
+    # Docs
+    ######################################
+    "docs")
+        build_docs objc
+        build_docs swift
+        exit 0
+        ;;
+
+    ######################################
+    # Examples
+    ######################################
+    "examples")
+        sh build.sh clean
+        sh build.sh prelaunch-simulator
+        export REALM_SKIP_PRELAUNCH=1
+        sh build.sh examples-ios
+        sh build.sh examples-ios-swift
+        sh build.sh examples-osx
+        sh build.sh examples-tvos
+        sh build.sh examples-tvos-swift
+        exit 0
+        ;;
+
+    "examples-ios")
+        workspace="examples/ios/objc/RealmExamples.xcworkspace"
+        pod install --project-directory="$workspace/.." --no-repo-update
+        examples="Simple TableView Migration Backlink GroupedTableView RACTableView Encryption Draw"
+        versions="0 1 2 3 4 5"
+        for example in $examples; do
+            if [ "$example" = "Migration" ]; then
+                # The migration example needs to be built for each schema version to ensure each compiles.
+                for version in $versions; do
+                    xc -workspace "$workspace" -scheme "$example" -configuration "$CONFIGURATION" -sdk iphonesimulator build ARCHS=x86_64 "${CODESIGN_PARAMS[@]}" GCC_PREPROCESSOR_DEFINITIONS="\$(GCC_PREPROCESSOR_DEFINITIONS) SCHEMA_VERSION_$version"
+                done
+            else
+                xc -workspace "$workspace" -scheme "$example" -configuration "$CONFIGURATION" -sdk iphonesimulator build ARCHS=x86_64 "${CODESIGN_PARAMS[@]}"
+            fi
+        done
+        if [ -n "${JENKINS_HOME}" ]; then
+            xc -workspace "$workspace" -scheme Extension -configuration "$CONFIGURATION" -sdk iphonesimulator build ARCHS=x86_64 "${CODESIGN_PARAMS[@]}"
+        fi
+
+        exit 0
+        ;;
+
+    "examples-ios-swift")
+        workspace="examples/ios/swift/RealmExamples.xcworkspace"
+        if [[ ! -d "$workspace" ]]; then
+            workspace="${workspace/swift/swift-$REALM_XCODE_VERSION}"
+        fi
+
+        examples="Simple TableView Migration Backlink GroupedTableView Encryption"
+        versions="0 1 2 3 4 5"
+        for example in $examples; do
+            if [ "$example" = "Migration" ]; then
+                # The migration example needs to be built for each schema version to ensure each compiles.
+                for version in $versions; do
+                    xc -workspace "$workspace" -scheme "$example" -configuration "$CONFIGURATION" -sdk iphonesimulator build ARCHS=x86_64 "${CODESIGN_PARAMS[@]}" OTHER_SWIFT_FLAGS="\$(OTHER_SWIFT_FLAGS) -DSCHEMA_VERSION_$version"
+                done
+            else
+                xc -workspace "$workspace" -scheme "$example" -configuration "$CONFIGURATION" -sdk iphonesimulator build ARCHS=x86_64 "${CODESIGN_PARAMS[@]}"
+            fi
+        done
+
+        exit 0
+        ;;
+
+    "examples-osx")
+        xc -workspace examples/osx/objc/RealmExamples.xcworkspace -scheme JSONImport -configuration "${CONFIGURATION}" build "${CODESIGN_PARAMS[@]}"
+        ;;
+
+    "examples-tvos")
+        workspace="examples/tvos/objc/RealmExamples.xcworkspace"
+        examples="DownloadCache PreloadedData"
+        for example in $examples; do
+            xc -workspace "$workspace" -scheme "$example" -configuration "$CONFIGURATION" -sdk appletvsimulator build ARCHS=x86_64 "${CODESIGN_PARAMS[@]}"
+        done
+
+        exit 0
+        ;;
+
+    "examples-tvos-swift")
+        workspace="examples/tvos/swift/RealmExamples.xcworkspace"
+        if [[ ! -d "$workspace" ]]; then
+            workspace="${workspace/swift/swift-$REALM_XCODE_VERSION}"
+        fi
+        examples="DownloadCache PreloadedData"
+        for example in $examples; do
+            xc -workspace "$workspace" -scheme "$example" -configuration "$CONFIGURATION" -sdk appletvsimulator build ARCHS=x86_64 "${CODESIGN_PARAMS[@]}"
+        done
+
+        exit 0
+        ;;
+
+    ######################################
+    # Versioning
+    ######################################
+    "get-version")
+        plist_get 'Realm/Realm-Info.plist' 'CFBundleShortVersionString'
+        exit 0
+        ;;
+
+    "set-version")
+        realm_version="$2"
+        version_files="Realm/Realm-Info.plist"
+
+        if [ -z "$realm_version" ]; then
+            echo "You must specify a version."
+            exit 1
+        fi
+        # The bundle version can contain only three groups of digits separated by periods,
+        # so strip off any -beta.x tag from the end of the version string.
+        bundle_version=$(echo "$realm_version" | cut -d - -f 1)
+        for version_file in $version_files; do
+            PlistBuddy -c "Set :CFBundleVersion $bundle_version" "$version_file"
+            PlistBuddy -c "Set :CFBundleShortVersionString $realm_version" "$version_file"
+        done
+        sed -i '' "s/^VERSION=.*/VERSION=$realm_version/" dependencies.list
+        sed -i '' "s/^let coreVersionStr =.*/let coreVersionStr = \"$REALM_CORE_VERSION\"/" Package.swift
+        sed -i '' "s/^let cocoaVersionStr =.*/let cocoaVersionStr = \"$realm_version\"/" Package.swift
+        sed -i '' "s/x.y.z Release notes (yyyy-MM-dd)/$realm_version Release notes ($(date '+%Y-%m-%d'))/" CHANGELOG.md
+
+        exit 0
+        ;;
+
+    ######################################
+    # Bitcode Detection
+    ######################################
+
+    "binary-has-bitcode")
+        # Disable pipefail as grep -q will make otool fail due to exiting
+        # before reading all the output
+        set +o pipefail
+
+        BINARY="$2"
+        if otool -l "$BINARY" | grep -q "segname __LLVM"; then
+            exit 0
+        fi
+        # Work around rdar://21826157 by checking for bitcode in thin binaries
+
+        # Get architectures for binary
+        archs="$(lipo -info "$BINARY" | rev | cut -d ':' -f1 | rev)"
+
+        archs_array=( $archs )
+        if [[ ${#archs_array[@]} -lt 2 ]]; then
+            echo 'Error: Built library is not a fat binary'
+            exit 1 # Early exit if not a fat binary
+        fi
+
+        TEMPDIR=$(mktemp -d $TMPDIR/realm-bitcode-check.XXXX)
+
+        for arch in $archs; do
+            lipo -thin "$arch" "$BINARY" -output "$TEMPDIR/$arch"
+            if otool -l "$TEMPDIR/$arch" | grep -q "segname __LLVM"; then
+                exit 0
+            fi
+        done
+        echo 'Error: Built library does not contain bitcode'
+        exit 1
+        ;;
+
+    ######################################
+    # CocoaPods
+    ######################################
+    "cocoapods-setup")
+        if [ ! -f core/version.txt ]; then
+          sh build.sh download-core
+        fi
+
+        rm -rf include
+        mkdir -p include
+        cp -R core/realm-monorepo.xcframework/ios-armv7_arm64/Headers include/core
+
+        mkdir -p include
+        echo '' > Realm/RLMPlatform.h
+        cp Realm/*.h Realm/*.hpp include
+        ;;
+
+    ######################################
+    # Continuous Integration
+    ######################################
+
+    "ci-pr")
+        mkdir -p build/reports
+        export REALM_DISABLE_ANALYTICS=1
+        export REALM_DISABLE_UPDATE_CHECKER=1
+        # FIXME: Re-enable once CI can properly unlock the keychain
+        export REALM_DISABLE_METADATA_ENCRYPTION=1
+
+        # Make sure there aren't any lingering server processes from previous jobs
+        pkill -9 mongo stitch || true
+
+        # strip off the ios|tvos version specifier, e.g. the last part of: `ios-device-objc-ios8`
+        if [[ "$target" =~ ^((ios|tvos)-device(-(objc|swift))?)(-(ios|tvos)[[:digit:]]+)?$ ]]; then
+            export target=${BASH_REMATCH[1]}
+        fi
+
+        if [ "$target" = "docs" ]; then
+            sh build.sh verify-docs
+        elif [ "$target" = "swiftlint" ]; then
+            sh build.sh verify-swiftlint
+        else
+            export sha=$GITHUB_PR_SOURCE_BRANCH
+            export REALM_EXTRA_BUILD_ARGUMENTS='GCC_GENERATE_DEBUGGING_SYMBOLS=NO -allowProvisioningUpdates'
+            if [[ "$target" = *ios* ]] || [[ "$target" = *tvos* ]] || [[ "$target" = *watchos* ]]; then
+                sh build.sh prelaunch-simulator "$target"
+            fi
+            export REALM_SKIP_PRELAUNCH=1
+
+            if [[ "$target" = *"server"* ]] || [[ "$target" = "swiftpm"* ]]; then
+                source "$(brew --prefix nvm)/nvm.sh" --no-use
+                nvm install 8.11.2
+                sh build.sh setup-baas
+            fi
+
+            # Reset CoreSimulator.log
+            mkdir -p ~/Library/Logs/CoreSimulator
+            echo > ~/Library/Logs/CoreSimulator/CoreSimulator.log
+
+            failed=0
+            sh build.sh "verify-$target" 2>&1 | tee build/build.log | xcpretty -r junit -o build/reports/junit.xml || failed=1
+            if [ "$failed" = "1" ] && grep -E 'DTXProxyChannel|DTXChannel|out of date and needs to be rebuilt|operation never finished bootstrapping' build/build.log ; then
+                echo "Known Xcode error detected. Running job again."
+                if grep -E 'out of date and needs to be rebuilt' build/build.log; then
+                    rm -rf build/DerivedData
+                fi
+                failed=0
+                sh build.sh "verify-$target" | tee build/build.log | xcpretty -r junit -o build/reports/junit.xml || failed=1
+            elif [ "$failed" = "1" ] && tail ~/Library/Logs/CoreSimulator/CoreSimulator.log | grep -E "Operation not supported|Failed to lookup com.apple.coreservices.lsuseractivity.simulatorsupport"; then
+                echo "Known Xcode error detected. Running job again."
+                failed=0
+                sh build.sh "verify-$target" | tee build/build.log | xcpretty -r junit -o build/reports/junit.xml || failed=1
+            fi
+            if [ "$failed" = "1" ]; then
+                set +e
+                printf "%s" "\n\n***\nbuild/build.log\n***\n\n" && cat build/build.log
+                printf "%s" "\n\n***\nCoreSimulator.log\n***\n\n" && cat ~/Library/Logs/CoreSimulator/CoreSimulator.log
+                exit 1
+            fi
+        fi
+
+        if [ "$target" = "osx" ] && [ "$configuration" = "Debug" ]; then
+          gcovr -r . -f ".*Realm.*" -e ".*Tests.*" -e ".*core.*" --xml > build/reports/coverage-report.xml
+          WS=$(pwd | sed "s/\//\\\\\//g")
+          sed -i ".bak" "s/<source>\./<source>${WS}/" build/reports/coverage-report.xml
+        fi
+        ;;
+
+    ######################################
+    # Release packaging
+    ######################################
+
+    "package-examples")
+        ./scripts/package_examples.rb
+        zip --symlinks -r realm-examples.zip examples -x "examples/installation/*"
+        ;;
+
+    "package-test-examples-objc")
+        if ! VERSION=$(echo realm-objc-*.zip | grep -E -o '\d*\.\d*\.\d*-[a-z]*(\.\d*)?'); then
+            VERSION=$(echo realm-objc-*.zip | grep -E -o '\d*\.\d*\.\d*')
+        fi
+        OBJC="realm-objc-${VERSION}"
+        unzip "${OBJC}.zip"
+
+        cp "$0" "${OBJC}"
+        cp -r "${source_root}/scripts" "${OBJC}"
+        cd "${OBJC}"
+        sh build.sh examples-ios
+        sh build.sh examples-tvos
+        sh build.sh examples-osx
+        cd ..
+        rm -rf "${OBJC}"
+        ;;
+
+    "package-test-examples-swift")
+        if ! VERSION=$(echo realm-swift-*.zip | grep -E -o '\d*\.\d*\.\d*-[a-z]*(\.\d*)?'); then
+            VERSION=$(echo realm-swift-*.zip | grep -E -o '\d*\.\d*\.\d*')
+        fi
+        SWIFT="realm-swift-${VERSION}"
+        unzip "${SWIFT}.zip"
+
+        cp "$0" "${SWIFT}"
+        cp -r "${source_root}/scripts" "${SWIFT}"
+        cd "${SWIFT}"
+        sh build.sh examples-ios-swift
+        sh build.sh examples-tvos-swift
+        cd ..
+        rm -rf "${SWIFT}"
+        ;;
+
+    "package-ios-static")
+        sh build.sh prelaunch-simulator
+        sh build.sh ios-static
+
+        cd build/ios-static
+        zip --symlinks -r realm-framework-ios-static.zip Realm.xcframework
+        ;;
+
+    "package")
+        PLATFORM="$2"
+        REALM_SWIFT_VERSION=
+
+        set_xcode_and_swift_versions
+
+        sh build.sh "$PLATFORM-swift"
+
+        cd "build/$PLATFORM"
+        zip --symlinks -r "realm-framework-$PLATFORM-$REALM_XCODE_VERSION.zip" "swift-$REALM_XCODE_VERSION"
+        ;;
+
+    "package-release")
+        LANG="$2"
+        tempdir="$(mktemp -d "$TMPDIR"/realm-release-package-"${LANG}".XXXX)"
+        extract_dir="$(mktemp -d "$TMPDIR"/realm-release-package-"${LANG}".XXXX)"
+        version="$(sh build.sh get-version)"
+        package_dir="${tempdir}/realm-${LANG}-${version}"
+
+        mkdir -p "${package_dir}"
+
+        if [[ "${LANG}" == "objc" ]]; then
+            mkdir -p "${extract_dir}"
+            unzip "${WORKSPACE}/realm-framework-ios-static.zip" -d "${package_dir}/ios-static"
+            for platform in osx ios watchos tvos catalyst; do
+                unzip "${WORKSPACE}/realm-framework-${platform}-${REALM_XCODE_VERSION}.zip" -d "${extract_dir}/${platform}"
+            done
+            find "${extract_dir}" -name 'Realm.framework' \
+                | sed 's/.*/-framework &/' \
+                | xargs xcodebuild -create-xcframework -allow-internal-distribution -output "${package_dir}/Realm.xcframework"
+
+            cp "${WORKSPACE}/Realm/Swift/RLMSupport.swift" "${package_dir}"
+            rm -r "${extract_dir}"
+        else
+            xcode_versions=$(find . -name 'realm-framework-*-1*' | sed 's@./realm-framework-[a-z]*-\(.*\).zip@\1@' | sort -u)
+            for xcode_version in $xcode_versions; do
+                mkdir -p "${extract_dir}"
+                for platform in osx ios watchos tvos catalyst; do
+                    unzip "realm-framework-$platform-$xcode_version.zip" -d "${extract_dir}/${platform}"
+                done
+                find "${extract_dir}" -name 'Realm.framework' \
+                    | sed 's/.*/-framework &/' \
+                    | xargs xcodebuild -create-xcframework -allow-internal-distribution -output "${package_dir}/${xcode_version}/Realm.xcframework"
+                find "${extract_dir}" -name 'RealmSwift.framework' \
+                    | sed 's/.*/-framework &/' \
+                    | xargs xcodebuild -create-xcframework -allow-internal-distribution -output "${package_dir}/${xcode_version}/RealmSwift.xcframework"
+                rm -r "${extract_dir}"
+            done
+        fi
+
+        (
+            cd "${WORKSPACE}"
+            cp -R plugin LICENSE "${package_dir}"
+        )
+
+        (
+            cd "${package_dir}"
+            unzip "${WORKSPACE}/realm-examples.zip"
+            cd examples
+            if [[ "${LANG}" == "objc" ]]; then
+                rm -rf ios/swift-* tvos/swift-*
+            else
+                rm -rf ios/objc osx tvos/objc
+            fi
+        )
+
+        cat > "${package_dir}"/docs.webloc <<EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+    <key>URL</key>
+    <string>https://realm.io/docs/${LANG}/${version}</string>
+</dict>
+</plist>
+EOF
+
+        (
+          cd "${tempdir}"
+          zip --symlinks -r "realm-${LANG}-${version}.zip" "realm-${LANG}-${version}"
+          mv "realm-${LANG}-${version}.zip" "${WORKSPACE}"
+        )
+        ;;
+
+    "test-package-release")
+        # Generate a release package locally for testing purposes
+        # Real releases should always be done via Jenkins
+        if [ -z "${WORKSPACE}" ]; then
+            echo 'WORKSPACE must be set to a directory to assemble the release in'
+            exit 1
+        fi
+        if [ -d "${WORKSPACE}" ]; then
+            echo 'WORKSPACE directory should not already exist'
+            exit 1
+        fi
+
+        REALM_SOURCE="$(pwd)"
+        mkdir -p "$WORKSPACE"
+        WORKSPACE="$(cd "$WORKSPACE" && pwd)"
+        export WORKSPACE
+        cd "$WORKSPACE"
+        git clone --recursive "$REALM_SOURCE" realm-cocoa
+        cd realm-cocoa
+
+        echo 'Packaging iOS'
+        sh build.sh package-ios-static
+        cp build/ios-static/realm-framework-ios-static.zip .
+        sh build.sh package ios
+        cp "build/ios/realm-framework-ios-$REALM_XCODE_VERSION.zip" .
+
+        echo 'Packaging macOS'
+        sh build.sh package osx
+        cp "build/osx/realm-framework-osx-$REALM_XCODE_VERSION.zip" .
+
+        echo 'Packaging watchOS'
+        sh build.sh package watchos
+        cp "build/watchos/realm-framework-watchos-$REALM_XCODE_VERSION.zip" .
+
+        echo 'Packaging tvOS'
+        sh build.sh package tvos
+        cp "build/tvos/realm-framework-tvos-$REALM_XCODE_VERSION.zip" .
+
+        echo 'Packaging Catalyst'
+        sh build.sh package catalyst
+        cp "build/catalyst/realm-framework-catalyst-$REALM_XCODE_VERSION.zip" .
+
+        echo 'Packaging examples'
+        sh build.sh package-examples
+
+        echo 'Building final release packages'
+        export WORKSPACE="${WORKSPACE}/realm-cocoa"
+        sh build.sh package-release objc
+        sh build.sh package-release swift
+
+        echo 'Testing packaged examples'
+        sh build.sh package-test-examples-objc
+        sh build.sh package-test-examples-swift
+        ;;
+
+    "github-release")
+        if [ -z "${GITHUB_ACCESS_TOKEN}" ]; then
+            echo 'GITHUB_ACCESS_TOKEN must be set to create GitHub releases'
+            exit 1
+        fi
+        ./scripts/github_release.rb
+        ;;
+
+    "add-empty-changelog")
+        empty_section=$(cat <<EOS
+x.y.z Release notes (yyyy-MM-dd)
+=============================================================
+### Enhancements
+* None.
+
+### Fixed
+* <How to hit and notice issue? what was the impact?> ([#????](https://github.com/realm/realm-cocoa/issues/????), since v?.?.?)
+* None.
+
+<!-- ### Breaking Changes - ONLY INCLUDE FOR NEW MAJOR version -->
+
+### Compatibility
+* Realm Studio: 10.0.0 or later.
+* APIs are backwards compatible with all previous releases in the 10.x.y series.
+* Carthage release for Swift is built with Xcode 12.5.
+* CocoaPods: 1.10 or later.
+
+### Internal
+* Upgraded realm-core from ? to ?
+
+EOS)
+        changelog=$(cat CHANGELOG.md)
+        echo "$empty_section" > CHANGELOG.md
+        echo >> CHANGELOG.md
+        echo "$changelog" >> CHANGELOG.md
+        ;;
+
+    *)
+        echo "Unknown command '$COMMAND'"
+        usage
+        exit 1
+        ;;
+esac

+ 126 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/Info.plist

@@ -0,0 +1,126 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>AvailableLibraries</key>
+	<array>
+		<dict>
+			<key>HeadersPath</key>
+			<string>Headers</string>
+			<key>LibraryIdentifier</key>
+			<string>macos-x86_64_arm64</string>
+			<key>LibraryPath</key>
+			<string>librealm-monorepo.a</string>
+			<key>SupportedArchitectures</key>
+			<array><string>x86_64</string>
+<string>arm64</string></array>
+			<key>SupportedPlatform</key>
+			<string>macos</string>
+		</dict>
+		<dict>
+			<key>HeadersPath</key>
+			<string>Headers</string>
+			<key>LibraryIdentifier</key>
+			<string>ios-armv7_arm64</string>
+			<key>LibraryPath</key>
+			<string>librealm-monorepo.a</string>
+			<key>SupportedArchitectures</key>
+			<array><string>armv7</string>
+<string>arm64</string></array>
+			<key>SupportedPlatform</key>
+			<string>ios</string>
+		</dict>
+		<dict>
+			<key>HeadersPath</key>
+			<string>Headers</string>
+			<key>LibraryIdentifier</key>
+			<string>ios-arm64_i386_x86_64-simulator</string>
+			<key>LibraryPath</key>
+			<string>librealm-monorepo.a</string>
+			<key>SupportedArchitectures</key>
+			<array><string>arm64</string>
+<string>i386</string>
+<string>x86_64</string></array>
+			<key>SupportedPlatform</key>
+			<string>ios</string>
+			<key>SupportedPlatformVariant</key>
+			<string>simulator</string>
+		</dict>
+		<dict>
+			<key>HeadersPath</key>
+			<string>Headers</string>
+			<key>LibraryIdentifier</key>
+			<string>ios-x86_64_arm64-maccatalyst</string>
+			<key>LibraryPath</key>
+			<string>librealm-monorepo.a</string>
+			<key>SupportedArchitectures</key>
+			<array><string>x86_64</string>
+<string>arm64</string></array>
+			<key>SupportedPlatform</key>
+			<string>ios</string>
+			<key>SupportedPlatformVariant</key>
+			<string>maccatalyst</string>
+		</dict>
+		<dict>
+			<key>HeadersPath</key>
+			<string>Headers</string>
+			<key>LibraryIdentifier</key>
+			<string>watchos-armv7k_arm64_32</string>
+			<key>LibraryPath</key>
+			<string>librealm-monorepo.a</string>
+			<key>SupportedArchitectures</key>
+			<array><string>armv7k</string>
+<string>arm64_32</string></array>
+			<key>SupportedPlatform</key>
+			<string>watchos</string>
+		</dict>
+		<dict>
+			<key>HeadersPath</key>
+			<string>Headers</string>
+			<key>LibraryIdentifier</key>
+			<string>watchos-arm64_i386_x86_64-simulator</string>
+			<key>LibraryPath</key>
+			<string>librealm-monorepo.a</string>
+			<key>SupportedArchitectures</key>
+			<array><string>arm64</string>
+<string>i386</string>
+<string>x86_64</string></array>
+			<key>SupportedPlatform</key>
+			<string>watchos</string>
+			<key>SupportedPlatformVariant</key>
+			<string>simulator</string>
+		</dict>
+		<dict>
+			<key>HeadersPath</key>
+			<string>Headers</string>
+			<key>LibraryIdentifier</key>
+			<string>tvos-arm64</string>
+			<key>LibraryPath</key>
+			<string>librealm-monorepo.a</string>
+			<key>SupportedArchitectures</key>
+			<array><string>arm64</string></array>
+			<key>SupportedPlatform</key>
+			<string>tvos</string>
+		</dict>
+		<dict>
+			<key>HeadersPath</key>
+			<string>Headers</string>
+			<key>LibraryIdentifier</key>
+			<string>tvos-arm64_x86_64-simulator</string>
+			<key>LibraryPath</key>
+			<string>librealm-monorepo.a</string>
+			<key>SupportedArchitectures</key>
+			<array><string>arm64</string>
+<string>x86_64</string></array>
+			<key>SupportedPlatform</key>
+			<string>tvos</string>
+			<key>SupportedPlatformVariant</key>
+			<string>simulator</string>
+		</dict>
+	</array>
+	<key>CFBundlePackageType</key>
+	<string>XFWK</string>
+	<key>XCFrameworkFormatVersion</key>
+	<string>1.0</string>
+</dict>
+</plist>

+ 22875 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/external/json/json.hpp

@@ -0,0 +1,22875 @@
+/*
+    __ _____ _____ _____
+ __|  |   __|     |   | |  JSON for Modern C++
+|  |  |__   |  |  | | | |  version 3.7.3
+|_____|_____|_____|_|___|  https://github.com/nlohmann/json
+
+Licensed under the MIT License <http://opensource.org/licenses/MIT>.
+SPDX-License-Identifier: MIT
+Copyright (c) 2013-2019 Niels Lohmann <http://nlohmann.me>.
+
+Permission is hereby  granted, free of charge, to any  person obtaining a copy
+of this software and associated  documentation files (the "Software"), to deal
+in the Software  without restriction, including without  limitation the rights
+to  use, copy,  modify, merge,  publish, distribute,  sublicense, and/or  sell
+copies  of  the Software,  and  to  permit persons  to  whom  the Software  is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE  IS PROVIDED "AS  IS", WITHOUT WARRANTY  OF ANY KIND,  EXPRESS OR
+IMPLIED,  INCLUDING BUT  NOT  LIMITED TO  THE  WARRANTIES OF  MERCHANTABILITY,
+FITNESS FOR  A PARTICULAR PURPOSE AND  NONINFRINGEMENT. IN NO EVENT  SHALL THE
+AUTHORS  OR COPYRIGHT  HOLDERS  BE  LIABLE FOR  ANY  CLAIM,  DAMAGES OR  OTHER
+LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE  OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+#ifndef INCLUDE_NLOHMANN_JSON_HPP_
+#define INCLUDE_NLOHMANN_JSON_HPP_
+
+#define NLOHMANN_JSON_VERSION_MAJOR 3
+#define NLOHMANN_JSON_VERSION_MINOR 7
+#define NLOHMANN_JSON_VERSION_PATCH 3
+
+#include <algorithm> // all_of, find, for_each
+#include <cassert> // assert
+#include <ciso646> // and, not, or
+#include <cstddef> // nullptr_t, ptrdiff_t, size_t
+#include <functional> // hash, less
+#include <initializer_list> // initializer_list
+#include <iosfwd> // istream, ostream
+#include <iterator> // random_access_iterator_tag
+#include <memory> // unique_ptr
+#include <numeric> // accumulate
+#include <string> // string, stoi, to_string
+#include <utility> // declval, forward, move, pair, swap
+#include <vector> // vector
+
+// #include <nlohmann/adl_serializer.hpp>
+
+
+#include <utility>
+
+// #include <nlohmann/detail/conversions/from_json.hpp>
+
+
+#include <algorithm> // transform
+#include <array> // array
+#include <ciso646> // and, not
+#include <forward_list> // forward_list
+#include <iterator> // inserter, front_inserter, end
+#include <map> // map
+#include <string> // string
+#include <tuple> // tuple, make_tuple
+#include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
+#include <unordered_map> // unordered_map
+#include <utility> // pair, declval
+#include <valarray> // valarray
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+
+#include <exception> // exception
+#include <stdexcept> // runtime_error
+#include <string> // to_string
+
+// #include <nlohmann/detail/input/position_t.hpp>
+
+
+#include <cstddef> // size_t
+
+namespace nlohmann
+{
+namespace detail
+{
+/// struct to capture the start position of the current token
+struct position_t
+{
+    /// the total number of characters read
+    std::size_t chars_read_total = 0;
+    /// the number of characters read in the current line
+    std::size_t chars_read_current_line = 0;
+    /// the number of lines read
+    std::size_t lines_read = 0;
+
+    /// conversion to size_t to preserve SAX interface
+    constexpr operator size_t() const
+    {
+        return chars_read_total;
+    }
+};
+
+} // namespace detail
+} // namespace nlohmann
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+#include <utility> // pair
+// #include <nlohmann/thirdparty/hedley/hedley.hpp>
+/* Hedley - https://nemequ.github.io/hedley
+ * Created by Evan Nemerson <evan@nemerson.com>
+ *
+ * To the extent possible under law, the author(s) have dedicated all
+ * copyright and related and neighboring rights to this software to
+ * the public domain worldwide. This software is distributed without
+ * any warranty.
+ *
+ * For details, see <http://creativecommons.org/publicdomain/zero/1.0/>.
+ * SPDX-License-Identifier: CC0-1.0
+ */
+
+#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 11)
+#if defined(JSON_HEDLEY_VERSION)
+    #undef JSON_HEDLEY_VERSION
+#endif
+#define JSON_HEDLEY_VERSION 11
+
+#if defined(JSON_HEDLEY_STRINGIFY_EX)
+    #undef JSON_HEDLEY_STRINGIFY_EX
+#endif
+#define JSON_HEDLEY_STRINGIFY_EX(x) #x
+
+#if defined(JSON_HEDLEY_STRINGIFY)
+    #undef JSON_HEDLEY_STRINGIFY
+#endif
+#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x)
+
+#if defined(JSON_HEDLEY_CONCAT_EX)
+    #undef JSON_HEDLEY_CONCAT_EX
+#endif
+#define JSON_HEDLEY_CONCAT_EX(a,b) a##b
+
+#if defined(JSON_HEDLEY_CONCAT)
+    #undef JSON_HEDLEY_CONCAT
+#endif
+#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b)
+
+#if defined(JSON_HEDLEY_VERSION_ENCODE)
+    #undef JSON_HEDLEY_VERSION_ENCODE
+#endif
+#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
+
+#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
+    #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
+#endif
+#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
+
+#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
+    #undef JSON_HEDLEY_VERSION_DECODE_MINOR
+#endif
+#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
+
+#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
+    #undef JSON_HEDLEY_VERSION_DECODE_REVISION
+#endif
+#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
+
+#if defined(JSON_HEDLEY_GNUC_VERSION)
+    #undef JSON_HEDLEY_GNUC_VERSION
+#endif
+#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
+    #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
+#elif defined(__GNUC__)
+    #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
+    #undef JSON_HEDLEY_GNUC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_GNUC_VERSION)
+    #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_MSVC_VERSION)
+    #undef JSON_HEDLEY_MSVC_VERSION
+#endif
+#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000)
+    #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
+#elif defined(_MSC_FULL_VER)
+    #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
+#elif defined(_MSC_VER)
+    #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
+#endif
+
+#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
+    #undef JSON_HEDLEY_MSVC_VERSION_CHECK
+#endif
+#if !defined(_MSC_VER)
+    #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0)
+#elif defined(_MSC_VER) && (_MSC_VER >= 1400)
+    #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
+#elif defined(_MSC_VER) && (_MSC_VER >= 1200)
+    #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
+#else
+    #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))
+#endif
+
+#if defined(JSON_HEDLEY_INTEL_VERSION)
+    #undef JSON_HEDLEY_INTEL_VERSION
+#endif
+#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE)
+    #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
+#elif defined(__INTEL_COMPILER)
+    #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
+#endif
+
+#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
+    #undef JSON_HEDLEY_INTEL_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_INTEL_VERSION)
+    #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_PGI_VERSION)
+    #undef JSON_HEDLEY_PGI_VERSION
+#endif
+#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
+    #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
+#endif
+
+#if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
+    #undef JSON_HEDLEY_PGI_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_PGI_VERSION)
+    #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_SUNPRO_VERSION)
+    #undef JSON_HEDLEY_SUNPRO_VERSION
+#endif
+#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
+    #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10)
+#elif defined(__SUNPRO_C)
+    #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
+#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
+    #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10)
+#elif defined(__SUNPRO_CC)
+    #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
+#endif
+
+#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
+    #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_SUNPRO_VERSION)
+    #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
+    #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
+#endif
+#if defined(__EMSCRIPTEN__)
+    #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
+#endif
+
+#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
+    #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
+    #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_ARM_VERSION)
+    #undef JSON_HEDLEY_ARM_VERSION
+#endif
+#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
+    #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100)
+#elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
+    #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
+#endif
+
+#if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
+    #undef JSON_HEDLEY_ARM_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_ARM_VERSION)
+    #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_IBM_VERSION)
+    #undef JSON_HEDLEY_IBM_VERSION
+#endif
+#if defined(__ibmxl__)
+    #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
+#elif defined(__xlC__) && defined(__xlC_ver__)
+    #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
+#elif defined(__xlC__)
+    #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
+#endif
+
+#if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
+    #undef JSON_HEDLEY_IBM_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_IBM_VERSION)
+    #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_VERSION)
+    #undef JSON_HEDLEY_TI_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__)
+    #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
+#endif
+
+#if defined(JSON_HEDLEY_TI_VERSION_CHECK)
+    #undef JSON_HEDLEY_TI_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_VERSION)
+    #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_CRAY_VERSION)
+    #undef JSON_HEDLEY_CRAY_VERSION
+#endif
+#if defined(_CRAYC)
+    #if defined(_RELEASE_PATCHLEVEL)
+        #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
+    #else
+        #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
+    #endif
+#endif
+
+#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
+    #undef JSON_HEDLEY_CRAY_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_CRAY_VERSION)
+    #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_IAR_VERSION)
+    #undef JSON_HEDLEY_IAR_VERSION
+#endif
+#if defined(__IAR_SYSTEMS_ICC__)
+    #if __VER__ > 1000
+        #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
+    #else
+        #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(VER / 100, __VER__ % 100, 0)
+    #endif
+#endif
+
+#if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
+    #undef JSON_HEDLEY_IAR_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_IAR_VERSION)
+    #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TINYC_VERSION)
+    #undef JSON_HEDLEY_TINYC_VERSION
+#endif
+#if defined(__TINYC__)
+    #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
+#endif
+
+#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
+    #undef JSON_HEDLEY_TINYC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TINYC_VERSION)
+    #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_DMC_VERSION)
+    #undef JSON_HEDLEY_DMC_VERSION
+#endif
+#if defined(__DMC__)
+    #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
+#endif
+
+#if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
+    #undef JSON_HEDLEY_DMC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_DMC_VERSION)
+    #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_COMPCERT_VERSION)
+    #undef JSON_HEDLEY_COMPCERT_VERSION
+#endif
+#if defined(__COMPCERT_VERSION__)
+    #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
+#endif
+
+#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
+    #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_COMPCERT_VERSION)
+    #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_PELLES_VERSION)
+    #undef JSON_HEDLEY_PELLES_VERSION
+#endif
+#if defined(__POCC__)
+    #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
+#endif
+
+#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
+    #undef JSON_HEDLEY_PELLES_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_PELLES_VERSION)
+    #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_VERSION)
+    #undef JSON_HEDLEY_GCC_VERSION
+#endif
+#if \
+    defined(JSON_HEDLEY_GNUC_VERSION) && \
+    !defined(__clang__) && \
+    !defined(JSON_HEDLEY_INTEL_VERSION) && \
+    !defined(JSON_HEDLEY_PGI_VERSION) && \
+    !defined(JSON_HEDLEY_ARM_VERSION) && \
+    !defined(JSON_HEDLEY_TI_VERSION) && \
+    !defined(__COMPCERT__)
+    #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
+#endif
+
+#if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
+    #undef JSON_HEDLEY_GCC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_GCC_VERSION)
+    #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
+    #undef JSON_HEDLEY_HAS_ATTRIBUTE
+#endif
+#if defined(__has_attribute)
+    #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
+#else
+    #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
+    #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
+#endif
+#if defined(__has_attribute)
+    #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
+    #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
+#endif
+#if defined(__has_attribute)
+    #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
+#else
+    #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
+    #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
+#endif
+#if \
+    defined(__has_cpp_attribute) && \
+    defined(__cplusplus) && \
+    (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0))
+    #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
+#else
+    #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS)
+    #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
+#endif
+#if !defined(__cplusplus) || !defined(__has_cpp_attribute)
+    #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
+#elif \
+    !defined(JSON_HEDLEY_PGI_VERSION) && \
+    (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \
+    (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0))
+    #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute)
+#else
+    #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
+    #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
+#endif
+#if defined(__has_cpp_attribute) && defined(__cplusplus)
+    #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
+    #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
+#endif
+#if defined(__has_cpp_attribute) && defined(__cplusplus)
+    #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
+#else
+    #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_BUILTIN)
+    #undef JSON_HEDLEY_HAS_BUILTIN
+#endif
+#if defined(__has_builtin)
+    #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
+#else
+    #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
+    #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
+#endif
+#if defined(__has_builtin)
+    #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
+    #undef JSON_HEDLEY_GCC_HAS_BUILTIN
+#endif
+#if defined(__has_builtin)
+    #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
+#else
+    #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_FEATURE)
+    #undef JSON_HEDLEY_HAS_FEATURE
+#endif
+#if defined(__has_feature)
+    #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
+#else
+    #define JSON_HEDLEY_HAS_FEATURE(feature) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
+    #undef JSON_HEDLEY_GNUC_HAS_FEATURE
+#endif
+#if defined(__has_feature)
+    #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
+    #undef JSON_HEDLEY_GCC_HAS_FEATURE
+#endif
+#if defined(__has_feature)
+    #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
+#else
+    #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_EXTENSION)
+    #undef JSON_HEDLEY_HAS_EXTENSION
+#endif
+#if defined(__has_extension)
+    #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
+#else
+    #define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
+    #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
+#endif
+#if defined(__has_extension)
+    #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
+    #undef JSON_HEDLEY_GCC_HAS_EXTENSION
+#endif
+#if defined(__has_extension)
+    #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
+#else
+    #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
+    #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
+#endif
+#if defined(__has_declspec_attribute)
+    #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
+#else
+    #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
+    #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
+#endif
+#if defined(__has_declspec_attribute)
+    #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
+    #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
+#endif
+#if defined(__has_declspec_attribute)
+    #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
+#else
+    #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_WARNING)
+    #undef JSON_HEDLEY_HAS_WARNING
+#endif
+#if defined(__has_warning)
+    #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
+#else
+    #define JSON_HEDLEY_HAS_WARNING(warning) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
+    #undef JSON_HEDLEY_GNUC_HAS_WARNING
+#endif
+#if defined(__has_warning)
+    #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_WARNING)
+    #undef JSON_HEDLEY_GCC_HAS_WARNING
+#endif
+#if defined(__has_warning)
+    #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
+#else
+    #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for
+   HEDLEY INTERNAL USE ONLY.  API subject to change without notice. */
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
+    #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
+#endif
+#if defined(__cplusplus) && JSON_HEDLEY_HAS_WARNING("-Wc++98-compat")
+#  define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
+    xpr \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#else
+#  define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x
+#endif
+
+#if \
+    (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
+    defined(__clang__) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
+    JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) || \
+    JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \
+    JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \
+    (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR))
+    #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
+    #define JSON_HEDLEY_PRAGMA(value) __pragma(value)
+#else
+    #define JSON_HEDLEY_PRAGMA(value)
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
+    #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
+#endif
+#if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
+    #undef JSON_HEDLEY_DIAGNOSTIC_POP
+#endif
+#if defined(__clang__)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
+    #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
+    #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
+    #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
+    #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
+#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
+    #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
+#elif JSON_HEDLEY_TI_VERSION_CHECK(8,1,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
+    #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
+    #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
+#else
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH
+    #define JSON_HEDLEY_DIAGNOSTIC_POP
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
+    #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996))
+#elif JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
+#else
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
+    #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))
+#elif JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
+#else
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES)
+    #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes")
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030))
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)")
+#elif JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173")
+#else
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
+    #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
+#else
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
+#endif
+
+#if defined(JSON_HEDLEY_DEPRECATED)
+    #undef JSON_HEDLEY_DEPRECATED
+#endif
+#if defined(JSON_HEDLEY_DEPRECATED_FOR)
+    #undef JSON_HEDLEY_DEPRECATED_FOR
+#endif
+#if defined(__cplusplus) && (__cplusplus >= 201402L)
+    #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]])
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]])
+#elif \
+    JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \
+    JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(8,3,0)
+    #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement)))
+#elif \
+    JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
+    (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
+    #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0)
+    #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since))
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
+#elif \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
+    JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0)
+    #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated)
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
+#else
+    #define JSON_HEDLEY_DEPRECATED(since)
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
+#endif
+
+#if defined(JSON_HEDLEY_UNAVAILABLE)
+    #undef JSON_HEDLEY_UNAVAILABLE
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+    #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
+#else
+    #define JSON_HEDLEY_UNAVAILABLE(available_since)
+#endif
+
+#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
+    #undef JSON_HEDLEY_WARN_UNUSED_RESULT
+#endif
+#if defined(__cplusplus) && (__cplusplus >= 201703L)
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
+#elif \
+    JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
+    (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
+    JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
+#elif defined(_Check_return_) /* SAL */
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
+#else
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT
+#endif
+
+#if defined(JSON_HEDLEY_SENTINEL)
+    #undef JSON_HEDLEY_SENTINEL
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0)
+    #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
+#else
+    #define JSON_HEDLEY_SENTINEL(position)
+#endif
+
+#if defined(JSON_HEDLEY_NO_RETURN)
+    #undef JSON_HEDLEY_NO_RETURN
+#endif
+#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_NO_RETURN __noreturn
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+    #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
+#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
+    #define JSON_HEDLEY_NO_RETURN _Noreturn
+#elif defined(__cplusplus) && (__cplusplus >= 201103L)
+    #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]])
+#elif \
+    JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(18,0,0) || \
+    (JSON_HEDLEY_TI_VERSION_CHECK(17,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
+    #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
+    #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
+    #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
+#elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
+    #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
+#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
+    #define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
+    #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
+#else
+    #define JSON_HEDLEY_NO_RETURN
+#endif
+
+#if defined(JSON_HEDLEY_NO_ESCAPE)
+    #undef JSON_HEDLEY_NO_ESCAPE
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape)
+    #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__))
+#else
+    #define JSON_HEDLEY_NO_ESCAPE
+#endif
+
+#if defined(JSON_HEDLEY_UNREACHABLE)
+    #undef JSON_HEDLEY_UNREACHABLE
+#endif
+#if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
+    #undef JSON_HEDLEY_UNREACHABLE_RETURN
+#endif
+#if \
+    (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
+    #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
+    #define JSON_HEDLEY_UNREACHABLE() __assume(0)
+#elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0)
+    #if defined(__cplusplus)
+        #define JSON_HEDLEY_UNREACHABLE() std::_nassert(0)
+    #else
+        #define JSON_HEDLEY_UNREACHABLE() _nassert(0)
+    #endif
+    #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return value
+#elif defined(EXIT_FAILURE)
+    #define JSON_HEDLEY_UNREACHABLE() abort()
+#else
+    #define JSON_HEDLEY_UNREACHABLE()
+    #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return value
+#endif
+#if !defined(JSON_HEDLEY_UNREACHABLE_RETURN)
+    #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
+#endif
+
+#if defined(JSON_HEDLEY_ASSUME)
+    #undef JSON_HEDLEY_ASSUME
+#endif
+#if \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+    #define JSON_HEDLEY_ASSUME(expr) __assume(expr)
+#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
+    #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
+#elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0)
+    #if defined(__cplusplus)
+        #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
+    #else
+        #define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
+    #endif
+#elif \
+    (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && !defined(JSON_HEDLEY_ARM_VERSION)) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
+    #define JSON_HEDLEY_ASSUME(expr) ((void) ((expr) ? 1 : (__builtin_unreachable(), 1)))
+#else
+    #define JSON_HEDLEY_ASSUME(expr) ((void) (expr))
+#endif
+
+JSON_HEDLEY_DIAGNOSTIC_PUSH
+#if JSON_HEDLEY_HAS_WARNING("-Wpedantic")
+    #pragma clang diagnostic ignored "-Wpedantic"
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus)
+    #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
+#endif
+#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0)
+    #if defined(__clang__)
+        #pragma clang diagnostic ignored "-Wvariadic-macros"
+    #elif defined(JSON_HEDLEY_GCC_VERSION)
+        #pragma GCC diagnostic ignored "-Wvariadic-macros"
+    #endif
+#endif
+#if defined(JSON_HEDLEY_NON_NULL)
+    #undef JSON_HEDLEY_NON_NULL
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
+    #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
+#else
+    #define JSON_HEDLEY_NON_NULL(...)
+#endif
+JSON_HEDLEY_DIAGNOSTIC_POP
+
+#if defined(JSON_HEDLEY_PRINTF_FORMAT)
+    #undef JSON_HEDLEY_PRINTF_FORMAT
+#endif
+#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO)
+    #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check)))
+#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO)
+    #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
+#elif \
+    JSON_HEDLEY_HAS_ATTRIBUTE(format) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
+    (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
+    #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check)))
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0)
+    #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check))
+#else
+    #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check)
+#endif
+
+#if defined(JSON_HEDLEY_CONSTEXPR)
+    #undef JSON_HEDLEY_CONSTEXPR
+#endif
+#if defined(__cplusplus)
+    #if __cplusplus >= 201103L
+        #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr)
+    #endif
+#endif
+#if !defined(JSON_HEDLEY_CONSTEXPR)
+    #define JSON_HEDLEY_CONSTEXPR
+#endif
+
+#if defined(JSON_HEDLEY_PREDICT)
+    #undef JSON_HEDLEY_PREDICT
+#endif
+#if defined(JSON_HEDLEY_LIKELY)
+    #undef JSON_HEDLEY_LIKELY
+#endif
+#if defined(JSON_HEDLEY_UNLIKELY)
+    #undef JSON_HEDLEY_UNLIKELY
+#endif
+#if defined(JSON_HEDLEY_UNPREDICTABLE)
+    #undef JSON_HEDLEY_UNPREDICTABLE
+#endif
+#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
+    #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable(!!(expr))
+#endif
+#if \
+  JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) || \
+  JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0)
+#  define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability(expr, value, probability)
+#  define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1, probability)
+#  define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0, probability)
+#  define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
+#  define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
+#if !defined(JSON_HEDLEY_BUILTIN_UNPREDICTABLE)
+    #define JSON_HEDLEY_BUILTIN_UNPREDICTABLE(expr) __builtin_expect_with_probability(!!(expr), 1, 0.5)
+#endif
+#elif \
+  JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) || \
+  JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
+  JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+  (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
+  JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+  JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+  JSON_HEDLEY_TI_VERSION_CHECK(6,1,0) || \
+  JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27)
+#  define JSON_HEDLEY_PREDICT(expr, expected, probability) \
+    (((probability) >= 0.9) ? __builtin_expect(!!(expr), (expected)) : (((void) (expected)), !!(expr)))
+#  define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
+    (__extension__ ({ \
+        JSON_HEDLEY_CONSTEXPR double hedley_probability_ = (probability); \
+        ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
+    }))
+#  define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
+    (__extension__ ({ \
+        JSON_HEDLEY_CONSTEXPR double hedley_probability_ = (probability); \
+        ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
+    }))
+#  define JSON_HEDLEY_LIKELY(expr)   __builtin_expect(!!(expr), 1)
+#  define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
+#else
+#  define JSON_HEDLEY_PREDICT(expr, expected, probability) (((void) (expected)), !!(expr))
+#  define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
+#  define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
+#  define JSON_HEDLEY_LIKELY(expr) (!!(expr))
+#  define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
+#endif
+#if !defined(JSON_HEDLEY_UNPREDICTABLE)
+    #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
+#endif
+
+#if defined(JSON_HEDLEY_MALLOC)
+    #undef JSON_HEDLEY_MALLOC
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
+    (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
+    #define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
+    #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0)
+    #define JSON_HEDLEY_MALLOC __declspec(restrict)
+#else
+    #define JSON_HEDLEY_MALLOC
+#endif
+
+#if defined(JSON_HEDLEY_PURE)
+    #undef JSON_HEDLEY_PURE
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
+    (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
+    #define JSON_HEDLEY_PURE __attribute__((__pure__))
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
+    #define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data")
+#elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
+    #define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
+#else
+    #define JSON_HEDLEY_PURE
+#endif
+
+#if defined(JSON_HEDLEY_CONST)
+    #undef JSON_HEDLEY_CONST
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(const) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
+    (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
+    #define JSON_HEDLEY_CONST __attribute__((__const__))
+#elif \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
+    #define JSON_HEDLEY_CONST _Pragma("no_side_effect")
+#else
+    #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
+#endif
+
+#if defined(JSON_HEDLEY_RESTRICT)
+    #undef JSON_HEDLEY_RESTRICT
+#endif
+#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
+    #define JSON_HEDLEY_RESTRICT restrict
+#elif \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+    JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
+    (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \
+    JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
+    defined(__clang__)
+    #define JSON_HEDLEY_RESTRICT __restrict
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus)
+    #define JSON_HEDLEY_RESTRICT _Restrict
+#else
+    #define JSON_HEDLEY_RESTRICT
+#endif
+
+#if defined(JSON_HEDLEY_INLINE)
+    #undef JSON_HEDLEY_INLINE
+#endif
+#if \
+    (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
+    (defined(__cplusplus) && (__cplusplus >= 199711L))
+    #define JSON_HEDLEY_INLINE inline
+#elif \
+    defined(JSON_HEDLEY_GCC_VERSION) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0)
+    #define JSON_HEDLEY_INLINE __inline__
+#elif \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_INLINE __inline
+#else
+    #define JSON_HEDLEY_INLINE
+#endif
+
+#if defined(JSON_HEDLEY_ALWAYS_INLINE)
+    #undef JSON_HEDLEY_ALWAYS_INLINE
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
+    (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
+    #define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0)
+    #define JSON_HEDLEY_ALWAYS_INLINE __forceinline
+#elif JSON_HEDLEY_TI_VERSION_CHECK(7,0,0) && defined(__cplusplus)
+    #define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
+#else
+    #define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
+#endif
+
+#if defined(JSON_HEDLEY_NEVER_INLINE)
+    #undef JSON_HEDLEY_NEVER_INLINE
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
+    (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
+    #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
+    #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0)
+    #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
+#elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
+    #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
+#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
+    #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
+    #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
+#else
+    #define JSON_HEDLEY_NEVER_INLINE
+#endif
+
+#if defined(JSON_HEDLEY_PRIVATE)
+    #undef JSON_HEDLEY_PRIVATE
+#endif
+#if defined(JSON_HEDLEY_PUBLIC)
+    #undef JSON_HEDLEY_PUBLIC
+#endif
+#if defined(JSON_HEDLEY_IMPORT)
+    #undef JSON_HEDLEY_IMPORT
+#endif
+#if defined(_WIN32) || defined(__CYGWIN__)
+    #define JSON_HEDLEY_PRIVATE
+    #define JSON_HEDLEY_PUBLIC   __declspec(dllexport)
+    #define JSON_HEDLEY_IMPORT   __declspec(dllimport)
+#else
+    #if \
+        JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \
+        JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
+        JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+        JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+        JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+        JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
+        JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
+        (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_EABI__) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
+        #define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
+        #define JSON_HEDLEY_PUBLIC  __attribute__((__visibility__("default")))
+    #else
+        #define JSON_HEDLEY_PRIVATE
+        #define JSON_HEDLEY_PUBLIC
+    #endif
+    #define JSON_HEDLEY_IMPORT    extern
+#endif
+
+#if defined(JSON_HEDLEY_NO_THROW)
+    #undef JSON_HEDLEY_NO_THROW
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+    #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
+#elif \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
+    #define JSON_HEDLEY_NO_THROW __declspec(nothrow)
+#else
+    #define JSON_HEDLEY_NO_THROW
+#endif
+
+#if defined(JSON_HEDLEY_FALL_THROUGH)
+    #undef JSON_HEDLEY_FALL_THROUGH
+#endif
+#if JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(fallthrough,7,0,0) && !defined(JSON_HEDLEY_PGI_VERSION)
+    #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
+#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough)
+    #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]])
+#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough)
+    #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]])
+#elif defined(__fallthrough) /* SAL */
+    #define JSON_HEDLEY_FALL_THROUGH __fallthrough
+#else
+    #define JSON_HEDLEY_FALL_THROUGH
+#endif
+
+#if defined(JSON_HEDLEY_RETURNS_NON_NULL)
+    #undef JSON_HEDLEY_RETURNS_NON_NULL
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0)
+    #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
+#elif defined(_Ret_notnull_) /* SAL */
+    #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
+#else
+    #define JSON_HEDLEY_RETURNS_NON_NULL
+#endif
+
+#if defined(JSON_HEDLEY_ARRAY_PARAM)
+    #undef JSON_HEDLEY_ARRAY_PARAM
+#endif
+#if \
+    defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
+    !defined(__STDC_NO_VLA__) && \
+    !defined(__cplusplus) && \
+    !defined(JSON_HEDLEY_PGI_VERSION) && \
+    !defined(JSON_HEDLEY_TINYC_VERSION)
+    #define JSON_HEDLEY_ARRAY_PARAM(name) (name)
+#else
+    #define JSON_HEDLEY_ARRAY_PARAM(name)
+#endif
+
+#if defined(JSON_HEDLEY_IS_CONSTANT)
+    #undef JSON_HEDLEY_IS_CONSTANT
+#endif
+#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
+    #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
+#endif
+/* JSON_HEDLEY_IS_CONSTEXPR_ is for
+   HEDLEY INTERNAL USE ONLY.  API subject to change without notice. */
+#if defined(JSON_HEDLEY_IS_CONSTEXPR_)
+    #undef JSON_HEDLEY_IS_CONSTEXPR_
+#endif
+#if \
+    JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(6,1,0) || \
+    (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \
+    JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0)
+    #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
+#endif
+#if !defined(__cplusplus)
+#  if \
+       JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \
+       JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
+       JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+       JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
+       JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
+       JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
+       JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24)
+#if defined(__INTPTR_TYPE__)
+    #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*)
+#else
+    #include <stdint.h>
+    #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*)
+#endif
+#  elif \
+       (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(JSON_HEDLEY_SUNPRO_VERSION) && !defined(JSON_HEDLEY_PGI_VERSION)) || \
+       JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) || \
+       JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
+       JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \
+       JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
+       JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0)
+#if defined(__INTPTR_TYPE__)
+    #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0)
+#else
+    #include <stdint.h>
+    #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0)
+#endif
+#  elif \
+       defined(JSON_HEDLEY_GCC_VERSION) || \
+       defined(JSON_HEDLEY_INTEL_VERSION) || \
+       defined(JSON_HEDLEY_TINYC_VERSION) || \
+       defined(JSON_HEDLEY_TI_VERSION) || \
+       defined(__clang__)
+#    define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \
+        sizeof(void) != \
+        sizeof(*( \
+                  1 ? \
+                  ((void*) ((expr) * 0L) ) : \
+((struct { char v[sizeof(void) * 2]; } *) 1) \
+                ) \
+              ) \
+                                            )
+#  endif
+#endif
+#if defined(JSON_HEDLEY_IS_CONSTEXPR_)
+    #if !defined(JSON_HEDLEY_IS_CONSTANT)
+        #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr)
+    #endif
+    #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1))
+#else
+    #if !defined(JSON_HEDLEY_IS_CONSTANT)
+        #define JSON_HEDLEY_IS_CONSTANT(expr) (0)
+    #endif
+    #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
+#endif
+
+#if defined(JSON_HEDLEY_BEGIN_C_DECLS)
+    #undef JSON_HEDLEY_BEGIN_C_DECLS
+#endif
+#if defined(JSON_HEDLEY_END_C_DECLS)
+    #undef JSON_HEDLEY_END_C_DECLS
+#endif
+#if defined(JSON_HEDLEY_C_DECL)
+    #undef JSON_HEDLEY_C_DECL
+#endif
+#if defined(__cplusplus)
+    #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
+    #define JSON_HEDLEY_END_C_DECLS }
+    #define JSON_HEDLEY_C_DECL extern "C"
+#else
+    #define JSON_HEDLEY_BEGIN_C_DECLS
+    #define JSON_HEDLEY_END_C_DECLS
+    #define JSON_HEDLEY_C_DECL
+#endif
+
+#if defined(JSON_HEDLEY_STATIC_ASSERT)
+    #undef JSON_HEDLEY_STATIC_ASSERT
+#endif
+#if \
+  !defined(__cplusplus) && ( \
+      (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
+      JSON_HEDLEY_HAS_FEATURE(c_static_assert) || \
+      JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \
+      JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+      defined(_Static_assert) \
+    )
+#  define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
+#elif \
+  (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
+  JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \
+  (defined(__cplusplus) && JSON_HEDLEY_TI_VERSION_CHECK(8,3,0))
+#  define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message))
+#else
+#  define JSON_HEDLEY_STATIC_ASSERT(expr, message)
+#endif
+
+#if defined(JSON_HEDLEY_CONST_CAST)
+    #undef JSON_HEDLEY_CONST_CAST
+#endif
+#if defined(__cplusplus)
+#  define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
+#elif \
+  JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \
+  JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \
+  JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+#  define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \
+        JSON_HEDLEY_DIAGNOSTIC_PUSH \
+        JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \
+        ((T) (expr)); \
+        JSON_HEDLEY_DIAGNOSTIC_POP \
+    }))
+#else
+#  define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr))
+#endif
+
+#if defined(JSON_HEDLEY_REINTERPRET_CAST)
+    #undef JSON_HEDLEY_REINTERPRET_CAST
+#endif
+#if defined(__cplusplus)
+    #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
+#else
+    #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (*((T*) &(expr)))
+#endif
+
+#if defined(JSON_HEDLEY_STATIC_CAST)
+    #undef JSON_HEDLEY_STATIC_CAST
+#endif
+#if defined(__cplusplus)
+    #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
+#else
+    #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr))
+#endif
+
+#if defined(JSON_HEDLEY_CPP_CAST)
+    #undef JSON_HEDLEY_CPP_CAST
+#endif
+#if defined(__cplusplus)
+    #define JSON_HEDLEY_CPP_CAST(T, expr) static_cast<T>(expr)
+#else
+    #define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
+#endif
+
+#if defined(JSON_HEDLEY_NULL)
+    #undef JSON_HEDLEY_NULL
+#endif
+#if defined(__cplusplus)
+    #if __cplusplus >= 201103L
+        #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr)
+    #elif defined(NULL)
+        #define JSON_HEDLEY_NULL NULL
+    #else
+        #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0)
+    #endif
+#elif defined(NULL)
+    #define JSON_HEDLEY_NULL NULL
+#else
+    #define JSON_HEDLEY_NULL ((void*) 0)
+#endif
+
+#if defined(JSON_HEDLEY_MESSAGE)
+    #undef JSON_HEDLEY_MESSAGE
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
+#  define JSON_HEDLEY_MESSAGE(msg) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
+    JSON_HEDLEY_PRAGMA(message msg) \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#elif \
+  JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \
+  JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+#  define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
+#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0)
+#  define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+#  define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0)
+#  define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
+#else
+#  define JSON_HEDLEY_MESSAGE(msg)
+#endif
+
+#if defined(JSON_HEDLEY_WARNING)
+    #undef JSON_HEDLEY_WARNING
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
+#  define JSON_HEDLEY_WARNING(msg) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
+    JSON_HEDLEY_PRAGMA(clang warning msg) \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#elif \
+  JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \
+  JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0)
+#  define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
+#  define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
+#else
+#  define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
+#endif
+
+#if defined(JSON_HEDLEY_REQUIRE)
+    #undef JSON_HEDLEY_REQUIRE
+#endif
+#if defined(JSON_HEDLEY_REQUIRE_MSG)
+    #undef JSON_HEDLEY_REQUIRE_MSG
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
+#  if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
+#    define JSON_HEDLEY_REQUIRE(expr) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
+    __attribute__((diagnose_if(!(expr), #expr, "error"))) \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#    define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
+    __attribute__((diagnose_if(!(expr), msg, "error"))) \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#  else
+#    define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error")))
+#    define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error")))
+#  endif
+#else
+#  define JSON_HEDLEY_REQUIRE(expr)
+#  define JSON_HEDLEY_REQUIRE_MSG(expr,msg)
+#endif
+
+#if defined(JSON_HEDLEY_FLAGS)
+    #undef JSON_HEDLEY_FLAGS
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum)
+    #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
+#endif
+
+#if defined(JSON_HEDLEY_FLAGS_CAST)
+    #undef JSON_HEDLEY_FLAGS_CAST
+#endif
+#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0)
+#  define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \
+        JSON_HEDLEY_DIAGNOSTIC_PUSH \
+        _Pragma("warning(disable:188)") \
+        ((T) (expr)); \
+        JSON_HEDLEY_DIAGNOSTIC_POP \
+    }))
+#else
+#  define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
+#endif
+
+#if defined(JSON_HEDLEY_EMPTY_BASES)
+    #undef JSON_HEDLEY_EMPTY_BASES
+#endif
+#if JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)
+    #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases)
+#else
+    #define JSON_HEDLEY_EMPTY_BASES
+#endif
+
+/* Remaining macros are deprecated. */
+
+#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
+    #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
+#endif
+#if defined(__clang__)
+    #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0)
+#else
+    #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
+    #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
+#endif
+#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
+    #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
+#endif
+#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
+    #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
+#endif
+#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
+    #undef JSON_HEDLEY_CLANG_HAS_FEATURE
+#endif
+#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
+    #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
+#endif
+#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
+    #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
+#endif
+#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
+    #undef JSON_HEDLEY_CLANG_HAS_WARNING
+#endif
+#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
+
+#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
+
+
+// This file contains all internal macro definitions
+// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
+
+// exclude unsupported compilers
+#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
+    #if defined(__clang__)
+        #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
+            #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
+        #endif
+    #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
+        #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
+            #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
+        #endif
+    #endif
+#endif
+
+// C++ language standard detection
+#if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
+    #define JSON_HAS_CPP_17
+    #define JSON_HAS_CPP_14
+#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
+    #define JSON_HAS_CPP_14
+#endif
+
+// disable float-equal warnings on GCC/clang
+#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
+    #pragma GCC diagnostic push
+    #pragma GCC diagnostic ignored "-Wfloat-equal"
+#endif
+
+// disable documentation warnings on clang
+#if defined(__clang__)
+    #pragma GCC diagnostic push
+    #pragma GCC diagnostic ignored "-Wdocumentation"
+#endif
+
+// allow to disable exceptions
+#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
+    #define JSON_THROW(exception) throw exception
+    #define JSON_TRY try
+    #define JSON_CATCH(exception) catch(exception)
+    #define JSON_INTERNAL_CATCH(exception) catch(exception)
+#else
+    #include <cstdlib>
+    #define JSON_THROW(exception) std::abort()
+    #define JSON_TRY if(true)
+    #define JSON_CATCH(exception) if(false)
+    #define JSON_INTERNAL_CATCH(exception) if(false)
+#endif
+
+// override exception macros
+#if defined(JSON_THROW_USER)
+    #undef JSON_THROW
+    #define JSON_THROW JSON_THROW_USER
+#endif
+#if defined(JSON_TRY_USER)
+    #undef JSON_TRY
+    #define JSON_TRY JSON_TRY_USER
+#endif
+#if defined(JSON_CATCH_USER)
+    #undef JSON_CATCH
+    #define JSON_CATCH JSON_CATCH_USER
+    #undef JSON_INTERNAL_CATCH
+    #define JSON_INTERNAL_CATCH JSON_CATCH_USER
+#endif
+#if defined(JSON_INTERNAL_CATCH_USER)
+    #undef JSON_INTERNAL_CATCH
+    #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
+#endif
+
+/*!
+@brief macro to briefly define a mapping between an enum and JSON
+@def NLOHMANN_JSON_SERIALIZE_ENUM
+@since version 3.4.0
+*/
+#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...)                                            \
+    template<typename BasicJsonType>                                                            \
+    inline void to_json(BasicJsonType& j, const ENUM_TYPE& e)                                   \
+    {                                                                                           \
+        static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!");          \
+        static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__;                     \
+        auto it = std::find_if(std::begin(m), std::end(m),                                      \
+                               [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool  \
+        {                                                                                       \
+            return ej_pair.first == e;                                                          \
+        });                                                                                     \
+        j = ((it != std::end(m)) ? it : std::begin(m))->second;                                 \
+    }                                                                                           \
+    template<typename BasicJsonType>                                                            \
+    inline void from_json(const BasicJsonType& j, ENUM_TYPE& e)                                 \
+    {                                                                                           \
+        static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!");          \
+        static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__;                     \
+        auto it = std::find_if(std::begin(m), std::end(m),                                      \
+                               [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
+        {                                                                                       \
+            return ej_pair.second == j;                                                         \
+        });                                                                                     \
+        e = ((it != std::end(m)) ? it : std::begin(m))->first;                                  \
+    }
+
+// Ugly macros to avoid uglier copy-paste when specializing basic_json. They
+// may be removed in the future once the class is split.
+
+#define NLOHMANN_BASIC_JSON_TPL_DECLARATION                                \
+    template<template<typename, typename, typename...> class ObjectType,   \
+             template<typename, typename...> class ArrayType,              \
+             class StringType, class BooleanType, class NumberIntegerType, \
+             class NumberUnsignedType, class NumberFloatType,              \
+             template<typename> class AllocatorType,                       \
+             template<typename, typename = void> class JSONSerializer>
+
+#define NLOHMANN_BASIC_JSON_TPL                                            \
+    basic_json<ObjectType, ArrayType, StringType, BooleanType,             \
+    NumberIntegerType, NumberUnsignedType, NumberFloatType,                \
+    AllocatorType, JSONSerializer>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+////////////////
+// exceptions //
+////////////////
+
+/*!
+@brief general exception of the @ref basic_json class
+
+This class is an extension of `std::exception` objects with a member @a id for
+exception ids. It is used as the base class for all exceptions thrown by the
+@ref basic_json class. This class can hence be used as "wildcard" to catch
+exceptions.
+
+Subclasses:
+- @ref parse_error for exceptions indicating a parse error
+- @ref invalid_iterator for exceptions indicating errors with iterators
+- @ref type_error for exceptions indicating executing a member function with
+                  a wrong type
+- @ref out_of_range for exceptions indicating access out of the defined range
+- @ref other_error for exceptions indicating other library errors
+
+@internal
+@note To have nothrow-copy-constructible exceptions, we internally use
+      `std::runtime_error` which can cope with arbitrary-length error messages.
+      Intermediate strings are built with static functions and then passed to
+      the actual constructor.
+@endinternal
+
+@liveexample{The following code shows how arbitrary library exceptions can be
+caught.,exception}
+
+@since version 3.0.0
+*/
+class exception : public std::exception
+{
+  public:
+    /// returns the explanatory string
+    JSON_HEDLEY_RETURNS_NON_NULL
+    const char* what() const noexcept override
+    {
+        return m.what();
+    }
+
+    /// the id of the exception
+    const int id;
+
+  protected:
+    JSON_HEDLEY_NON_NULL(3)
+    exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
+
+    static std::string name(const std::string& ename, int id_)
+    {
+        return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
+    }
+
+  private:
+    /// an exception object as storage for error messages
+    std::runtime_error m;
+};
+
+/*!
+@brief exception indicating a parse error
+
+This exception is thrown by the library when a parse error occurs. Parse errors
+can occur during the deserialization of JSON text, CBOR, MessagePack, as well
+as when using JSON Patch.
+
+Member @a byte holds the byte index of the last read character in the input
+file.
+
+Exceptions have ids 1xx.
+
+name / id                      | example message | description
+------------------------------ | --------------- | -------------------------
+json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position.
+json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.
+json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
+json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects.
+json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors.
+json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`.
+json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character.
+json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences.
+json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
+json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
+json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read.
+json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read.
+json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
+
+@note For an input with n bytes, 1 is the index of the first character and n+1
+      is the index of the terminating null byte or the end of file. This also
+      holds true when reading a byte vector (CBOR or MessagePack).
+
+@liveexample{The following code shows how a `parse_error` exception can be
+caught.,parse_error}
+
+@sa - @ref exception for the base class of the library exceptions
+@sa - @ref invalid_iterator for exceptions indicating errors with iterators
+@sa - @ref type_error for exceptions indicating executing a member function with
+                    a wrong type
+@sa - @ref out_of_range for exceptions indicating access out of the defined range
+@sa - @ref other_error for exceptions indicating other library errors
+
+@since version 3.0.0
+*/
+class parse_error : public exception
+{
+  public:
+    /*!
+    @brief create a parse error exception
+    @param[in] id_       the id of the exception
+    @param[in] pos       the position where the error occurred (or with
+                         chars_read_total=0 if the position cannot be
+                         determined)
+    @param[in] what_arg  the explanatory string
+    @return parse_error object
+    */
+    static parse_error create(int id_, const position_t& pos, const std::string& what_arg)
+    {
+        std::string w = exception::name("parse_error", id_) + "parse error" +
+                        position_string(pos) + ": " + what_arg;
+        return parse_error(id_, pos.chars_read_total, w.c_str());
+    }
+
+    static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
+    {
+        std::string w = exception::name("parse_error", id_) + "parse error" +
+                        (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
+                        ": " + what_arg;
+        return parse_error(id_, byte_, w.c_str());
+    }
+
+    /*!
+    @brief byte index of the parse error
+
+    The byte index of the last read character in the input file.
+
+    @note For an input with n bytes, 1 is the index of the first character and
+          n+1 is the index of the terminating null byte or the end of file.
+          This also holds true when reading a byte vector (CBOR or MessagePack).
+    */
+    const std::size_t byte;
+
+  private:
+    parse_error(int id_, std::size_t byte_, const char* what_arg)
+        : exception(id_, what_arg), byte(byte_) {}
+
+    static std::string position_string(const position_t& pos)
+    {
+        return " at line " + std::to_string(pos.lines_read + 1) +
+               ", column " + std::to_string(pos.chars_read_current_line);
+    }
+};
+
+/*!
+@brief exception indicating errors with iterators
+
+This exception is thrown if iterators passed to a library function do not match
+the expected semantics.
+
+Exceptions have ids 2xx.
+
+name / id                           | example message | description
+----------------------------------- | --------------- | -------------------------
+json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
+json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
+json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
+json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid.
+json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.
+json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.
+json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
+json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
+json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
+json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
+json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to.
+json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
+json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
+json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin().
+
+@liveexample{The following code shows how an `invalid_iterator` exception can be
+caught.,invalid_iterator}
+
+@sa - @ref exception for the base class of the library exceptions
+@sa - @ref parse_error for exceptions indicating a parse error
+@sa - @ref type_error for exceptions indicating executing a member function with
+                    a wrong type
+@sa - @ref out_of_range for exceptions indicating access out of the defined range
+@sa - @ref other_error for exceptions indicating other library errors
+
+@since version 3.0.0
+*/
+class invalid_iterator : public exception
+{
+  public:
+    static invalid_iterator create(int id_, const std::string& what_arg)
+    {
+        std::string w = exception::name("invalid_iterator", id_) + what_arg;
+        return invalid_iterator(id_, w.c_str());
+    }
+
+  private:
+    JSON_HEDLEY_NON_NULL(3)
+    invalid_iterator(int id_, const char* what_arg)
+        : exception(id_, what_arg) {}
+};
+
+/*!
+@brief exception indicating executing a member function with a wrong type
+
+This exception is thrown in case of a type error; that is, a library function is
+executed on a JSON value whose type does not match the expected semantics.
+
+Exceptions have ids 3xx.
+
+name / id                     | example message | description
+----------------------------- | --------------- | -------------------------
+json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
+json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
+json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &.
+json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
+json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
+json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
+json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
+json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types.
+json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
+json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
+json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types.
+json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
+json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined.
+json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
+json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive.
+json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. |
+json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) |
+
+@liveexample{The following code shows how a `type_error` exception can be
+caught.,type_error}
+
+@sa - @ref exception for the base class of the library exceptions
+@sa - @ref parse_error for exceptions indicating a parse error
+@sa - @ref invalid_iterator for exceptions indicating errors with iterators
+@sa - @ref out_of_range for exceptions indicating access out of the defined range
+@sa - @ref other_error for exceptions indicating other library errors
+
+@since version 3.0.0
+*/
+class type_error : public exception
+{
+  public:
+    static type_error create(int id_, const std::string& what_arg)
+    {
+        std::string w = exception::name("type_error", id_) + what_arg;
+        return type_error(id_, w.c_str());
+    }
+
+  private:
+    JSON_HEDLEY_NON_NULL(3)
+    type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
+};
+
+/*!
+@brief exception indicating access out of the defined range
+
+This exception is thrown in case a library function is called on an input
+parameter that exceeds the expected range, for instance in case of array
+indices or nonexisting object keys.
+
+Exceptions have ids 4xx.
+
+name / id                       | example message | description
+------------------------------- | --------------- | -------------------------
+json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1.
+json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
+json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
+json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
+json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
+json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF.
+json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. |
+json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
+json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string |
+
+@liveexample{The following code shows how an `out_of_range` exception can be
+caught.,out_of_range}
+
+@sa - @ref exception for the base class of the library exceptions
+@sa - @ref parse_error for exceptions indicating a parse error
+@sa - @ref invalid_iterator for exceptions indicating errors with iterators
+@sa - @ref type_error for exceptions indicating executing a member function with
+                    a wrong type
+@sa - @ref other_error for exceptions indicating other library errors
+
+@since version 3.0.0
+*/
+class out_of_range : public exception
+{
+  public:
+    static out_of_range create(int id_, const std::string& what_arg)
+    {
+        std::string w = exception::name("out_of_range", id_) + what_arg;
+        return out_of_range(id_, w.c_str());
+    }
+
+  private:
+    JSON_HEDLEY_NON_NULL(3)
+    out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
+};
+
+/*!
+@brief exception indicating other library errors
+
+This exception is thrown in case of errors that cannot be classified with the
+other exception types.
+
+Exceptions have ids 5xx.
+
+name / id                      | example message | description
+------------------------------ | --------------- | -------------------------
+json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
+
+@sa - @ref exception for the base class of the library exceptions
+@sa - @ref parse_error for exceptions indicating a parse error
+@sa - @ref invalid_iterator for exceptions indicating errors with iterators
+@sa - @ref type_error for exceptions indicating executing a member function with
+                    a wrong type
+@sa - @ref out_of_range for exceptions indicating access out of the defined range
+
+@liveexample{The following code shows how an `other_error` exception can be
+caught.,other_error}
+
+@since version 3.0.0
+*/
+class other_error : public exception
+{
+  public:
+    static other_error create(int id_, const std::string& what_arg)
+    {
+        std::string w = exception::name("other_error", id_) + what_arg;
+        return other_error(id_, w.c_str());
+    }
+
+  private:
+    JSON_HEDLEY_NON_NULL(3)
+    other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+
+#include <ciso646> // not
+#include <cstddef> // size_t
+#include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
+
+namespace nlohmann
+{
+namespace detail
+{
+// alias templates to reduce boilerplate
+template<bool B, typename T = void>
+using enable_if_t = typename std::enable_if<B, T>::type;
+
+template<typename T>
+using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
+
+// implementation of C++14 index_sequence and affiliates
+// source: https://stackoverflow.com/a/32223343
+template<std::size_t... Ints>
+struct index_sequence
+{
+    using type = index_sequence;
+    using value_type = std::size_t;
+    static constexpr std::size_t size() noexcept
+    {
+        return sizeof...(Ints);
+    }
+};
+
+template<class Sequence1, class Sequence2>
+struct merge_and_renumber;
+
+template<std::size_t... I1, std::size_t... I2>
+struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
+        : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
+
+template<std::size_t N>
+struct make_index_sequence
+    : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
+      typename make_index_sequence < N - N / 2 >::type > {};
+
+template<> struct make_index_sequence<0> : index_sequence<> {};
+template<> struct make_index_sequence<1> : index_sequence<0> {};
+
+template<typename... Ts>
+using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
+
+// dispatch utility (taken from ranges-v3)
+template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
+template<> struct priority_tag<0> {};
+
+// taken from ranges-v3
+template<typename T>
+struct static_const
+{
+    static constexpr T value{};
+};
+
+template<typename T>
+constexpr T static_const<T>::value;
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+
+#include <ciso646> // not
+#include <limits> // numeric_limits
+#include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
+#include <utility> // declval
+
+// #include <nlohmann/detail/iterators/iterator_traits.hpp>
+
+
+#include <iterator> // random_access_iterator_tag
+
+// #include <nlohmann/detail/meta/void_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+template <typename ...Ts> struct make_void
+{
+    using type = void;
+};
+template <typename ...Ts> using void_t = typename make_void<Ts...>::type;
+} // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+template <typename It, typename = void>
+struct iterator_types {};
+
+template <typename It>
+struct iterator_types <
+    It,
+    void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
+    typename It::reference, typename It::iterator_category >>
+{
+    using difference_type = typename It::difference_type;
+    using value_type = typename It::value_type;
+    using pointer = typename It::pointer;
+    using reference = typename It::reference;
+    using iterator_category = typename It::iterator_category;
+};
+
+// This is required as some compilers implement std::iterator_traits in a way that
+// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
+template <typename T, typename = void>
+struct iterator_traits
+{
+};
+
+template <typename T>
+struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
+            : iterator_types<T>
+{
+};
+
+template <typename T>
+struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
+{
+    using iterator_category = std::random_access_iterator_tag;
+    using value_type = T;
+    using difference_type = ptrdiff_t;
+    using pointer = T*;
+    using reference = T&;
+};
+} // namespace detail
+} // namespace nlohmann
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/detected.hpp>
+
+
+#include <type_traits>
+
+// #include <nlohmann/detail/meta/void_t.hpp>
+
+
+// https://en.cppreference.com/w/cpp/experimental/is_detected
+namespace nlohmann
+{
+namespace detail
+{
+struct nonesuch
+{
+    nonesuch() = delete;
+    ~nonesuch() = delete;
+    nonesuch(nonesuch const&) = delete;
+    nonesuch(nonesuch const&&) = delete;
+    void operator=(nonesuch const&) = delete;
+    void operator=(nonesuch&&) = delete;
+};
+
+template <class Default,
+          class AlwaysVoid,
+          template <class...> class Op,
+          class... Args>
+struct detector
+{
+    using value_t = std::false_type;
+    using type = Default;
+};
+
+template <class Default, template <class...> class Op, class... Args>
+struct detector<Default, void_t<Op<Args...>>, Op, Args...>
+{
+    using value_t = std::true_type;
+    using type = Op<Args...>;
+};
+
+template <template <class...> class Op, class... Args>
+using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
+
+template <template <class...> class Op, class... Args>
+using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
+
+template <class Default, template <class...> class Op, class... Args>
+using detected_or = detector<Default, void, Op, Args...>;
+
+template <class Default, template <class...> class Op, class... Args>
+using detected_or_t = typename detected_or<Default, Op, Args...>::type;
+
+template <class Expected, template <class...> class Op, class... Args>
+using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
+
+template <class To, template <class...> class Op, class... Args>
+using is_detected_convertible =
+    std::is_convertible<detected_t<Op, Args...>, To>;
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/json_fwd.hpp>
+#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
+#define INCLUDE_NLOHMANN_JSON_FWD_HPP_
+
+#include <cstdint> // int64_t, uint64_t
+#include <map> // map
+#include <memory> // allocator
+#include <string> // string
+#include <vector> // vector
+
+/*!
+@brief namespace for Niels Lohmann
+@see https://github.com/nlohmann
+@since version 1.0.0
+*/
+namespace nlohmann
+{
+/*!
+@brief default JSONSerializer template argument
+
+This serializer ignores the template arguments and uses ADL
+([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
+for serialization.
+*/
+template<typename T = void, typename SFINAE = void>
+struct adl_serializer;
+
+template<template<typename U, typename V, typename... Args> class ObjectType =
+         std::map,
+         template<typename U, typename... Args> class ArrayType = std::vector,
+         class StringType = std::string, class BooleanType = bool,
+         class NumberIntegerType = std::int64_t,
+         class NumberUnsignedType = std::uint64_t,
+         class NumberFloatType = double,
+         template<typename U> class AllocatorType = std::allocator,
+         template<typename T, typename SFINAE = void> class JSONSerializer =
+         adl_serializer>
+class basic_json;
+
+/*!
+@brief JSON Pointer
+
+A JSON pointer defines a string syntax for identifying a specific value
+within a JSON document. It can be used with functions `at` and
+`operator[]`. Furthermore, JSON pointers are the base for JSON patches.
+
+@sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
+
+@since version 2.0.0
+*/
+template<typename BasicJsonType>
+class json_pointer;
+
+/*!
+@brief default JSON class
+
+This type is the default specialization of the @ref basic_json class which
+uses the standard template types.
+
+@since version 1.0.0
+*/
+using json = basic_json<>;
+}  // namespace nlohmann
+
+#endif  // INCLUDE_NLOHMANN_JSON_FWD_HPP_
+
+
+namespace nlohmann
+{
+/*!
+@brief detail namespace with internal helper functions
+
+This namespace collects functions that should not be exposed,
+implementations of some @ref basic_json methods, and meta-programming helpers.
+
+@since version 2.1.0
+*/
+namespace detail
+{
+/////////////
+// helpers //
+/////////////
+
+// Note to maintainers:
+//
+// Every trait in this file expects a non CV-qualified type.
+// The only exceptions are in the 'aliases for detected' section
+// (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
+//
+// In this case, T has to be properly CV-qualified to constraint the function arguments
+// (e.g. to_json(BasicJsonType&, const T&))
+
+template<typename> struct is_basic_json : std::false_type {};
+
+NLOHMANN_BASIC_JSON_TPL_DECLARATION
+struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
+
+//////////////////////////
+// aliases for detected //
+//////////////////////////
+
+template <typename T>
+using mapped_type_t = typename T::mapped_type;
+
+template <typename T>
+using key_type_t = typename T::key_type;
+
+template <typename T>
+using value_type_t = typename T::value_type;
+
+template <typename T>
+using difference_type_t = typename T::difference_type;
+
+template <typename T>
+using pointer_t = typename T::pointer;
+
+template <typename T>
+using reference_t = typename T::reference;
+
+template <typename T>
+using iterator_category_t = typename T::iterator_category;
+
+template <typename T>
+using iterator_t = typename T::iterator;
+
+template <typename T, typename... Args>
+using to_json_function = decltype(T::to_json(std::declval<Args>()...));
+
+template <typename T, typename... Args>
+using from_json_function = decltype(T::from_json(std::declval<Args>()...));
+
+template <typename T, typename U>
+using get_template_function = decltype(std::declval<T>().template get<U>());
+
+// trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
+template <typename BasicJsonType, typename T, typename = void>
+struct has_from_json : std::false_type {};
+
+template <typename BasicJsonType, typename T>
+struct has_from_json<BasicJsonType, T,
+           enable_if_t<not is_basic_json<T>::value>>
+{
+    using serializer = typename BasicJsonType::template json_serializer<T, void>;
+
+    static constexpr bool value =
+        is_detected_exact<void, from_json_function, serializer,
+        const BasicJsonType&, T&>::value;
+};
+
+// This trait checks if JSONSerializer<T>::from_json(json const&) exists
+// this overload is used for non-default-constructible user-defined-types
+template <typename BasicJsonType, typename T, typename = void>
+struct has_non_default_from_json : std::false_type {};
+
+template<typename BasicJsonType, typename T>
+struct has_non_default_from_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
+{
+    using serializer = typename BasicJsonType::template json_serializer<T, void>;
+
+    static constexpr bool value =
+        is_detected_exact<T, from_json_function, serializer,
+        const BasicJsonType&>::value;
+};
+
+// This trait checks if BasicJsonType::json_serializer<T>::to_json exists
+// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
+template <typename BasicJsonType, typename T, typename = void>
+struct has_to_json : std::false_type {};
+
+template <typename BasicJsonType, typename T>
+struct has_to_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
+{
+    using serializer = typename BasicJsonType::template json_serializer<T, void>;
+
+    static constexpr bool value =
+        is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
+        T>::value;
+};
+
+
+///////////////////
+// is_ functions //
+///////////////////
+
+template <typename T, typename = void>
+struct is_iterator_traits : std::false_type {};
+
+template <typename T>
+struct is_iterator_traits<iterator_traits<T>>
+{
+  private:
+    using traits = iterator_traits<T>;
+
+  public:
+    static constexpr auto value =
+        is_detected<value_type_t, traits>::value &&
+        is_detected<difference_type_t, traits>::value &&
+        is_detected<pointer_t, traits>::value &&
+        is_detected<iterator_category_t, traits>::value &&
+        is_detected<reference_t, traits>::value;
+};
+
+// source: https://stackoverflow.com/a/37193089/4116453
+
+template <typename T, typename = void>
+struct is_complete_type : std::false_type {};
+
+template <typename T>
+struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
+
+template <typename BasicJsonType, typename CompatibleObjectType,
+          typename = void>
+struct is_compatible_object_type_impl : std::false_type {};
+
+template <typename BasicJsonType, typename CompatibleObjectType>
+struct is_compatible_object_type_impl <
+    BasicJsonType, CompatibleObjectType,
+    enable_if_t<is_detected<mapped_type_t, CompatibleObjectType>::value and
+    is_detected<key_type_t, CompatibleObjectType>::value >>
+{
+
+    using object_t = typename BasicJsonType::object_t;
+
+    // macOS's is_constructible does not play well with nonesuch...
+    static constexpr bool value =
+        std::is_constructible<typename object_t::key_type,
+        typename CompatibleObjectType::key_type>::value and
+        std::is_constructible<typename object_t::mapped_type,
+        typename CompatibleObjectType::mapped_type>::value;
+};
+
+template <typename BasicJsonType, typename CompatibleObjectType>
+struct is_compatible_object_type
+    : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
+
+template <typename BasicJsonType, typename ConstructibleObjectType,
+          typename = void>
+struct is_constructible_object_type_impl : std::false_type {};
+
+template <typename BasicJsonType, typename ConstructibleObjectType>
+struct is_constructible_object_type_impl <
+    BasicJsonType, ConstructibleObjectType,
+    enable_if_t<is_detected<mapped_type_t, ConstructibleObjectType>::value and
+    is_detected<key_type_t, ConstructibleObjectType>::value >>
+{
+    using object_t = typename BasicJsonType::object_t;
+
+    static constexpr bool value =
+        (std::is_default_constructible<ConstructibleObjectType>::value and
+         (std::is_move_assignable<ConstructibleObjectType>::value or
+          std::is_copy_assignable<ConstructibleObjectType>::value) and
+         (std::is_constructible<typename ConstructibleObjectType::key_type,
+          typename object_t::key_type>::value and
+          std::is_same <
+          typename object_t::mapped_type,
+          typename ConstructibleObjectType::mapped_type >::value)) or
+        (has_from_json<BasicJsonType,
+         typename ConstructibleObjectType::mapped_type>::value or
+         has_non_default_from_json <
+         BasicJsonType,
+         typename ConstructibleObjectType::mapped_type >::value);
+};
+
+template <typename BasicJsonType, typename ConstructibleObjectType>
+struct is_constructible_object_type
+    : is_constructible_object_type_impl<BasicJsonType,
+      ConstructibleObjectType> {};
+
+template <typename BasicJsonType, typename CompatibleStringType,
+          typename = void>
+struct is_compatible_string_type_impl : std::false_type {};
+
+template <typename BasicJsonType, typename CompatibleStringType>
+struct is_compatible_string_type_impl <
+    BasicJsonType, CompatibleStringType,
+    enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
+    value_type_t, CompatibleStringType>::value >>
+{
+    static constexpr auto value =
+        std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
+};
+
+template <typename BasicJsonType, typename ConstructibleStringType>
+struct is_compatible_string_type
+    : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
+
+template <typename BasicJsonType, typename ConstructibleStringType,
+          typename = void>
+struct is_constructible_string_type_impl : std::false_type {};
+
+template <typename BasicJsonType, typename ConstructibleStringType>
+struct is_constructible_string_type_impl <
+    BasicJsonType, ConstructibleStringType,
+    enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
+    value_type_t, ConstructibleStringType>::value >>
+{
+    static constexpr auto value =
+        std::is_constructible<ConstructibleStringType,
+        typename BasicJsonType::string_t>::value;
+};
+
+template <typename BasicJsonType, typename ConstructibleStringType>
+struct is_constructible_string_type
+    : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
+
+template <typename BasicJsonType, typename CompatibleArrayType, typename = void>
+struct is_compatible_array_type_impl : std::false_type {};
+
+template <typename BasicJsonType, typename CompatibleArrayType>
+struct is_compatible_array_type_impl <
+    BasicJsonType, CompatibleArrayType,
+    enable_if_t<is_detected<value_type_t, CompatibleArrayType>::value and
+    is_detected<iterator_t, CompatibleArrayType>::value and
+// This is needed because json_reverse_iterator has a ::iterator type...
+// Therefore it is detected as a CompatibleArrayType.
+// The real fix would be to have an Iterable concept.
+    not is_iterator_traits<
+    iterator_traits<CompatibleArrayType>>::value >>
+{
+    static constexpr bool value =
+        std::is_constructible<BasicJsonType,
+        typename CompatibleArrayType::value_type>::value;
+};
+
+template <typename BasicJsonType, typename CompatibleArrayType>
+struct is_compatible_array_type
+    : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
+
+template <typename BasicJsonType, typename ConstructibleArrayType, typename = void>
+struct is_constructible_array_type_impl : std::false_type {};
+
+template <typename BasicJsonType, typename ConstructibleArrayType>
+struct is_constructible_array_type_impl <
+    BasicJsonType, ConstructibleArrayType,
+    enable_if_t<std::is_same<ConstructibleArrayType,
+    typename BasicJsonType::value_type>::value >>
+            : std::true_type {};
+
+template <typename BasicJsonType, typename ConstructibleArrayType>
+struct is_constructible_array_type_impl <
+    BasicJsonType, ConstructibleArrayType,
+    enable_if_t<not std::is_same<ConstructibleArrayType,
+    typename BasicJsonType::value_type>::value and
+    std::is_default_constructible<ConstructibleArrayType>::value and
+(std::is_move_assignable<ConstructibleArrayType>::value or
+ std::is_copy_assignable<ConstructibleArrayType>::value) and
+is_detected<value_type_t, ConstructibleArrayType>::value and
+is_detected<iterator_t, ConstructibleArrayType>::value and
+is_complete_type<
+detected_t<value_type_t, ConstructibleArrayType>>::value >>
+{
+    static constexpr bool value =
+        // This is needed because json_reverse_iterator has a ::iterator type,
+        // furthermore, std::back_insert_iterator (and other iterators) have a
+        // base class `iterator`... Therefore it is detected as a
+        // ConstructibleArrayType. The real fix would be to have an Iterable
+        // concept.
+        not is_iterator_traits<iterator_traits<ConstructibleArrayType>>::value and
+
+        (std::is_same<typename ConstructibleArrayType::value_type,
+         typename BasicJsonType::array_t::value_type>::value or
+         has_from_json<BasicJsonType,
+         typename ConstructibleArrayType::value_type>::value or
+         has_non_default_from_json <
+         BasicJsonType, typename ConstructibleArrayType::value_type >::value);
+};
+
+template <typename BasicJsonType, typename ConstructibleArrayType>
+struct is_constructible_array_type
+    : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
+
+template <typename RealIntegerType, typename CompatibleNumberIntegerType,
+          typename = void>
+struct is_compatible_integer_type_impl : std::false_type {};
+
+template <typename RealIntegerType, typename CompatibleNumberIntegerType>
+struct is_compatible_integer_type_impl <
+    RealIntegerType, CompatibleNumberIntegerType,
+    enable_if_t<std::is_integral<RealIntegerType>::value and
+    std::is_integral<CompatibleNumberIntegerType>::value and
+    not std::is_same<bool, CompatibleNumberIntegerType>::value >>
+{
+    // is there an assert somewhere on overflows?
+    using RealLimits = std::numeric_limits<RealIntegerType>;
+    using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
+
+    static constexpr auto value =
+        std::is_constructible<RealIntegerType,
+        CompatibleNumberIntegerType>::value and
+        CompatibleLimits::is_integer and
+        RealLimits::is_signed == CompatibleLimits::is_signed;
+};
+
+template <typename RealIntegerType, typename CompatibleNumberIntegerType>
+struct is_compatible_integer_type
+    : is_compatible_integer_type_impl<RealIntegerType,
+      CompatibleNumberIntegerType> {};
+
+template <typename BasicJsonType, typename CompatibleType, typename = void>
+struct is_compatible_type_impl: std::false_type {};
+
+template <typename BasicJsonType, typename CompatibleType>
+struct is_compatible_type_impl <
+    BasicJsonType, CompatibleType,
+    enable_if_t<is_complete_type<CompatibleType>::value >>
+{
+    static constexpr bool value =
+        has_to_json<BasicJsonType, CompatibleType>::value;
+};
+
+template <typename BasicJsonType, typename CompatibleType>
+struct is_compatible_type
+    : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
+
+// https://en.cppreference.com/w/cpp/types/conjunction
+template<class...> struct conjunction : std::true_type { };
+template<class B1> struct conjunction<B1> : B1 { };
+template<class B1, class... Bn>
+struct conjunction<B1, Bn...>
+: std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
+
+template <typename T1, typename T2>
+struct is_constructible_tuple : std::false_type {};
+
+template <typename T1, typename... Args>
+struct is_constructible_tuple<T1, std::tuple<Args...>> : conjunction<std::is_constructible<T1, Args>...> {};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+#include <array> // array
+#include <ciso646> // and
+#include <cstddef> // size_t
+#include <cstdint> // uint8_t
+#include <string> // string
+
+namespace nlohmann
+{
+namespace detail
+{
+///////////////////////////
+// JSON type enumeration //
+///////////////////////////
+
+/*!
+@brief the JSON type enumeration
+
+This enumeration collects the different JSON types. It is internally used to
+distinguish the stored values, and the functions @ref basic_json::is_null(),
+@ref basic_json::is_object(), @ref basic_json::is_array(),
+@ref basic_json::is_string(), @ref basic_json::is_boolean(),
+@ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
+@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
+@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
+@ref basic_json::is_structured() rely on it.
+
+@note There are three enumeration entries (number_integer, number_unsigned, and
+number_float), because the library distinguishes these three types for numbers:
+@ref basic_json::number_unsigned_t is used for unsigned integers,
+@ref basic_json::number_integer_t is used for signed integers, and
+@ref basic_json::number_float_t is used for floating-point numbers or to
+approximate integers which do not fit in the limits of their respective type.
+
+@sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
+value with the default value for a given type
+
+@since version 1.0.0
+*/
+enum class value_t : std::uint8_t
+{
+    null,             ///< null value
+    object,           ///< object (unordered set of name/value pairs)
+    array,            ///< array (ordered collection of values)
+    string,           ///< string value
+    boolean,          ///< boolean value
+    number_integer,   ///< number value (signed integer)
+    number_unsigned,  ///< number value (unsigned integer)
+    number_float,     ///< number value (floating-point)
+    discarded         ///< discarded by the parser callback function
+};
+
+/*!
+@brief comparison operator for JSON types
+
+Returns an ordering that is similar to Python:
+- order: null < boolean < number < object < array < string
+- furthermore, each type is not smaller than itself
+- discarded values are not comparable
+
+@since version 1.0.0
+*/
+inline bool operator<(const value_t lhs, const value_t rhs) noexcept
+{
+    static constexpr std::array<std::uint8_t, 8> order = {{
+            0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
+            1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
+        }
+    };
+
+    const auto l_index = static_cast<std::size_t>(lhs);
+    const auto r_index = static_cast<std::size_t>(rhs);
+    return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
+}
+}  // namespace detail
+}  // namespace nlohmann
+
+
+namespace nlohmann
+{
+namespace detail
+{
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
+{
+    if (JSON_HEDLEY_UNLIKELY(not j.is_null()))
+    {
+        JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
+    }
+    n = nullptr;
+}
+
+// overloads for basic_json template parameters
+template<typename BasicJsonType, typename ArithmeticType,
+         enable_if_t<std::is_arithmetic<ArithmeticType>::value and
+                     not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
+                     int> = 0>
+void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
+{
+    switch (static_cast<value_t>(j))
+    {
+        case value_t::number_unsigned:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
+            break;
+        }
+        case value_t::number_integer:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
+            break;
+        }
+        case value_t::number_float:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
+            break;
+        }
+
+        default:
+            JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
+    }
+}
+
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
+{
+    if (JSON_HEDLEY_UNLIKELY(not j.is_boolean()))
+    {
+        JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
+    }
+    b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
+}
+
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
+{
+    if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
+    {
+        JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
+    }
+    s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
+}
+
+template <
+    typename BasicJsonType, typename ConstructibleStringType,
+    enable_if_t <
+        is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value and
+        not std::is_same<typename BasicJsonType::string_t,
+                         ConstructibleStringType>::value,
+        int > = 0 >
+void from_json(const BasicJsonType& j, ConstructibleStringType& s)
+{
+    if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
+    {
+        JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
+    }
+
+    s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
+}
+
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
+{
+    get_arithmetic_value(j, val);
+}
+
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
+{
+    get_arithmetic_value(j, val);
+}
+
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
+{
+    get_arithmetic_value(j, val);
+}
+
+template<typename BasicJsonType, typename EnumType,
+         enable_if_t<std::is_enum<EnumType>::value, int> = 0>
+void from_json(const BasicJsonType& j, EnumType& e)
+{
+    typename std::underlying_type<EnumType>::type val;
+    get_arithmetic_value(j, val);
+    e = static_cast<EnumType>(val);
+}
+
+// forward_list doesn't have an insert method
+template<typename BasicJsonType, typename T, typename Allocator,
+         enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
+void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
+{
+    if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
+    {
+        JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
+    }
+    l.clear();
+    std::transform(j.rbegin(), j.rend(),
+                   std::front_inserter(l), [](const BasicJsonType & i)
+    {
+        return i.template get<T>();
+    });
+}
+
+// valarray doesn't have an insert method
+template<typename BasicJsonType, typename T,
+         enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
+void from_json(const BasicJsonType& j, std::valarray<T>& l)
+{
+    if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
+    {
+        JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
+    }
+    l.resize(j.size());
+    std::copy(j.begin(), j.end(), std::begin(l));
+}
+
+template <typename BasicJsonType, typename T, std::size_t N>
+auto from_json(const BasicJsonType& j, T (&arr)[N])
+-> decltype(j.template get<T>(), void())
+{
+    for (std::size_t i = 0; i < N; ++i)
+    {
+        arr[i] = j.at(i).template get<T>();
+    }
+}
+
+template<typename BasicJsonType>
+void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
+{
+    arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
+}
+
+template <typename BasicJsonType, typename T, std::size_t N>
+auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
+                          priority_tag<2> /*unused*/)
+-> decltype(j.template get<T>(), void())
+{
+    for (std::size_t i = 0; i < N; ++i)
+    {
+        arr[i] = j.at(i).template get<T>();
+    }
+}
+
+template<typename BasicJsonType, typename ConstructibleArrayType>
+auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
+-> decltype(
+    arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
+    j.template get<typename ConstructibleArrayType::value_type>(),
+    void())
+{
+    using std::end;
+
+    ConstructibleArrayType ret;
+    ret.reserve(j.size());
+    std::transform(j.begin(), j.end(),
+                   std::inserter(ret, end(ret)), [](const BasicJsonType & i)
+    {
+        // get<BasicJsonType>() returns *this, this won't call a from_json
+        // method when value_type is BasicJsonType
+        return i.template get<typename ConstructibleArrayType::value_type>();
+    });
+    arr = std::move(ret);
+}
+
+template <typename BasicJsonType, typename ConstructibleArrayType>
+void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
+                          priority_tag<0> /*unused*/)
+{
+    using std::end;
+
+    ConstructibleArrayType ret;
+    std::transform(
+        j.begin(), j.end(), std::inserter(ret, end(ret)),
+        [](const BasicJsonType & i)
+    {
+        // get<BasicJsonType>() returns *this, this won't call a from_json
+        // method when value_type is BasicJsonType
+        return i.template get<typename ConstructibleArrayType::value_type>();
+    });
+    arr = std::move(ret);
+}
+
+template <typename BasicJsonType, typename ConstructibleArrayType,
+          enable_if_t <
+              is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value and
+              not is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value and
+              not is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value and
+              not is_basic_json<ConstructibleArrayType>::value,
+              int > = 0 >
+
+auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
+-> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
+j.template get<typename ConstructibleArrayType::value_type>(),
+void())
+{
+    if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
+    {
+        JSON_THROW(type_error::create(302, "type must be array, but is " +
+                                      std::string(j.type_name())));
+    }
+
+    from_json_array_impl(j, arr, priority_tag<3> {});
+}
+
+template<typename BasicJsonType, typename ConstructibleObjectType,
+         enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
+void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
+{
+    if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
+    {
+        JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
+    }
+
+    ConstructibleObjectType ret;
+    auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
+    using value_type = typename ConstructibleObjectType::value_type;
+    std::transform(
+        inner_object->begin(), inner_object->end(),
+        std::inserter(ret, ret.begin()),
+        [](typename BasicJsonType::object_t::value_type const & p)
+    {
+        return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
+    });
+    obj = std::move(ret);
+}
+
+// overload for arithmetic types, not chosen for basic_json template arguments
+// (BooleanType, etc..); note: Is it really necessary to provide explicit
+// overloads for boolean_t etc. in case of a custom BooleanType which is not
+// an arithmetic type?
+template<typename BasicJsonType, typename ArithmeticType,
+         enable_if_t <
+             std::is_arithmetic<ArithmeticType>::value and
+             not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
+             not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
+             not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
+             not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
+             int> = 0>
+void from_json(const BasicJsonType& j, ArithmeticType& val)
+{
+    switch (static_cast<value_t>(j))
+    {
+        case value_t::number_unsigned:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
+            break;
+        }
+        case value_t::number_integer:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
+            break;
+        }
+        case value_t::number_float:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
+            break;
+        }
+        case value_t::boolean:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
+            break;
+        }
+
+        default:
+            JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
+    }
+}
+
+template<typename BasicJsonType, typename A1, typename A2>
+void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
+{
+    p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
+}
+
+template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
+void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...> /*unused*/)
+{
+    t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
+}
+
+template<typename BasicJsonType, typename... Args>
+void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
+{
+    from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
+}
+
+template <typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
+          typename = enable_if_t<not std::is_constructible<
+                                     typename BasicJsonType::string_t, Key>::value>>
+void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
+{
+    if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
+    {
+        JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
+    }
+    m.clear();
+    for (const auto& p : j)
+    {
+        if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
+        {
+            JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
+        }
+        m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
+    }
+}
+
+template <typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
+          typename = enable_if_t<not std::is_constructible<
+                                     typename BasicJsonType::string_t, Key>::value>>
+void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
+{
+    if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
+    {
+        JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
+    }
+    m.clear();
+    for (const auto& p : j)
+    {
+        if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
+        {
+            JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
+        }
+        m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
+    }
+}
+
+struct from_json_fn
+{
+    template<typename BasicJsonType, typename T>
+    auto operator()(const BasicJsonType& j, T& val) const
+    noexcept(noexcept(from_json(j, val)))
+    -> decltype(from_json(j, val), void())
+    {
+        return from_json(j, val);
+    }
+};
+}  // namespace detail
+
+/// namespace to hold default `from_json` function
+/// to see why this is required:
+/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
+namespace
+{
+constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
+} // namespace
+} // namespace nlohmann
+
+// #include <nlohmann/detail/conversions/to_json.hpp>
+
+
+#include <algorithm> // copy
+#include <ciso646> // or, and, not
+#include <iterator> // begin, end
+#include <string> // string
+#include <tuple> // tuple, get
+#include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
+#include <utility> // move, forward, declval, pair
+#include <valarray> // valarray
+#include <vector> // vector
+
+// #include <nlohmann/detail/iterators/iteration_proxy.hpp>
+
+
+#include <cstddef> // size_t
+#include <iterator> // input_iterator_tag
+#include <string> // string, to_string
+#include <tuple> // tuple_size, get, tuple_element
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+template<typename string_type>
+void int_to_string( string_type& target, std::size_t value )
+{
+    target = std::to_string(value);
+}
+template <typename IteratorType> class iteration_proxy_value
+{
+  public:
+    using difference_type = std::ptrdiff_t;
+    using value_type = iteration_proxy_value;
+    using pointer = value_type * ;
+    using reference = value_type & ;
+    using iterator_category = std::input_iterator_tag;
+    using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type;
+
+  private:
+    /// the iterator
+    IteratorType anchor;
+    /// an index for arrays (used to create key names)
+    std::size_t array_index = 0;
+    /// last stringified array index
+    mutable std::size_t array_index_last = 0;
+    /// a string representation of the array index
+    mutable string_type array_index_str = "0";
+    /// an empty string (to return a reference for primitive values)
+    const string_type empty_str = "";
+
+  public:
+    explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {}
+
+    /// dereference operator (needed for range-based for)
+    iteration_proxy_value& operator*()
+    {
+        return *this;
+    }
+
+    /// increment operator (needed for range-based for)
+    iteration_proxy_value& operator++()
+    {
+        ++anchor;
+        ++array_index;
+
+        return *this;
+    }
+
+    /// equality operator (needed for InputIterator)
+    bool operator==(const iteration_proxy_value& o) const
+    {
+        return anchor == o.anchor;
+    }
+
+    /// inequality operator (needed for range-based for)
+    bool operator!=(const iteration_proxy_value& o) const
+    {
+        return anchor != o.anchor;
+    }
+
+    /// return key of the iterator
+    const string_type& key() const
+    {
+        assert(anchor.m_object != nullptr);
+
+        switch (anchor.m_object->type())
+        {
+            // use integer array index as key
+            case value_t::array:
+            {
+                if (array_index != array_index_last)
+                {
+                    int_to_string( array_index_str, array_index );
+                    array_index_last = array_index;
+                }
+                return array_index_str;
+            }
+
+            // use key from the object
+            case value_t::object:
+                return anchor.key();
+
+            // use an empty key for all primitive types
+            default:
+                return empty_str;
+        }
+    }
+
+    /// return value of the iterator
+    typename IteratorType::reference value() const
+    {
+        return anchor.value();
+    }
+};
+
+/// proxy class for the items() function
+template<typename IteratorType> class iteration_proxy
+{
+  private:
+    /// the container to iterate
+    typename IteratorType::reference container;
+
+  public:
+    /// construct iteration proxy from a container
+    explicit iteration_proxy(typename IteratorType::reference cont) noexcept
+        : container(cont) {}
+
+    /// return iterator begin (needed for range-based for)
+    iteration_proxy_value<IteratorType> begin() noexcept
+    {
+        return iteration_proxy_value<IteratorType>(container.begin());
+    }
+
+    /// return iterator end (needed for range-based for)
+    iteration_proxy_value<IteratorType> end() noexcept
+    {
+        return iteration_proxy_value<IteratorType>(container.end());
+    }
+};
+// Structured Bindings Support
+// For further reference see https://blog.tartanllama.xyz/structured-bindings/
+// And see https://github.com/nlohmann/json/pull/1391
+template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
+auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
+{
+    return i.key();
+}
+// Structured Bindings Support
+// For further reference see https://blog.tartanllama.xyz/structured-bindings/
+// And see https://github.com/nlohmann/json/pull/1391
+template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
+auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
+{
+    return i.value();
+}
+}  // namespace detail
+}  // namespace nlohmann
+
+// The Addition to the STD Namespace is required to add
+// Structured Bindings Support to the iteration_proxy_value class
+// For further reference see https://blog.tartanllama.xyz/structured-bindings/
+// And see https://github.com/nlohmann/json/pull/1391
+namespace std
+{
+#if defined(__clang__)
+    // Fix: https://github.com/nlohmann/json/issues/1401
+    #pragma clang diagnostic push
+    #pragma clang diagnostic ignored "-Wmismatched-tags"
+#endif
+template <typename IteratorType>
+class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
+            : public std::integral_constant<std::size_t, 2> {};
+
+template <std::size_t N, typename IteratorType>
+class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
+{
+  public:
+    using type = decltype(
+                     get<N>(std::declval <
+                            ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
+};
+#if defined(__clang__)
+    #pragma clang diagnostic pop
+#endif
+} // namespace std
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+//////////////////
+// constructors //
+//////////////////
+
+template<value_t> struct external_constructor;
+
+template<>
+struct external_constructor<value_t::boolean>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
+    {
+        j.m_type = value_t::boolean;
+        j.m_value = b;
+        j.assert_invariant();
+    }
+};
+
+template<>
+struct external_constructor<value_t::string>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
+    {
+        j.m_type = value_t::string;
+        j.m_value = s;
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
+    {
+        j.m_type = value_t::string;
+        j.m_value = std::move(s);
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType, typename CompatibleStringType,
+             enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
+                         int> = 0>
+    static void construct(BasicJsonType& j, const CompatibleStringType& str)
+    {
+        j.m_type = value_t::string;
+        j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
+        j.assert_invariant();
+    }
+};
+
+template<>
+struct external_constructor<value_t::number_float>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
+    {
+        j.m_type = value_t::number_float;
+        j.m_value = val;
+        j.assert_invariant();
+    }
+};
+
+template<>
+struct external_constructor<value_t::number_unsigned>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
+    {
+        j.m_type = value_t::number_unsigned;
+        j.m_value = val;
+        j.assert_invariant();
+    }
+};
+
+template<>
+struct external_constructor<value_t::number_integer>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
+    {
+        j.m_type = value_t::number_integer;
+        j.m_value = val;
+        j.assert_invariant();
+    }
+};
+
+template<>
+struct external_constructor<value_t::array>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
+    {
+        j.m_type = value_t::array;
+        j.m_value = arr;
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
+    {
+        j.m_type = value_t::array;
+        j.m_value = std::move(arr);
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType, typename CompatibleArrayType,
+             enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
+                         int> = 0>
+    static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
+    {
+        using std::begin;
+        using std::end;
+        j.m_type = value_t::array;
+        j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, const std::vector<bool>& arr)
+    {
+        j.m_type = value_t::array;
+        j.m_value = value_t::array;
+        j.m_value.array->reserve(arr.size());
+        for (const bool x : arr)
+        {
+            j.m_value.array->push_back(x);
+        }
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType, typename T,
+             enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
+    static void construct(BasicJsonType& j, const std::valarray<T>& arr)
+    {
+        j.m_type = value_t::array;
+        j.m_value = value_t::array;
+        j.m_value.array->resize(arr.size());
+        if (arr.size() > 0)
+        {
+            std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
+        }
+        j.assert_invariant();
+    }
+};
+
+template<>
+struct external_constructor<value_t::object>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
+    {
+        j.m_type = value_t::object;
+        j.m_value = obj;
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
+    {
+        j.m_type = value_t::object;
+        j.m_value = std::move(obj);
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType, typename CompatibleObjectType,
+             enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
+    static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
+    {
+        using std::begin;
+        using std::end;
+
+        j.m_type = value_t::object;
+        j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
+        j.assert_invariant();
+    }
+};
+
+/////////////
+// to_json //
+/////////////
+
+template<typename BasicJsonType, typename T,
+         enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
+void to_json(BasicJsonType& j, T b) noexcept
+{
+    external_constructor<value_t::boolean>::construct(j, b);
+}
+
+template<typename BasicJsonType, typename CompatibleString,
+         enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
+void to_json(BasicJsonType& j, const CompatibleString& s)
+{
+    external_constructor<value_t::string>::construct(j, s);
+}
+
+template<typename BasicJsonType>
+void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
+{
+    external_constructor<value_t::string>::construct(j, std::move(s));
+}
+
+template<typename BasicJsonType, typename FloatType,
+         enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
+void to_json(BasicJsonType& j, FloatType val) noexcept
+{
+    external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
+}
+
+template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
+         enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
+void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
+{
+    external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
+}
+
+template<typename BasicJsonType, typename CompatibleNumberIntegerType,
+         enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
+void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
+{
+    external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
+}
+
+template<typename BasicJsonType, typename EnumType,
+         enable_if_t<std::is_enum<EnumType>::value, int> = 0>
+void to_json(BasicJsonType& j, EnumType e) noexcept
+{
+    using underlying_type = typename std::underlying_type<EnumType>::type;
+    external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
+}
+
+template<typename BasicJsonType>
+void to_json(BasicJsonType& j, const std::vector<bool>& e)
+{
+    external_constructor<value_t::array>::construct(j, e);
+}
+
+template <typename BasicJsonType, typename CompatibleArrayType,
+          enable_if_t<is_compatible_array_type<BasicJsonType,
+                      CompatibleArrayType>::value and
+                      not is_compatible_object_type<
+                          BasicJsonType, CompatibleArrayType>::value and
+                      not is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value and
+                      not is_basic_json<CompatibleArrayType>::value,
+                      int> = 0>
+void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
+{
+    external_constructor<value_t::array>::construct(j, arr);
+}
+
+template<typename BasicJsonType, typename T,
+         enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
+void to_json(BasicJsonType& j, const std::valarray<T>& arr)
+{
+    external_constructor<value_t::array>::construct(j, std::move(arr));
+}
+
+template<typename BasicJsonType>
+void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
+{
+    external_constructor<value_t::array>::construct(j, std::move(arr));
+}
+
+template<typename BasicJsonType, typename CompatibleObjectType,
+         enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value and not is_basic_json<CompatibleObjectType>::value, int> = 0>
+void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
+{
+    external_constructor<value_t::object>::construct(j, obj);
+}
+
+template<typename BasicJsonType>
+void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
+{
+    external_constructor<value_t::object>::construct(j, std::move(obj));
+}
+
+template <
+    typename BasicJsonType, typename T, std::size_t N,
+    enable_if_t<not std::is_constructible<typename BasicJsonType::string_t,
+                const T(&)[N]>::value,
+                int> = 0 >
+void to_json(BasicJsonType& j, const T(&arr)[N])
+{
+    external_constructor<value_t::array>::construct(j, arr);
+}
+
+template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 >
+void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
+{
+    j = { p.first, p.second };
+}
+
+// for https://github.com/nlohmann/json/pull/1134
+template < typename BasicJsonType, typename T,
+           enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
+void to_json(BasicJsonType& j, const T& b)
+{
+    j = { {b.key(), b.value()} };
+}
+
+template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
+void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
+{
+    j = { std::get<Idx>(t)... };
+}
+
+template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0>
+void to_json(BasicJsonType& j, const T& t)
+{
+    to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {});
+}
+
+struct to_json_fn
+{
+    template<typename BasicJsonType, typename T>
+    auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
+    -> decltype(to_json(j, std::forward<T>(val)), void())
+    {
+        return to_json(j, std::forward<T>(val));
+    }
+};
+}  // namespace detail
+
+/// namespace to hold default `to_json` function
+namespace
+{
+constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
+} // namespace
+} // namespace nlohmann
+
+
+namespace nlohmann
+{
+
+template<typename, typename>
+struct adl_serializer
+{
+    /*!
+    @brief convert a JSON value to any value type
+
+    This function is usually called by the `get()` function of the
+    @ref basic_json class (either explicit or via conversion operators).
+
+    @param[in] j        JSON value to read from
+    @param[in,out] val  value to write to
+    */
+    template<typename BasicJsonType, typename ValueType>
+    static auto from_json(BasicJsonType&& j, ValueType& val) noexcept(
+        noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
+    -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
+    {
+        ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
+    }
+
+    /*!
+    @brief convert any value type to a JSON value
+
+    This function is usually called by the constructors of the @ref basic_json
+    class.
+
+    @param[in,out] j  JSON value to write to
+    @param[in] val    value to read from
+    */
+    template <typename BasicJsonType, typename ValueType>
+    static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(
+        noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
+    -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())
+    {
+        ::nlohmann::to_json(j, std::forward<ValueType>(val));
+    }
+};
+
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/conversions/from_json.hpp>
+
+// #include <nlohmann/detail/conversions/to_json.hpp>
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/input/binary_reader.hpp>
+
+
+#include <algorithm> // generate_n
+#include <array> // array
+#include <cassert> // assert
+#include <cmath> // ldexp
+#include <cstddef> // size_t
+#include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
+#include <cstdio> // snprintf
+#include <cstring> // memcpy
+#include <iterator> // back_inserter
+#include <limits> // numeric_limits
+#include <string> // char_traits, string
+#include <utility> // make_pair, move
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/input/input_adapters.hpp>
+
+
+#include <array> // array
+#include <cassert> // assert
+#include <cstddef> // size_t
+#include <cstdio> //FILE *
+#include <cstring> // strlen
+#include <istream> // istream
+#include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
+#include <memory> // shared_ptr, make_shared, addressof
+#include <numeric> // accumulate
+#include <string> // string, char_traits
+#include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
+#include <utility> // pair, declval
+
+// #include <nlohmann/detail/iterators/iterator_traits.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+/// the supported input formats
+enum class input_format_t { json, cbor, msgpack, ubjson, bson };
+
+////////////////////
+// input adapters //
+////////////////////
+
+/*!
+@brief abstract input adapter interface
+
+Produces a stream of std::char_traits<char>::int_type characters from a
+std::istream, a buffer, or some other input type. Accepts the return of
+exactly one non-EOF character for future input. The int_type characters
+returned consist of all valid char values as positive values (typically
+unsigned char), plus an EOF value outside that range, specified by the value
+of the function std::char_traits<char>::eof(). This value is typically -1, but
+could be any arbitrary value which is not a valid char value.
+*/
+struct input_adapter_protocol
+{
+    /// get a character [0,255] or std::char_traits<char>::eof().
+    virtual std::char_traits<char>::int_type get_character() = 0;
+    virtual ~input_adapter_protocol() = default;
+};
+
+/// a type to simplify interfaces
+using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
+
+/*!
+Input adapter for stdio file access. This adapter read only 1 byte and do not use any
+ buffer. This adapter is a very low level adapter.
+*/
+class file_input_adapter : public input_adapter_protocol
+{
+  public:
+    JSON_HEDLEY_NON_NULL(2)
+    explicit file_input_adapter(std::FILE* f)  noexcept
+        : m_file(f)
+    {}
+
+    // make class move-only
+    file_input_adapter(const file_input_adapter&) = delete;
+    file_input_adapter(file_input_adapter&&) = default;
+    file_input_adapter& operator=(const file_input_adapter&) = delete;
+    file_input_adapter& operator=(file_input_adapter&&) = default;
+    ~file_input_adapter() override = default;
+
+    std::char_traits<char>::int_type get_character() noexcept override
+    {
+        return std::fgetc(m_file);
+    }
+
+  private:
+    /// the file pointer to read from
+    std::FILE* m_file;
+};
+
+
+/*!
+Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
+beginning of input. Does not support changing the underlying std::streambuf
+in mid-input. Maintains underlying std::istream and std::streambuf to support
+subsequent use of standard std::istream operations to process any input
+characters following those used in parsing the JSON input.  Clears the
+std::istream flags; any input errors (e.g., EOF) will be detected by the first
+subsequent call for input from the std::istream.
+*/
+class input_stream_adapter : public input_adapter_protocol
+{
+  public:
+    ~input_stream_adapter() override
+    {
+        // clear stream flags; we use underlying streambuf I/O, do not
+        // maintain ifstream flags, except eof
+        is.clear(is.rdstate() & std::ios::eofbit);
+    }
+
+    explicit input_stream_adapter(std::istream& i)
+        : is(i), sb(*i.rdbuf())
+    {}
+
+    // delete because of pointer members
+    input_stream_adapter(const input_stream_adapter&) = delete;
+    input_stream_adapter& operator=(input_stream_adapter&) = delete;
+    input_stream_adapter(input_stream_adapter&&) = delete;
+    input_stream_adapter& operator=(input_stream_adapter&&) = delete;
+
+    // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
+    // ensure that std::char_traits<char>::eof() and the character 0xFF do not
+    // end up as the same value, eg. 0xFFFFFFFF.
+    std::char_traits<char>::int_type get_character() override
+    {
+        auto res = sb.sbumpc();
+        // set eof manually, as we don't use the istream interface.
+        if (res == EOF)
+        {
+            is.clear(is.rdstate() | std::ios::eofbit);
+        }
+        return res;
+    }
+
+  private:
+    /// the associated input stream
+    std::istream& is;
+    std::streambuf& sb;
+};
+
+/// input adapter for buffer input
+class input_buffer_adapter : public input_adapter_protocol
+{
+  public:
+    input_buffer_adapter(const char* b, const std::size_t l) noexcept
+        : cursor(b), limit(b == nullptr ? nullptr : (b + l))
+    {}
+
+    // delete because of pointer members
+    input_buffer_adapter(const input_buffer_adapter&) = delete;
+    input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
+    input_buffer_adapter(input_buffer_adapter&&) = delete;
+    input_buffer_adapter& operator=(input_buffer_adapter&&) = delete;
+    ~input_buffer_adapter() override = default;
+
+    std::char_traits<char>::int_type get_character() noexcept override
+    {
+        if (JSON_HEDLEY_LIKELY(cursor < limit))
+        {
+            assert(cursor != nullptr and limit != nullptr);
+            return std::char_traits<char>::to_int_type(*(cursor++));
+        }
+
+        return std::char_traits<char>::eof();
+    }
+
+  private:
+    /// pointer to the current character
+    const char* cursor;
+    /// pointer past the last character
+    const char* const limit;
+};
+
+template<typename WideStringType, size_t T>
+struct wide_string_input_helper
+{
+    // UTF-32
+    static void fill_buffer(const WideStringType& str,
+                            size_t& current_wchar,
+                            std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
+                            size_t& utf8_bytes_index,
+                            size_t& utf8_bytes_filled)
+    {
+        utf8_bytes_index = 0;
+
+        if (current_wchar == str.size())
+        {
+            utf8_bytes[0] = std::char_traits<char>::eof();
+            utf8_bytes_filled = 1;
+        }
+        else
+        {
+            // get the current character
+            const auto wc = static_cast<unsigned int>(str[current_wchar++]);
+
+            // UTF-32 to UTF-8 encoding
+            if (wc < 0x80)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
+                utf8_bytes_filled = 1;
+            }
+            else if (wc <= 0x7FF)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u) & 0x1Fu));
+                utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
+                utf8_bytes_filled = 2;
+            }
+            else if (wc <= 0xFFFF)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u) & 0x0Fu));
+                utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
+                utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
+                utf8_bytes_filled = 3;
+            }
+            else if (wc <= 0x10FFFF)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((wc >> 18u) & 0x07u));
+                utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 12u) & 0x3Fu));
+                utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
+                utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
+                utf8_bytes_filled = 4;
+            }
+            else
+            {
+                // unknown character
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
+                utf8_bytes_filled = 1;
+            }
+        }
+    }
+};
+
+template<typename WideStringType>
+struct wide_string_input_helper<WideStringType, 2>
+{
+    // UTF-16
+    static void fill_buffer(const WideStringType& str,
+                            size_t& current_wchar,
+                            std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
+                            size_t& utf8_bytes_index,
+                            size_t& utf8_bytes_filled)
+    {
+        utf8_bytes_index = 0;
+
+        if (current_wchar == str.size())
+        {
+            utf8_bytes[0] = std::char_traits<char>::eof();
+            utf8_bytes_filled = 1;
+        }
+        else
+        {
+            // get the current character
+            const auto wc = static_cast<unsigned int>(str[current_wchar++]);
+
+            // UTF-16 to UTF-8 encoding
+            if (wc < 0x80)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
+                utf8_bytes_filled = 1;
+            }
+            else if (wc <= 0x7FF)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u)));
+                utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
+                utf8_bytes_filled = 2;
+            }
+            else if (0xD800 > wc or wc >= 0xE000)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u)));
+                utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
+                utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
+                utf8_bytes_filled = 3;
+            }
+            else
+            {
+                if (current_wchar < str.size())
+                {
+                    const auto wc2 = static_cast<unsigned int>(str[current_wchar++]);
+                    const auto charcode = 0x10000u + (((wc & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
+                    utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
+                    utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
+                    utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
+                    utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
+                    utf8_bytes_filled = 4;
+                }
+                else
+                {
+                    // unknown character
+                    ++current_wchar;
+                    utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
+                    utf8_bytes_filled = 1;
+                }
+            }
+        }
+    }
+};
+
+template<typename WideStringType>
+class wide_string_input_adapter : public input_adapter_protocol
+{
+  public:
+    explicit wide_string_input_adapter(const WideStringType& w) noexcept
+        : str(w)
+    {}
+
+    std::char_traits<char>::int_type get_character() noexcept override
+    {
+        // check if buffer needs to be filled
+        if (utf8_bytes_index == utf8_bytes_filled)
+        {
+            fill_buffer<sizeof(typename WideStringType::value_type)>();
+
+            assert(utf8_bytes_filled > 0);
+            assert(utf8_bytes_index == 0);
+        }
+
+        // use buffer
+        assert(utf8_bytes_filled > 0);
+        assert(utf8_bytes_index < utf8_bytes_filled);
+        return utf8_bytes[utf8_bytes_index++];
+    }
+
+  private:
+    template<size_t T>
+    void fill_buffer()
+    {
+        wide_string_input_helper<WideStringType, T>::fill_buffer(str, current_wchar, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
+    }
+
+    /// the wstring to process
+    const WideStringType& str;
+
+    /// index of the current wchar in str
+    std::size_t current_wchar = 0;
+
+    /// a buffer for UTF-8 bytes
+    std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
+
+    /// index to the utf8_codes array for the next valid byte
+    std::size_t utf8_bytes_index = 0;
+    /// number of valid bytes in the utf8_codes array
+    std::size_t utf8_bytes_filled = 0;
+};
+
+class input_adapter
+{
+  public:
+    // native support
+    JSON_HEDLEY_NON_NULL(2)
+    input_adapter(std::FILE* file)
+        : ia(std::make_shared<file_input_adapter>(file)) {}
+    /// input adapter for input stream
+    input_adapter(std::istream& i)
+        : ia(std::make_shared<input_stream_adapter>(i)) {}
+
+    /// input adapter for input stream
+    input_adapter(std::istream&& i)
+        : ia(std::make_shared<input_stream_adapter>(i)) {}
+
+    input_adapter(const std::wstring& ws)
+        : ia(std::make_shared<wide_string_input_adapter<std::wstring>>(ws)) {}
+
+    input_adapter(const std::u16string& ws)
+        : ia(std::make_shared<wide_string_input_adapter<std::u16string>>(ws)) {}
+
+    input_adapter(const std::u32string& ws)
+        : ia(std::make_shared<wide_string_input_adapter<std::u32string>>(ws)) {}
+
+    /// input adapter for buffer
+    template<typename CharT,
+             typename std::enable_if<
+                 std::is_pointer<CharT>::value and
+                 std::is_integral<typename std::remove_pointer<CharT>::type>::value and
+                 sizeof(typename std::remove_pointer<CharT>::type) == 1,
+                 int>::type = 0>
+    input_adapter(CharT b, std::size_t l)
+        : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
+
+    // derived support
+
+    /// input adapter for string literal
+    template<typename CharT,
+             typename std::enable_if<
+                 std::is_pointer<CharT>::value and
+                 std::is_integral<typename std::remove_pointer<CharT>::type>::value and
+                 sizeof(typename std::remove_pointer<CharT>::type) == 1,
+                 int>::type = 0>
+    input_adapter(CharT b)
+        : input_adapter(reinterpret_cast<const char*>(b),
+                        std::strlen(reinterpret_cast<const char*>(b))) {}
+
+    /// input adapter for iterator range with contiguous storage
+    template<class IteratorType,
+             typename std::enable_if<
+                 std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
+                 int>::type = 0>
+    input_adapter(IteratorType first, IteratorType last)
+    {
+#ifndef NDEBUG
+        // assertion to check that the iterator range is indeed contiguous,
+        // see https://stackoverflow.com/a/35008842/266378 for more discussion
+        const auto is_contiguous = std::accumulate(
+                                       first, last, std::pair<bool, int>(true, 0),
+                                       [&first](std::pair<bool, int> res, decltype(*first) val)
+        {
+            res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
+            return res;
+        }).first;
+        assert(is_contiguous);
+#endif
+
+        // assertion to check that each element is 1 byte long
+        static_assert(
+            sizeof(typename iterator_traits<IteratorType>::value_type) == 1,
+            "each element in the iterator range must have the size of 1 byte");
+
+        const auto len = static_cast<size_t>(std::distance(first, last));
+        if (JSON_HEDLEY_LIKELY(len > 0))
+        {
+            // there is at least one element: use the address of first
+            ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
+        }
+        else
+        {
+            // the address of first cannot be used: use nullptr
+            ia = std::make_shared<input_buffer_adapter>(nullptr, len);
+        }
+    }
+
+    /// input adapter for array
+    template<class T, std::size_t N>
+    input_adapter(T (&array)[N])
+        : input_adapter(std::begin(array), std::end(array)) {}
+
+    /// input adapter for contiguous container
+    template<class ContiguousContainer, typename
+             std::enable_if<not std::is_pointer<ContiguousContainer>::value and
+                            std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
+                            int>::type = 0>
+    input_adapter(const ContiguousContainer& c)
+        : input_adapter(std::begin(c), std::end(c)) {}
+
+    operator input_adapter_t()
+    {
+        return ia;
+    }
+
+  private:
+    /// the actual adapter
+    input_adapter_t ia = nullptr;
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/input/json_sax.hpp>
+
+
+#include <cassert> // assert
+#include <cstddef>
+#include <string> // string
+#include <utility> // move
+#include <vector> // vector
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+
+/*!
+@brief SAX interface
+
+This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
+Each function is called in different situations while the input is parsed. The
+boolean return value informs the parser whether to continue processing the
+input.
+*/
+template<typename BasicJsonType>
+struct json_sax
+{
+    /// type for (signed) integers
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    /// type for unsigned integers
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    /// type for floating-point numbers
+    using number_float_t = typename BasicJsonType::number_float_t;
+    /// type for strings
+    using string_t = typename BasicJsonType::string_t;
+
+    /*!
+    @brief a null value was read
+    @return whether parsing should proceed
+    */
+    virtual bool null() = 0;
+
+    /*!
+    @brief a boolean value was read
+    @param[in] val  boolean value
+    @return whether parsing should proceed
+    */
+    virtual bool boolean(bool val) = 0;
+
+    /*!
+    @brief an integer number was read
+    @param[in] val  integer value
+    @return whether parsing should proceed
+    */
+    virtual bool number_integer(number_integer_t val) = 0;
+
+    /*!
+    @brief an unsigned integer number was read
+    @param[in] val  unsigned integer value
+    @return whether parsing should proceed
+    */
+    virtual bool number_unsigned(number_unsigned_t val) = 0;
+
+    /*!
+    @brief an floating-point number was read
+    @param[in] val  floating-point value
+    @param[in] s    raw token value
+    @return whether parsing should proceed
+    */
+    virtual bool number_float(number_float_t val, const string_t& s) = 0;
+
+    /*!
+    @brief a string was read
+    @param[in] val  string value
+    @return whether parsing should proceed
+    @note It is safe to move the passed string.
+    */
+    virtual bool string(string_t& val) = 0;
+
+    /*!
+    @brief the beginning of an object was read
+    @param[in] elements  number of object elements or -1 if unknown
+    @return whether parsing should proceed
+    @note binary formats may report the number of elements
+    */
+    virtual bool start_object(std::size_t elements) = 0;
+
+    /*!
+    @brief an object key was read
+    @param[in] val  object key
+    @return whether parsing should proceed
+    @note It is safe to move the passed string.
+    */
+    virtual bool key(string_t& val) = 0;
+
+    /*!
+    @brief the end of an object was read
+    @return whether parsing should proceed
+    */
+    virtual bool end_object() = 0;
+
+    /*!
+    @brief the beginning of an array was read
+    @param[in] elements  number of array elements or -1 if unknown
+    @return whether parsing should proceed
+    @note binary formats may report the number of elements
+    */
+    virtual bool start_array(std::size_t elements) = 0;
+
+    /*!
+    @brief the end of an array was read
+    @return whether parsing should proceed
+    */
+    virtual bool end_array() = 0;
+
+    /*!
+    @brief a parse error occurred
+    @param[in] position    the position in the input where the error occurs
+    @param[in] last_token  the last read token
+    @param[in] ex          an exception object describing the error
+    @return whether parsing should proceed (must return false)
+    */
+    virtual bool parse_error(std::size_t position,
+                             const std::string& last_token,
+                             const detail::exception& ex) = 0;
+
+    virtual ~json_sax() = default;
+};
+
+
+namespace detail
+{
+/*!
+@brief SAX implementation to create a JSON value from SAX events
+
+This class implements the @ref json_sax interface and processes the SAX events
+to create a JSON value which makes it basically a DOM parser. The structure or
+hierarchy of the JSON value is managed by the stack `ref_stack` which contains
+a pointer to the respective array or object for each recursion depth.
+
+After successful parsing, the value that is passed by reference to the
+constructor contains the parsed value.
+
+@tparam BasicJsonType  the JSON type
+*/
+template<typename BasicJsonType>
+class json_sax_dom_parser
+{
+  public:
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+
+    /*!
+    @param[in, out] r  reference to a JSON value that is manipulated while
+                       parsing
+    @param[in] allow_exceptions_  whether parse errors yield exceptions
+    */
+    explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
+        : root(r), allow_exceptions(allow_exceptions_)
+    {}
+
+    // make class move-only
+    json_sax_dom_parser(const json_sax_dom_parser&) = delete;
+    json_sax_dom_parser(json_sax_dom_parser&&) = default;
+    json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
+    json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default;
+    ~json_sax_dom_parser() = default;
+
+    bool null()
+    {
+        handle_value(nullptr);
+        return true;
+    }
+
+    bool boolean(bool val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool number_integer(number_integer_t val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool number_unsigned(number_unsigned_t val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool number_float(number_float_t val, const string_t& /*unused*/)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool string(string_t& val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool start_object(std::size_t len)
+    {
+        ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
+
+        if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
+        {
+            JSON_THROW(out_of_range::create(408,
+                                            "excessive object size: " + std::to_string(len)));
+        }
+
+        return true;
+    }
+
+    bool key(string_t& val)
+    {
+        // add null at given key and store the reference for later
+        object_element = &(ref_stack.back()->m_value.object->operator[](val));
+        return true;
+    }
+
+    bool end_object()
+    {
+        ref_stack.pop_back();
+        return true;
+    }
+
+    bool start_array(std::size_t len)
+    {
+        ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
+
+        if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
+        {
+            JSON_THROW(out_of_range::create(408,
+                                            "excessive array size: " + std::to_string(len)));
+        }
+
+        return true;
+    }
+
+    bool end_array()
+    {
+        ref_stack.pop_back();
+        return true;
+    }
+
+    bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
+                     const detail::exception& ex)
+    {
+        errored = true;
+        if (allow_exceptions)
+        {
+            // determine the proper exception type from the id
+            switch ((ex.id / 100) % 100)
+            {
+                case 1:
+                    JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
+                case 4:
+                    JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
+                // LCOV_EXCL_START
+                case 2:
+                    JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
+                case 3:
+                    JSON_THROW(*static_cast<const detail::type_error*>(&ex));
+                case 5:
+                    JSON_THROW(*static_cast<const detail::other_error*>(&ex));
+                default:
+                    assert(false);
+                    // LCOV_EXCL_STOP
+            }
+        }
+        return false;
+    }
+
+    constexpr bool is_errored() const
+    {
+        return errored;
+    }
+
+  private:
+    /*!
+    @invariant If the ref stack is empty, then the passed value will be the new
+               root.
+    @invariant If the ref stack contains a value, then it is an array or an
+               object to which we can add elements
+    */
+    template<typename Value>
+    JSON_HEDLEY_RETURNS_NON_NULL
+    BasicJsonType* handle_value(Value&& v)
+    {
+        if (ref_stack.empty())
+        {
+            root = BasicJsonType(std::forward<Value>(v));
+            return &root;
+        }
+
+        assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
+
+        if (ref_stack.back()->is_array())
+        {
+            ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
+            return &(ref_stack.back()->m_value.array->back());
+        }
+
+        assert(ref_stack.back()->is_object());
+        assert(object_element);
+        *object_element = BasicJsonType(std::forward<Value>(v));
+        return object_element;
+    }
+
+    /// the parsed JSON value
+    BasicJsonType& root;
+    /// stack to model hierarchy of values
+    std::vector<BasicJsonType*> ref_stack {};
+    /// helper to hold the reference for the next object element
+    BasicJsonType* object_element = nullptr;
+    /// whether a syntax error occurred
+    bool errored = false;
+    /// whether to throw exceptions in case of errors
+    const bool allow_exceptions = true;
+};
+
+template<typename BasicJsonType>
+class json_sax_dom_callback_parser
+{
+  public:
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using parser_callback_t = typename BasicJsonType::parser_callback_t;
+    using parse_event_t = typename BasicJsonType::parse_event_t;
+
+    json_sax_dom_callback_parser(BasicJsonType& r,
+                                 const parser_callback_t cb,
+                                 const bool allow_exceptions_ = true)
+        : root(r), callback(cb), allow_exceptions(allow_exceptions_)
+    {
+        keep_stack.push_back(true);
+    }
+
+    // make class move-only
+    json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
+    json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default;
+    json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
+    json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default;
+    ~json_sax_dom_callback_parser() = default;
+
+    bool null()
+    {
+        handle_value(nullptr);
+        return true;
+    }
+
+    bool boolean(bool val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool number_integer(number_integer_t val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool number_unsigned(number_unsigned_t val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool number_float(number_float_t val, const string_t& /*unused*/)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool string(string_t& val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool start_object(std::size_t len)
+    {
+        // check callback for object start
+        const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
+        keep_stack.push_back(keep);
+
+        auto val = handle_value(BasicJsonType::value_t::object, true);
+        ref_stack.push_back(val.second);
+
+        // check object limit
+        if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
+        {
+            JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len)));
+        }
+
+        return true;
+    }
+
+    bool key(string_t& val)
+    {
+        BasicJsonType k = BasicJsonType(val);
+
+        // check callback for key
+        const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
+        key_keep_stack.push_back(keep);
+
+        // add discarded value at given key and store the reference for later
+        if (keep and ref_stack.back())
+        {
+            object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
+        }
+
+        return true;
+    }
+
+    bool end_object()
+    {
+        if (ref_stack.back() and not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
+        {
+            // discard object
+            *ref_stack.back() = discarded;
+        }
+
+        assert(not ref_stack.empty());
+        assert(not keep_stack.empty());
+        ref_stack.pop_back();
+        keep_stack.pop_back();
+
+        if (not ref_stack.empty() and ref_stack.back() and ref_stack.back()->is_object())
+        {
+            // remove discarded value
+            for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
+            {
+                if (it->is_discarded())
+                {
+                    ref_stack.back()->erase(it);
+                    break;
+                }
+            }
+        }
+
+        return true;
+    }
+
+    bool start_array(std::size_t len)
+    {
+        const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
+        keep_stack.push_back(keep);
+
+        auto val = handle_value(BasicJsonType::value_t::array, true);
+        ref_stack.push_back(val.second);
+
+        // check array limit
+        if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
+        {
+            JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len)));
+        }
+
+        return true;
+    }
+
+    bool end_array()
+    {
+        bool keep = true;
+
+        if (ref_stack.back())
+        {
+            keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
+            if (not keep)
+            {
+                // discard array
+                *ref_stack.back() = discarded;
+            }
+        }
+
+        assert(not ref_stack.empty());
+        assert(not keep_stack.empty());
+        ref_stack.pop_back();
+        keep_stack.pop_back();
+
+        // remove discarded value
+        if (not keep and not ref_stack.empty() and ref_stack.back()->is_array())
+        {
+            ref_stack.back()->m_value.array->pop_back();
+        }
+
+        return true;
+    }
+
+    bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
+                     const detail::exception& ex)
+    {
+        errored = true;
+        if (allow_exceptions)
+        {
+            // determine the proper exception type from the id
+            switch ((ex.id / 100) % 100)
+            {
+                case 1:
+                    JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
+                case 4:
+                    JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
+                // LCOV_EXCL_START
+                case 2:
+                    JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
+                case 3:
+                    JSON_THROW(*static_cast<const detail::type_error*>(&ex));
+                case 5:
+                    JSON_THROW(*static_cast<const detail::other_error*>(&ex));
+                default:
+                    assert(false);
+                    // LCOV_EXCL_STOP
+            }
+        }
+        return false;
+    }
+
+    constexpr bool is_errored() const
+    {
+        return errored;
+    }
+
+  private:
+    /*!
+    @param[in] v  value to add to the JSON value we build during parsing
+    @param[in] skip_callback  whether we should skip calling the callback
+               function; this is required after start_array() and
+               start_object() SAX events, because otherwise we would call the
+               callback function with an empty array or object, respectively.
+
+    @invariant If the ref stack is empty, then the passed value will be the new
+               root.
+    @invariant If the ref stack contains a value, then it is an array or an
+               object to which we can add elements
+
+    @return pair of boolean (whether value should be kept) and pointer (to the
+            passed value in the ref_stack hierarchy; nullptr if not kept)
+    */
+    template<typename Value>
+    std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
+    {
+        assert(not keep_stack.empty());
+
+        // do not handle this value if we know it would be added to a discarded
+        // container
+        if (not keep_stack.back())
+        {
+            return {false, nullptr};
+        }
+
+        // create value
+        auto value = BasicJsonType(std::forward<Value>(v));
+
+        // check callback
+        const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
+
+        // do not handle this value if we just learnt it shall be discarded
+        if (not keep)
+        {
+            return {false, nullptr};
+        }
+
+        if (ref_stack.empty())
+        {
+            root = std::move(value);
+            return {true, &root};
+        }
+
+        // skip this value if we already decided to skip the parent
+        // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
+        if (not ref_stack.back())
+        {
+            return {false, nullptr};
+        }
+
+        // we now only expect arrays and objects
+        assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
+
+        // array
+        if (ref_stack.back()->is_array())
+        {
+            ref_stack.back()->m_value.array->push_back(std::move(value));
+            return {true, &(ref_stack.back()->m_value.array->back())};
+        }
+
+        // object
+        assert(ref_stack.back()->is_object());
+        // check if we should store an element for the current key
+        assert(not key_keep_stack.empty());
+        const bool store_element = key_keep_stack.back();
+        key_keep_stack.pop_back();
+
+        if (not store_element)
+        {
+            return {false, nullptr};
+        }
+
+        assert(object_element);
+        *object_element = std::move(value);
+        return {true, object_element};
+    }
+
+    /// the parsed JSON value
+    BasicJsonType& root;
+    /// stack to model hierarchy of values
+    std::vector<BasicJsonType*> ref_stack {};
+    /// stack to manage which values to keep
+    std::vector<bool> keep_stack {};
+    /// stack to manage which object keys to keep
+    std::vector<bool> key_keep_stack {};
+    /// helper to hold the reference for the next object element
+    BasicJsonType* object_element = nullptr;
+    /// whether a syntax error occurred
+    bool errored = false;
+    /// callback function
+    const parser_callback_t callback = nullptr;
+    /// whether to throw exceptions in case of errors
+    const bool allow_exceptions = true;
+    /// a discarded value for the callback
+    BasicJsonType discarded = BasicJsonType::value_t::discarded;
+};
+
+template<typename BasicJsonType>
+class json_sax_acceptor
+{
+  public:
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+
+    bool null()
+    {
+        return true;
+    }
+
+    bool boolean(bool /*unused*/)
+    {
+        return true;
+    }
+
+    bool number_integer(number_integer_t /*unused*/)
+    {
+        return true;
+    }
+
+    bool number_unsigned(number_unsigned_t /*unused*/)
+    {
+        return true;
+    }
+
+    bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
+    {
+        return true;
+    }
+
+    bool string(string_t& /*unused*/)
+    {
+        return true;
+    }
+
+    bool start_object(std::size_t  /*unused*/ = std::size_t(-1))
+    {
+        return true;
+    }
+
+    bool key(string_t& /*unused*/)
+    {
+        return true;
+    }
+
+    bool end_object()
+    {
+        return true;
+    }
+
+    bool start_array(std::size_t  /*unused*/ = std::size_t(-1))
+    {
+        return true;
+    }
+
+    bool end_array()
+    {
+        return true;
+    }
+
+    bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
+    {
+        return false;
+    }
+};
+}  // namespace detail
+
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/is_sax.hpp>
+
+
+#include <cstdint> // size_t
+#include <utility> // declval
+#include <string> // string
+
+// #include <nlohmann/detail/meta/detected.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+template <typename T>
+using null_function_t = decltype(std::declval<T&>().null());
+
+template <typename T>
+using boolean_function_t =
+    decltype(std::declval<T&>().boolean(std::declval<bool>()));
+
+template <typename T, typename Integer>
+using number_integer_function_t =
+    decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
+
+template <typename T, typename Unsigned>
+using number_unsigned_function_t =
+    decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
+
+template <typename T, typename Float, typename String>
+using number_float_function_t = decltype(std::declval<T&>().number_float(
+                                    std::declval<Float>(), std::declval<const String&>()));
+
+template <typename T, typename String>
+using string_function_t =
+    decltype(std::declval<T&>().string(std::declval<String&>()));
+
+template <typename T>
+using start_object_function_t =
+    decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
+
+template <typename T, typename String>
+using key_function_t =
+    decltype(std::declval<T&>().key(std::declval<String&>()));
+
+template <typename T>
+using end_object_function_t = decltype(std::declval<T&>().end_object());
+
+template <typename T>
+using start_array_function_t =
+    decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
+
+template <typename T>
+using end_array_function_t = decltype(std::declval<T&>().end_array());
+
+template <typename T, typename Exception>
+using parse_error_function_t = decltype(std::declval<T&>().parse_error(
+        std::declval<std::size_t>(), std::declval<const std::string&>(),
+        std::declval<const Exception&>()));
+
+template <typename SAX, typename BasicJsonType>
+struct is_sax
+{
+  private:
+    static_assert(is_basic_json<BasicJsonType>::value,
+                  "BasicJsonType must be of type basic_json<...>");
+
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using exception_t = typename BasicJsonType::exception;
+
+  public:
+    static constexpr bool value =
+        is_detected_exact<bool, null_function_t, SAX>::value &&
+        is_detected_exact<bool, boolean_function_t, SAX>::value &&
+        is_detected_exact<bool, number_integer_function_t, SAX,
+        number_integer_t>::value &&
+        is_detected_exact<bool, number_unsigned_function_t, SAX,
+        number_unsigned_t>::value &&
+        is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
+        string_t>::value &&
+        is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
+        is_detected_exact<bool, start_object_function_t, SAX>::value &&
+        is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
+        is_detected_exact<bool, end_object_function_t, SAX>::value &&
+        is_detected_exact<bool, start_array_function_t, SAX>::value &&
+        is_detected_exact<bool, end_array_function_t, SAX>::value &&
+        is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
+};
+
+template <typename SAX, typename BasicJsonType>
+struct is_sax_static_asserts
+{
+  private:
+    static_assert(is_basic_json<BasicJsonType>::value,
+                  "BasicJsonType must be of type basic_json<...>");
+
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using exception_t = typename BasicJsonType::exception;
+
+  public:
+    static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
+                  "Missing/invalid function: bool null()");
+    static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
+                  "Missing/invalid function: bool boolean(bool)");
+    static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
+                  "Missing/invalid function: bool boolean(bool)");
+    static_assert(
+        is_detected_exact<bool, number_integer_function_t, SAX,
+        number_integer_t>::value,
+        "Missing/invalid function: bool number_integer(number_integer_t)");
+    static_assert(
+        is_detected_exact<bool, number_unsigned_function_t, SAX,
+        number_unsigned_t>::value,
+        "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
+    static_assert(is_detected_exact<bool, number_float_function_t, SAX,
+                  number_float_t, string_t>::value,
+                  "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
+    static_assert(
+        is_detected_exact<bool, string_function_t, SAX, string_t>::value,
+        "Missing/invalid function: bool string(string_t&)");
+    static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
+                  "Missing/invalid function: bool start_object(std::size_t)");
+    static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
+                  "Missing/invalid function: bool key(string_t&)");
+    static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
+                  "Missing/invalid function: bool end_object()");
+    static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
+                  "Missing/invalid function: bool start_array(std::size_t)");
+    static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
+                  "Missing/invalid function: bool end_array()");
+    static_assert(
+        is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
+        "Missing/invalid function: bool parse_error(std::size_t, const "
+        "std::string&, const exception&)");
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+///////////////////
+// binary reader //
+///////////////////
+
+/*!
+@brief deserialization of CBOR, MessagePack, and UBJSON values
+*/
+template<typename BasicJsonType, typename SAX = json_sax_dom_parser<BasicJsonType>>
+class binary_reader
+{
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using json_sax_t = SAX;
+
+  public:
+    /*!
+    @brief create a binary reader
+
+    @param[in] adapter  input adapter to read from
+    */
+    explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
+    {
+        (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
+        assert(ia);
+    }
+
+    // make class move-only
+    binary_reader(const binary_reader&) = delete;
+    binary_reader(binary_reader&&) = default;
+    binary_reader& operator=(const binary_reader&) = delete;
+    binary_reader& operator=(binary_reader&&) = default;
+    ~binary_reader() = default;
+
+    /*!
+    @param[in] format  the binary format to parse
+    @param[in] sax_    a SAX event processor
+    @param[in] strict  whether to expect the input to be consumed completed
+
+    @return
+    */
+    JSON_HEDLEY_NON_NULL(3)
+    bool sax_parse(const input_format_t format,
+                   json_sax_t* sax_,
+                   const bool strict = true)
+    {
+        sax = sax_;
+        bool result = false;
+
+        switch (format)
+        {
+            case input_format_t::bson:
+                result = parse_bson_internal();
+                break;
+
+            case input_format_t::cbor:
+                result = parse_cbor_internal();
+                break;
+
+            case input_format_t::msgpack:
+                result = parse_msgpack_internal();
+                break;
+
+            case input_format_t::ubjson:
+                result = parse_ubjson_internal();
+                break;
+
+            default:            // LCOV_EXCL_LINE
+                assert(false);  // LCOV_EXCL_LINE
+        }
+
+        // strict mode: next byte must be EOF
+        if (result and strict)
+        {
+            if (format == input_format_t::ubjson)
+            {
+                get_ignore_noop();
+            }
+            else
+            {
+                get();
+            }
+
+            if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char>::eof()))
+            {
+                return sax->parse_error(chars_read, get_token_string(),
+                                        parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value")));
+            }
+        }
+
+        return result;
+    }
+
+    /*!
+    @brief determine system byte order
+
+    @return true if and only if system's byte order is little endian
+
+    @note from https://stackoverflow.com/a/1001328/266378
+    */
+    static constexpr bool little_endianess(int num = 1) noexcept
+    {
+        return *reinterpret_cast<char*>(&num) == 1;
+    }
+
+  private:
+    //////////
+    // BSON //
+    //////////
+
+    /*!
+    @brief Reads in a BSON-object and passes it to the SAX-parser.
+    @return whether a valid BSON-value was passed to the SAX parser
+    */
+    bool parse_bson_internal()
+    {
+        std::int32_t document_size;
+        get_number<std::int32_t, true>(input_format_t::bson, document_size);
+
+        if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
+        {
+            return false;
+        }
+
+        if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/false)))
+        {
+            return false;
+        }
+
+        return sax->end_object();
+    }
+
+    /*!
+    @brief Parses a C-style string from the BSON input.
+    @param[in, out] result  A reference to the string variable where the read
+                            string is to be stored.
+    @return `true` if the \x00-byte indicating the end of the string was
+             encountered before the EOF; false` indicates an unexpected EOF.
+    */
+    bool get_bson_cstr(string_t& result)
+    {
+        auto out = std::back_inserter(result);
+        while (true)
+        {
+            get();
+            if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "cstring")))
+            {
+                return false;
+            }
+            if (current == 0x00)
+            {
+                return true;
+            }
+            *out++ = static_cast<char>(current);
+        }
+
+        return true;
+    }
+
+    /*!
+    @brief Parses a zero-terminated string of length @a len from the BSON
+           input.
+    @param[in] len  The length (including the zero-byte at the end) of the
+                    string to be read.
+    @param[in, out] result  A reference to the string variable where the read
+                            string is to be stored.
+    @tparam NumberType The type of the length @a len
+    @pre len >= 1
+    @return `true` if the string was successfully parsed
+    */
+    template<typename NumberType>
+    bool get_bson_string(const NumberType len, string_t& result)
+    {
+        if (JSON_HEDLEY_UNLIKELY(len < 1))
+        {
+            auto last_token = get_token_string();
+            return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string")));
+        }
+
+        return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) and get() != std::char_traits<char>::eof();
+    }
+
+    /*!
+    @brief Read a BSON document element of the given @a element_type.
+    @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
+    @param[in] element_type_parse_position The position in the input stream,
+               where the `element_type` was read.
+    @warning Not all BSON element types are supported yet. An unsupported
+             @a element_type will give rise to a parse_error.114:
+             Unsupported BSON record type 0x...
+    @return whether a valid BSON-object/array was passed to the SAX parser
+    */
+    bool parse_bson_element_internal(const int element_type,
+                                     const std::size_t element_type_parse_position)
+    {
+        switch (element_type)
+        {
+            case 0x01: // double
+            {
+                double number;
+                return get_number<double, true>(input_format_t::bson, number) and sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            case 0x02: // string
+            {
+                std::int32_t len;
+                string_t value;
+                return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_string(len, value) and sax->string(value);
+            }
+
+            case 0x03: // object
+            {
+                return parse_bson_internal();
+            }
+
+            case 0x04: // array
+            {
+                return parse_bson_array();
+            }
+
+            case 0x08: // boolean
+            {
+                return sax->boolean(get() != 0);
+            }
+
+            case 0x0A: // null
+            {
+                return sax->null();
+            }
+
+            case 0x10: // int32
+            {
+                std::int32_t value;
+                return get_number<std::int32_t, true>(input_format_t::bson, value) and sax->number_integer(value);
+            }
+
+            case 0x12: // int64
+            {
+                std::int64_t value;
+                return get_number<std::int64_t, true>(input_format_t::bson, value) and sax->number_integer(value);
+            }
+
+            default: // anything else not supported (yet)
+            {
+                std::array<char, 3> cr{{}};
+                (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type));
+                return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data())));
+            }
+        }
+    }
+
+    /*!
+    @brief Read a BSON element list (as specified in the BSON-spec)
+
+    The same binary layout is used for objects and arrays, hence it must be
+    indicated with the argument @a is_array which one is expected
+    (true --> array, false --> object).
+
+    @param[in] is_array Determines if the element list being read is to be
+                        treated as an object (@a is_array == false), or as an
+                        array (@a is_array == true).
+    @return whether a valid BSON-object/array was passed to the SAX parser
+    */
+    bool parse_bson_element_list(const bool is_array)
+    {
+        string_t key;
+        while (int element_type = get())
+        {
+            if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "element list")))
+            {
+                return false;
+            }
+
+            const std::size_t element_type_parse_position = chars_read;
+            if (JSON_HEDLEY_UNLIKELY(not get_bson_cstr(key)))
+            {
+                return false;
+            }
+
+            if (not is_array and not sax->key(key))
+            {
+                return false;
+            }
+
+            if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_internal(element_type, element_type_parse_position)))
+            {
+                return false;
+            }
+
+            // get_bson_cstr only appends
+            key.clear();
+        }
+
+        return true;
+    }
+
+    /*!
+    @brief Reads an array from the BSON input and passes it to the SAX-parser.
+    @return whether a valid BSON-array was passed to the SAX parser
+    */
+    bool parse_bson_array()
+    {
+        std::int32_t document_size;
+        get_number<std::int32_t, true>(input_format_t::bson, document_size);
+
+        if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
+        {
+            return false;
+        }
+
+        if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/true)))
+        {
+            return false;
+        }
+
+        return sax->end_array();
+    }
+
+    //////////
+    // CBOR //
+    //////////
+
+    /*!
+    @param[in] get_char  whether a new character should be retrieved from the
+                         input (true, default) or whether the last read
+                         character should be considered instead
+
+    @return whether a valid CBOR value was passed to the SAX parser
+    */
+    bool parse_cbor_internal(const bool get_char = true)
+    {
+        switch (get_char ? get() : current)
+        {
+            // EOF
+            case std::char_traits<char>::eof():
+                return unexpect_eof(input_format_t::cbor, "value");
+
+            // Integer 0x00..0x17 (0..23)
+            case 0x00:
+            case 0x01:
+            case 0x02:
+            case 0x03:
+            case 0x04:
+            case 0x05:
+            case 0x06:
+            case 0x07:
+            case 0x08:
+            case 0x09:
+            case 0x0A:
+            case 0x0B:
+            case 0x0C:
+            case 0x0D:
+            case 0x0E:
+            case 0x0F:
+            case 0x10:
+            case 0x11:
+            case 0x12:
+            case 0x13:
+            case 0x14:
+            case 0x15:
+            case 0x16:
+            case 0x17:
+                return sax->number_unsigned(static_cast<number_unsigned_t>(current));
+
+            case 0x18: // Unsigned integer (one-byte uint8_t follows)
+            {
+                std::uint8_t number;
+                return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
+            }
+
+            case 0x19: // Unsigned integer (two-byte uint16_t follows)
+            {
+                std::uint16_t number;
+                return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
+            }
+
+            case 0x1A: // Unsigned integer (four-byte uint32_t follows)
+            {
+                std::uint32_t number;
+                return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
+            }
+
+            case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
+            {
+                std::uint64_t number;
+                return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
+            }
+
+            // Negative integer -1-0x00..-1-0x17 (-1..-24)
+            case 0x20:
+            case 0x21:
+            case 0x22:
+            case 0x23:
+            case 0x24:
+            case 0x25:
+            case 0x26:
+            case 0x27:
+            case 0x28:
+            case 0x29:
+            case 0x2A:
+            case 0x2B:
+            case 0x2C:
+            case 0x2D:
+            case 0x2E:
+            case 0x2F:
+            case 0x30:
+            case 0x31:
+            case 0x32:
+            case 0x33:
+            case 0x34:
+            case 0x35:
+            case 0x36:
+            case 0x37:
+                return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
+
+            case 0x38: // Negative integer (one-byte uint8_t follows)
+            {
+                std::uint8_t number;
+                return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
+            }
+
+            case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
+            {
+                std::uint16_t number;
+                return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
+            }
+
+            case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
+            {
+                std::uint32_t number;
+                return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
+            }
+
+            case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
+            {
+                std::uint64_t number;
+                return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1)
+                        - static_cast<number_integer_t>(number));
+            }
+
+            // UTF-8 string (0x00..0x17 bytes follow)
+            case 0x60:
+            case 0x61:
+            case 0x62:
+            case 0x63:
+            case 0x64:
+            case 0x65:
+            case 0x66:
+            case 0x67:
+            case 0x68:
+            case 0x69:
+            case 0x6A:
+            case 0x6B:
+            case 0x6C:
+            case 0x6D:
+            case 0x6E:
+            case 0x6F:
+            case 0x70:
+            case 0x71:
+            case 0x72:
+            case 0x73:
+            case 0x74:
+            case 0x75:
+            case 0x76:
+            case 0x77:
+            case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
+            case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
+            case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
+            case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
+            case 0x7F: // UTF-8 string (indefinite length)
+            {
+                string_t s;
+                return get_cbor_string(s) and sax->string(s);
+            }
+
+            // array (0x00..0x17 data items follow)
+            case 0x80:
+            case 0x81:
+            case 0x82:
+            case 0x83:
+            case 0x84:
+            case 0x85:
+            case 0x86:
+            case 0x87:
+            case 0x88:
+            case 0x89:
+            case 0x8A:
+            case 0x8B:
+            case 0x8C:
+            case 0x8D:
+            case 0x8E:
+            case 0x8F:
+            case 0x90:
+            case 0x91:
+            case 0x92:
+            case 0x93:
+            case 0x94:
+            case 0x95:
+            case 0x96:
+            case 0x97:
+                return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
+
+            case 0x98: // array (one-byte uint8_t for n follows)
+            {
+                std::uint8_t len;
+                return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
+            }
+
+            case 0x99: // array (two-byte uint16_t for n follow)
+            {
+                std::uint16_t len;
+                return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
+            }
+
+            case 0x9A: // array (four-byte uint32_t for n follow)
+            {
+                std::uint32_t len;
+                return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
+            }
+
+            case 0x9B: // array (eight-byte uint64_t for n follow)
+            {
+                std::uint64_t len;
+                return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
+            }
+
+            case 0x9F: // array (indefinite length)
+                return get_cbor_array(std::size_t(-1));
+
+            // map (0x00..0x17 pairs of data items follow)
+            case 0xA0:
+            case 0xA1:
+            case 0xA2:
+            case 0xA3:
+            case 0xA4:
+            case 0xA5:
+            case 0xA6:
+            case 0xA7:
+            case 0xA8:
+            case 0xA9:
+            case 0xAA:
+            case 0xAB:
+            case 0xAC:
+            case 0xAD:
+            case 0xAE:
+            case 0xAF:
+            case 0xB0:
+            case 0xB1:
+            case 0xB2:
+            case 0xB3:
+            case 0xB4:
+            case 0xB5:
+            case 0xB6:
+            case 0xB7:
+                return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
+
+            case 0xB8: // map (one-byte uint8_t for n follows)
+            {
+                std::uint8_t len;
+                return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
+            }
+
+            case 0xB9: // map (two-byte uint16_t for n follow)
+            {
+                std::uint16_t len;
+                return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
+            }
+
+            case 0xBA: // map (four-byte uint32_t for n follow)
+            {
+                std::uint32_t len;
+                return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
+            }
+
+            case 0xBB: // map (eight-byte uint64_t for n follow)
+            {
+                std::uint64_t len;
+                return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
+            }
+
+            case 0xBF: // map (indefinite length)
+                return get_cbor_object(std::size_t(-1));
+
+            case 0xF4: // false
+                return sax->boolean(false);
+
+            case 0xF5: // true
+                return sax->boolean(true);
+
+            case 0xF6: // null
+                return sax->null();
+
+            case 0xF9: // Half-Precision Float (two-byte IEEE 754)
+            {
+                const int byte1_raw = get();
+                if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
+                {
+                    return false;
+                }
+                const int byte2_raw = get();
+                if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
+                {
+                    return false;
+                }
+
+                const auto byte1 = static_cast<unsigned char>(byte1_raw);
+                const auto byte2 = static_cast<unsigned char>(byte2_raw);
+
+                // code from RFC 7049, Appendix D, Figure 3:
+                // As half-precision floating-point numbers were only added
+                // to IEEE 754 in 2008, today's programming platforms often
+                // still only have limited support for them. It is very
+                // easy to include at least decoding support for them even
+                // without such support. An example of a small decoder for
+                // half-precision floating-point numbers in the C language
+                // is shown in Fig. 3.
+                const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
+                const double val = [&half]
+                {
+                    const int exp = (half >> 10u) & 0x1Fu;
+                    const unsigned int mant = half & 0x3FFu;
+                    assert(0 <= exp and exp <= 32);
+                    assert(mant <= 1024);
+                    switch (exp)
+                    {
+                        case 0:
+                            return std::ldexp(mant, -24);
+                        case 31:
+                            return (mant == 0)
+                            ? std::numeric_limits<double>::infinity()
+                            : std::numeric_limits<double>::quiet_NaN();
+                        default:
+                            return std::ldexp(mant + 1024, exp - 25);
+                    }
+                }();
+                return sax->number_float((half & 0x8000u) != 0
+                                         ? static_cast<number_float_t>(-val)
+                                         : static_cast<number_float_t>(val), "");
+            }
+
+            case 0xFA: // Single-Precision Float (four-byte IEEE 754)
+            {
+                float number;
+                return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
+            {
+                double number;
+                return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            default: // anything else (0xFF is handled inside the other types)
+            {
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value")));
+            }
+        }
+    }
+
+    /*!
+    @brief reads a CBOR string
+
+    This function first reads starting bytes to determine the expected
+    string length and then copies this number of bytes into a string.
+    Additionally, CBOR's strings with indefinite lengths are supported.
+
+    @param[out] result  created string
+
+    @return whether string creation completed
+    */
+    bool get_cbor_string(string_t& result)
+    {
+        if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "string")))
+        {
+            return false;
+        }
+
+        switch (current)
+        {
+            // UTF-8 string (0x00..0x17 bytes follow)
+            case 0x60:
+            case 0x61:
+            case 0x62:
+            case 0x63:
+            case 0x64:
+            case 0x65:
+            case 0x66:
+            case 0x67:
+            case 0x68:
+            case 0x69:
+            case 0x6A:
+            case 0x6B:
+            case 0x6C:
+            case 0x6D:
+            case 0x6E:
+            case 0x6F:
+            case 0x70:
+            case 0x71:
+            case 0x72:
+            case 0x73:
+            case 0x74:
+            case 0x75:
+            case 0x76:
+            case 0x77:
+            {
+                return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
+            }
+
+            case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
+            {
+                std::uint8_t len;
+                return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
+            }
+
+            case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
+            {
+                std::uint16_t len;
+                return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
+            }
+
+            case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
+            {
+                std::uint32_t len;
+                return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
+            }
+
+            case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
+            {
+                std::uint64_t len;
+                return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
+            }
+
+            case 0x7F: // UTF-8 string (indefinite length)
+            {
+                while (get() != 0xFF)
+                {
+                    string_t chunk;
+                    if (not get_cbor_string(chunk))
+                    {
+                        return false;
+                    }
+                    result.append(chunk);
+                }
+                return true;
+            }
+
+            default:
+            {
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string")));
+            }
+        }
+    }
+
+    /*!
+    @param[in] len  the length of the array or std::size_t(-1) for an
+                    array of indefinite size
+    @return whether array creation completed
+    */
+    bool get_cbor_array(const std::size_t len)
+    {
+        if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
+        {
+            return false;
+        }
+
+        if (len != std::size_t(-1))
+        {
+            for (std::size_t i = 0; i < len; ++i)
+            {
+                if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
+                {
+                    return false;
+                }
+            }
+        }
+        else
+        {
+            while (get() != 0xFF)
+            {
+                if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal(false)))
+                {
+                    return false;
+                }
+            }
+        }
+
+        return sax->end_array();
+    }
+
+    /*!
+    @param[in] len  the length of the object or std::size_t(-1) for an
+                    object of indefinite size
+    @return whether object creation completed
+    */
+    bool get_cbor_object(const std::size_t len)
+    {
+        if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
+        {
+            return false;
+        }
+
+        string_t key;
+        if (len != std::size_t(-1))
+        {
+            for (std::size_t i = 0; i < len; ++i)
+            {
+                get();
+                if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
+                {
+                    return false;
+                }
+
+                if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
+                {
+                    return false;
+                }
+                key.clear();
+            }
+        }
+        else
+        {
+            while (get() != 0xFF)
+            {
+                if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
+                {
+                    return false;
+                }
+
+                if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
+                {
+                    return false;
+                }
+                key.clear();
+            }
+        }
+
+        return sax->end_object();
+    }
+
+    /////////////
+    // MsgPack //
+    /////////////
+
+    /*!
+    @return whether a valid MessagePack value was passed to the SAX parser
+    */
+    bool parse_msgpack_internal()
+    {
+        switch (get())
+        {
+            // EOF
+            case std::char_traits<char>::eof():
+                return unexpect_eof(input_format_t::msgpack, "value");
+
+            // positive fixint
+            case 0x00:
+            case 0x01:
+            case 0x02:
+            case 0x03:
+            case 0x04:
+            case 0x05:
+            case 0x06:
+            case 0x07:
+            case 0x08:
+            case 0x09:
+            case 0x0A:
+            case 0x0B:
+            case 0x0C:
+            case 0x0D:
+            case 0x0E:
+            case 0x0F:
+            case 0x10:
+            case 0x11:
+            case 0x12:
+            case 0x13:
+            case 0x14:
+            case 0x15:
+            case 0x16:
+            case 0x17:
+            case 0x18:
+            case 0x19:
+            case 0x1A:
+            case 0x1B:
+            case 0x1C:
+            case 0x1D:
+            case 0x1E:
+            case 0x1F:
+            case 0x20:
+            case 0x21:
+            case 0x22:
+            case 0x23:
+            case 0x24:
+            case 0x25:
+            case 0x26:
+            case 0x27:
+            case 0x28:
+            case 0x29:
+            case 0x2A:
+            case 0x2B:
+            case 0x2C:
+            case 0x2D:
+            case 0x2E:
+            case 0x2F:
+            case 0x30:
+            case 0x31:
+            case 0x32:
+            case 0x33:
+            case 0x34:
+            case 0x35:
+            case 0x36:
+            case 0x37:
+            case 0x38:
+            case 0x39:
+            case 0x3A:
+            case 0x3B:
+            case 0x3C:
+            case 0x3D:
+            case 0x3E:
+            case 0x3F:
+            case 0x40:
+            case 0x41:
+            case 0x42:
+            case 0x43:
+            case 0x44:
+            case 0x45:
+            case 0x46:
+            case 0x47:
+            case 0x48:
+            case 0x49:
+            case 0x4A:
+            case 0x4B:
+            case 0x4C:
+            case 0x4D:
+            case 0x4E:
+            case 0x4F:
+            case 0x50:
+            case 0x51:
+            case 0x52:
+            case 0x53:
+            case 0x54:
+            case 0x55:
+            case 0x56:
+            case 0x57:
+            case 0x58:
+            case 0x59:
+            case 0x5A:
+            case 0x5B:
+            case 0x5C:
+            case 0x5D:
+            case 0x5E:
+            case 0x5F:
+            case 0x60:
+            case 0x61:
+            case 0x62:
+            case 0x63:
+            case 0x64:
+            case 0x65:
+            case 0x66:
+            case 0x67:
+            case 0x68:
+            case 0x69:
+            case 0x6A:
+            case 0x6B:
+            case 0x6C:
+            case 0x6D:
+            case 0x6E:
+            case 0x6F:
+            case 0x70:
+            case 0x71:
+            case 0x72:
+            case 0x73:
+            case 0x74:
+            case 0x75:
+            case 0x76:
+            case 0x77:
+            case 0x78:
+            case 0x79:
+            case 0x7A:
+            case 0x7B:
+            case 0x7C:
+            case 0x7D:
+            case 0x7E:
+            case 0x7F:
+                return sax->number_unsigned(static_cast<number_unsigned_t>(current));
+
+            // fixmap
+            case 0x80:
+            case 0x81:
+            case 0x82:
+            case 0x83:
+            case 0x84:
+            case 0x85:
+            case 0x86:
+            case 0x87:
+            case 0x88:
+            case 0x89:
+            case 0x8A:
+            case 0x8B:
+            case 0x8C:
+            case 0x8D:
+            case 0x8E:
+            case 0x8F:
+                return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
+
+            // fixarray
+            case 0x90:
+            case 0x91:
+            case 0x92:
+            case 0x93:
+            case 0x94:
+            case 0x95:
+            case 0x96:
+            case 0x97:
+            case 0x98:
+            case 0x99:
+            case 0x9A:
+            case 0x9B:
+            case 0x9C:
+            case 0x9D:
+            case 0x9E:
+            case 0x9F:
+                return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
+
+            // fixstr
+            case 0xA0:
+            case 0xA1:
+            case 0xA2:
+            case 0xA3:
+            case 0xA4:
+            case 0xA5:
+            case 0xA6:
+            case 0xA7:
+            case 0xA8:
+            case 0xA9:
+            case 0xAA:
+            case 0xAB:
+            case 0xAC:
+            case 0xAD:
+            case 0xAE:
+            case 0xAF:
+            case 0xB0:
+            case 0xB1:
+            case 0xB2:
+            case 0xB3:
+            case 0xB4:
+            case 0xB5:
+            case 0xB6:
+            case 0xB7:
+            case 0xB8:
+            case 0xB9:
+            case 0xBA:
+            case 0xBB:
+            case 0xBC:
+            case 0xBD:
+            case 0xBE:
+            case 0xBF:
+            case 0xD9: // str 8
+            case 0xDA: // str 16
+            case 0xDB: // str 32
+            {
+                string_t s;
+                return get_msgpack_string(s) and sax->string(s);
+            }
+
+            case 0xC0: // nil
+                return sax->null();
+
+            case 0xC2: // false
+                return sax->boolean(false);
+
+            case 0xC3: // true
+                return sax->boolean(true);
+
+            case 0xCA: // float 32
+            {
+                float number;
+                return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            case 0xCB: // float 64
+            {
+                double number;
+                return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            case 0xCC: // uint 8
+            {
+                std::uint8_t number;
+                return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
+            }
+
+            case 0xCD: // uint 16
+            {
+                std::uint16_t number;
+                return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
+            }
+
+            case 0xCE: // uint 32
+            {
+                std::uint32_t number;
+                return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
+            }
+
+            case 0xCF: // uint 64
+            {
+                std::uint64_t number;
+                return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
+            }
+
+            case 0xD0: // int 8
+            {
+                std::int8_t number;
+                return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
+            }
+
+            case 0xD1: // int 16
+            {
+                std::int16_t number;
+                return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
+            }
+
+            case 0xD2: // int 32
+            {
+                std::int32_t number;
+                return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
+            }
+
+            case 0xD3: // int 64
+            {
+                std::int64_t number;
+                return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
+            }
+
+            case 0xDC: // array 16
+            {
+                std::uint16_t len;
+                return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
+            }
+
+            case 0xDD: // array 32
+            {
+                std::uint32_t len;
+                return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
+            }
+
+            case 0xDE: // map 16
+            {
+                std::uint16_t len;
+                return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
+            }
+
+            case 0xDF: // map 32
+            {
+                std::uint32_t len;
+                return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
+            }
+
+            // negative fixint
+            case 0xE0:
+            case 0xE1:
+            case 0xE2:
+            case 0xE3:
+            case 0xE4:
+            case 0xE5:
+            case 0xE6:
+            case 0xE7:
+            case 0xE8:
+            case 0xE9:
+            case 0xEA:
+            case 0xEB:
+            case 0xEC:
+            case 0xED:
+            case 0xEE:
+            case 0xEF:
+            case 0xF0:
+            case 0xF1:
+            case 0xF2:
+            case 0xF3:
+            case 0xF4:
+            case 0xF5:
+            case 0xF6:
+            case 0xF7:
+            case 0xF8:
+            case 0xF9:
+            case 0xFA:
+            case 0xFB:
+            case 0xFC:
+            case 0xFD:
+            case 0xFE:
+            case 0xFF:
+                return sax->number_integer(static_cast<std::int8_t>(current));
+
+            default: // anything else
+            {
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value")));
+            }
+        }
+    }
+
+    /*!
+    @brief reads a MessagePack string
+
+    This function first reads starting bytes to determine the expected
+    string length and then copies this number of bytes into a string.
+
+    @param[out] result  created string
+
+    @return whether string creation completed
+    */
+    bool get_msgpack_string(string_t& result)
+    {
+        if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::msgpack, "string")))
+        {
+            return false;
+        }
+
+        switch (current)
+        {
+            // fixstr
+            case 0xA0:
+            case 0xA1:
+            case 0xA2:
+            case 0xA3:
+            case 0xA4:
+            case 0xA5:
+            case 0xA6:
+            case 0xA7:
+            case 0xA8:
+            case 0xA9:
+            case 0xAA:
+            case 0xAB:
+            case 0xAC:
+            case 0xAD:
+            case 0xAE:
+            case 0xAF:
+            case 0xB0:
+            case 0xB1:
+            case 0xB2:
+            case 0xB3:
+            case 0xB4:
+            case 0xB5:
+            case 0xB6:
+            case 0xB7:
+            case 0xB8:
+            case 0xB9:
+            case 0xBA:
+            case 0xBB:
+            case 0xBC:
+            case 0xBD:
+            case 0xBE:
+            case 0xBF:
+            {
+                return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
+            }
+
+            case 0xD9: // str 8
+            {
+                std::uint8_t len;
+                return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
+            }
+
+            case 0xDA: // str 16
+            {
+                std::uint16_t len;
+                return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
+            }
+
+            case 0xDB: // str 32
+            {
+                std::uint32_t len;
+                return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
+            }
+
+            default:
+            {
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string")));
+            }
+        }
+    }
+
+    /*!
+    @param[in] len  the length of the array
+    @return whether array creation completed
+    */
+    bool get_msgpack_array(const std::size_t len)
+    {
+        if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
+        {
+            return false;
+        }
+
+        for (std::size_t i = 0; i < len; ++i)
+        {
+            if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
+            {
+                return false;
+            }
+        }
+
+        return sax->end_array();
+    }
+
+    /*!
+    @param[in] len  the length of the object
+    @return whether object creation completed
+    */
+    bool get_msgpack_object(const std::size_t len)
+    {
+        if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
+        {
+            return false;
+        }
+
+        string_t key;
+        for (std::size_t i = 0; i < len; ++i)
+        {
+            get();
+            if (JSON_HEDLEY_UNLIKELY(not get_msgpack_string(key) or not sax->key(key)))
+            {
+                return false;
+            }
+
+            if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
+            {
+                return false;
+            }
+            key.clear();
+        }
+
+        return sax->end_object();
+    }
+
+    ////////////
+    // UBJSON //
+    ////////////
+
+    /*!
+    @param[in] get_char  whether a new character should be retrieved from the
+                         input (true, default) or whether the last read
+                         character should be considered instead
+
+    @return whether a valid UBJSON value was passed to the SAX parser
+    */
+    bool parse_ubjson_internal(const bool get_char = true)
+    {
+        return get_ubjson_value(get_char ? get_ignore_noop() : current);
+    }
+
+    /*!
+    @brief reads a UBJSON string
+
+    This function is either called after reading the 'S' byte explicitly
+    indicating a string, or in case of an object key where the 'S' byte can be
+    left out.
+
+    @param[out] result   created string
+    @param[in] get_char  whether a new character should be retrieved from the
+                         input (true, default) or whether the last read
+                         character should be considered instead
+
+    @return whether string creation completed
+    */
+    bool get_ubjson_string(string_t& result, const bool get_char = true)
+    {
+        if (get_char)
+        {
+            get();  // TODO(niels): may we ignore N here?
+        }
+
+        if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
+        {
+            return false;
+        }
+
+        switch (current)
+        {
+            case 'U':
+            {
+                std::uint8_t len;
+                return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
+            }
+
+            case 'i':
+            {
+                std::int8_t len;
+                return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
+            }
+
+            case 'I':
+            {
+                std::int16_t len;
+                return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
+            }
+
+            case 'l':
+            {
+                std::int32_t len;
+                return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
+            }
+
+            case 'L':
+            {
+                std::int64_t len;
+                return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
+            }
+
+            default:
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string")));
+        }
+    }
+
+    /*!
+    @param[out] result  determined size
+    @return whether size determination completed
+    */
+    bool get_ubjson_size_value(std::size_t& result)
+    {
+        switch (get_ignore_noop())
+        {
+            case 'U':
+            {
+                std::uint8_t number;
+                if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
+                {
+                    return false;
+                }
+                result = static_cast<std::size_t>(number);
+                return true;
+            }
+
+            case 'i':
+            {
+                std::int8_t number;
+                if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
+                {
+                    return false;
+                }
+                result = static_cast<std::size_t>(number);
+                return true;
+            }
+
+            case 'I':
+            {
+                std::int16_t number;
+                if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
+                {
+                    return false;
+                }
+                result = static_cast<std::size_t>(number);
+                return true;
+            }
+
+            case 'l':
+            {
+                std::int32_t number;
+                if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
+                {
+                    return false;
+                }
+                result = static_cast<std::size_t>(number);
+                return true;
+            }
+
+            case 'L':
+            {
+                std::int64_t number;
+                if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
+                {
+                    return false;
+                }
+                result = static_cast<std::size_t>(number);
+                return true;
+            }
+
+            default:
+            {
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size")));
+            }
+        }
+    }
+
+    /*!
+    @brief determine the type and size for a container
+
+    In the optimized UBJSON format, a type and a size can be provided to allow
+    for a more compact representation.
+
+    @param[out] result  pair of the size and the type
+
+    @return whether pair creation completed
+    */
+    bool get_ubjson_size_type(std::pair<std::size_t, int>& result)
+    {
+        result.first = string_t::npos; // size
+        result.second = 0; // type
+
+        get_ignore_noop();
+
+        if (current == '$')
+        {
+            result.second = get();  // must not ignore 'N', because 'N' maybe the type
+            if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "type")))
+            {
+                return false;
+            }
+
+            get_ignore_noop();
+            if (JSON_HEDLEY_UNLIKELY(current != '#'))
+            {
+                if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
+                {
+                    return false;
+                }
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size")));
+            }
+
+            return get_ubjson_size_value(result.first);
+        }
+
+        if (current == '#')
+        {
+            return get_ubjson_size_value(result.first);
+        }
+
+        return true;
+    }
+
+    /*!
+    @param prefix  the previously read or set type prefix
+    @return whether value creation completed
+    */
+    bool get_ubjson_value(const int prefix)
+    {
+        switch (prefix)
+        {
+            case std::char_traits<char>::eof():  // EOF
+                return unexpect_eof(input_format_t::ubjson, "value");
+
+            case 'T':  // true
+                return sax->boolean(true);
+            case 'F':  // false
+                return sax->boolean(false);
+
+            case 'Z':  // null
+                return sax->null();
+
+            case 'U':
+            {
+                std::uint8_t number;
+                return get_number(input_format_t::ubjson, number) and sax->number_unsigned(number);
+            }
+
+            case 'i':
+            {
+                std::int8_t number;
+                return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
+            }
+
+            case 'I':
+            {
+                std::int16_t number;
+                return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
+            }
+
+            case 'l':
+            {
+                std::int32_t number;
+                return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
+            }
+
+            case 'L':
+            {
+                std::int64_t number;
+                return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
+            }
+
+            case 'd':
+            {
+                float number;
+                return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            case 'D':
+            {
+                double number;
+                return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            case 'C':  // char
+            {
+                get();
+                if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "char")))
+                {
+                    return false;
+                }
+                if (JSON_HEDLEY_UNLIKELY(current > 127))
+                {
+                    auto last_token = get_token_string();
+                    return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char")));
+                }
+                string_t s(1, static_cast<char>(current));
+                return sax->string(s);
+            }
+
+            case 'S':  // string
+            {
+                string_t s;
+                return get_ubjson_string(s) and sax->string(s);
+            }
+
+            case '[':  // array
+                return get_ubjson_array();
+
+            case '{':  // object
+                return get_ubjson_object();
+
+            default: // anything else
+            {
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value")));
+            }
+        }
+    }
+
+    /*!
+    @return whether array creation completed
+    */
+    bool get_ubjson_array()
+    {
+        std::pair<std::size_t, int> size_and_type;
+        if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
+        {
+            return false;
+        }
+
+        if (size_and_type.first != string_t::npos)
+        {
+            if (JSON_HEDLEY_UNLIKELY(not sax->start_array(size_and_type.first)))
+            {
+                return false;
+            }
+
+            if (size_and_type.second != 0)
+            {
+                if (size_and_type.second != 'N')
+                {
+                    for (std::size_t i = 0; i < size_and_type.first; ++i)
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
+                        {
+                            return false;
+                        }
+                    }
+                }
+            }
+            else
+            {
+                for (std::size_t i = 0; i < size_and_type.first; ++i)
+                {
+                    if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
+                    {
+                        return false;
+                    }
+                }
+            }
+        }
+        else
+        {
+            if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
+            {
+                return false;
+            }
+
+            while (current != ']')
+            {
+                if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal(false)))
+                {
+                    return false;
+                }
+                get_ignore_noop();
+            }
+        }
+
+        return sax->end_array();
+    }
+
+    /*!
+    @return whether object creation completed
+    */
+    bool get_ubjson_object()
+    {
+        std::pair<std::size_t, int> size_and_type;
+        if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
+        {
+            return false;
+        }
+
+        string_t key;
+        if (size_and_type.first != string_t::npos)
+        {
+            if (JSON_HEDLEY_UNLIKELY(not sax->start_object(size_and_type.first)))
+            {
+                return false;
+            }
+
+            if (size_and_type.second != 0)
+            {
+                for (std::size_t i = 0; i < size_and_type.first; ++i)
+                {
+                    if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
+                    {
+                        return false;
+                    }
+                    if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
+                    {
+                        return false;
+                    }
+                    key.clear();
+                }
+            }
+            else
+            {
+                for (std::size_t i = 0; i < size_and_type.first; ++i)
+                {
+                    if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
+                    {
+                        return false;
+                    }
+                    if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
+                    {
+                        return false;
+                    }
+                    key.clear();
+                }
+            }
+        }
+        else
+        {
+            if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
+            {
+                return false;
+            }
+
+            while (current != '}')
+            {
+                if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key)))
+                {
+                    return false;
+                }
+                if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
+                {
+                    return false;
+                }
+                get_ignore_noop();
+                key.clear();
+            }
+        }
+
+        return sax->end_object();
+    }
+
+    ///////////////////////
+    // Utility functions //
+    ///////////////////////
+
+    /*!
+    @brief get next character from the input
+
+    This function provides the interface to the used input adapter. It does
+    not throw in case the input reached EOF, but returns a -'ve valued
+    `std::char_traits<char>::eof()` in that case.
+
+    @return character read from the input
+    */
+    int get()
+    {
+        ++chars_read;
+        return current = ia->get_character();
+    }
+
+    /*!
+    @return character read from the input after ignoring all 'N' entries
+    */
+    int get_ignore_noop()
+    {
+        do
+        {
+            get();
+        }
+        while (current == 'N');
+
+        return current;
+    }
+
+    /*
+    @brief read a number from the input
+
+    @tparam NumberType the type of the number
+    @param[in] format   the current format (for diagnostics)
+    @param[out] result  number of type @a NumberType
+
+    @return whether conversion completed
+
+    @note This function needs to respect the system's endianess, because
+          bytes in CBOR, MessagePack, and UBJSON are stored in network order
+          (big endian) and therefore need reordering on little endian systems.
+    */
+    template<typename NumberType, bool InputIsLittleEndian = false>
+    bool get_number(const input_format_t format, NumberType& result)
+    {
+        // step 1: read input into array with system's byte order
+        std::array<std::uint8_t, sizeof(NumberType)> vec;
+        for (std::size_t i = 0; i < sizeof(NumberType); ++i)
+        {
+            get();
+            if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "number")))
+            {
+                return false;
+            }
+
+            // reverse byte order prior to conversion if necessary
+            if (is_little_endian != InputIsLittleEndian)
+            {
+                vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
+            }
+            else
+            {
+                vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
+            }
+        }
+
+        // step 2: convert array into number of type T and return
+        std::memcpy(&result, vec.data(), sizeof(NumberType));
+        return true;
+    }
+
+    /*!
+    @brief create a string by reading characters from the input
+
+    @tparam NumberType the type of the number
+    @param[in] format the current format (for diagnostics)
+    @param[in] len number of characters to read
+    @param[out] result string created by reading @a len bytes
+
+    @return whether string creation completed
+
+    @note We can not reserve @a len bytes for the result, because @a len
+          may be too large. Usually, @ref unexpect_eof() detects the end of
+          the input before we run out of string memory.
+    */
+    template<typename NumberType>
+    bool get_string(const input_format_t format,
+                    const NumberType len,
+                    string_t& result)
+    {
+        bool success = true;
+        std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
+        {
+            get();
+            if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "string")))
+            {
+                success = false;
+            }
+            return static_cast<char>(current);
+        });
+        return success;
+    }
+
+    /*!
+    @param[in] format   the current format (for diagnostics)
+    @param[in] context  further context information (for diagnostics)
+    @return whether the last read character is not EOF
+    */
+    JSON_HEDLEY_NON_NULL(3)
+    bool unexpect_eof(const input_format_t format, const char* context) const
+    {
+        if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char>::eof()))
+        {
+            return sax->parse_error(chars_read, "<end of file>",
+                                    parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context)));
+        }
+        return true;
+    }
+
+    /*!
+    @return a string representation of the last read byte
+    */
+    std::string get_token_string() const
+    {
+        std::array<char, 3> cr{{}};
+        (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current));
+        return std::string{cr.data()};
+    }
+
+    /*!
+    @param[in] format   the current format
+    @param[in] detail   a detailed error message
+    @param[in] context  further context information
+    @return a message string to use in the parse_error exceptions
+    */
+    std::string exception_message(const input_format_t format,
+                                  const std::string& detail,
+                                  const std::string& context) const
+    {
+        std::string error_msg = "syntax error while parsing ";
+
+        switch (format)
+        {
+            case input_format_t::cbor:
+                error_msg += "CBOR";
+                break;
+
+            case input_format_t::msgpack:
+                error_msg += "MessagePack";
+                break;
+
+            case input_format_t::ubjson:
+                error_msg += "UBJSON";
+                break;
+
+            case input_format_t::bson:
+                error_msg += "BSON";
+                break;
+
+            default:            // LCOV_EXCL_LINE
+                assert(false);  // LCOV_EXCL_LINE
+        }
+
+        return error_msg + " " + context + ": " + detail;
+    }
+
+  private:
+    /// input adapter
+    input_adapter_t ia = nullptr;
+
+    /// the current character
+    int current = std::char_traits<char>::eof();
+
+    /// the number of characters read
+    std::size_t chars_read = 0;
+
+    /// whether we can assume little endianess
+    const bool is_little_endian = little_endianess();
+
+    /// the SAX parser
+    json_sax_t* sax = nullptr;
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/input/input_adapters.hpp>
+
+// #include <nlohmann/detail/input/lexer.hpp>
+
+
+#include <array> // array
+#include <clocale> // localeconv
+#include <cstddef> // size_t
+#include <cstdio> // snprintf
+#include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
+#include <initializer_list> // initializer_list
+#include <string> // char_traits, string
+#include <utility> // move
+#include <vector> // vector
+
+// #include <nlohmann/detail/input/input_adapters.hpp>
+
+// #include <nlohmann/detail/input/position_t.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+///////////
+// lexer //
+///////////
+
+/*!
+@brief lexical analysis
+
+This class organizes the lexical analysis during JSON deserialization.
+*/
+template<typename BasicJsonType>
+class lexer
+{
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+
+  public:
+    /// token types for the parser
+    enum class token_type
+    {
+        uninitialized,    ///< indicating the scanner is uninitialized
+        literal_true,     ///< the `true` literal
+        literal_false,    ///< the `false` literal
+        literal_null,     ///< the `null` literal
+        value_string,     ///< a string -- use get_string() for actual value
+        value_unsigned,   ///< an unsigned integer -- use get_number_unsigned() for actual value
+        value_integer,    ///< a signed integer -- use get_number_integer() for actual value
+        value_float,      ///< an floating point number -- use get_number_float() for actual value
+        begin_array,      ///< the character for array begin `[`
+        begin_object,     ///< the character for object begin `{`
+        end_array,        ///< the character for array end `]`
+        end_object,       ///< the character for object end `}`
+        name_separator,   ///< the name separator `:`
+        value_separator,  ///< the value separator `,`
+        parse_error,      ///< indicating a parse error
+        end_of_input,     ///< indicating the end of the input buffer
+        literal_or_value  ///< a literal or the begin of a value (only for diagnostics)
+    };
+
+    /// return name of values of type token_type (only used for errors)
+    JSON_HEDLEY_RETURNS_NON_NULL
+    JSON_HEDLEY_CONST
+    static const char* token_type_name(const token_type t) noexcept
+    {
+        switch (t)
+        {
+            case token_type::uninitialized:
+                return "<uninitialized>";
+            case token_type::literal_true:
+                return "true literal";
+            case token_type::literal_false:
+                return "false literal";
+            case token_type::literal_null:
+                return "null literal";
+            case token_type::value_string:
+                return "string literal";
+            case lexer::token_type::value_unsigned:
+            case lexer::token_type::value_integer:
+            case lexer::token_type::value_float:
+                return "number literal";
+            case token_type::begin_array:
+                return "'['";
+            case token_type::begin_object:
+                return "'{'";
+            case token_type::end_array:
+                return "']'";
+            case token_type::end_object:
+                return "'}'";
+            case token_type::name_separator:
+                return "':'";
+            case token_type::value_separator:
+                return "','";
+            case token_type::parse_error:
+                return "<parse error>";
+            case token_type::end_of_input:
+                return "end of input";
+            case token_type::literal_or_value:
+                return "'[', '{', or a literal";
+            // LCOV_EXCL_START
+            default: // catch non-enum values
+                return "unknown token";
+                // LCOV_EXCL_STOP
+        }
+    }
+
+    explicit lexer(detail::input_adapter_t&& adapter)
+        : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
+
+    // delete because of pointer members
+    lexer(const lexer&) = delete;
+    lexer(lexer&&) = delete;
+    lexer& operator=(lexer&) = delete;
+    lexer& operator=(lexer&&) = delete;
+    ~lexer() = default;
+
+  private:
+    /////////////////////
+    // locales
+    /////////////////////
+
+    /// return the locale-dependent decimal point
+    JSON_HEDLEY_PURE
+    static char get_decimal_point() noexcept
+    {
+        const auto loc = localeconv();
+        assert(loc != nullptr);
+        return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
+    }
+
+    /////////////////////
+    // scan functions
+    /////////////////////
+
+    /*!
+    @brief get codepoint from 4 hex characters following `\u`
+
+    For input "\u c1 c2 c3 c4" the codepoint is:
+      (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
+    = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
+
+    Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
+    must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
+    conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
+    between the ASCII value of the character and the desired integer value.
+
+    @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
+            non-hex character)
+    */
+    int get_codepoint()
+    {
+        // this function only makes sense after reading `\u`
+        assert(current == 'u');
+        int codepoint = 0;
+
+        const auto factors = { 12u, 8u, 4u, 0u };
+        for (const auto factor : factors)
+        {
+            get();
+
+            if (current >= '0' and current <= '9')
+            {
+                codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
+            }
+            else if (current >= 'A' and current <= 'F')
+            {
+                codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
+            }
+            else if (current >= 'a' and current <= 'f')
+            {
+                codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
+            }
+            else
+            {
+                return -1;
+            }
+        }
+
+        assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
+        return codepoint;
+    }
+
+    /*!
+    @brief check if the next byte(s) are inside a given range
+
+    Adds the current byte and, for each passed range, reads a new byte and
+    checks if it is inside the range. If a violation was detected, set up an
+    error message and return false. Otherwise, return true.
+
+    @param[in] ranges  list of integers; interpreted as list of pairs of
+                       inclusive lower and upper bound, respectively
+
+    @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
+         1, 2, or 3 pairs. This precondition is enforced by an assertion.
+
+    @return true if and only if no range violation was detected
+    */
+    bool next_byte_in_range(std::initializer_list<int> ranges)
+    {
+        assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
+        add(current);
+
+        for (auto range = ranges.begin(); range != ranges.end(); ++range)
+        {
+            get();
+            if (JSON_HEDLEY_LIKELY(*range <= current and current <= *(++range)))
+            {
+                add(current);
+            }
+            else
+            {
+                error_message = "invalid string: ill-formed UTF-8 byte";
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    /*!
+    @brief scan a string literal
+
+    This function scans a string according to Sect. 7 of RFC 7159. While
+    scanning, bytes are escaped and copied into buffer token_buffer. Then the
+    function returns successfully, token_buffer is *not* null-terminated (as it
+    may contain \0 bytes), and token_buffer.size() is the number of bytes in the
+    string.
+
+    @return token_type::value_string if string could be successfully scanned,
+            token_type::parse_error otherwise
+
+    @note In case of errors, variable error_message contains a textual
+          description.
+    */
+    token_type scan_string()
+    {
+        // reset token_buffer (ignore opening quote)
+        reset();
+
+        // we entered the function by reading an open quote
+        assert(current == '\"');
+
+        while (true)
+        {
+            // get next character
+            switch (get())
+            {
+                // end of file while parsing string
+                case std::char_traits<char>::eof():
+                {
+                    error_message = "invalid string: missing closing quote";
+                    return token_type::parse_error;
+                }
+
+                // closing quote
+                case '\"':
+                {
+                    return token_type::value_string;
+                }
+
+                // escapes
+                case '\\':
+                {
+                    switch (get())
+                    {
+                        // quotation mark
+                        case '\"':
+                            add('\"');
+                            break;
+                        // reverse solidus
+                        case '\\':
+                            add('\\');
+                            break;
+                        // solidus
+                        case '/':
+                            add('/');
+                            break;
+                        // backspace
+                        case 'b':
+                            add('\b');
+                            break;
+                        // form feed
+                        case 'f':
+                            add('\f');
+                            break;
+                        // line feed
+                        case 'n':
+                            add('\n');
+                            break;
+                        // carriage return
+                        case 'r':
+                            add('\r');
+                            break;
+                        // tab
+                        case 't':
+                            add('\t');
+                            break;
+
+                        // unicode escapes
+                        case 'u':
+                        {
+                            const int codepoint1 = get_codepoint();
+                            int codepoint = codepoint1; // start with codepoint1
+
+                            if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
+                            {
+                                error_message = "invalid string: '\\u' must be followed by 4 hex digits";
+                                return token_type::parse_error;
+                            }
+
+                            // check if code point is a high surrogate
+                            if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
+                            {
+                                // expect next \uxxxx entry
+                                if (JSON_HEDLEY_LIKELY(get() == '\\' and get() == 'u'))
+                                {
+                                    const int codepoint2 = get_codepoint();
+
+                                    if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
+                                    {
+                                        error_message = "invalid string: '\\u' must be followed by 4 hex digits";
+                                        return token_type::parse_error;
+                                    }
+
+                                    // check if codepoint2 is a low surrogate
+                                    if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
+                                    {
+                                        // overwrite codepoint
+                                        codepoint = static_cast<int>(
+                                                        // high surrogate occupies the most significant 22 bits
+                                                        (static_cast<unsigned int>(codepoint1) << 10u)
+                                                        // low surrogate occupies the least significant 15 bits
+                                                        + static_cast<unsigned int>(codepoint2)
+                                                        // there is still the 0xD800, 0xDC00 and 0x10000 noise
+                                                        // in the result so we have to subtract with:
+                                                        // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
+                                                        - 0x35FDC00u);
+                                    }
+                                    else
+                                    {
+                                        error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
+                                        return token_type::parse_error;
+                                    }
+                                }
+                                else
+                                {
+                                    error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
+                                    return token_type::parse_error;
+                                }
+                            }
+                            else
+                            {
+                                if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
+                                {
+                                    error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
+                                    return token_type::parse_error;
+                                }
+                            }
+
+                            // result of the above calculation yields a proper codepoint
+                            assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
+
+                            // translate codepoint into bytes
+                            if (codepoint < 0x80)
+                            {
+                                // 1-byte characters: 0xxxxxxx (ASCII)
+                                add(codepoint);
+                            }
+                            else if (codepoint <= 0x7FF)
+                            {
+                                // 2-byte characters: 110xxxxx 10xxxxxx
+                                add(static_cast<int>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
+                                add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
+                            }
+                            else if (codepoint <= 0xFFFF)
+                            {
+                                // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
+                                add(static_cast<int>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
+                                add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
+                                add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
+                            }
+                            else
+                            {
+                                // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+                                add(static_cast<int>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
+                                add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
+                                add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
+                                add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
+                            }
+
+                            break;
+                        }
+
+                        // other characters after escape
+                        default:
+                            error_message = "invalid string: forbidden character after backslash";
+                            return token_type::parse_error;
+                    }
+
+                    break;
+                }
+
+                // invalid control characters
+                case 0x00:
+                {
+                    error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
+                    return token_type::parse_error;
+                }
+
+                case 0x01:
+                {
+                    error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
+                    return token_type::parse_error;
+                }
+
+                case 0x02:
+                {
+                    error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
+                    return token_type::parse_error;
+                }
+
+                case 0x03:
+                {
+                    error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
+                    return token_type::parse_error;
+                }
+
+                case 0x04:
+                {
+                    error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
+                    return token_type::parse_error;
+                }
+
+                case 0x05:
+                {
+                    error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
+                    return token_type::parse_error;
+                }
+
+                case 0x06:
+                {
+                    error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
+                    return token_type::parse_error;
+                }
+
+                case 0x07:
+                {
+                    error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
+                    return token_type::parse_error;
+                }
+
+                case 0x08:
+                {
+                    error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
+                    return token_type::parse_error;
+                }
+
+                case 0x09:
+                {
+                    error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
+                    return token_type::parse_error;
+                }
+
+                case 0x0A:
+                {
+                    error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
+                    return token_type::parse_error;
+                }
+
+                case 0x0B:
+                {
+                    error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
+                    return token_type::parse_error;
+                }
+
+                case 0x0C:
+                {
+                    error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
+                    return token_type::parse_error;
+                }
+
+                case 0x0D:
+                {
+                    error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
+                    return token_type::parse_error;
+                }
+
+                case 0x0E:
+                {
+                    error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
+                    return token_type::parse_error;
+                }
+
+                case 0x0F:
+                {
+                    error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
+                    return token_type::parse_error;
+                }
+
+                case 0x10:
+                {
+                    error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
+                    return token_type::parse_error;
+                }
+
+                case 0x11:
+                {
+                    error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
+                    return token_type::parse_error;
+                }
+
+                case 0x12:
+                {
+                    error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
+                    return token_type::parse_error;
+                }
+
+                case 0x13:
+                {
+                    error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
+                    return token_type::parse_error;
+                }
+
+                case 0x14:
+                {
+                    error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
+                    return token_type::parse_error;
+                }
+
+                case 0x15:
+                {
+                    error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
+                    return token_type::parse_error;
+                }
+
+                case 0x16:
+                {
+                    error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
+                    return token_type::parse_error;
+                }
+
+                case 0x17:
+                {
+                    error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
+                    return token_type::parse_error;
+                }
+
+                case 0x18:
+                {
+                    error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
+                    return token_type::parse_error;
+                }
+
+                case 0x19:
+                {
+                    error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
+                    return token_type::parse_error;
+                }
+
+                case 0x1A:
+                {
+                    error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
+                    return token_type::parse_error;
+                }
+
+                case 0x1B:
+                {
+                    error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
+                    return token_type::parse_error;
+                }
+
+                case 0x1C:
+                {
+                    error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
+                    return token_type::parse_error;
+                }
+
+                case 0x1D:
+                {
+                    error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
+                    return token_type::parse_error;
+                }
+
+                case 0x1E:
+                {
+                    error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
+                    return token_type::parse_error;
+                }
+
+                case 0x1F:
+                {
+                    error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
+                    return token_type::parse_error;
+                }
+
+                // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
+                case 0x20:
+                case 0x21:
+                case 0x23:
+                case 0x24:
+                case 0x25:
+                case 0x26:
+                case 0x27:
+                case 0x28:
+                case 0x29:
+                case 0x2A:
+                case 0x2B:
+                case 0x2C:
+                case 0x2D:
+                case 0x2E:
+                case 0x2F:
+                case 0x30:
+                case 0x31:
+                case 0x32:
+                case 0x33:
+                case 0x34:
+                case 0x35:
+                case 0x36:
+                case 0x37:
+                case 0x38:
+                case 0x39:
+                case 0x3A:
+                case 0x3B:
+                case 0x3C:
+                case 0x3D:
+                case 0x3E:
+                case 0x3F:
+                case 0x40:
+                case 0x41:
+                case 0x42:
+                case 0x43:
+                case 0x44:
+                case 0x45:
+                case 0x46:
+                case 0x47:
+                case 0x48:
+                case 0x49:
+                case 0x4A:
+                case 0x4B:
+                case 0x4C:
+                case 0x4D:
+                case 0x4E:
+                case 0x4F:
+                case 0x50:
+                case 0x51:
+                case 0x52:
+                case 0x53:
+                case 0x54:
+                case 0x55:
+                case 0x56:
+                case 0x57:
+                case 0x58:
+                case 0x59:
+                case 0x5A:
+                case 0x5B:
+                case 0x5D:
+                case 0x5E:
+                case 0x5F:
+                case 0x60:
+                case 0x61:
+                case 0x62:
+                case 0x63:
+                case 0x64:
+                case 0x65:
+                case 0x66:
+                case 0x67:
+                case 0x68:
+                case 0x69:
+                case 0x6A:
+                case 0x6B:
+                case 0x6C:
+                case 0x6D:
+                case 0x6E:
+                case 0x6F:
+                case 0x70:
+                case 0x71:
+                case 0x72:
+                case 0x73:
+                case 0x74:
+                case 0x75:
+                case 0x76:
+                case 0x77:
+                case 0x78:
+                case 0x79:
+                case 0x7A:
+                case 0x7B:
+                case 0x7C:
+                case 0x7D:
+                case 0x7E:
+                case 0x7F:
+                {
+                    add(current);
+                    break;
+                }
+
+                // U+0080..U+07FF: bytes C2..DF 80..BF
+                case 0xC2:
+                case 0xC3:
+                case 0xC4:
+                case 0xC5:
+                case 0xC6:
+                case 0xC7:
+                case 0xC8:
+                case 0xC9:
+                case 0xCA:
+                case 0xCB:
+                case 0xCC:
+                case 0xCD:
+                case 0xCE:
+                case 0xCF:
+                case 0xD0:
+                case 0xD1:
+                case 0xD2:
+                case 0xD3:
+                case 0xD4:
+                case 0xD5:
+                case 0xD6:
+                case 0xD7:
+                case 0xD8:
+                case 0xD9:
+                case 0xDA:
+                case 0xDB:
+                case 0xDC:
+                case 0xDD:
+                case 0xDE:
+                case 0xDF:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
+                case 0xE0:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
+                // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
+                case 0xE1:
+                case 0xE2:
+                case 0xE3:
+                case 0xE4:
+                case 0xE5:
+                case 0xE6:
+                case 0xE7:
+                case 0xE8:
+                case 0xE9:
+                case 0xEA:
+                case 0xEB:
+                case 0xEC:
+                case 0xEE:
+                case 0xEF:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // U+D000..U+D7FF: bytes ED 80..9F 80..BF
+                case 0xED:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
+                case 0xF0:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
+                case 0xF1:
+                case 0xF2:
+                case 0xF3:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
+                case 0xF4:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // remaining bytes (80..C1 and F5..FF) are ill-formed
+                default:
+                {
+                    error_message = "invalid string: ill-formed UTF-8 byte";
+                    return token_type::parse_error;
+                }
+            }
+        }
+    }
+
+    JSON_HEDLEY_NON_NULL(2)
+    static void strtof(float& f, const char* str, char** endptr) noexcept
+    {
+        f = std::strtof(str, endptr);
+    }
+
+    JSON_HEDLEY_NON_NULL(2)
+    static void strtof(double& f, const char* str, char** endptr) noexcept
+    {
+        f = std::strtod(str, endptr);
+    }
+
+    JSON_HEDLEY_NON_NULL(2)
+    static void strtof(long double& f, const char* str, char** endptr) noexcept
+    {
+        f = std::strtold(str, endptr);
+    }
+
+    /*!
+    @brief scan a number literal
+
+    This function scans a string according to Sect. 6 of RFC 7159.
+
+    The function is realized with a deterministic finite state machine derived
+    from the grammar described in RFC 7159. Starting in state "init", the
+    input is read and used to determined the next state. Only state "done"
+    accepts the number. State "error" is a trap state to model errors. In the
+    table below, "anything" means any character but the ones listed before.
+
+    state    | 0        | 1-9      | e E      | +       | -       | .        | anything
+    ---------|----------|----------|----------|---------|---------|----------|-----------
+    init     | zero     | any1     | [error]  | [error] | minus   | [error]  | [error]
+    minus    | zero     | any1     | [error]  | [error] | [error] | [error]  | [error]
+    zero     | done     | done     | exponent | done    | done    | decimal1 | done
+    any1     | any1     | any1     | exponent | done    | done    | decimal1 | done
+    decimal1 | decimal2 | decimal2 | [error]  | [error] | [error] | [error]  | [error]
+    decimal2 | decimal2 | decimal2 | exponent | done    | done    | done     | done
+    exponent | any2     | any2     | [error]  | sign    | sign    | [error]  | [error]
+    sign     | any2     | any2     | [error]  | [error] | [error] | [error]  | [error]
+    any2     | any2     | any2     | done     | done    | done    | done     | done
+
+    The state machine is realized with one label per state (prefixed with
+    "scan_number_") and `goto` statements between them. The state machine
+    contains cycles, but any cycle can be left when EOF is read. Therefore,
+    the function is guaranteed to terminate.
+
+    During scanning, the read bytes are stored in token_buffer. This string is
+    then converted to a signed integer, an unsigned integer, or a
+    floating-point number.
+
+    @return token_type::value_unsigned, token_type::value_integer, or
+            token_type::value_float if number could be successfully scanned,
+            token_type::parse_error otherwise
+
+    @note The scanner is independent of the current locale. Internally, the
+          locale's decimal point is used instead of `.` to work with the
+          locale-dependent converters.
+    */
+    token_type scan_number()  // lgtm [cpp/use-of-goto]
+    {
+        // reset token_buffer to store the number's bytes
+        reset();
+
+        // the type of the parsed number; initially set to unsigned; will be
+        // changed if minus sign, decimal point or exponent is read
+        token_type number_type = token_type::value_unsigned;
+
+        // state (init): we just found out we need to scan a number
+        switch (current)
+        {
+            case '-':
+            {
+                add(current);
+                goto scan_number_minus;
+            }
+
+            case '0':
+            {
+                add(current);
+                goto scan_number_zero;
+            }
+
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_any1;
+            }
+
+            // all other characters are rejected outside scan_number()
+            default:            // LCOV_EXCL_LINE
+                assert(false);  // LCOV_EXCL_LINE
+        }
+
+scan_number_minus:
+        // state: we just parsed a leading minus sign
+        number_type = token_type::value_integer;
+        switch (get())
+        {
+            case '0':
+            {
+                add(current);
+                goto scan_number_zero;
+            }
+
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_any1;
+            }
+
+            default:
+            {
+                error_message = "invalid number; expected digit after '-'";
+                return token_type::parse_error;
+            }
+        }
+
+scan_number_zero:
+        // state: we just parse a zero (maybe with a leading minus sign)
+        switch (get())
+        {
+            case '.':
+            {
+                add(decimal_point_char);
+                goto scan_number_decimal1;
+            }
+
+            case 'e':
+            case 'E':
+            {
+                add(current);
+                goto scan_number_exponent;
+            }
+
+            default:
+                goto scan_number_done;
+        }
+
+scan_number_any1:
+        // state: we just parsed a number 0-9 (maybe with a leading minus sign)
+        switch (get())
+        {
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_any1;
+            }
+
+            case '.':
+            {
+                add(decimal_point_char);
+                goto scan_number_decimal1;
+            }
+
+            case 'e':
+            case 'E':
+            {
+                add(current);
+                goto scan_number_exponent;
+            }
+
+            default:
+                goto scan_number_done;
+        }
+
+scan_number_decimal1:
+        // state: we just parsed a decimal point
+        number_type = token_type::value_float;
+        switch (get())
+        {
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_decimal2;
+            }
+
+            default:
+            {
+                error_message = "invalid number; expected digit after '.'";
+                return token_type::parse_error;
+            }
+        }
+
+scan_number_decimal2:
+        // we just parsed at least one number after a decimal point
+        switch (get())
+        {
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_decimal2;
+            }
+
+            case 'e':
+            case 'E':
+            {
+                add(current);
+                goto scan_number_exponent;
+            }
+
+            default:
+                goto scan_number_done;
+        }
+
+scan_number_exponent:
+        // we just parsed an exponent
+        number_type = token_type::value_float;
+        switch (get())
+        {
+            case '+':
+            case '-':
+            {
+                add(current);
+                goto scan_number_sign;
+            }
+
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_any2;
+            }
+
+            default:
+            {
+                error_message =
+                    "invalid number; expected '+', '-', or digit after exponent";
+                return token_type::parse_error;
+            }
+        }
+
+scan_number_sign:
+        // we just parsed an exponent sign
+        switch (get())
+        {
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_any2;
+            }
+
+            default:
+            {
+                error_message = "invalid number; expected digit after exponent sign";
+                return token_type::parse_error;
+            }
+        }
+
+scan_number_any2:
+        // we just parsed a number after the exponent or exponent sign
+        switch (get())
+        {
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_any2;
+            }
+
+            default:
+                goto scan_number_done;
+        }
+
+scan_number_done:
+        // unget the character after the number (we only read it to know that
+        // we are done scanning a number)
+        unget();
+
+        char* endptr = nullptr;
+        errno = 0;
+
+        // try to parse integers first and fall back to floats
+        if (number_type == token_type::value_unsigned)
+        {
+            const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
+
+            // we checked the number format before
+            assert(endptr == token_buffer.data() + token_buffer.size());
+
+            if (errno == 0)
+            {
+                value_unsigned = static_cast<number_unsigned_t>(x);
+                if (value_unsigned == x)
+                {
+                    return token_type::value_unsigned;
+                }
+            }
+        }
+        else if (number_type == token_type::value_integer)
+        {
+            const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
+
+            // we checked the number format before
+            assert(endptr == token_buffer.data() + token_buffer.size());
+
+            if (errno == 0)
+            {
+                value_integer = static_cast<number_integer_t>(x);
+                if (value_integer == x)
+                {
+                    return token_type::value_integer;
+                }
+            }
+        }
+
+        // this code is reached if we parse a floating-point number or if an
+        // integer conversion above failed
+        strtof(value_float, token_buffer.data(), &endptr);
+
+        // we checked the number format before
+        assert(endptr == token_buffer.data() + token_buffer.size());
+
+        return token_type::value_float;
+    }
+
+    /*!
+    @param[in] literal_text  the literal text to expect
+    @param[in] length        the length of the passed literal text
+    @param[in] return_type   the token type to return on success
+    */
+    JSON_HEDLEY_NON_NULL(2)
+    token_type scan_literal(const char* literal_text, const std::size_t length,
+                            token_type return_type)
+    {
+        assert(current == literal_text[0]);
+        for (std::size_t i = 1; i < length; ++i)
+        {
+            if (JSON_HEDLEY_UNLIKELY(get() != literal_text[i]))
+            {
+                error_message = "invalid literal";
+                return token_type::parse_error;
+            }
+        }
+        return return_type;
+    }
+
+    /////////////////////
+    // input management
+    /////////////////////
+
+    /// reset token_buffer; current character is beginning of token
+    void reset() noexcept
+    {
+        token_buffer.clear();
+        token_string.clear();
+        token_string.push_back(std::char_traits<char>::to_char_type(current));
+    }
+
+    /*
+    @brief get next character from the input
+
+    This function provides the interface to the used input adapter. It does
+    not throw in case the input reached EOF, but returns a
+    `std::char_traits<char>::eof()` in that case.  Stores the scanned characters
+    for use in error messages.
+
+    @return character read from the input
+    */
+    std::char_traits<char>::int_type get()
+    {
+        ++position.chars_read_total;
+        ++position.chars_read_current_line;
+
+        if (next_unget)
+        {
+            // just reset the next_unget variable and work with current
+            next_unget = false;
+        }
+        else
+        {
+            current = ia->get_character();
+        }
+
+        if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
+        {
+            token_string.push_back(std::char_traits<char>::to_char_type(current));
+        }
+
+        if (current == '\n')
+        {
+            ++position.lines_read;
+            position.chars_read_current_line = 0;
+        }
+
+        return current;
+    }
+
+    /*!
+    @brief unget current character (read it again on next get)
+
+    We implement unget by setting variable next_unget to true. The input is not
+    changed - we just simulate ungetting by modifying chars_read_total,
+    chars_read_current_line, and token_string. The next call to get() will
+    behave as if the unget character is read again.
+    */
+    void unget()
+    {
+        next_unget = true;
+
+        --position.chars_read_total;
+
+        // in case we "unget" a newline, we have to also decrement the lines_read
+        if (position.chars_read_current_line == 0)
+        {
+            if (position.lines_read > 0)
+            {
+                --position.lines_read;
+            }
+        }
+        else
+        {
+            --position.chars_read_current_line;
+        }
+
+        if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
+        {
+            assert(not token_string.empty());
+            token_string.pop_back();
+        }
+    }
+
+    /// add a character to token_buffer
+    void add(int c)
+    {
+        token_buffer.push_back(std::char_traits<char>::to_char_type(c));
+    }
+
+  public:
+    /////////////////////
+    // value getters
+    /////////////////////
+
+    /// return integer value
+    constexpr number_integer_t get_number_integer() const noexcept
+    {
+        return value_integer;
+    }
+
+    /// return unsigned integer value
+    constexpr number_unsigned_t get_number_unsigned() const noexcept
+    {
+        return value_unsigned;
+    }
+
+    /// return floating-point value
+    constexpr number_float_t get_number_float() const noexcept
+    {
+        return value_float;
+    }
+
+    /// return current string value (implicitly resets the token; useful only once)
+    string_t& get_string()
+    {
+        return token_buffer;
+    }
+
+    /////////////////////
+    // diagnostics
+    /////////////////////
+
+    /// return position of last read token
+    constexpr position_t get_position() const noexcept
+    {
+        return position;
+    }
+
+    /// return the last read token (for errors only).  Will never contain EOF
+    /// (an arbitrary value that is not a valid char value, often -1), because
+    /// 255 may legitimately occur.  May contain NUL, which should be escaped.
+    std::string get_token_string() const
+    {
+        // escape control characters
+        std::string result;
+        for (const auto c : token_string)
+        {
+            if ('\x00' <= c and c <= '\x1F')
+            {
+                // escape control characters
+                std::array<char, 9> cs{{}};
+                (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c));
+                result += cs.data();
+            }
+            else
+            {
+                // add character as is
+                result.push_back(c);
+            }
+        }
+
+        return result;
+    }
+
+    /// return syntax error message
+    JSON_HEDLEY_RETURNS_NON_NULL
+    constexpr const char* get_error_message() const noexcept
+    {
+        return error_message;
+    }
+
+    /////////////////////
+    // actual scanner
+    /////////////////////
+
+    /*!
+    @brief skip the UTF-8 byte order mark
+    @return true iff there is no BOM or the correct BOM has been skipped
+    */
+    bool skip_bom()
+    {
+        if (get() == 0xEF)
+        {
+            // check if we completely parse the BOM
+            return get() == 0xBB and get() == 0xBF;
+        }
+
+        // the first character is not the beginning of the BOM; unget it to
+        // process is later
+        unget();
+        return true;
+    }
+
+    token_type scan()
+    {
+        // initially, skip the BOM
+        if (position.chars_read_total == 0 and not skip_bom())
+        {
+            error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
+            return token_type::parse_error;
+        }
+
+        // read next character and ignore whitespace
+        do
+        {
+            get();
+        }
+        while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
+
+        switch (current)
+        {
+            // structural characters
+            case '[':
+                return token_type::begin_array;
+            case ']':
+                return token_type::end_array;
+            case '{':
+                return token_type::begin_object;
+            case '}':
+                return token_type::end_object;
+            case ':':
+                return token_type::name_separator;
+            case ',':
+                return token_type::value_separator;
+
+            // literals
+            case 't':
+                return scan_literal("true", 4, token_type::literal_true);
+            case 'f':
+                return scan_literal("false", 5, token_type::literal_false);
+            case 'n':
+                return scan_literal("null", 4, token_type::literal_null);
+
+            // string
+            case '\"':
+                return scan_string();
+
+            // number
+            case '-':
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+                return scan_number();
+
+            // end of input (the null byte is needed when parsing from
+            // string literals)
+            case '\0':
+            case std::char_traits<char>::eof():
+                return token_type::end_of_input;
+
+            // error
+            default:
+                error_message = "invalid literal";
+                return token_type::parse_error;
+        }
+    }
+
+  private:
+    /// input adapter
+    detail::input_adapter_t ia = nullptr;
+
+    /// the current character
+    std::char_traits<char>::int_type current = std::char_traits<char>::eof();
+
+    /// whether the next get() call should just return current
+    bool next_unget = false;
+
+    /// the start position of the current token
+    position_t position {};
+
+    /// raw input token string (for error messages)
+    std::vector<char> token_string {};
+
+    /// buffer for variable-length tokens (numbers, strings)
+    string_t token_buffer {};
+
+    /// a description of occurred lexer errors
+    const char* error_message = "";
+
+    // number values
+    number_integer_t value_integer = 0;
+    number_unsigned_t value_unsigned = 0;
+    number_float_t value_float = 0;
+
+    /// the decimal point
+    const char decimal_point_char = '.';
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/input/parser.hpp>
+
+
+#include <cassert> // assert
+#include <cmath> // isfinite
+#include <cstdint> // uint8_t
+#include <functional> // function
+#include <string> // string
+#include <utility> // move
+#include <vector> // vector
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/input/input_adapters.hpp>
+
+// #include <nlohmann/detail/input/json_sax.hpp>
+
+// #include <nlohmann/detail/input/lexer.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/is_sax.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+////////////
+// parser //
+////////////
+
+/*!
+@brief syntax analysis
+
+This class implements a recursive descent parser.
+*/
+template<typename BasicJsonType>
+class parser
+{
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using lexer_t = lexer<BasicJsonType>;
+    using token_type = typename lexer_t::token_type;
+
+  public:
+    enum class parse_event_t : uint8_t
+    {
+        /// the parser read `{` and started to process a JSON object
+        object_start,
+        /// the parser read `}` and finished processing a JSON object
+        object_end,
+        /// the parser read `[` and started to process a JSON array
+        array_start,
+        /// the parser read `]` and finished processing a JSON array
+        array_end,
+        /// the parser read a key of a value in an object
+        key,
+        /// the parser finished reading a JSON value
+        value
+    };
+
+    using parser_callback_t =
+        std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
+
+    /// a parser reading from an input adapter
+    explicit parser(detail::input_adapter_t&& adapter,
+                    const parser_callback_t cb = nullptr,
+                    const bool allow_exceptions_ = true)
+        : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_)
+    {
+        // read first token
+        get_token();
+    }
+
+    /*!
+    @brief public parser interface
+
+    @param[in] strict      whether to expect the last token to be EOF
+    @param[in,out] result  parsed JSON value
+
+    @throw parse_error.101 in case of an unexpected token
+    @throw parse_error.102 if to_unicode fails or surrogate error
+    @throw parse_error.103 if to_unicode fails
+    */
+    void parse(const bool strict, BasicJsonType& result)
+    {
+        if (callback)
+        {
+            json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
+            sax_parse_internal(&sdp);
+            result.assert_invariant();
+
+            // in strict mode, input must be completely read
+            if (strict and (get_token() != token_type::end_of_input))
+            {
+                sdp.parse_error(m_lexer.get_position(),
+                                m_lexer.get_token_string(),
+                                parse_error::create(101, m_lexer.get_position(),
+                                                    exception_message(token_type::end_of_input, "value")));
+            }
+
+            // in case of an error, return discarded value
+            if (sdp.is_errored())
+            {
+                result = value_t::discarded;
+                return;
+            }
+
+            // set top-level value to null if it was discarded by the callback
+            // function
+            if (result.is_discarded())
+            {
+                result = nullptr;
+            }
+        }
+        else
+        {
+            json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
+            sax_parse_internal(&sdp);
+            result.assert_invariant();
+
+            // in strict mode, input must be completely read
+            if (strict and (get_token() != token_type::end_of_input))
+            {
+                sdp.parse_error(m_lexer.get_position(),
+                                m_lexer.get_token_string(),
+                                parse_error::create(101, m_lexer.get_position(),
+                                                    exception_message(token_type::end_of_input, "value")));
+            }
+
+            // in case of an error, return discarded value
+            if (sdp.is_errored())
+            {
+                result = value_t::discarded;
+                return;
+            }
+        }
+    }
+
+    /*!
+    @brief public accept interface
+
+    @param[in] strict  whether to expect the last token to be EOF
+    @return whether the input is a proper JSON text
+    */
+    bool accept(const bool strict = true)
+    {
+        json_sax_acceptor<BasicJsonType> sax_acceptor;
+        return sax_parse(&sax_acceptor, strict);
+    }
+
+    template <typename SAX>
+    JSON_HEDLEY_NON_NULL(2)
+    bool sax_parse(SAX* sax, const bool strict = true)
+    {
+        (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
+        const bool result = sax_parse_internal(sax);
+
+        // strict mode: next byte must be EOF
+        if (result and strict and (get_token() != token_type::end_of_input))
+        {
+            return sax->parse_error(m_lexer.get_position(),
+                                    m_lexer.get_token_string(),
+                                    parse_error::create(101, m_lexer.get_position(),
+                                            exception_message(token_type::end_of_input, "value")));
+        }
+
+        return result;
+    }
+
+  private:
+    template <typename SAX>
+    JSON_HEDLEY_NON_NULL(2)
+    bool sax_parse_internal(SAX* sax)
+    {
+        // stack to remember the hierarchy of structured values we are parsing
+        // true = array; false = object
+        std::vector<bool> states;
+        // value to avoid a goto (see comment where set to true)
+        bool skip_to_state_evaluation = false;
+
+        while (true)
+        {
+            if (not skip_to_state_evaluation)
+            {
+                // invariant: get_token() was called before each iteration
+                switch (last_token)
+                {
+                    case token_type::begin_object:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
+                        {
+                            return false;
+                        }
+
+                        // closing } -> we are done
+                        if (get_token() == token_type::end_object)
+                        {
+                            if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
+                            {
+                                return false;
+                            }
+                            break;
+                        }
+
+                        // parse key
+                        if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
+                        {
+                            return sax->parse_error(m_lexer.get_position(),
+                                                    m_lexer.get_token_string(),
+                                                    parse_error::create(101, m_lexer.get_position(),
+                                                            exception_message(token_type::value_string, "object key")));
+                        }
+                        if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
+                        {
+                            return false;
+                        }
+
+                        // parse separator (:)
+                        if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
+                        {
+                            return sax->parse_error(m_lexer.get_position(),
+                                                    m_lexer.get_token_string(),
+                                                    parse_error::create(101, m_lexer.get_position(),
+                                                            exception_message(token_type::name_separator, "object separator")));
+                        }
+
+                        // remember we are now inside an object
+                        states.push_back(false);
+
+                        // parse values
+                        get_token();
+                        continue;
+                    }
+
+                    case token_type::begin_array:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
+                        {
+                            return false;
+                        }
+
+                        // closing ] -> we are done
+                        if (get_token() == token_type::end_array)
+                        {
+                            if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
+                            {
+                                return false;
+                            }
+                            break;
+                        }
+
+                        // remember we are now inside an array
+                        states.push_back(true);
+
+                        // parse values (no need to call get_token)
+                        continue;
+                    }
+
+                    case token_type::value_float:
+                    {
+                        const auto res = m_lexer.get_number_float();
+
+                        if (JSON_HEDLEY_UNLIKELY(not std::isfinite(res)))
+                        {
+                            return sax->parse_error(m_lexer.get_position(),
+                                                    m_lexer.get_token_string(),
+                                                    out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
+                        }
+
+                        if (JSON_HEDLEY_UNLIKELY(not sax->number_float(res, m_lexer.get_string())))
+                        {
+                            return false;
+                        }
+
+                        break;
+                    }
+
+                    case token_type::literal_false:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(not sax->boolean(false)))
+                        {
+                            return false;
+                        }
+                        break;
+                    }
+
+                    case token_type::literal_null:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(not sax->null()))
+                        {
+                            return false;
+                        }
+                        break;
+                    }
+
+                    case token_type::literal_true:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(not sax->boolean(true)))
+                        {
+                            return false;
+                        }
+                        break;
+                    }
+
+                    case token_type::value_integer:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer())))
+                        {
+                            return false;
+                        }
+                        break;
+                    }
+
+                    case token_type::value_string:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(not sax->string(m_lexer.get_string())))
+                        {
+                            return false;
+                        }
+                        break;
+                    }
+
+                    case token_type::value_unsigned:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned())))
+                        {
+                            return false;
+                        }
+                        break;
+                    }
+
+                    case token_type::parse_error:
+                    {
+                        // using "uninitialized" to avoid "expected" message
+                        return sax->parse_error(m_lexer.get_position(),
+                                                m_lexer.get_token_string(),
+                                                parse_error::create(101, m_lexer.get_position(),
+                                                        exception_message(token_type::uninitialized, "value")));
+                    }
+
+                    default: // the last token was unexpected
+                    {
+                        return sax->parse_error(m_lexer.get_position(),
+                                                m_lexer.get_token_string(),
+                                                parse_error::create(101, m_lexer.get_position(),
+                                                        exception_message(token_type::literal_or_value, "value")));
+                    }
+                }
+            }
+            else
+            {
+                skip_to_state_evaluation = false;
+            }
+
+            // we reached this line after we successfully parsed a value
+            if (states.empty())
+            {
+                // empty stack: we reached the end of the hierarchy: done
+                return true;
+            }
+
+            if (states.back())  // array
+            {
+                // comma -> next value
+                if (get_token() == token_type::value_separator)
+                {
+                    // parse a new value
+                    get_token();
+                    continue;
+                }
+
+                // closing ]
+                if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
+                {
+                    if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
+                    {
+                        return false;
+                    }
+
+                    // We are done with this array. Before we can parse a
+                    // new value, we need to evaluate the new state first.
+                    // By setting skip_to_state_evaluation to false, we
+                    // are effectively jumping to the beginning of this if.
+                    assert(not states.empty());
+                    states.pop_back();
+                    skip_to_state_evaluation = true;
+                    continue;
+                }
+
+                return sax->parse_error(m_lexer.get_position(),
+                                        m_lexer.get_token_string(),
+                                        parse_error::create(101, m_lexer.get_position(),
+                                                exception_message(token_type::end_array, "array")));
+            }
+            else  // object
+            {
+                // comma -> next value
+                if (get_token() == token_type::value_separator)
+                {
+                    // parse key
+                    if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
+                    {
+                        return sax->parse_error(m_lexer.get_position(),
+                                                m_lexer.get_token_string(),
+                                                parse_error::create(101, m_lexer.get_position(),
+                                                        exception_message(token_type::value_string, "object key")));
+                    }
+
+                    if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
+                    {
+                        return false;
+                    }
+
+                    // parse separator (:)
+                    if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
+                    {
+                        return sax->parse_error(m_lexer.get_position(),
+                                                m_lexer.get_token_string(),
+                                                parse_error::create(101, m_lexer.get_position(),
+                                                        exception_message(token_type::name_separator, "object separator")));
+                    }
+
+                    // parse values
+                    get_token();
+                    continue;
+                }
+
+                // closing }
+                if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
+                {
+                    if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
+                    {
+                        return false;
+                    }
+
+                    // We are done with this object. Before we can parse a
+                    // new value, we need to evaluate the new state first.
+                    // By setting skip_to_state_evaluation to false, we
+                    // are effectively jumping to the beginning of this if.
+                    assert(not states.empty());
+                    states.pop_back();
+                    skip_to_state_evaluation = true;
+                    continue;
+                }
+
+                return sax->parse_error(m_lexer.get_position(),
+                                        m_lexer.get_token_string(),
+                                        parse_error::create(101, m_lexer.get_position(),
+                                                exception_message(token_type::end_object, "object")));
+            }
+        }
+    }
+
+    /// get next token from lexer
+    token_type get_token()
+    {
+        return last_token = m_lexer.scan();
+    }
+
+    std::string exception_message(const token_type expected, const std::string& context)
+    {
+        std::string error_msg = "syntax error ";
+
+        if (not context.empty())
+        {
+            error_msg += "while parsing " + context + " ";
+        }
+
+        error_msg += "- ";
+
+        if (last_token == token_type::parse_error)
+        {
+            error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
+                         m_lexer.get_token_string() + "'";
+        }
+        else
+        {
+            error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
+        }
+
+        if (expected != token_type::uninitialized)
+        {
+            error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
+        }
+
+        return error_msg;
+    }
+
+  private:
+    /// callback function
+    const parser_callback_t callback = nullptr;
+    /// the type of the last read token
+    token_type last_token = token_type::uninitialized;
+    /// the lexer
+    lexer_t m_lexer;
+    /// whether to throw exceptions in case of errors
+    const bool allow_exceptions = true;
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/iterators/internal_iterator.hpp>
+
+
+// #include <nlohmann/detail/iterators/primitive_iterator.hpp>
+
+
+#include <cstddef> // ptrdiff_t
+#include <limits>  // numeric_limits
+
+namespace nlohmann
+{
+namespace detail
+{
+/*
+@brief an iterator for primitive JSON types
+
+This class models an iterator for primitive JSON types (boolean, number,
+string). It's only purpose is to allow the iterator/const_iterator classes
+to "iterate" over primitive values. Internally, the iterator is modeled by
+a `difference_type` variable. Value begin_value (`0`) models the begin,
+end_value (`1`) models past the end.
+*/
+class primitive_iterator_t
+{
+  private:
+    using difference_type = std::ptrdiff_t;
+    static constexpr difference_type begin_value = 0;
+    static constexpr difference_type end_value = begin_value + 1;
+
+    /// iterator as signed integer type
+    difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
+
+  public:
+    constexpr difference_type get_value() const noexcept
+    {
+        return m_it;
+    }
+
+    /// set iterator to a defined beginning
+    void set_begin() noexcept
+    {
+        m_it = begin_value;
+    }
+
+    /// set iterator to a defined past the end
+    void set_end() noexcept
+    {
+        m_it = end_value;
+    }
+
+    /// return whether the iterator can be dereferenced
+    constexpr bool is_begin() const noexcept
+    {
+        return m_it == begin_value;
+    }
+
+    /// return whether the iterator is at end
+    constexpr bool is_end() const noexcept
+    {
+        return m_it == end_value;
+    }
+
+    friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
+    {
+        return lhs.m_it == rhs.m_it;
+    }
+
+    friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
+    {
+        return lhs.m_it < rhs.m_it;
+    }
+
+    primitive_iterator_t operator+(difference_type n) noexcept
+    {
+        auto result = *this;
+        result += n;
+        return result;
+    }
+
+    friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
+    {
+        return lhs.m_it - rhs.m_it;
+    }
+
+    primitive_iterator_t& operator++() noexcept
+    {
+        ++m_it;
+        return *this;
+    }
+
+    primitive_iterator_t const operator++(int) noexcept
+    {
+        auto result = *this;
+        ++m_it;
+        return result;
+    }
+
+    primitive_iterator_t& operator--() noexcept
+    {
+        --m_it;
+        return *this;
+    }
+
+    primitive_iterator_t const operator--(int) noexcept
+    {
+        auto result = *this;
+        --m_it;
+        return result;
+    }
+
+    primitive_iterator_t& operator+=(difference_type n) noexcept
+    {
+        m_it += n;
+        return *this;
+    }
+
+    primitive_iterator_t& operator-=(difference_type n) noexcept
+    {
+        m_it -= n;
+        return *this;
+    }
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+
+namespace nlohmann
+{
+namespace detail
+{
+/*!
+@brief an iterator value
+
+@note This structure could easily be a union, but MSVC currently does not allow
+unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
+*/
+template<typename BasicJsonType> struct internal_iterator
+{
+    /// iterator for JSON objects
+    typename BasicJsonType::object_t::iterator object_iterator {};
+    /// iterator for JSON arrays
+    typename BasicJsonType::array_t::iterator array_iterator {};
+    /// generic iterator for all other types
+    primitive_iterator_t primitive_iterator {};
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/iterators/iter_impl.hpp>
+
+
+#include <ciso646> // not
+#include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
+#include <type_traits> // conditional, is_const, remove_const
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/iterators/internal_iterator.hpp>
+
+// #include <nlohmann/detail/iterators/primitive_iterator.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+// forward declare, to be able to friend it later on
+template<typename IteratorType> class iteration_proxy;
+template<typename IteratorType> class iteration_proxy_value;
+
+/*!
+@brief a template for a bidirectional iterator for the @ref basic_json class
+This class implements a both iterators (iterator and const_iterator) for the
+@ref basic_json class.
+@note An iterator is called *initialized* when a pointer to a JSON value has
+      been set (e.g., by a constructor or a copy assignment). If the iterator is
+      default-constructed, it is *uninitialized* and most methods are undefined.
+      **The library uses assertions to detect calls on uninitialized iterators.**
+@requirement The class satisfies the following concept requirements:
+-
+[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
+  The iterator that can be moved can be moved in both directions (i.e.
+  incremented and decremented).
+@since version 1.0.0, simplified in version 2.0.9, change to bidirectional
+       iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
+*/
+template<typename BasicJsonType>
+class iter_impl
+{
+    /// allow basic_json to access private members
+    friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
+    friend BasicJsonType;
+    friend iteration_proxy<iter_impl>;
+    friend iteration_proxy_value<iter_impl>;
+
+    using object_t = typename BasicJsonType::object_t;
+    using array_t = typename BasicJsonType::array_t;
+    // make sure BasicJsonType is basic_json or const basic_json
+    static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
+                  "iter_impl only accepts (const) basic_json");
+
+  public:
+
+    /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
+    /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
+    /// A user-defined iterator should provide publicly accessible typedefs named
+    /// iterator_category, value_type, difference_type, pointer, and reference.
+    /// Note that value_type is required to be non-const, even for constant iterators.
+    using iterator_category = std::bidirectional_iterator_tag;
+
+    /// the type of the values when the iterator is dereferenced
+    using value_type = typename BasicJsonType::value_type;
+    /// a type to represent differences between iterators
+    using difference_type = typename BasicJsonType::difference_type;
+    /// defines a pointer to the type iterated over (value_type)
+    using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
+          typename BasicJsonType::const_pointer,
+          typename BasicJsonType::pointer>::type;
+    /// defines a reference to the type iterated over (value_type)
+    using reference =
+        typename std::conditional<std::is_const<BasicJsonType>::value,
+        typename BasicJsonType::const_reference,
+        typename BasicJsonType::reference>::type;
+
+    /// default constructor
+    iter_impl() = default;
+
+    /*!
+    @brief constructor for a given JSON instance
+    @param[in] object  pointer to a JSON object for this iterator
+    @pre object != nullptr
+    @post The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    explicit iter_impl(pointer object) noexcept : m_object(object)
+    {
+        assert(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                m_it.object_iterator = typename object_t::iterator();
+                break;
+            }
+
+            case value_t::array:
+            {
+                m_it.array_iterator = typename array_t::iterator();
+                break;
+            }
+
+            default:
+            {
+                m_it.primitive_iterator = primitive_iterator_t();
+                break;
+            }
+        }
+    }
+
+    /*!
+    @note The conventional copy constructor and copy assignment are implicitly
+          defined. Combined with the following converting constructor and
+          assignment, they support: (1) copy from iterator to iterator, (2)
+          copy from const iterator to const iterator, and (3) conversion from
+          iterator to const iterator. However conversion from const iterator
+          to iterator is not defined.
+    */
+
+    /*!
+    @brief const copy constructor
+    @param[in] other const iterator to copy from
+    @note This copy constructor had to be defined explicitly to circumvent a bug
+          occurring on msvc v19.0 compiler (VS 2015) debug build. For more
+          information refer to: https://github.com/nlohmann/json/issues/1608
+    */
+    iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
+        : m_object(other.m_object), m_it(other.m_it)
+    {}
+
+    /*!
+    @brief converting assignment
+    @param[in] other const iterator to copy from
+    @return const/non-const iterator
+    @note It is not checked whether @a other is initialized.
+    */
+    iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
+    {
+        m_object = other.m_object;
+        m_it = other.m_it;
+        return *this;
+    }
+
+    /*!
+    @brief converting constructor
+    @param[in] other  non-const iterator to copy from
+    @note It is not checked whether @a other is initialized.
+    */
+    iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
+        : m_object(other.m_object), m_it(other.m_it)
+    {}
+
+    /*!
+    @brief converting assignment
+    @param[in] other  non-const iterator to copy from
+    @return const/non-const iterator
+    @note It is not checked whether @a other is initialized.
+    */
+    iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
+    {
+        m_object = other.m_object;
+        m_it = other.m_it;
+        return *this;
+    }
+
+  private:
+    /*!
+    @brief set the iterator to the first value
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    void set_begin() noexcept
+    {
+        assert(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                m_it.object_iterator = m_object->m_value.object->begin();
+                break;
+            }
+
+            case value_t::array:
+            {
+                m_it.array_iterator = m_object->m_value.array->begin();
+                break;
+            }
+
+            case value_t::null:
+            {
+                // set to end so begin()==end() is true: null is empty
+                m_it.primitive_iterator.set_end();
+                break;
+            }
+
+            default:
+            {
+                m_it.primitive_iterator.set_begin();
+                break;
+            }
+        }
+    }
+
+    /*!
+    @brief set the iterator past the last value
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    void set_end() noexcept
+    {
+        assert(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                m_it.object_iterator = m_object->m_value.object->end();
+                break;
+            }
+
+            case value_t::array:
+            {
+                m_it.array_iterator = m_object->m_value.array->end();
+                break;
+            }
+
+            default:
+            {
+                m_it.primitive_iterator.set_end();
+                break;
+            }
+        }
+    }
+
+  public:
+    /*!
+    @brief return a reference to the value pointed to by the iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    reference operator*() const
+    {
+        assert(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                assert(m_it.object_iterator != m_object->m_value.object->end());
+                return m_it.object_iterator->second;
+            }
+
+            case value_t::array:
+            {
+                assert(m_it.array_iterator != m_object->m_value.array->end());
+                return *m_it.array_iterator;
+            }
+
+            case value_t::null:
+                JSON_THROW(invalid_iterator::create(214, "cannot get value"));
+
+            default:
+            {
+                if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
+                {
+                    return *m_object;
+                }
+
+                JSON_THROW(invalid_iterator::create(214, "cannot get value"));
+            }
+        }
+    }
+
+    /*!
+    @brief dereference the iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    pointer operator->() const
+    {
+        assert(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                assert(m_it.object_iterator != m_object->m_value.object->end());
+                return &(m_it.object_iterator->second);
+            }
+
+            case value_t::array:
+            {
+                assert(m_it.array_iterator != m_object->m_value.array->end());
+                return &*m_it.array_iterator;
+            }
+
+            default:
+            {
+                if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
+                {
+                    return m_object;
+                }
+
+                JSON_THROW(invalid_iterator::create(214, "cannot get value"));
+            }
+        }
+    }
+
+    /*!
+    @brief post-increment (it++)
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl const operator++(int)
+    {
+        auto result = *this;
+        ++(*this);
+        return result;
+    }
+
+    /*!
+    @brief pre-increment (++it)
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl& operator++()
+    {
+        assert(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                std::advance(m_it.object_iterator, 1);
+                break;
+            }
+
+            case value_t::array:
+            {
+                std::advance(m_it.array_iterator, 1);
+                break;
+            }
+
+            default:
+            {
+                ++m_it.primitive_iterator;
+                break;
+            }
+        }
+
+        return *this;
+    }
+
+    /*!
+    @brief post-decrement (it--)
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl const operator--(int)
+    {
+        auto result = *this;
+        --(*this);
+        return result;
+    }
+
+    /*!
+    @brief pre-decrement (--it)
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl& operator--()
+    {
+        assert(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                std::advance(m_it.object_iterator, -1);
+                break;
+            }
+
+            case value_t::array:
+            {
+                std::advance(m_it.array_iterator, -1);
+                break;
+            }
+
+            default:
+            {
+                --m_it.primitive_iterator;
+                break;
+            }
+        }
+
+        return *this;
+    }
+
+    /*!
+    @brief  comparison: equal
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    bool operator==(const iter_impl& other) const
+    {
+        // if objects are not the same, the comparison is undefined
+        if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
+        }
+
+        assert(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+                return (m_it.object_iterator == other.m_it.object_iterator);
+
+            case value_t::array:
+                return (m_it.array_iterator == other.m_it.array_iterator);
+
+            default:
+                return (m_it.primitive_iterator == other.m_it.primitive_iterator);
+        }
+    }
+
+    /*!
+    @brief  comparison: not equal
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    bool operator!=(const iter_impl& other) const
+    {
+        return not operator==(other);
+    }
+
+    /*!
+    @brief  comparison: smaller
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    bool operator<(const iter_impl& other) const
+    {
+        // if objects are not the same, the comparison is undefined
+        if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
+        }
+
+        assert(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+                JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
+
+            case value_t::array:
+                return (m_it.array_iterator < other.m_it.array_iterator);
+
+            default:
+                return (m_it.primitive_iterator < other.m_it.primitive_iterator);
+        }
+    }
+
+    /*!
+    @brief  comparison: less than or equal
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    bool operator<=(const iter_impl& other) const
+    {
+        return not other.operator < (*this);
+    }
+
+    /*!
+    @brief  comparison: greater than
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    bool operator>(const iter_impl& other) const
+    {
+        return not operator<=(other);
+    }
+
+    /*!
+    @brief  comparison: greater than or equal
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    bool operator>=(const iter_impl& other) const
+    {
+        return not operator<(other);
+    }
+
+    /*!
+    @brief  add to iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl& operator+=(difference_type i)
+    {
+        assert(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+                JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
+
+            case value_t::array:
+            {
+                std::advance(m_it.array_iterator, i);
+                break;
+            }
+
+            default:
+            {
+                m_it.primitive_iterator += i;
+                break;
+            }
+        }
+
+        return *this;
+    }
+
+    /*!
+    @brief  subtract from iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl& operator-=(difference_type i)
+    {
+        return operator+=(-i);
+    }
+
+    /*!
+    @brief  add to iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl operator+(difference_type i) const
+    {
+        auto result = *this;
+        result += i;
+        return result;
+    }
+
+    /*!
+    @brief  addition of distance and iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    friend iter_impl operator+(difference_type i, const iter_impl& it)
+    {
+        auto result = it;
+        result += i;
+        return result;
+    }
+
+    /*!
+    @brief  subtract from iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl operator-(difference_type i) const
+    {
+        auto result = *this;
+        result -= i;
+        return result;
+    }
+
+    /*!
+    @brief  return difference
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    difference_type operator-(const iter_impl& other) const
+    {
+        assert(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+                JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
+
+            case value_t::array:
+                return m_it.array_iterator - other.m_it.array_iterator;
+
+            default:
+                return m_it.primitive_iterator - other.m_it.primitive_iterator;
+        }
+    }
+
+    /*!
+    @brief  access to successor
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    reference operator[](difference_type n) const
+    {
+        assert(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+                JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
+
+            case value_t::array:
+                return *std::next(m_it.array_iterator, n);
+
+            case value_t::null:
+                JSON_THROW(invalid_iterator::create(214, "cannot get value"));
+
+            default:
+            {
+                if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
+                {
+                    return *m_object;
+                }
+
+                JSON_THROW(invalid_iterator::create(214, "cannot get value"));
+            }
+        }
+    }
+
+    /*!
+    @brief  return the key of an object iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    const typename object_t::key_type& key() const
+    {
+        assert(m_object != nullptr);
+
+        if (JSON_HEDLEY_LIKELY(m_object->is_object()))
+        {
+            return m_it.object_iterator->first;
+        }
+
+        JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
+    }
+
+    /*!
+    @brief  return the value of an iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    reference value() const
+    {
+        return operator*();
+    }
+
+  private:
+    /// associated JSON instance
+    pointer m_object = nullptr;
+    /// the actual iterator of the associated instance
+    internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
+};
+} // namespace detail
+} // namespace nlohmann
+
+// #include <nlohmann/detail/iterators/iteration_proxy.hpp>
+
+// #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
+
+
+#include <cstddef> // ptrdiff_t
+#include <iterator> // reverse_iterator
+#include <utility> // declval
+
+namespace nlohmann
+{
+namespace detail
+{
+//////////////////////
+// reverse_iterator //
+//////////////////////
+
+/*!
+@brief a template for a reverse iterator class
+
+@tparam Base the base iterator type to reverse. Valid types are @ref
+iterator (to create @ref reverse_iterator) and @ref const_iterator (to
+create @ref const_reverse_iterator).
+
+@requirement The class satisfies the following concept requirements:
+-
+[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
+  The iterator that can be moved can be moved in both directions (i.e.
+  incremented and decremented).
+- [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
+  It is possible to write to the pointed-to element (only if @a Base is
+  @ref iterator).
+
+@since version 1.0.0
+*/
+template<typename Base>
+class json_reverse_iterator : public std::reverse_iterator<Base>
+{
+  public:
+    using difference_type = std::ptrdiff_t;
+    /// shortcut to the reverse iterator adapter
+    using base_iterator = std::reverse_iterator<Base>;
+    /// the reference type for the pointed-to element
+    using reference = typename Base::reference;
+
+    /// create reverse iterator from iterator
+    explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
+        : base_iterator(it) {}
+
+    /// create reverse iterator from base class
+    explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
+
+    /// post-increment (it++)
+    json_reverse_iterator const operator++(int)
+    {
+        return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
+    }
+
+    /// pre-increment (++it)
+    json_reverse_iterator& operator++()
+    {
+        return static_cast<json_reverse_iterator&>(base_iterator::operator++());
+    }
+
+    /// post-decrement (it--)
+    json_reverse_iterator const operator--(int)
+    {
+        return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
+    }
+
+    /// pre-decrement (--it)
+    json_reverse_iterator& operator--()
+    {
+        return static_cast<json_reverse_iterator&>(base_iterator::operator--());
+    }
+
+    /// add to iterator
+    json_reverse_iterator& operator+=(difference_type i)
+    {
+        return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
+    }
+
+    /// add to iterator
+    json_reverse_iterator operator+(difference_type i) const
+    {
+        return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
+    }
+
+    /// subtract from iterator
+    json_reverse_iterator operator-(difference_type i) const
+    {
+        return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
+    }
+
+    /// return difference
+    difference_type operator-(const json_reverse_iterator& other) const
+    {
+        return base_iterator(*this) - base_iterator(other);
+    }
+
+    /// access to successor
+    reference operator[](difference_type n) const
+    {
+        return *(this->operator+(n));
+    }
+
+    /// return the key of an object iterator
+    auto key() const -> decltype(std::declval<Base>().key())
+    {
+        auto it = --this->base();
+        return it.key();
+    }
+
+    /// return the value of an iterator
+    reference value() const
+    {
+        auto it = --this->base();
+        return it.operator * ();
+    }
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/iterators/primitive_iterator.hpp>
+
+// #include <nlohmann/detail/json_pointer.hpp>
+
+
+#include <algorithm> // all_of
+#include <cassert> // assert
+#include <cctype> // isdigit
+#include <numeric> // accumulate
+#include <string> // string
+#include <utility> // move
+#include <vector> // vector
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+template<typename BasicJsonType>
+class json_pointer
+{
+    // allow basic_json to access private members
+    NLOHMANN_BASIC_JSON_TPL_DECLARATION
+    friend class basic_json;
+
+  public:
+    /*!
+    @brief create JSON pointer
+
+    Create a JSON pointer according to the syntax described in
+    [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
+
+    @param[in] s  string representing the JSON pointer; if omitted, the empty
+                  string is assumed which references the whole JSON value
+
+    @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
+                           not begin with a slash (`/`); see example below
+
+    @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
+    not followed by `0` (representing `~`) or `1` (representing `/`); see
+    example below
+
+    @liveexample{The example shows the construction several valid JSON pointers
+    as well as the exceptional behavior.,json_pointer}
+
+    @since version 2.0.0
+    */
+    explicit json_pointer(const std::string& s = "")
+        : reference_tokens(split(s))
+    {}
+
+    /*!
+    @brief return a string representation of the JSON pointer
+
+    @invariant For each JSON pointer `ptr`, it holds:
+    @code {.cpp}
+    ptr == json_pointer(ptr.to_string());
+    @endcode
+
+    @return a string representation of the JSON pointer
+
+    @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
+
+    @since version 2.0.0
+    */
+    std::string to_string() const
+    {
+        return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
+                               std::string{},
+                               [](const std::string & a, const std::string & b)
+        {
+            return a + "/" + escape(b);
+        });
+    }
+
+    /// @copydoc to_string()
+    operator std::string() const
+    {
+        return to_string();
+    }
+
+    /*!
+    @brief append another JSON pointer at the end of this JSON pointer
+
+    @param[in] ptr  JSON pointer to append
+    @return JSON pointer with @a ptr appended
+
+    @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
+
+    @complexity Linear in the length of @a ptr.
+
+    @sa @ref operator/=(std::string) to append a reference token
+    @sa @ref operator/=(std::size_t) to append an array index
+    @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
+
+    @since version 3.6.0
+    */
+    json_pointer& operator/=(const json_pointer& ptr)
+    {
+        reference_tokens.insert(reference_tokens.end(),
+                                ptr.reference_tokens.begin(),
+                                ptr.reference_tokens.end());
+        return *this;
+    }
+
+    /*!
+    @brief append an unescaped reference token at the end of this JSON pointer
+
+    @param[in] token  reference token to append
+    @return JSON pointer with @a token appended without escaping @a token
+
+    @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
+
+    @complexity Amortized constant.
+
+    @sa @ref operator/=(const json_pointer&) to append a JSON pointer
+    @sa @ref operator/=(std::size_t) to append an array index
+    @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator
+
+    @since version 3.6.0
+    */
+    json_pointer& operator/=(std::string token)
+    {
+        push_back(std::move(token));
+        return *this;
+    }
+
+    /*!
+    @brief append an array index at the end of this JSON pointer
+
+    @param[in] array_index  array index to append
+    @return JSON pointer with @a array_index appended
+
+    @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
+
+    @complexity Amortized constant.
+
+    @sa @ref operator/=(const json_pointer&) to append a JSON pointer
+    @sa @ref operator/=(std::string) to append a reference token
+    @sa @ref operator/(const json_pointer&, std::string) for a binary operator
+
+    @since version 3.6.0
+    */
+    json_pointer& operator/=(std::size_t array_index)
+    {
+        return *this /= std::to_string(array_index);
+    }
+
+    /*!
+    @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
+
+    @param[in] lhs  JSON pointer
+    @param[in] rhs  JSON pointer
+    @return a new JSON pointer with @a rhs appended to @a lhs
+
+    @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
+
+    @complexity Linear in the length of @a lhs and @a rhs.
+
+    @sa @ref operator/=(const json_pointer&) to append a JSON pointer
+
+    @since version 3.6.0
+    */
+    friend json_pointer operator/(const json_pointer& lhs,
+                                  const json_pointer& rhs)
+    {
+        return json_pointer(lhs) /= rhs;
+    }
+
+    /*!
+    @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
+
+    @param[in] ptr  JSON pointer
+    @param[in] token  reference token
+    @return a new JSON pointer with unescaped @a token appended to @a ptr
+
+    @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
+
+    @complexity Linear in the length of @a ptr.
+
+    @sa @ref operator/=(std::string) to append a reference token
+
+    @since version 3.6.0
+    */
+    friend json_pointer operator/(const json_pointer& ptr, std::string token)
+    {
+        return json_pointer(ptr) /= std::move(token);
+    }
+
+    /*!
+    @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
+
+    @param[in] ptr  JSON pointer
+    @param[in] array_index  array index
+    @return a new JSON pointer with @a array_index appended to @a ptr
+
+    @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
+
+    @complexity Linear in the length of @a ptr.
+
+    @sa @ref operator/=(std::size_t) to append an array index
+
+    @since version 3.6.0
+    */
+    friend json_pointer operator/(const json_pointer& ptr, std::size_t array_index)
+    {
+        return json_pointer(ptr) /= array_index;
+    }
+
+    /*!
+    @brief returns the parent of this JSON pointer
+
+    @return parent of this JSON pointer; in case this JSON pointer is the root,
+            the root itself is returned
+
+    @complexity Linear in the length of the JSON pointer.
+
+    @liveexample{The example shows the result of `parent_pointer` for different
+    JSON Pointers.,json_pointer__parent_pointer}
+
+    @since version 3.6.0
+    */
+    json_pointer parent_pointer() const
+    {
+        if (empty())
+        {
+            return *this;
+        }
+
+        json_pointer res = *this;
+        res.pop_back();
+        return res;
+    }
+
+    /*!
+    @brief remove last reference token
+
+    @pre not `empty()`
+
+    @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
+
+    @complexity Constant.
+
+    @throw out_of_range.405 if JSON pointer has no parent
+
+    @since version 3.6.0
+    */
+    void pop_back()
+    {
+        if (JSON_HEDLEY_UNLIKELY(empty()))
+        {
+            JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
+        }
+
+        reference_tokens.pop_back();
+    }
+
+    /*!
+    @brief return last reference token
+
+    @pre not `empty()`
+    @return last reference token
+
+    @liveexample{The example shows the usage of `back`.,json_pointer__back}
+
+    @complexity Constant.
+
+    @throw out_of_range.405 if JSON pointer has no parent
+
+    @since version 3.6.0
+    */
+    const std::string& back() const
+    {
+        if (JSON_HEDLEY_UNLIKELY(empty()))
+        {
+            JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
+        }
+
+        return reference_tokens.back();
+    }
+
+    /*!
+    @brief append an unescaped token at the end of the reference pointer
+
+    @param[in] token  token to add
+
+    @complexity Amortized constant.
+
+    @liveexample{The example shows the result of `push_back` for different
+    JSON Pointers.,json_pointer__push_back}
+
+    @since version 3.6.0
+    */
+    void push_back(const std::string& token)
+    {
+        reference_tokens.push_back(token);
+    }
+
+    /// @copydoc push_back(const std::string&)
+    void push_back(std::string&& token)
+    {
+        reference_tokens.push_back(std::move(token));
+    }
+
+    /*!
+    @brief return whether pointer points to the root document
+
+    @return true iff the JSON pointer points to the root document
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+
+    @liveexample{The example shows the result of `empty` for different JSON
+    Pointers.,json_pointer__empty}
+
+    @since version 3.6.0
+    */
+    bool empty() const noexcept
+    {
+        return reference_tokens.empty();
+    }
+
+  private:
+    /*!
+    @param[in] s  reference token to be converted into an array index
+
+    @return integer representation of @a s
+
+    @throw out_of_range.404 if string @a s could not be converted to an integer
+    */
+    static int array_index(const std::string& s)
+    {
+        std::size_t processed_chars = 0;
+        const int res = std::stoi(s, &processed_chars);
+
+        // check if the string was completely read
+        if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
+        {
+            JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
+        }
+
+        return res;
+    }
+
+    json_pointer top() const
+    {
+        if (JSON_HEDLEY_UNLIKELY(empty()))
+        {
+            JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
+        }
+
+        json_pointer result = *this;
+        result.reference_tokens = {reference_tokens[0]};
+        return result;
+    }
+
+    /*!
+    @brief create and return a reference to the pointed to value
+
+    @complexity Linear in the number of reference tokens.
+
+    @throw parse_error.109 if array index is not a number
+    @throw type_error.313 if value cannot be unflattened
+    */
+    BasicJsonType& get_and_create(BasicJsonType& j) const
+    {
+        using size_type = typename BasicJsonType::size_type;
+        auto result = &j;
+
+        // in case no reference tokens exist, return a reference to the JSON value
+        // j which will be overwritten by a primitive value
+        for (const auto& reference_token : reference_tokens)
+        {
+            switch (result->type())
+            {
+                case detail::value_t::null:
+                {
+                    if (reference_token == "0")
+                    {
+                        // start a new array if reference token is 0
+                        result = &result->operator[](0);
+                    }
+                    else
+                    {
+                        // start a new object otherwise
+                        result = &result->operator[](reference_token);
+                    }
+                    break;
+                }
+
+                case detail::value_t::object:
+                {
+                    // create an entry in the object
+                    result = &result->operator[](reference_token);
+                    break;
+                }
+
+                case detail::value_t::array:
+                {
+                    // create an entry in the array
+                    JSON_TRY
+                    {
+                        result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
+                    }
+                    JSON_CATCH(std::invalid_argument&)
+                    {
+                        JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
+                    }
+                    break;
+                }
+
+                /*
+                The following code is only reached if there exists a reference
+                token _and_ the current value is primitive. In this case, we have
+                an error situation, because primitive values may only occur as
+                single value; that is, with an empty list of reference tokens.
+                */
+                default:
+                    JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
+            }
+        }
+
+        return *result;
+    }
+
+    /*!
+    @brief return a reference to the pointed to value
+
+    @note This version does not throw if a value is not present, but tries to
+          create nested values instead. For instance, calling this function
+          with pointer `"/this/that"` on a null value is equivalent to calling
+          `operator[]("this").operator[]("that")` on that value, effectively
+          changing the null value to an object.
+
+    @param[in] ptr  a JSON value
+
+    @return reference to the JSON value pointed to by the JSON pointer
+
+    @complexity Linear in the length of the JSON pointer.
+
+    @throw parse_error.106   if an array index begins with '0'
+    @throw parse_error.109   if an array index was not a number
+    @throw out_of_range.404  if the JSON pointer can not be resolved
+    */
+    BasicJsonType& get_unchecked(BasicJsonType* ptr) const
+    {
+        using size_type = typename BasicJsonType::size_type;
+        for (const auto& reference_token : reference_tokens)
+        {
+            // convert null values to arrays or objects before continuing
+            if (ptr->is_null())
+            {
+                // check if reference token is a number
+                const bool nums =
+                    std::all_of(reference_token.begin(), reference_token.end(),
+                                [](const unsigned char x)
+                {
+                    return std::isdigit(x);
+                });
+
+                // change value to array for numbers or "-" or to object otherwise
+                *ptr = (nums or reference_token == "-")
+                       ? detail::value_t::array
+                       : detail::value_t::object;
+            }
+
+            switch (ptr->type())
+            {
+                case detail::value_t::object:
+                {
+                    // use unchecked object access
+                    ptr = &ptr->operator[](reference_token);
+                    break;
+                }
+
+                case detail::value_t::array:
+                {
+                    // error condition (cf. RFC 6901, Sect. 4)
+                    if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
+                    {
+                        JSON_THROW(detail::parse_error::create(106, 0,
+                                                               "array index '" + reference_token +
+                                                               "' must not begin with '0'"));
+                    }
+
+                    if (reference_token == "-")
+                    {
+                        // explicitly treat "-" as index beyond the end
+                        ptr = &ptr->operator[](ptr->m_value.array->size());
+                    }
+                    else
+                    {
+                        // convert array index to number; unchecked access
+                        JSON_TRY
+                        {
+                            ptr = &ptr->operator[](
+                                static_cast<size_type>(array_index(reference_token)));
+                        }
+                        JSON_CATCH(std::invalid_argument&)
+                        {
+                            JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
+                        }
+                    }
+                    break;
+                }
+
+                default:
+                    JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
+            }
+        }
+
+        return *ptr;
+    }
+
+    /*!
+    @throw parse_error.106   if an array index begins with '0'
+    @throw parse_error.109   if an array index was not a number
+    @throw out_of_range.402  if the array index '-' is used
+    @throw out_of_range.404  if the JSON pointer can not be resolved
+    */
+    BasicJsonType& get_checked(BasicJsonType* ptr) const
+    {
+        using size_type = typename BasicJsonType::size_type;
+        for (const auto& reference_token : reference_tokens)
+        {
+            switch (ptr->type())
+            {
+                case detail::value_t::object:
+                {
+                    // note: at performs range check
+                    ptr = &ptr->at(reference_token);
+                    break;
+                }
+
+                case detail::value_t::array:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
+                    {
+                        // "-" always fails the range check
+                        JSON_THROW(detail::out_of_range::create(402,
+                                                                "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
+                                                                ") is out of range"));
+                    }
+
+                    // error condition (cf. RFC 6901, Sect. 4)
+                    if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
+                    {
+                        JSON_THROW(detail::parse_error::create(106, 0,
+                                                               "array index '" + reference_token +
+                                                               "' must not begin with '0'"));
+                    }
+
+                    // note: at performs range check
+                    JSON_TRY
+                    {
+                        ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
+                    }
+                    JSON_CATCH(std::invalid_argument&)
+                    {
+                        JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
+                    }
+                    break;
+                }
+
+                default:
+                    JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
+            }
+        }
+
+        return *ptr;
+    }
+
+    /*!
+    @brief return a const reference to the pointed to value
+
+    @param[in] ptr  a JSON value
+
+    @return const reference to the JSON value pointed to by the JSON
+    pointer
+
+    @throw parse_error.106   if an array index begins with '0'
+    @throw parse_error.109   if an array index was not a number
+    @throw out_of_range.402  if the array index '-' is used
+    @throw out_of_range.404  if the JSON pointer can not be resolved
+    */
+    const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
+    {
+        using size_type = typename BasicJsonType::size_type;
+        for (const auto& reference_token : reference_tokens)
+        {
+            switch (ptr->type())
+            {
+                case detail::value_t::object:
+                {
+                    // use unchecked object access
+                    ptr = &ptr->operator[](reference_token);
+                    break;
+                }
+
+                case detail::value_t::array:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
+                    {
+                        // "-" cannot be used for const access
+                        JSON_THROW(detail::out_of_range::create(402,
+                                                                "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
+                                                                ") is out of range"));
+                    }
+
+                    // error condition (cf. RFC 6901, Sect. 4)
+                    if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
+                    {
+                        JSON_THROW(detail::parse_error::create(106, 0,
+                                                               "array index '" + reference_token +
+                                                               "' must not begin with '0'"));
+                    }
+
+                    // use unchecked array access
+                    JSON_TRY
+                    {
+                        ptr = &ptr->operator[](
+                            static_cast<size_type>(array_index(reference_token)));
+                    }
+                    JSON_CATCH(std::invalid_argument&)
+                    {
+                        JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
+                    }
+                    break;
+                }
+
+                default:
+                    JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
+            }
+        }
+
+        return *ptr;
+    }
+
+    /*!
+    @throw parse_error.106   if an array index begins with '0'
+    @throw parse_error.109   if an array index was not a number
+    @throw out_of_range.402  if the array index '-' is used
+    @throw out_of_range.404  if the JSON pointer can not be resolved
+    */
+    const BasicJsonType& get_checked(const BasicJsonType* ptr) const
+    {
+        using size_type = typename BasicJsonType::size_type;
+        for (const auto& reference_token : reference_tokens)
+        {
+            switch (ptr->type())
+            {
+                case detail::value_t::object:
+                {
+                    // note: at performs range check
+                    ptr = &ptr->at(reference_token);
+                    break;
+                }
+
+                case detail::value_t::array:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
+                    {
+                        // "-" always fails the range check
+                        JSON_THROW(detail::out_of_range::create(402,
+                                                                "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
+                                                                ") is out of range"));
+                    }
+
+                    // error condition (cf. RFC 6901, Sect. 4)
+                    if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
+                    {
+                        JSON_THROW(detail::parse_error::create(106, 0,
+                                                               "array index '" + reference_token +
+                                                               "' must not begin with '0'"));
+                    }
+
+                    // note: at performs range check
+                    JSON_TRY
+                    {
+                        ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
+                    }
+                    JSON_CATCH(std::invalid_argument&)
+                    {
+                        JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
+                    }
+                    break;
+                }
+
+                default:
+                    JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
+            }
+        }
+
+        return *ptr;
+    }
+
+    /*!
+    @throw parse_error.106   if an array index begins with '0'
+    @throw parse_error.109   if an array index was not a number
+    */
+    bool contains(const BasicJsonType* ptr) const
+    {
+        using size_type = typename BasicJsonType::size_type;
+        for (const auto& reference_token : reference_tokens)
+        {
+            switch (ptr->type())
+            {
+                case detail::value_t::object:
+                {
+                    if (not ptr->contains(reference_token))
+                    {
+                        // we did not find the key in the object
+                        return false;
+                    }
+
+                    ptr = &ptr->operator[](reference_token);
+                    break;
+                }
+
+                case detail::value_t::array:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
+                    {
+                        // "-" always fails the range check
+                        return false;
+                    }
+
+                    // error condition (cf. RFC 6901, Sect. 4)
+                    if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
+                    {
+                        JSON_THROW(detail::parse_error::create(106, 0,
+                                                               "array index '" + reference_token +
+                                                               "' must not begin with '0'"));
+                    }
+
+                    JSON_TRY
+                    {
+                        const auto idx = static_cast<size_type>(array_index(reference_token));
+                        if (idx >= ptr->size())
+                        {
+                            // index out of range
+                            return false;
+                        }
+
+                        ptr = &ptr->operator[](idx);
+                        break;
+                    }
+                    JSON_CATCH(std::invalid_argument&)
+                    {
+                        JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
+                    }
+                    break;
+                }
+
+                default:
+                {
+                    // we do not expect primitive values if there is still a
+                    // reference token to process
+                    return false;
+                }
+            }
+        }
+
+        // no reference token left means we found a primitive value
+        return true;
+    }
+
+    /*!
+    @brief split the string input to reference tokens
+
+    @note This function is only called by the json_pointer constructor.
+          All exceptions below are documented there.
+
+    @throw parse_error.107  if the pointer is not empty or begins with '/'
+    @throw parse_error.108  if character '~' is not followed by '0' or '1'
+    */
+    static std::vector<std::string> split(const std::string& reference_string)
+    {
+        std::vector<std::string> result;
+
+        // special case: empty reference string -> no reference tokens
+        if (reference_string.empty())
+        {
+            return result;
+        }
+
+        // check if nonempty reference string begins with slash
+        if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
+        {
+            JSON_THROW(detail::parse_error::create(107, 1,
+                                                   "JSON pointer must be empty or begin with '/' - was: '" +
+                                                   reference_string + "'"));
+        }
+
+        // extract the reference tokens:
+        // - slash: position of the last read slash (or end of string)
+        // - start: position after the previous slash
+        for (
+            // search for the first slash after the first character
+            std::size_t slash = reference_string.find_first_of('/', 1),
+            // set the beginning of the first reference token
+            start = 1;
+            // we can stop if start == 0 (if slash == std::string::npos)
+            start != 0;
+            // set the beginning of the next reference token
+            // (will eventually be 0 if slash == std::string::npos)
+            start = (slash == std::string::npos) ? 0 : slash + 1,
+            // find next slash
+            slash = reference_string.find_first_of('/', start))
+        {
+            // use the text between the beginning of the reference token
+            // (start) and the last slash (slash).
+            auto reference_token = reference_string.substr(start, slash - start);
+
+            // check reference tokens are properly escaped
+            for (std::size_t pos = reference_token.find_first_of('~');
+                    pos != std::string::npos;
+                    pos = reference_token.find_first_of('~', pos + 1))
+            {
+                assert(reference_token[pos] == '~');
+
+                // ~ must be followed by 0 or 1
+                if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 or
+                                         (reference_token[pos + 1] != '0' and
+                                          reference_token[pos + 1] != '1')))
+                {
+                    JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
+                }
+            }
+
+            // finally, store the reference token
+            unescape(reference_token);
+            result.push_back(reference_token);
+        }
+
+        return result;
+    }
+
+    /*!
+    @brief replace all occurrences of a substring by another string
+
+    @param[in,out] s  the string to manipulate; changed so that all
+                   occurrences of @a f are replaced with @a t
+    @param[in]     f  the substring to replace with @a t
+    @param[in]     t  the string to replace @a f
+
+    @pre The search string @a f must not be empty. **This precondition is
+    enforced with an assertion.**
+
+    @since version 2.0.0
+    */
+    static void replace_substring(std::string& s, const std::string& f,
+                                  const std::string& t)
+    {
+        assert(not f.empty());
+        for (auto pos = s.find(f);                // find first occurrence of f
+                pos != std::string::npos;         // make sure f was found
+                s.replace(pos, f.size(), t),      // replace with t, and
+                pos = s.find(f, pos + t.size()))  // find next occurrence of f
+        {}
+    }
+
+    /// escape "~" to "~0" and "/" to "~1"
+    static std::string escape(std::string s)
+    {
+        replace_substring(s, "~", "~0");
+        replace_substring(s, "/", "~1");
+        return s;
+    }
+
+    /// unescape "~1" to tilde and "~0" to slash (order is important!)
+    static void unescape(std::string& s)
+    {
+        replace_substring(s, "~1", "/");
+        replace_substring(s, "~0", "~");
+    }
+
+    /*!
+    @param[in] reference_string  the reference string to the current value
+    @param[in] value             the value to consider
+    @param[in,out] result        the result object to insert values to
+
+    @note Empty objects or arrays are flattened to `null`.
+    */
+    static void flatten(const std::string& reference_string,
+                        const BasicJsonType& value,
+                        BasicJsonType& result)
+    {
+        switch (value.type())
+        {
+            case detail::value_t::array:
+            {
+                if (value.m_value.array->empty())
+                {
+                    // flatten empty array as null
+                    result[reference_string] = nullptr;
+                }
+                else
+                {
+                    // iterate array and use index as reference string
+                    for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
+                    {
+                        flatten(reference_string + "/" + std::to_string(i),
+                                value.m_value.array->operator[](i), result);
+                    }
+                }
+                break;
+            }
+
+            case detail::value_t::object:
+            {
+                if (value.m_value.object->empty())
+                {
+                    // flatten empty object as null
+                    result[reference_string] = nullptr;
+                }
+                else
+                {
+                    // iterate object and use keys as reference string
+                    for (const auto& element : *value.m_value.object)
+                    {
+                        flatten(reference_string + "/" + escape(element.first), element.second, result);
+                    }
+                }
+                break;
+            }
+
+            default:
+            {
+                // add primitive value with its reference string
+                result[reference_string] = value;
+                break;
+            }
+        }
+    }
+
+    /*!
+    @param[in] value  flattened JSON
+
+    @return unflattened JSON
+
+    @throw parse_error.109 if array index is not a number
+    @throw type_error.314  if value is not an object
+    @throw type_error.315  if object values are not primitive
+    @throw type_error.313  if value cannot be unflattened
+    */
+    static BasicJsonType
+    unflatten(const BasicJsonType& value)
+    {
+        if (JSON_HEDLEY_UNLIKELY(not value.is_object()))
+        {
+            JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
+        }
+
+        BasicJsonType result;
+
+        // iterate the JSON object values
+        for (const auto& element : *value.m_value.object)
+        {
+            if (JSON_HEDLEY_UNLIKELY(not element.second.is_primitive()))
+            {
+                JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
+            }
+
+            // assign value to reference pointed to by JSON pointer; Note that if
+            // the JSON pointer is "" (i.e., points to the whole value), function
+            // get_and_create returns a reference to result itself. An assignment
+            // will then create a primitive value.
+            json_pointer(element.first).get_and_create(result) = element.second;
+        }
+
+        return result;
+    }
+
+    /*!
+    @brief compares two JSON pointers for equality
+
+    @param[in] lhs  JSON pointer to compare
+    @param[in] rhs  JSON pointer to compare
+    @return whether @a lhs is equal to @a rhs
+
+    @complexity Linear in the length of the JSON pointer
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+    */
+    friend bool operator==(json_pointer const& lhs,
+                           json_pointer const& rhs) noexcept
+    {
+        return lhs.reference_tokens == rhs.reference_tokens;
+    }
+
+    /*!
+    @brief compares two JSON pointers for inequality
+
+    @param[in] lhs  JSON pointer to compare
+    @param[in] rhs  JSON pointer to compare
+    @return whether @a lhs is not equal @a rhs
+
+    @complexity Linear in the length of the JSON pointer
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+    */
+    friend bool operator!=(json_pointer const& lhs,
+                           json_pointer const& rhs) noexcept
+    {
+        return not (lhs == rhs);
+    }
+
+    /// the reference tokens
+    std::vector<std::string> reference_tokens;
+};
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/json_ref.hpp>
+
+
+#include <initializer_list>
+#include <utility>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+template<typename BasicJsonType>
+class json_ref
+{
+  public:
+    using value_type = BasicJsonType;
+
+    json_ref(value_type&& value)
+        : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
+    {}
+
+    json_ref(const value_type& value)
+        : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
+    {}
+
+    json_ref(std::initializer_list<json_ref> init)
+        : owned_value(init), value_ref(&owned_value), is_rvalue(true)
+    {}
+
+    template <
+        class... Args,
+        enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
+    json_ref(Args && ... args)
+        : owned_value(std::forward<Args>(args)...), value_ref(&owned_value),
+          is_rvalue(true) {}
+
+    // class should be movable only
+    json_ref(json_ref&&) = default;
+    json_ref(const json_ref&) = delete;
+    json_ref& operator=(const json_ref&) = delete;
+    json_ref& operator=(json_ref&&) = delete;
+    ~json_ref() = default;
+
+    value_type moved_or_copied() const
+    {
+        if (is_rvalue)
+        {
+            return std::move(*value_ref);
+        }
+        return *value_ref;
+    }
+
+    value_type const& operator*() const
+    {
+        return *static_cast<value_type const*>(value_ref);
+    }
+
+    value_type const* operator->() const
+    {
+        return static_cast<value_type const*>(value_ref);
+    }
+
+  private:
+    mutable value_type owned_value = nullptr;
+    value_type* value_ref = nullptr;
+    const bool is_rvalue;
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/output/binary_writer.hpp>
+
+
+#include <algorithm> // reverse
+#include <array> // array
+#include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
+#include <cstring> // memcpy
+#include <limits> // numeric_limits
+#include <string> // string
+
+// #include <nlohmann/detail/input/binary_reader.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/output/output_adapters.hpp>
+
+
+#include <algorithm> // copy
+#include <cstddef> // size_t
+#include <ios> // streamsize
+#include <iterator> // back_inserter
+#include <memory> // shared_ptr, make_shared
+#include <ostream> // basic_ostream
+#include <string> // basic_string
+#include <vector> // vector
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+/// abstract output adapter interface
+template<typename CharType> struct output_adapter_protocol
+{
+    virtual void write_character(CharType c) = 0;
+    virtual void write_characters(const CharType* s, std::size_t length) = 0;
+    virtual ~output_adapter_protocol() = default;
+};
+
+/// a type to simplify interfaces
+template<typename CharType>
+using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
+
+/// output adapter for byte vectors
+template<typename CharType>
+class output_vector_adapter : public output_adapter_protocol<CharType>
+{
+  public:
+    explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
+        : v(vec)
+    {}
+
+    void write_character(CharType c) override
+    {
+        v.push_back(c);
+    }
+
+    JSON_HEDLEY_NON_NULL(2)
+    void write_characters(const CharType* s, std::size_t length) override
+    {
+        std::copy(s, s + length, std::back_inserter(v));
+    }
+
+  private:
+    std::vector<CharType>& v;
+};
+
+/// output adapter for output streams
+template<typename CharType>
+class output_stream_adapter : public output_adapter_protocol<CharType>
+{
+  public:
+    explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
+        : stream(s)
+    {}
+
+    void write_character(CharType c) override
+    {
+        stream.put(c);
+    }
+
+    JSON_HEDLEY_NON_NULL(2)
+    void write_characters(const CharType* s, std::size_t length) override
+    {
+        stream.write(s, static_cast<std::streamsize>(length));
+    }
+
+  private:
+    std::basic_ostream<CharType>& stream;
+};
+
+/// output adapter for basic_string
+template<typename CharType, typename StringType = std::basic_string<CharType>>
+class output_string_adapter : public output_adapter_protocol<CharType>
+{
+  public:
+    explicit output_string_adapter(StringType& s) noexcept
+        : str(s)
+    {}
+
+    void write_character(CharType c) override
+    {
+        str.push_back(c);
+    }
+
+    JSON_HEDLEY_NON_NULL(2)
+    void write_characters(const CharType* s, std::size_t length) override
+    {
+        str.append(s, length);
+    }
+
+  private:
+    StringType& str;
+};
+
+template<typename CharType, typename StringType = std::basic_string<CharType>>
+class output_adapter
+{
+  public:
+    output_adapter(std::vector<CharType>& vec)
+        : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
+
+    output_adapter(std::basic_ostream<CharType>& s)
+        : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
+
+    output_adapter(StringType& s)
+        : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
+
+    operator output_adapter_t<CharType>()
+    {
+        return oa;
+    }
+
+  private:
+    output_adapter_t<CharType> oa = nullptr;
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+
+namespace nlohmann
+{
+namespace detail
+{
+///////////////////
+// binary writer //
+///////////////////
+
+/*!
+@brief serialization to CBOR and MessagePack values
+*/
+template<typename BasicJsonType, typename CharType>
+class binary_writer
+{
+    using string_t = typename BasicJsonType::string_t;
+
+  public:
+    /*!
+    @brief create a binary writer
+
+    @param[in] adapter  output adapter to write to
+    */
+    explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
+    {
+        assert(oa);
+    }
+
+    /*!
+    @param[in] j  JSON value to serialize
+    @pre       j.type() == value_t::object
+    */
+    void write_bson(const BasicJsonType& j)
+    {
+        switch (j.type())
+        {
+            case value_t::object:
+            {
+                write_bson_object(*j.m_value.object);
+                break;
+            }
+
+            default:
+            {
+                JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name())));
+            }
+        }
+    }
+
+    /*!
+    @param[in] j  JSON value to serialize
+    */
+    void write_cbor(const BasicJsonType& j)
+    {
+        switch (j.type())
+        {
+            case value_t::null:
+            {
+                oa->write_character(to_char_type(0xF6));
+                break;
+            }
+
+            case value_t::boolean:
+            {
+                oa->write_character(j.m_value.boolean
+                                    ? to_char_type(0xF5)
+                                    : to_char_type(0xF4));
+                break;
+            }
+
+            case value_t::number_integer:
+            {
+                if (j.m_value.number_integer >= 0)
+                {
+                    // CBOR does not differentiate between positive signed
+                    // integers and unsigned integers. Therefore, we used the
+                    // code from the value_t::number_unsigned case here.
+                    if (j.m_value.number_integer <= 0x17)
+                    {
+                        write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
+                    {
+                        oa->write_character(to_char_type(0x18));
+                        write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
+                    {
+                        oa->write_character(to_char_type(0x19));
+                        write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
+                    {
+                        oa->write_character(to_char_type(0x1A));
+                        write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
+                    }
+                    else
+                    {
+                        oa->write_character(to_char_type(0x1B));
+                        write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
+                    }
+                }
+                else
+                {
+                    // The conversions below encode the sign in the first
+                    // byte, and the value is converted to a positive number.
+                    const auto positive_number = -1 - j.m_value.number_integer;
+                    if (j.m_value.number_integer >= -24)
+                    {
+                        write_number(static_cast<std::uint8_t>(0x20 + positive_number));
+                    }
+                    else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
+                    {
+                        oa->write_character(to_char_type(0x38));
+                        write_number(static_cast<std::uint8_t>(positive_number));
+                    }
+                    else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
+                    {
+                        oa->write_character(to_char_type(0x39));
+                        write_number(static_cast<std::uint16_t>(positive_number));
+                    }
+                    else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
+                    {
+                        oa->write_character(to_char_type(0x3A));
+                        write_number(static_cast<std::uint32_t>(positive_number));
+                    }
+                    else
+                    {
+                        oa->write_character(to_char_type(0x3B));
+                        write_number(static_cast<std::uint64_t>(positive_number));
+                    }
+                }
+                break;
+            }
+
+            case value_t::number_unsigned:
+            {
+                if (j.m_value.number_unsigned <= 0x17)
+                {
+                    write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x18));
+                    write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x19));
+                    write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x1A));
+                    write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
+                }
+                else
+                {
+                    oa->write_character(to_char_type(0x1B));
+                    write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
+                }
+                break;
+            }
+
+            case value_t::number_float:
+            {
+                oa->write_character(get_cbor_float_prefix(j.m_value.number_float));
+                write_number(j.m_value.number_float);
+                break;
+            }
+
+            case value_t::string:
+            {
+                // step 1: write control byte and the string length
+                const auto N = j.m_value.string->size();
+                if (N <= 0x17)
+                {
+                    write_number(static_cast<std::uint8_t>(0x60 + N));
+                }
+                else if (N <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x78));
+                    write_number(static_cast<std::uint8_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x79));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x7A));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+                // LCOV_EXCL_START
+                else if (N <= (std::numeric_limits<std::uint64_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x7B));
+                    write_number(static_cast<std::uint64_t>(N));
+                }
+                // LCOV_EXCL_STOP
+
+                // step 2: write the string
+                oa->write_characters(
+                    reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
+                    j.m_value.string->size());
+                break;
+            }
+
+            case value_t::array:
+            {
+                // step 1: write control byte and the array size
+                const auto N = j.m_value.array->size();
+                if (N <= 0x17)
+                {
+                    write_number(static_cast<std::uint8_t>(0x80 + N));
+                }
+                else if (N <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x98));
+                    write_number(static_cast<std::uint8_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x99));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x9A));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+                // LCOV_EXCL_START
+                else if (N <= (std::numeric_limits<std::uint64_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x9B));
+                    write_number(static_cast<std::uint64_t>(N));
+                }
+                // LCOV_EXCL_STOP
+
+                // step 2: write each element
+                for (const auto& el : *j.m_value.array)
+                {
+                    write_cbor(el);
+                }
+                break;
+            }
+
+            case value_t::object:
+            {
+                // step 1: write control byte and the object size
+                const auto N = j.m_value.object->size();
+                if (N <= 0x17)
+                {
+                    write_number(static_cast<std::uint8_t>(0xA0 + N));
+                }
+                else if (N <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    oa->write_character(to_char_type(0xB8));
+                    write_number(static_cast<std::uint8_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    oa->write_character(to_char_type(0xB9));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    oa->write_character(to_char_type(0xBA));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+                // LCOV_EXCL_START
+                else if (N <= (std::numeric_limits<std::uint64_t>::max)())
+                {
+                    oa->write_character(to_char_type(0xBB));
+                    write_number(static_cast<std::uint64_t>(N));
+                }
+                // LCOV_EXCL_STOP
+
+                // step 2: write each element
+                for (const auto& el : *j.m_value.object)
+                {
+                    write_cbor(el.first);
+                    write_cbor(el.second);
+                }
+                break;
+            }
+
+            default:
+                break;
+        }
+    }
+
+    /*!
+    @param[in] j  JSON value to serialize
+    */
+    void write_msgpack(const BasicJsonType& j)
+    {
+        switch (j.type())
+        {
+            case value_t::null: // nil
+            {
+                oa->write_character(to_char_type(0xC0));
+                break;
+            }
+
+            case value_t::boolean: // true and false
+            {
+                oa->write_character(j.m_value.boolean
+                                    ? to_char_type(0xC3)
+                                    : to_char_type(0xC2));
+                break;
+            }
+
+            case value_t::number_integer:
+            {
+                if (j.m_value.number_integer >= 0)
+                {
+                    // MessagePack does not differentiate between positive
+                    // signed integers and unsigned integers. Therefore, we used
+                    // the code from the value_t::number_unsigned case here.
+                    if (j.m_value.number_unsigned < 128)
+                    {
+                        // positive fixnum
+                        write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
+                    {
+                        // uint 8
+                        oa->write_character(to_char_type(0xCC));
+                        write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
+                    {
+                        // uint 16
+                        oa->write_character(to_char_type(0xCD));
+                        write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
+                    {
+                        // uint 32
+                        oa->write_character(to_char_type(0xCE));
+                        write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
+                    {
+                        // uint 64
+                        oa->write_character(to_char_type(0xCF));
+                        write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
+                    }
+                }
+                else
+                {
+                    if (j.m_value.number_integer >= -32)
+                    {
+                        // negative fixnum
+                        write_number(static_cast<std::int8_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() and
+                             j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
+                    {
+                        // int 8
+                        oa->write_character(to_char_type(0xD0));
+                        write_number(static_cast<std::int8_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() and
+                             j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
+                    {
+                        // int 16
+                        oa->write_character(to_char_type(0xD1));
+                        write_number(static_cast<std::int16_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() and
+                             j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
+                    {
+                        // int 32
+                        oa->write_character(to_char_type(0xD2));
+                        write_number(static_cast<std::int32_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() and
+                             j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
+                    {
+                        // int 64
+                        oa->write_character(to_char_type(0xD3));
+                        write_number(static_cast<std::int64_t>(j.m_value.number_integer));
+                    }
+                }
+                break;
+            }
+
+            case value_t::number_unsigned:
+            {
+                if (j.m_value.number_unsigned < 128)
+                {
+                    // positive fixnum
+                    write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    // uint 8
+                    oa->write_character(to_char_type(0xCC));
+                    write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    // uint 16
+                    oa->write_character(to_char_type(0xCD));
+                    write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    // uint 32
+                    oa->write_character(to_char_type(0xCE));
+                    write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
+                {
+                    // uint 64
+                    oa->write_character(to_char_type(0xCF));
+                    write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
+                }
+                break;
+            }
+
+            case value_t::number_float:
+            {
+                oa->write_character(get_msgpack_float_prefix(j.m_value.number_float));
+                write_number(j.m_value.number_float);
+                break;
+            }
+
+            case value_t::string:
+            {
+                // step 1: write control byte and the string length
+                const auto N = j.m_value.string->size();
+                if (N <= 31)
+                {
+                    // fixstr
+                    write_number(static_cast<std::uint8_t>(0xA0 | N));
+                }
+                else if (N <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    // str 8
+                    oa->write_character(to_char_type(0xD9));
+                    write_number(static_cast<std::uint8_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    // str 16
+                    oa->write_character(to_char_type(0xDA));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    // str 32
+                    oa->write_character(to_char_type(0xDB));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+
+                // step 2: write the string
+                oa->write_characters(
+                    reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
+                    j.m_value.string->size());
+                break;
+            }
+
+            case value_t::array:
+            {
+                // step 1: write control byte and the array size
+                const auto N = j.m_value.array->size();
+                if (N <= 15)
+                {
+                    // fixarray
+                    write_number(static_cast<std::uint8_t>(0x90 | N));
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    // array 16
+                    oa->write_character(to_char_type(0xDC));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    // array 32
+                    oa->write_character(to_char_type(0xDD));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+
+                // step 2: write each element
+                for (const auto& el : *j.m_value.array)
+                {
+                    write_msgpack(el);
+                }
+                break;
+            }
+
+            case value_t::object:
+            {
+                // step 1: write control byte and the object size
+                const auto N = j.m_value.object->size();
+                if (N <= 15)
+                {
+                    // fixmap
+                    write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    // map 16
+                    oa->write_character(to_char_type(0xDE));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    // map 32
+                    oa->write_character(to_char_type(0xDF));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+
+                // step 2: write each element
+                for (const auto& el : *j.m_value.object)
+                {
+                    write_msgpack(el.first);
+                    write_msgpack(el.second);
+                }
+                break;
+            }
+
+            default:
+                break;
+        }
+    }
+
+    /*!
+    @param[in] j  JSON value to serialize
+    @param[in] use_count   whether to use '#' prefixes (optimized format)
+    @param[in] use_type    whether to use '$' prefixes (optimized format)
+    @param[in] add_prefix  whether prefixes need to be used for this value
+    */
+    void write_ubjson(const BasicJsonType& j, const bool use_count,
+                      const bool use_type, const bool add_prefix = true)
+    {
+        switch (j.type())
+        {
+            case value_t::null:
+            {
+                if (add_prefix)
+                {
+                    oa->write_character(to_char_type('Z'));
+                }
+                break;
+            }
+
+            case value_t::boolean:
+            {
+                if (add_prefix)
+                {
+                    oa->write_character(j.m_value.boolean
+                                        ? to_char_type('T')
+                                        : to_char_type('F'));
+                }
+                break;
+            }
+
+            case value_t::number_integer:
+            {
+                write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
+                break;
+            }
+
+            case value_t::number_unsigned:
+            {
+                write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
+                break;
+            }
+
+            case value_t::number_float:
+            {
+                write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
+                break;
+            }
+
+            case value_t::string:
+            {
+                if (add_prefix)
+                {
+                    oa->write_character(to_char_type('S'));
+                }
+                write_number_with_ubjson_prefix(j.m_value.string->size(), true);
+                oa->write_characters(
+                    reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
+                    j.m_value.string->size());
+                break;
+            }
+
+            case value_t::array:
+            {
+                if (add_prefix)
+                {
+                    oa->write_character(to_char_type('['));
+                }
+
+                bool prefix_required = true;
+                if (use_type and not j.m_value.array->empty())
+                {
+                    assert(use_count);
+                    const CharType first_prefix = ubjson_prefix(j.front());
+                    const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
+                                                         [this, first_prefix](const BasicJsonType & v)
+                    {
+                        return ubjson_prefix(v) == first_prefix;
+                    });
+
+                    if (same_prefix)
+                    {
+                        prefix_required = false;
+                        oa->write_character(to_char_type('$'));
+                        oa->write_character(first_prefix);
+                    }
+                }
+
+                if (use_count)
+                {
+                    oa->write_character(to_char_type('#'));
+                    write_number_with_ubjson_prefix(j.m_value.array->size(), true);
+                }
+
+                for (const auto& el : *j.m_value.array)
+                {
+                    write_ubjson(el, use_count, use_type, prefix_required);
+                }
+
+                if (not use_count)
+                {
+                    oa->write_character(to_char_type(']'));
+                }
+
+                break;
+            }
+
+            case value_t::object:
+            {
+                if (add_prefix)
+                {
+                    oa->write_character(to_char_type('{'));
+                }
+
+                bool prefix_required = true;
+                if (use_type and not j.m_value.object->empty())
+                {
+                    assert(use_count);
+                    const CharType first_prefix = ubjson_prefix(j.front());
+                    const bool same_prefix = std::all_of(j.begin(), j.end(),
+                                                         [this, first_prefix](const BasicJsonType & v)
+                    {
+                        return ubjson_prefix(v) == first_prefix;
+                    });
+
+                    if (same_prefix)
+                    {
+                        prefix_required = false;
+                        oa->write_character(to_char_type('$'));
+                        oa->write_character(first_prefix);
+                    }
+                }
+
+                if (use_count)
+                {
+                    oa->write_character(to_char_type('#'));
+                    write_number_with_ubjson_prefix(j.m_value.object->size(), true);
+                }
+
+                for (const auto& el : *j.m_value.object)
+                {
+                    write_number_with_ubjson_prefix(el.first.size(), true);
+                    oa->write_characters(
+                        reinterpret_cast<const CharType*>(el.first.c_str()),
+                        el.first.size());
+                    write_ubjson(el.second, use_count, use_type, prefix_required);
+                }
+
+                if (not use_count)
+                {
+                    oa->write_character(to_char_type('}'));
+                }
+
+                break;
+            }
+
+            default:
+                break;
+        }
+    }
+
+  private:
+    //////////
+    // BSON //
+    //////////
+
+    /*!
+    @return The size of a BSON document entry header, including the id marker
+            and the entry name size (and its null-terminator).
+    */
+    static std::size_t calc_bson_entry_header_size(const string_t& name)
+    {
+        const auto it = name.find(static_cast<typename string_t::value_type>(0));
+        if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
+        {
+            JSON_THROW(out_of_range::create(409,
+                                            "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")"));
+        }
+
+        return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
+    }
+
+    /*!
+    @brief Writes the given @a element_type and @a name to the output adapter
+    */
+    void write_bson_entry_header(const string_t& name,
+                                 const std::uint8_t element_type)
+    {
+        oa->write_character(to_char_type(element_type)); // boolean
+        oa->write_characters(
+            reinterpret_cast<const CharType*>(name.c_str()),
+            name.size() + 1u);
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and boolean value @a value
+    */
+    void write_bson_boolean(const string_t& name,
+                            const bool value)
+    {
+        write_bson_entry_header(name, 0x08);
+        oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and double value @a value
+    */
+    void write_bson_double(const string_t& name,
+                           const double value)
+    {
+        write_bson_entry_header(name, 0x01);
+        write_number<double, true>(value);
+    }
+
+    /*!
+    @return The size of the BSON-encoded string in @a value
+    */
+    static std::size_t calc_bson_string_size(const string_t& value)
+    {
+        return sizeof(std::int32_t) + value.size() + 1ul;
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and string value @a value
+    */
+    void write_bson_string(const string_t& name,
+                           const string_t& value)
+    {
+        write_bson_entry_header(name, 0x02);
+
+        write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
+        oa->write_characters(
+            reinterpret_cast<const CharType*>(value.c_str()),
+            value.size() + 1);
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and null value
+    */
+    void write_bson_null(const string_t& name)
+    {
+        write_bson_entry_header(name, 0x0A);
+    }
+
+    /*!
+    @return The size of the BSON-encoded integer @a value
+    */
+    static std::size_t calc_bson_integer_size(const std::int64_t value)
+    {
+        return (std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)()
+               ? sizeof(std::int32_t)
+               : sizeof(std::int64_t);
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and integer @a value
+    */
+    void write_bson_integer(const string_t& name,
+                            const std::int64_t value)
+    {
+        if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)())
+        {
+            write_bson_entry_header(name, 0x10); // int32
+            write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
+        }
+        else
+        {
+            write_bson_entry_header(name, 0x12); // int64
+            write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
+        }
+    }
+
+    /*!
+    @return The size of the BSON-encoded unsigned integer in @a j
+    */
+    static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
+    {
+        return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
+               ? sizeof(std::int32_t)
+               : sizeof(std::int64_t);
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and unsigned @a value
+    */
+    void write_bson_unsigned(const string_t& name,
+                             const std::uint64_t value)
+    {
+        if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
+        {
+            write_bson_entry_header(name, 0x10 /* int32 */);
+            write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
+        }
+        else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
+        {
+            write_bson_entry_header(name, 0x12 /* int64 */);
+            write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
+        }
+        else
+        {
+            JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64"));
+        }
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and object @a value
+    */
+    void write_bson_object_entry(const string_t& name,
+                                 const typename BasicJsonType::object_t& value)
+    {
+        write_bson_entry_header(name, 0x03); // object
+        write_bson_object(value);
+    }
+
+    /*!
+    @return The size of the BSON-encoded array @a value
+    */
+    static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
+    {
+        std::size_t array_index = 0ul;
+
+        const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), std::size_t(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el)
+        {
+            return result + calc_bson_element_size(std::to_string(array_index++), el);
+        });
+
+        return sizeof(std::int32_t) + embedded_document_size + 1ul;
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and array @a value
+    */
+    void write_bson_array(const string_t& name,
+                          const typename BasicJsonType::array_t& value)
+    {
+        write_bson_entry_header(name, 0x04); // array
+        write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
+
+        std::size_t array_index = 0ul;
+
+        for (const auto& el : value)
+        {
+            write_bson_element(std::to_string(array_index++), el);
+        }
+
+        oa->write_character(to_char_type(0x00));
+    }
+
+    /*!
+    @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
+    @return The calculated size for the BSON document entry for @a j with the given @a name.
+    */
+    static std::size_t calc_bson_element_size(const string_t& name,
+            const BasicJsonType& j)
+    {
+        const auto header_size = calc_bson_entry_header_size(name);
+        switch (j.type())
+        {
+            case value_t::object:
+                return header_size + calc_bson_object_size(*j.m_value.object);
+
+            case value_t::array:
+                return header_size + calc_bson_array_size(*j.m_value.array);
+
+            case value_t::boolean:
+                return header_size + 1ul;
+
+            case value_t::number_float:
+                return header_size + 8ul;
+
+            case value_t::number_integer:
+                return header_size + calc_bson_integer_size(j.m_value.number_integer);
+
+            case value_t::number_unsigned:
+                return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
+
+            case value_t::string:
+                return header_size + calc_bson_string_size(*j.m_value.string);
+
+            case value_t::null:
+                return header_size + 0ul;
+
+            // LCOV_EXCL_START
+            default:
+                assert(false);
+                return 0ul;
+                // LCOV_EXCL_STOP
+        }
+    }
+
+    /*!
+    @brief Serializes the JSON value @a j to BSON and associates it with the
+           key @a name.
+    @param name The name to associate with the JSON entity @a j within the
+                current BSON document
+    @return The size of the BSON entry
+    */
+    void write_bson_element(const string_t& name,
+                            const BasicJsonType& j)
+    {
+        switch (j.type())
+        {
+            case value_t::object:
+                return write_bson_object_entry(name, *j.m_value.object);
+
+            case value_t::array:
+                return write_bson_array(name, *j.m_value.array);
+
+            case value_t::boolean:
+                return write_bson_boolean(name, j.m_value.boolean);
+
+            case value_t::number_float:
+                return write_bson_double(name, j.m_value.number_float);
+
+            case value_t::number_integer:
+                return write_bson_integer(name, j.m_value.number_integer);
+
+            case value_t::number_unsigned:
+                return write_bson_unsigned(name, j.m_value.number_unsigned);
+
+            case value_t::string:
+                return write_bson_string(name, *j.m_value.string);
+
+            case value_t::null:
+                return write_bson_null(name);
+
+            // LCOV_EXCL_START
+            default:
+                assert(false);
+                return;
+                // LCOV_EXCL_STOP
+        }
+    }
+
+    /*!
+    @brief Calculates the size of the BSON serialization of the given
+           JSON-object @a j.
+    @param[in] j  JSON value to serialize
+    @pre       j.type() == value_t::object
+    */
+    static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
+    {
+        std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0),
+                                    [](size_t result, const typename BasicJsonType::object_t::value_type & el)
+        {
+            return result += calc_bson_element_size(el.first, el.second);
+        });
+
+        return sizeof(std::int32_t) + document_size + 1ul;
+    }
+
+    /*!
+    @param[in] j  JSON value to serialize
+    @pre       j.type() == value_t::object
+    */
+    void write_bson_object(const typename BasicJsonType::object_t& value)
+    {
+        write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
+
+        for (const auto& el : value)
+        {
+            write_bson_element(el.first, el.second);
+        }
+
+        oa->write_character(to_char_type(0x00));
+    }
+
+    //////////
+    // CBOR //
+    //////////
+
+    static constexpr CharType get_cbor_float_prefix(float /*unused*/)
+    {
+        return to_char_type(0xFA);  // Single-Precision Float
+    }
+
+    static constexpr CharType get_cbor_float_prefix(double /*unused*/)
+    {
+        return to_char_type(0xFB);  // Double-Precision Float
+    }
+
+    /////////////
+    // MsgPack //
+    /////////////
+
+    static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
+    {
+        return to_char_type(0xCA);  // float 32
+    }
+
+    static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
+    {
+        return to_char_type(0xCB);  // float 64
+    }
+
+    ////////////
+    // UBJSON //
+    ////////////
+
+    // UBJSON: write number (floating point)
+    template<typename NumberType, typename std::enable_if<
+                 std::is_floating_point<NumberType>::value, int>::type = 0>
+    void write_number_with_ubjson_prefix(const NumberType n,
+                                         const bool add_prefix)
+    {
+        if (add_prefix)
+        {
+            oa->write_character(get_ubjson_float_prefix(n));
+        }
+        write_number(n);
+    }
+
+    // UBJSON: write number (unsigned integer)
+    template<typename NumberType, typename std::enable_if<
+                 std::is_unsigned<NumberType>::value, int>::type = 0>
+    void write_number_with_ubjson_prefix(const NumberType n,
+                                         const bool add_prefix)
+    {
+        if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('i'));  // int8
+            }
+            write_number(static_cast<std::uint8_t>(n));
+        }
+        else if (n <= (std::numeric_limits<std::uint8_t>::max)())
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('U'));  // uint8
+            }
+            write_number(static_cast<std::uint8_t>(n));
+        }
+        else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('I'));  // int16
+            }
+            write_number(static_cast<std::int16_t>(n));
+        }
+        else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('l'));  // int32
+            }
+            write_number(static_cast<std::int32_t>(n));
+        }
+        else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('L'));  // int64
+            }
+            write_number(static_cast<std::int64_t>(n));
+        }
+        else
+        {
+            JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
+        }
+    }
+
+    // UBJSON: write number (signed integer)
+    template<typename NumberType, typename std::enable_if<
+                 std::is_signed<NumberType>::value and
+                 not std::is_floating_point<NumberType>::value, int>::type = 0>
+    void write_number_with_ubjson_prefix(const NumberType n,
+                                         const bool add_prefix)
+    {
+        if ((std::numeric_limits<std::int8_t>::min)() <= n and n <= (std::numeric_limits<std::int8_t>::max)())
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('i'));  // int8
+            }
+            write_number(static_cast<std::int8_t>(n));
+        }
+        else if (static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::min)()) <= n and n <= static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::max)()))
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('U'));  // uint8
+            }
+            write_number(static_cast<std::uint8_t>(n));
+        }
+        else if ((std::numeric_limits<std::int16_t>::min)() <= n and n <= (std::numeric_limits<std::int16_t>::max)())
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('I'));  // int16
+            }
+            write_number(static_cast<std::int16_t>(n));
+        }
+        else if ((std::numeric_limits<std::int32_t>::min)() <= n and n <= (std::numeric_limits<std::int32_t>::max)())
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('l'));  // int32
+            }
+            write_number(static_cast<std::int32_t>(n));
+        }
+        else if ((std::numeric_limits<std::int64_t>::min)() <= n and n <= (std::numeric_limits<std::int64_t>::max)())
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('L'));  // int64
+            }
+            write_number(static_cast<std::int64_t>(n));
+        }
+        // LCOV_EXCL_START
+        else
+        {
+            JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
+        }
+        // LCOV_EXCL_STOP
+    }
+
+    /*!
+    @brief determine the type prefix of container values
+
+    @note This function does not need to be 100% accurate when it comes to
+          integer limits. In case a number exceeds the limits of int64_t,
+          this will be detected by a later call to function
+          write_number_with_ubjson_prefix. Therefore, we return 'L' for any
+          value that does not fit the previous limits.
+    */
+    CharType ubjson_prefix(const BasicJsonType& j) const noexcept
+    {
+        switch (j.type())
+        {
+            case value_t::null:
+                return 'Z';
+
+            case value_t::boolean:
+                return j.m_value.boolean ? 'T' : 'F';
+
+            case value_t::number_integer:
+            {
+                if ((std::numeric_limits<std::int8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
+                {
+                    return 'i';
+                }
+                if ((std::numeric_limits<std::uint8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    return 'U';
+                }
+                if ((std::numeric_limits<std::int16_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
+                {
+                    return 'I';
+                }
+                if ((std::numeric_limits<std::int32_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
+                {
+                    return 'l';
+                }
+                // no check and assume int64_t (see note above)
+                return 'L';
+            }
+
+            case value_t::number_unsigned:
+            {
+                if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
+                {
+                    return 'i';
+                }
+                if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
+                {
+                    return 'U';
+                }
+                if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
+                {
+                    return 'I';
+                }
+                if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
+                {
+                    return 'l';
+                }
+                // no check and assume int64_t (see note above)
+                return 'L';
+            }
+
+            case value_t::number_float:
+                return get_ubjson_float_prefix(j.m_value.number_float);
+
+            case value_t::string:
+                return 'S';
+
+            case value_t::array:
+                return '[';
+
+            case value_t::object:
+                return '{';
+
+            default:  // discarded values
+                return 'N';
+        }
+    }
+
+    static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
+    {
+        return 'd';  // float 32
+    }
+
+    static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
+    {
+        return 'D';  // float 64
+    }
+
+    ///////////////////////
+    // Utility functions //
+    ///////////////////////
+
+    /*
+    @brief write a number to output input
+    @param[in] n number of type @a NumberType
+    @tparam NumberType the type of the number
+    @tparam OutputIsLittleEndian Set to true if output data is
+                                 required to be little endian
+
+    @note This function needs to respect the system's endianess, because bytes
+          in CBOR, MessagePack, and UBJSON are stored in network order (big
+          endian) and therefore need reordering on little endian systems.
+    */
+    template<typename NumberType, bool OutputIsLittleEndian = false>
+    void write_number(const NumberType n)
+    {
+        // step 1: write number to array of length NumberType
+        std::array<CharType, sizeof(NumberType)> vec;
+        std::memcpy(vec.data(), &n, sizeof(NumberType));
+
+        // step 2: write array to output (with possible reordering)
+        if (is_little_endian != OutputIsLittleEndian)
+        {
+            // reverse byte order prior to conversion if necessary
+            std::reverse(vec.begin(), vec.end());
+        }
+
+        oa->write_characters(vec.data(), sizeof(NumberType));
+    }
+
+  public:
+    // The following to_char_type functions are implement the conversion
+    // between uint8_t and CharType. In case CharType is not unsigned,
+    // such a conversion is required to allow values greater than 128.
+    // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
+    template < typename C = CharType,
+               enable_if_t < std::is_signed<C>::value and std::is_signed<char>::value > * = nullptr >
+    static constexpr CharType to_char_type(std::uint8_t x) noexcept
+    {
+        return *reinterpret_cast<char*>(&x);
+    }
+
+    template < typename C = CharType,
+               enable_if_t < std::is_signed<C>::value and std::is_unsigned<char>::value > * = nullptr >
+    static CharType to_char_type(std::uint8_t x) noexcept
+    {
+        static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
+        static_assert(std::is_pod<CharType>::value, "CharType must be POD");
+        CharType result;
+        std::memcpy(&result, &x, sizeof(x));
+        return result;
+    }
+
+    template<typename C = CharType,
+             enable_if_t<std::is_unsigned<C>::value>* = nullptr>
+    static constexpr CharType to_char_type(std::uint8_t x) noexcept
+    {
+        return x;
+    }
+
+    template < typename InputCharType, typename C = CharType,
+               enable_if_t <
+                   std::is_signed<C>::value and
+                   std::is_signed<char>::value and
+                   std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
+                   > * = nullptr >
+    static constexpr CharType to_char_type(InputCharType x) noexcept
+    {
+        return x;
+    }
+
+  private:
+    /// whether we can assume little endianess
+    const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
+
+    /// the output
+    output_adapter_t<CharType> oa = nullptr;
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/output/output_adapters.hpp>
+
+// #include <nlohmann/detail/output/serializer.hpp>
+
+
+#include <algorithm> // reverse, remove, fill, find, none_of
+#include <array> // array
+#include <cassert> // assert
+#include <ciso646> // and, or
+#include <clocale> // localeconv, lconv
+#include <cmath> // labs, isfinite, isnan, signbit
+#include <cstddef> // size_t, ptrdiff_t
+#include <cstdint> // uint8_t
+#include <cstdio> // snprintf
+#include <limits> // numeric_limits
+#include <string> // string
+#include <type_traits> // is_same
+#include <utility> // move
+
+// #include <nlohmann/detail/conversions/to_chars.hpp>
+
+
+#include <array> // array
+#include <cassert> // assert
+#include <ciso646> // or, and, not
+#include <cmath>   // signbit, isfinite
+#include <cstdint> // intN_t, uintN_t
+#include <cstring> // memcpy, memmove
+#include <limits> // numeric_limits
+#include <type_traits> // conditional
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+
+/*!
+@brief implements the Grisu2 algorithm for binary to decimal floating-point
+conversion.
+
+This implementation is a slightly modified version of the reference
+implementation which may be obtained from
+http://florian.loitsch.com/publications (bench.tar.gz).
+
+The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
+
+For a detailed description of the algorithm see:
+
+[1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
+    Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
+    Language Design and Implementation, PLDI 2010
+[2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
+    Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
+    Design and Implementation, PLDI 1996
+*/
+namespace dtoa_impl
+{
+
+template <typename Target, typename Source>
+Target reinterpret_bits(const Source source)
+{
+    static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
+
+    Target target;
+    std::memcpy(&target, &source, sizeof(Source));
+    return target;
+}
+
+struct diyfp // f * 2^e
+{
+    static constexpr int kPrecision = 64; // = q
+
+    std::uint64_t f = 0;
+    int e = 0;
+
+    constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
+
+    /*!
+    @brief returns x - y
+    @pre x.e == y.e and x.f >= y.f
+    */
+    static diyfp sub(const diyfp& x, const diyfp& y) noexcept
+    {
+        assert(x.e == y.e);
+        assert(x.f >= y.f);
+
+        return {x.f - y.f, x.e};
+    }
+
+    /*!
+    @brief returns x * y
+    @note The result is rounded. (Only the upper q bits are returned.)
+    */
+    static diyfp mul(const diyfp& x, const diyfp& y) noexcept
+    {
+        static_assert(kPrecision == 64, "internal error");
+
+        // Computes:
+        //  f = round((x.f * y.f) / 2^q)
+        //  e = x.e + y.e + q
+
+        // Emulate the 64-bit * 64-bit multiplication:
+        //
+        // p = u * v
+        //   = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
+        //   = (u_lo v_lo         ) + 2^32 ((u_lo v_hi         ) + (u_hi v_lo         )) + 2^64 (u_hi v_hi         )
+        //   = (p0                ) + 2^32 ((p1                ) + (p2                )) + 2^64 (p3                )
+        //   = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3                )
+        //   = (p0_lo             ) + 2^32 (p0_hi + p1_lo + p2_lo                      ) + 2^64 (p1_hi + p2_hi + p3)
+        //   = (p0_lo             ) + 2^32 (Q                                          ) + 2^64 (H                 )
+        //   = (p0_lo             ) + 2^32 (Q_lo + 2^32 Q_hi                           ) + 2^64 (H                 )
+        //
+        // (Since Q might be larger than 2^32 - 1)
+        //
+        //   = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
+        //
+        // (Q_hi + H does not overflow a 64-bit int)
+        //
+        //   = p_lo + 2^64 p_hi
+
+        const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
+        const std::uint64_t u_hi = x.f >> 32u;
+        const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
+        const std::uint64_t v_hi = y.f >> 32u;
+
+        const std::uint64_t p0 = u_lo * v_lo;
+        const std::uint64_t p1 = u_lo * v_hi;
+        const std::uint64_t p2 = u_hi * v_lo;
+        const std::uint64_t p3 = u_hi * v_hi;
+
+        const std::uint64_t p0_hi = p0 >> 32u;
+        const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
+        const std::uint64_t p1_hi = p1 >> 32u;
+        const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
+        const std::uint64_t p2_hi = p2 >> 32u;
+
+        std::uint64_t Q = p0_hi + p1_lo + p2_lo;
+
+        // The full product might now be computed as
+        //
+        // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
+        // p_lo = p0_lo + (Q << 32)
+        //
+        // But in this particular case here, the full p_lo is not required.
+        // Effectively we only need to add the highest bit in p_lo to p_hi (and
+        // Q_hi + 1 does not overflow).
+
+        Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
+
+        const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
+
+        return {h, x.e + y.e + 64};
+    }
+
+    /*!
+    @brief normalize x such that the significand is >= 2^(q-1)
+    @pre x.f != 0
+    */
+    static diyfp normalize(diyfp x) noexcept
+    {
+        assert(x.f != 0);
+
+        while ((x.f >> 63u) == 0)
+        {
+            x.f <<= 1u;
+            x.e--;
+        }
+
+        return x;
+    }
+
+    /*!
+    @brief normalize x such that the result has the exponent E
+    @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
+    */
+    static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
+    {
+        const int delta = x.e - target_exponent;
+
+        assert(delta >= 0);
+        assert(((x.f << delta) >> delta) == x.f);
+
+        return {x.f << delta, target_exponent};
+    }
+};
+
+struct boundaries
+{
+    diyfp w;
+    diyfp minus;
+    diyfp plus;
+};
+
+/*!
+Compute the (normalized) diyfp representing the input number 'value' and its
+boundaries.
+
+@pre value must be finite and positive
+*/
+template <typename FloatType>
+boundaries compute_boundaries(FloatType value)
+{
+    assert(std::isfinite(value));
+    assert(value > 0);
+
+    // Convert the IEEE representation into a diyfp.
+    //
+    // If v is denormal:
+    //      value = 0.F * 2^(1 - bias) = (          F) * 2^(1 - bias - (p-1))
+    // If v is normalized:
+    //      value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
+
+    static_assert(std::numeric_limits<FloatType>::is_iec559,
+                  "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
+
+    constexpr int      kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
+    constexpr int      kBias      = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
+    constexpr int      kMinExp    = 1 - kBias;
+    constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
+
+    using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
+
+    const std::uint64_t bits = reinterpret_bits<bits_type>(value);
+    const std::uint64_t E = bits >> (kPrecision - 1);
+    const std::uint64_t F = bits & (kHiddenBit - 1);
+
+    const bool is_denormal = E == 0;
+    const diyfp v = is_denormal
+                    ? diyfp(F, kMinExp)
+                    : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
+
+    // Compute the boundaries m- and m+ of the floating-point value
+    // v = f * 2^e.
+    //
+    // Determine v- and v+, the floating-point predecessor and successor if v,
+    // respectively.
+    //
+    //      v- = v - 2^e        if f != 2^(p-1) or e == e_min                (A)
+    //         = v - 2^(e-1)    if f == 2^(p-1) and e > e_min                (B)
+    //
+    //      v+ = v + 2^e
+    //
+    // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
+    // between m- and m+ round to v, regardless of how the input rounding
+    // algorithm breaks ties.
+    //
+    //      ---+-------------+-------------+-------------+-------------+---  (A)
+    //         v-            m-            v             m+            v+
+    //
+    //      -----------------+------+------+-------------+-------------+---  (B)
+    //                       v-     m-     v             m+            v+
+
+    const bool lower_boundary_is_closer = F == 0 and E > 1;
+    const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
+    const diyfp m_minus = lower_boundary_is_closer
+                          ? diyfp(4 * v.f - 1, v.e - 2)  // (B)
+                          : diyfp(2 * v.f - 1, v.e - 1); // (A)
+
+    // Determine the normalized w+ = m+.
+    const diyfp w_plus = diyfp::normalize(m_plus);
+
+    // Determine w- = m- such that e_(w-) = e_(w+).
+    const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
+
+    return {diyfp::normalize(v), w_minus, w_plus};
+}
+
+// Given normalized diyfp w, Grisu needs to find a (normalized) cached
+// power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
+// within a certain range [alpha, gamma] (Definition 3.2 from [1])
+//
+//      alpha <= e = e_c + e_w + q <= gamma
+//
+// or
+//
+//      f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
+//                          <= f_c * f_w * 2^gamma
+//
+// Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
+//
+//      2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
+//
+// or
+//
+//      2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
+//
+// The choice of (alpha,gamma) determines the size of the table and the form of
+// the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
+// in practice:
+//
+// The idea is to cut the number c * w = f * 2^e into two parts, which can be
+// processed independently: An integral part p1, and a fractional part p2:
+//
+//      f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
+//              = (f div 2^-e) + (f mod 2^-e) * 2^e
+//              = p1 + p2 * 2^e
+//
+// The conversion of p1 into decimal form requires a series of divisions and
+// modulos by (a power of) 10. These operations are faster for 32-bit than for
+// 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
+// achieved by choosing
+//
+//      -e >= 32   or   e <= -32 := gamma
+//
+// In order to convert the fractional part
+//
+//      p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
+//
+// into decimal form, the fraction is repeatedly multiplied by 10 and the digits
+// d[-i] are extracted in order:
+//
+//      (10 * p2) div 2^-e = d[-1]
+//      (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
+//
+// The multiplication by 10 must not overflow. It is sufficient to choose
+//
+//      10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
+//
+// Since p2 = f mod 2^-e < 2^-e,
+//
+//      -e <= 60   or   e >= -60 := alpha
+
+constexpr int kAlpha = -60;
+constexpr int kGamma = -32;
+
+struct cached_power // c = f * 2^e ~= 10^k
+{
+    std::uint64_t f;
+    int e;
+    int k;
+};
+
+/*!
+For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
+power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
+satisfies (Definition 3.2 from [1])
+
+     alpha <= e_c + e + q <= gamma.
+*/
+inline cached_power get_cached_power_for_binary_exponent(int e)
+{
+    // Now
+    //
+    //      alpha <= e_c + e + q <= gamma                                    (1)
+    //      ==> f_c * 2^alpha <= c * 2^e * 2^q
+    //
+    // and since the c's are normalized, 2^(q-1) <= f_c,
+    //
+    //      ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
+    //      ==> 2^(alpha - e - 1) <= c
+    //
+    // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
+    //
+    //      k = ceil( log_10( 2^(alpha - e - 1) ) )
+    //        = ceil( (alpha - e - 1) * log_10(2) )
+    //
+    // From the paper:
+    // "In theory the result of the procedure could be wrong since c is rounded,
+    //  and the computation itself is approximated [...]. In practice, however,
+    //  this simple function is sufficient."
+    //
+    // For IEEE double precision floating-point numbers converted into
+    // normalized diyfp's w = f * 2^e, with q = 64,
+    //
+    //      e >= -1022      (min IEEE exponent)
+    //           -52        (p - 1)
+    //           -52        (p - 1, possibly normalize denormal IEEE numbers)
+    //           -11        (normalize the diyfp)
+    //         = -1137
+    //
+    // and
+    //
+    //      e <= +1023      (max IEEE exponent)
+    //           -52        (p - 1)
+    //           -11        (normalize the diyfp)
+    //         = 960
+    //
+    // This binary exponent range [-1137,960] results in a decimal exponent
+    // range [-307,324]. One does not need to store a cached power for each
+    // k in this range. For each such k it suffices to find a cached power
+    // such that the exponent of the product lies in [alpha,gamma].
+    // This implies that the difference of the decimal exponents of adjacent
+    // table entries must be less than or equal to
+    //
+    //      floor( (gamma - alpha) * log_10(2) ) = 8.
+    //
+    // (A smaller distance gamma-alpha would require a larger table.)
+
+    // NB:
+    // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
+
+    constexpr int kCachedPowersMinDecExp = -300;
+    constexpr int kCachedPowersDecStep = 8;
+
+    static constexpr std::array<cached_power, 79> kCachedPowers =
+    {
+        {
+            { 0xAB70FE17C79AC6CA, -1060, -300 },
+            { 0xFF77B1FCBEBCDC4F, -1034, -292 },
+            { 0xBE5691EF416BD60C, -1007, -284 },
+            { 0x8DD01FAD907FFC3C,  -980, -276 },
+            { 0xD3515C2831559A83,  -954, -268 },
+            { 0x9D71AC8FADA6C9B5,  -927, -260 },
+            { 0xEA9C227723EE8BCB,  -901, -252 },
+            { 0xAECC49914078536D,  -874, -244 },
+            { 0x823C12795DB6CE57,  -847, -236 },
+            { 0xC21094364DFB5637,  -821, -228 },
+            { 0x9096EA6F3848984F,  -794, -220 },
+            { 0xD77485CB25823AC7,  -768, -212 },
+            { 0xA086CFCD97BF97F4,  -741, -204 },
+            { 0xEF340A98172AACE5,  -715, -196 },
+            { 0xB23867FB2A35B28E,  -688, -188 },
+            { 0x84C8D4DFD2C63F3B,  -661, -180 },
+            { 0xC5DD44271AD3CDBA,  -635, -172 },
+            { 0x936B9FCEBB25C996,  -608, -164 },
+            { 0xDBAC6C247D62A584,  -582, -156 },
+            { 0xA3AB66580D5FDAF6,  -555, -148 },
+            { 0xF3E2F893DEC3F126,  -529, -140 },
+            { 0xB5B5ADA8AAFF80B8,  -502, -132 },
+            { 0x87625F056C7C4A8B,  -475, -124 },
+            { 0xC9BCFF6034C13053,  -449, -116 },
+            { 0x964E858C91BA2655,  -422, -108 },
+            { 0xDFF9772470297EBD,  -396, -100 },
+            { 0xA6DFBD9FB8E5B88F,  -369,  -92 },
+            { 0xF8A95FCF88747D94,  -343,  -84 },
+            { 0xB94470938FA89BCF,  -316,  -76 },
+            { 0x8A08F0F8BF0F156B,  -289,  -68 },
+            { 0xCDB02555653131B6,  -263,  -60 },
+            { 0x993FE2C6D07B7FAC,  -236,  -52 },
+            { 0xE45C10C42A2B3B06,  -210,  -44 },
+            { 0xAA242499697392D3,  -183,  -36 },
+            { 0xFD87B5F28300CA0E,  -157,  -28 },
+            { 0xBCE5086492111AEB,  -130,  -20 },
+            { 0x8CBCCC096F5088CC,  -103,  -12 },
+            { 0xD1B71758E219652C,   -77,   -4 },
+            { 0x9C40000000000000,   -50,    4 },
+            { 0xE8D4A51000000000,   -24,   12 },
+            { 0xAD78EBC5AC620000,     3,   20 },
+            { 0x813F3978F8940984,    30,   28 },
+            { 0xC097CE7BC90715B3,    56,   36 },
+            { 0x8F7E32CE7BEA5C70,    83,   44 },
+            { 0xD5D238A4ABE98068,   109,   52 },
+            { 0x9F4F2726179A2245,   136,   60 },
+            { 0xED63A231D4C4FB27,   162,   68 },
+            { 0xB0DE65388CC8ADA8,   189,   76 },
+            { 0x83C7088E1AAB65DB,   216,   84 },
+            { 0xC45D1DF942711D9A,   242,   92 },
+            { 0x924D692CA61BE758,   269,  100 },
+            { 0xDA01EE641A708DEA,   295,  108 },
+            { 0xA26DA3999AEF774A,   322,  116 },
+            { 0xF209787BB47D6B85,   348,  124 },
+            { 0xB454E4A179DD1877,   375,  132 },
+            { 0x865B86925B9BC5C2,   402,  140 },
+            { 0xC83553C5C8965D3D,   428,  148 },
+            { 0x952AB45CFA97A0B3,   455,  156 },
+            { 0xDE469FBD99A05FE3,   481,  164 },
+            { 0xA59BC234DB398C25,   508,  172 },
+            { 0xF6C69A72A3989F5C,   534,  180 },
+            { 0xB7DCBF5354E9BECE,   561,  188 },
+            { 0x88FCF317F22241E2,   588,  196 },
+            { 0xCC20CE9BD35C78A5,   614,  204 },
+            { 0x98165AF37B2153DF,   641,  212 },
+            { 0xE2A0B5DC971F303A,   667,  220 },
+            { 0xA8D9D1535CE3B396,   694,  228 },
+            { 0xFB9B7CD9A4A7443C,   720,  236 },
+            { 0xBB764C4CA7A44410,   747,  244 },
+            { 0x8BAB8EEFB6409C1A,   774,  252 },
+            { 0xD01FEF10A657842C,   800,  260 },
+            { 0x9B10A4E5E9913129,   827,  268 },
+            { 0xE7109BFBA19C0C9D,   853,  276 },
+            { 0xAC2820D9623BF429,   880,  284 },
+            { 0x80444B5E7AA7CF85,   907,  292 },
+            { 0xBF21E44003ACDD2D,   933,  300 },
+            { 0x8E679C2F5E44FF8F,   960,  308 },
+            { 0xD433179D9C8CB841,   986,  316 },
+            { 0x9E19DB92B4E31BA9,  1013,  324 },
+        }
+    };
+
+    // This computation gives exactly the same results for k as
+    //      k = ceil((kAlpha - e - 1) * 0.30102999566398114)
+    // for |e| <= 1500, but doesn't require floating-point operations.
+    // NB: log_10(2) ~= 78913 / 2^18
+    assert(e >= -1500);
+    assert(e <=  1500);
+    const int f = kAlpha - e - 1;
+    const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
+
+    const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
+    assert(index >= 0);
+    assert(static_cast<std::size_t>(index) < kCachedPowers.size());
+
+    const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
+    assert(kAlpha <= cached.e + e + 64);
+    assert(kGamma >= cached.e + e + 64);
+
+    return cached;
+}
+
+/*!
+For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
+For n == 0, returns 1 and sets pow10 := 1.
+*/
+inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
+{
+    // LCOV_EXCL_START
+    if (n >= 1000000000)
+    {
+        pow10 = 1000000000;
+        return 10;
+    }
+    // LCOV_EXCL_STOP
+    else if (n >= 100000000)
+    {
+        pow10 = 100000000;
+        return  9;
+    }
+    else if (n >= 10000000)
+    {
+        pow10 = 10000000;
+        return  8;
+    }
+    else if (n >= 1000000)
+    {
+        pow10 = 1000000;
+        return  7;
+    }
+    else if (n >= 100000)
+    {
+        pow10 = 100000;
+        return  6;
+    }
+    else if (n >= 10000)
+    {
+        pow10 = 10000;
+        return  5;
+    }
+    else if (n >= 1000)
+    {
+        pow10 = 1000;
+        return  4;
+    }
+    else if (n >= 100)
+    {
+        pow10 = 100;
+        return  3;
+    }
+    else if (n >= 10)
+    {
+        pow10 = 10;
+        return  2;
+    }
+    else
+    {
+        pow10 = 1;
+        return 1;
+    }
+}
+
+inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
+                         std::uint64_t rest, std::uint64_t ten_k)
+{
+    assert(len >= 1);
+    assert(dist <= delta);
+    assert(rest <= delta);
+    assert(ten_k > 0);
+
+    //               <--------------------------- delta ---->
+    //                                  <---- dist --------->
+    // --------------[------------------+-------------------]--------------
+    //               M-                 w                   M+
+    //
+    //                                  ten_k
+    //                                <------>
+    //                                       <---- rest ---->
+    // --------------[------------------+----+--------------]--------------
+    //                                  w    V
+    //                                       = buf * 10^k
+    //
+    // ten_k represents a unit-in-the-last-place in the decimal representation
+    // stored in buf.
+    // Decrement buf by ten_k while this takes buf closer to w.
+
+    // The tests are written in this order to avoid overflow in unsigned
+    // integer arithmetic.
+
+    while (rest < dist
+            and delta - rest >= ten_k
+            and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
+    {
+        assert(buf[len - 1] != '0');
+        buf[len - 1]--;
+        rest += ten_k;
+    }
+}
+
+/*!
+Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
+M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
+*/
+inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
+                             diyfp M_minus, diyfp w, diyfp M_plus)
+{
+    static_assert(kAlpha >= -60, "internal error");
+    static_assert(kGamma <= -32, "internal error");
+
+    // Generates the digits (and the exponent) of a decimal floating-point
+    // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
+    // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
+    //
+    //               <--------------------------- delta ---->
+    //                                  <---- dist --------->
+    // --------------[------------------+-------------------]--------------
+    //               M-                 w                   M+
+    //
+    // Grisu2 generates the digits of M+ from left to right and stops as soon as
+    // V is in [M-,M+].
+
+    assert(M_plus.e >= kAlpha);
+    assert(M_plus.e <= kGamma);
+
+    std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
+    std::uint64_t dist  = diyfp::sub(M_plus, w      ).f; // (significand of (M+ - w ), implicit exponent is e)
+
+    // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
+    //
+    //      M+ = f * 2^e
+    //         = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
+    //         = ((p1        ) * 2^-e + (p2        )) * 2^e
+    //         = p1 + p2 * 2^e
+
+    const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
+
+    auto p1 = static_cast<std::uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.)
+    std::uint64_t p2 = M_plus.f & (one.f - 1);                    // p2 = f mod 2^-e
+
+    // 1)
+    //
+    // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
+
+    assert(p1 > 0);
+
+    std::uint32_t pow10;
+    const int k = find_largest_pow10(p1, pow10);
+
+    //      10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
+    //
+    //      p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
+    //         = (d[k-1]         ) * 10^(k-1) + (p1 mod 10^(k-1))
+    //
+    //      M+ = p1                                             + p2 * 2^e
+    //         = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1))          + p2 * 2^e
+    //         = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
+    //         = d[k-1] * 10^(k-1) + (                         rest) * 2^e
+    //
+    // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
+    //
+    //      p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
+    //
+    // but stop as soon as
+    //
+    //      rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
+
+    int n = k;
+    while (n > 0)
+    {
+        // Invariants:
+        //      M+ = buffer * 10^n + (p1 + p2 * 2^e)    (buffer = 0 for n = k)
+        //      pow10 = 10^(n-1) <= p1 < 10^n
+        //
+        const std::uint32_t d = p1 / pow10;  // d = p1 div 10^(n-1)
+        const std::uint32_t r = p1 % pow10;  // r = p1 mod 10^(n-1)
+        //
+        //      M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
+        //         = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
+        //
+        assert(d <= 9);
+        buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
+        //
+        //      M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
+        //
+        p1 = r;
+        n--;
+        //
+        //      M+ = buffer * 10^n + (p1 + p2 * 2^e)
+        //      pow10 = 10^n
+        //
+
+        // Now check if enough digits have been generated.
+        // Compute
+        //
+        //      p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
+        //
+        // Note:
+        // Since rest and delta share the same exponent e, it suffices to
+        // compare the significands.
+        const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
+        if (rest <= delta)
+        {
+            // V = buffer * 10^n, with M- <= V <= M+.
+
+            decimal_exponent += n;
+
+            // We may now just stop. But instead look if the buffer could be
+            // decremented to bring V closer to w.
+            //
+            // pow10 = 10^n is now 1 ulp in the decimal representation V.
+            // The rounding procedure works with diyfp's with an implicit
+            // exponent of e.
+            //
+            //      10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
+            //
+            const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
+            grisu2_round(buffer, length, dist, delta, rest, ten_n);
+
+            return;
+        }
+
+        pow10 /= 10;
+        //
+        //      pow10 = 10^(n-1) <= p1 < 10^n
+        // Invariants restored.
+    }
+
+    // 2)
+    //
+    // The digits of the integral part have been generated:
+    //
+    //      M+ = d[k-1]...d[1]d[0] + p2 * 2^e
+    //         = buffer            + p2 * 2^e
+    //
+    // Now generate the digits of the fractional part p2 * 2^e.
+    //
+    // Note:
+    // No decimal point is generated: the exponent is adjusted instead.
+    //
+    // p2 actually represents the fraction
+    //
+    //      p2 * 2^e
+    //          = p2 / 2^-e
+    //          = d[-1] / 10^1 + d[-2] / 10^2 + ...
+    //
+    // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
+    //
+    //      p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
+    //                      + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
+    //
+    // using
+    //
+    //      10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
+    //                = (                   d) * 2^-e + (                   r)
+    //
+    // or
+    //      10^m * p2 * 2^e = d + r * 2^e
+    //
+    // i.e.
+    //
+    //      M+ = buffer + p2 * 2^e
+    //         = buffer + 10^-m * (d + r * 2^e)
+    //         = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
+    //
+    // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
+
+    assert(p2 > delta);
+
+    int m = 0;
+    for (;;)
+    {
+        // Invariant:
+        //      M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
+        //         = buffer * 10^-m + 10^-m * (p2                                 ) * 2^e
+        //         = buffer * 10^-m + 10^-m * (1/10 * (10 * p2)                   ) * 2^e
+        //         = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
+        //
+        assert(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
+        p2 *= 10;
+        const std::uint64_t d = p2 >> -one.e;     // d = (10 * p2) div 2^-e
+        const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
+        //
+        //      M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
+        //         = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
+        //         = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
+        //
+        assert(d <= 9);
+        buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
+        //
+        //      M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
+        //
+        p2 = r;
+        m++;
+        //
+        //      M+ = buffer * 10^-m + 10^-m * p2 * 2^e
+        // Invariant restored.
+
+        // Check if enough digits have been generated.
+        //
+        //      10^-m * p2 * 2^e <= delta * 2^e
+        //              p2 * 2^e <= 10^m * delta * 2^e
+        //                    p2 <= 10^m * delta
+        delta *= 10;
+        dist  *= 10;
+        if (p2 <= delta)
+        {
+            break;
+        }
+    }
+
+    // V = buffer * 10^-m, with M- <= V <= M+.
+
+    decimal_exponent -= m;
+
+    // 1 ulp in the decimal representation is now 10^-m.
+    // Since delta and dist are now scaled by 10^m, we need to do the
+    // same with ulp in order to keep the units in sync.
+    //
+    //      10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
+    //
+    const std::uint64_t ten_m = one.f;
+    grisu2_round(buffer, length, dist, delta, p2, ten_m);
+
+    // By construction this algorithm generates the shortest possible decimal
+    // number (Loitsch, Theorem 6.2) which rounds back to w.
+    // For an input number of precision p, at least
+    //
+    //      N = 1 + ceil(p * log_10(2))
+    //
+    // decimal digits are sufficient to identify all binary floating-point
+    // numbers (Matula, "In-and-Out conversions").
+    // This implies that the algorithm does not produce more than N decimal
+    // digits.
+    //
+    //      N = 17 for p = 53 (IEEE double precision)
+    //      N = 9  for p = 24 (IEEE single precision)
+}
+
+/*!
+v = buf * 10^decimal_exponent
+len is the length of the buffer (number of decimal digits)
+The buffer must be large enough, i.e. >= max_digits10.
+*/
+JSON_HEDLEY_NON_NULL(1)
+inline void grisu2(char* buf, int& len, int& decimal_exponent,
+                   diyfp m_minus, diyfp v, diyfp m_plus)
+{
+    assert(m_plus.e == m_minus.e);
+    assert(m_plus.e == v.e);
+
+    //  --------(-----------------------+-----------------------)--------    (A)
+    //          m-                      v                       m+
+    //
+    //  --------------------(-----------+-----------------------)--------    (B)
+    //                      m-          v                       m+
+    //
+    // First scale v (and m- and m+) such that the exponent is in the range
+    // [alpha, gamma].
+
+    const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
+
+    const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
+
+    // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
+    const diyfp w       = diyfp::mul(v,       c_minus_k);
+    const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
+    const diyfp w_plus  = diyfp::mul(m_plus,  c_minus_k);
+
+    //  ----(---+---)---------------(---+---)---------------(---+---)----
+    //          w-                      w                       w+
+    //          = c*m-                  = c*v                   = c*m+
+    //
+    // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
+    // w+ are now off by a small amount.
+    // In fact:
+    //
+    //      w - v * 10^k < 1 ulp
+    //
+    // To account for this inaccuracy, add resp. subtract 1 ulp.
+    //
+    //  --------+---[---------------(---+---)---------------]---+--------
+    //          w-  M-                  w                   M+  w+
+    //
+    // Now any number in [M-, M+] (bounds included) will round to w when input,
+    // regardless of how the input rounding algorithm breaks ties.
+    //
+    // And digit_gen generates the shortest possible such number in [M-, M+].
+    // Note that this does not mean that Grisu2 always generates the shortest
+    // possible number in the interval (m-, m+).
+    const diyfp M_minus(w_minus.f + 1, w_minus.e);
+    const diyfp M_plus (w_plus.f  - 1, w_plus.e );
+
+    decimal_exponent = -cached.k; // = -(-k) = k
+
+    grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
+}
+
+/*!
+v = buf * 10^decimal_exponent
+len is the length of the buffer (number of decimal digits)
+The buffer must be large enough, i.e. >= max_digits10.
+*/
+template <typename FloatType>
+JSON_HEDLEY_NON_NULL(1)
+void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
+{
+    static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
+                  "internal error: not enough precision");
+
+    assert(std::isfinite(value));
+    assert(value > 0);
+
+    // If the neighbors (and boundaries) of 'value' are always computed for double-precision
+    // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
+    // decimal representations are not exactly "short".
+    //
+    // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
+    // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
+    // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
+    // does.
+    // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
+    // representation using the corresponding std::from_chars function recovers value exactly". That
+    // indicates that single precision floating-point numbers should be recovered using
+    // 'std::strtof'.
+    //
+    // NB: If the neighbors are computed for single-precision numbers, there is a single float
+    //     (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
+    //     value is off by 1 ulp.
+#if 0
+    const boundaries w = compute_boundaries(static_cast<double>(value));
+#else
+    const boundaries w = compute_boundaries(value);
+#endif
+
+    grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
+}
+
+/*!
+@brief appends a decimal representation of e to buf
+@return a pointer to the element following the exponent.
+@pre -1000 < e < 1000
+*/
+JSON_HEDLEY_NON_NULL(1)
+JSON_HEDLEY_RETURNS_NON_NULL
+inline char* append_exponent(char* buf, int e)
+{
+    assert(e > -1000);
+    assert(e <  1000);
+
+    if (e < 0)
+    {
+        e = -e;
+        *buf++ = '-';
+    }
+    else
+    {
+        *buf++ = '+';
+    }
+
+    auto k = static_cast<std::uint32_t>(e);
+    if (k < 10)
+    {
+        // Always print at least two digits in the exponent.
+        // This is for compatibility with printf("%g").
+        *buf++ = '0';
+        *buf++ = static_cast<char>('0' + k);
+    }
+    else if (k < 100)
+    {
+        *buf++ = static_cast<char>('0' + k / 10);
+        k %= 10;
+        *buf++ = static_cast<char>('0' + k);
+    }
+    else
+    {
+        *buf++ = static_cast<char>('0' + k / 100);
+        k %= 100;
+        *buf++ = static_cast<char>('0' + k / 10);
+        k %= 10;
+        *buf++ = static_cast<char>('0' + k);
+    }
+
+    return buf;
+}
+
+/*!
+@brief prettify v = buf * 10^decimal_exponent
+
+If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
+notation. Otherwise it will be printed in exponential notation.
+
+@pre min_exp < 0
+@pre max_exp > 0
+*/
+JSON_HEDLEY_NON_NULL(1)
+JSON_HEDLEY_RETURNS_NON_NULL
+inline char* format_buffer(char* buf, int len, int decimal_exponent,
+                           int min_exp, int max_exp)
+{
+    assert(min_exp < 0);
+    assert(max_exp > 0);
+
+    const int k = len;
+    const int n = len + decimal_exponent;
+
+    // v = buf * 10^(n-k)
+    // k is the length of the buffer (number of decimal digits)
+    // n is the position of the decimal point relative to the start of the buffer.
+
+    if (k <= n and n <= max_exp)
+    {
+        // digits[000]
+        // len <= max_exp + 2
+
+        std::memset(buf + k, '0', static_cast<size_t>(n - k));
+        // Make it look like a floating-point number (#362, #378)
+        buf[n + 0] = '.';
+        buf[n + 1] = '0';
+        return buf + (n + 2);
+    }
+
+    if (0 < n and n <= max_exp)
+    {
+        // dig.its
+        // len <= max_digits10 + 1
+
+        assert(k > n);
+
+        std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n));
+        buf[n] = '.';
+        return buf + (k + 1);
+    }
+
+    if (min_exp < n and n <= 0)
+    {
+        // 0.[000]digits
+        // len <= 2 + (-min_exp - 1) + max_digits10
+
+        std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k));
+        buf[0] = '0';
+        buf[1] = '.';
+        std::memset(buf + 2, '0', static_cast<size_t>(-n));
+        return buf + (2 + (-n) + k);
+    }
+
+    if (k == 1)
+    {
+        // dE+123
+        // len <= 1 + 5
+
+        buf += 1;
+    }
+    else
+    {
+        // d.igitsE+123
+        // len <= max_digits10 + 1 + 5
+
+        std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1));
+        buf[1] = '.';
+        buf += 1 + k;
+    }
+
+    *buf++ = 'e';
+    return append_exponent(buf, n - 1);
+}
+
+} // namespace dtoa_impl
+
+/*!
+@brief generates a decimal representation of the floating-point number value in [first, last).
+
+The format of the resulting decimal representation is similar to printf's %g
+format. Returns an iterator pointing past-the-end of the decimal representation.
+
+@note The input number must be finite, i.e. NaN's and Inf's are not supported.
+@note The buffer must be large enough.
+@note The result is NOT null-terminated.
+*/
+template <typename FloatType>
+JSON_HEDLEY_NON_NULL(1, 2)
+JSON_HEDLEY_RETURNS_NON_NULL
+char* to_chars(char* first, const char* last, FloatType value)
+{
+    static_cast<void>(last); // maybe unused - fix warning
+    assert(std::isfinite(value));
+
+    // Use signbit(value) instead of (value < 0) since signbit works for -0.
+    if (std::signbit(value))
+    {
+        value = -value;
+        *first++ = '-';
+    }
+
+    if (value == 0) // +-0
+    {
+        *first++ = '0';
+        // Make it look like a floating-point number (#362, #378)
+        *first++ = '.';
+        *first++ = '0';
+        return first;
+    }
+
+    assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
+
+    // Compute v = buffer * 10^decimal_exponent.
+    // The decimal digits are stored in the buffer, which needs to be interpreted
+    // as an unsigned decimal integer.
+    // len is the length of the buffer, i.e. the number of decimal digits.
+    int len = 0;
+    int decimal_exponent = 0;
+    dtoa_impl::grisu2(first, len, decimal_exponent, value);
+
+    assert(len <= std::numeric_limits<FloatType>::max_digits10);
+
+    // Format the buffer like printf("%.*g", prec, value)
+    constexpr int kMinExp = -4;
+    // Use digits10 here to increase compatibility with version 2.
+    constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
+
+    assert(last - first >= kMaxExp + 2);
+    assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
+    assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
+
+    return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
+}
+
+} // namespace detail
+} // namespace nlohmann
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/output/binary_writer.hpp>
+
+// #include <nlohmann/detail/output/output_adapters.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+///////////////////
+// serialization //
+///////////////////
+
+/// how to treat decoding errors
+enum class error_handler_t
+{
+    strict,  ///< throw a type_error exception in case of invalid UTF-8
+    replace, ///< replace invalid UTF-8 sequences with U+FFFD
+    ignore   ///< ignore invalid UTF-8 sequences
+};
+
+template<typename BasicJsonType>
+class serializer
+{
+    using string_t = typename BasicJsonType::string_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    static constexpr std::uint8_t UTF8_ACCEPT = 0;
+    static constexpr std::uint8_t UTF8_REJECT = 1;
+
+  public:
+    /*!
+    @param[in] s  output stream to serialize to
+    @param[in] ichar  indentation character to use
+    @param[in] error_handler_  how to react on decoding errors
+    */
+    serializer(output_adapter_t<char> s, const char ichar,
+               error_handler_t error_handler_ = error_handler_t::strict)
+        : o(std::move(s))
+        , loc(std::localeconv())
+        , thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep))
+        , decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point))
+        , indent_char(ichar)
+        , indent_string(512, indent_char)
+        , error_handler(error_handler_)
+    {}
+
+    // delete because of pointer members
+    serializer(const serializer&) = delete;
+    serializer& operator=(const serializer&) = delete;
+    serializer(serializer&&) = delete;
+    serializer& operator=(serializer&&) = delete;
+    ~serializer() = default;
+
+    /*!
+    @brief internal implementation of the serialization function
+
+    This function is called by the public member function dump and organizes
+    the serialization internally. The indentation level is propagated as
+    additional parameter. In case of arrays and objects, the function is
+    called recursively.
+
+    - strings and object keys are escaped using `escape_string()`
+    - integer numbers are converted implicitly via `operator<<`
+    - floating-point numbers are converted to a string using `"%g"` format
+
+    @param[in] val             value to serialize
+    @param[in] pretty_print    whether the output shall be pretty-printed
+    @param[in] indent_step     the indent level
+    @param[in] current_indent  the current indent level (only used internally)
+    */
+    void dump(const BasicJsonType& val, const bool pretty_print,
+              const bool ensure_ascii,
+              const unsigned int indent_step,
+              const unsigned int current_indent = 0)
+    {
+        switch (val.m_type)
+        {
+            case value_t::object:
+            {
+                if (val.m_value.object->empty())
+                {
+                    o->write_characters("{}", 2);
+                    return;
+                }
+
+                if (pretty_print)
+                {
+                    o->write_characters("{\n", 2);
+
+                    // variable to hold indentation for recursive calls
+                    const auto new_indent = current_indent + indent_step;
+                    if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
+                    {
+                        indent_string.resize(indent_string.size() * 2, ' ');
+                    }
+
+                    // first n-1 elements
+                    auto i = val.m_value.object->cbegin();
+                    for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
+                    {
+                        o->write_characters(indent_string.c_str(), new_indent);
+                        o->write_character('\"');
+                        dump_escaped(i->first, ensure_ascii);
+                        o->write_characters("\": ", 3);
+                        dump(i->second, true, ensure_ascii, indent_step, new_indent);
+                        o->write_characters(",\n", 2);
+                    }
+
+                    // last element
+                    assert(i != val.m_value.object->cend());
+                    assert(std::next(i) == val.m_value.object->cend());
+                    o->write_characters(indent_string.c_str(), new_indent);
+                    o->write_character('\"');
+                    dump_escaped(i->first, ensure_ascii);
+                    o->write_characters("\": ", 3);
+                    dump(i->second, true, ensure_ascii, indent_step, new_indent);
+
+                    o->write_character('\n');
+                    o->write_characters(indent_string.c_str(), current_indent);
+                    o->write_character('}');
+                }
+                else
+                {
+                    o->write_character('{');
+
+                    // first n-1 elements
+                    auto i = val.m_value.object->cbegin();
+                    for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
+                    {
+                        o->write_character('\"');
+                        dump_escaped(i->first, ensure_ascii);
+                        o->write_characters("\":", 2);
+                        dump(i->second, false, ensure_ascii, indent_step, current_indent);
+                        o->write_character(',');
+                    }
+
+                    // last element
+                    assert(i != val.m_value.object->cend());
+                    assert(std::next(i) == val.m_value.object->cend());
+                    o->write_character('\"');
+                    dump_escaped(i->first, ensure_ascii);
+                    o->write_characters("\":", 2);
+                    dump(i->second, false, ensure_ascii, indent_step, current_indent);
+
+                    o->write_character('}');
+                }
+
+                return;
+            }
+
+            case value_t::array:
+            {
+                if (val.m_value.array->empty())
+                {
+                    o->write_characters("[]", 2);
+                    return;
+                }
+
+                if (pretty_print)
+                {
+                    o->write_characters("[\n", 2);
+
+                    // variable to hold indentation for recursive calls
+                    const auto new_indent = current_indent + indent_step;
+                    if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
+                    {
+                        indent_string.resize(indent_string.size() * 2, ' ');
+                    }
+
+                    // first n-1 elements
+                    for (auto i = val.m_value.array->cbegin();
+                            i != val.m_value.array->cend() - 1; ++i)
+                    {
+                        o->write_characters(indent_string.c_str(), new_indent);
+                        dump(*i, true, ensure_ascii, indent_step, new_indent);
+                        o->write_characters(",\n", 2);
+                    }
+
+                    // last element
+                    assert(not val.m_value.array->empty());
+                    o->write_characters(indent_string.c_str(), new_indent);
+                    dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
+
+                    o->write_character('\n');
+                    o->write_characters(indent_string.c_str(), current_indent);
+                    o->write_character(']');
+                }
+                else
+                {
+                    o->write_character('[');
+
+                    // first n-1 elements
+                    for (auto i = val.m_value.array->cbegin();
+                            i != val.m_value.array->cend() - 1; ++i)
+                    {
+                        dump(*i, false, ensure_ascii, indent_step, current_indent);
+                        o->write_character(',');
+                    }
+
+                    // last element
+                    assert(not val.m_value.array->empty());
+                    dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
+
+                    o->write_character(']');
+                }
+
+                return;
+            }
+
+            case value_t::string:
+            {
+                o->write_character('\"');
+                dump_escaped(*val.m_value.string, ensure_ascii);
+                o->write_character('\"');
+                return;
+            }
+
+            case value_t::boolean:
+            {
+                if (val.m_value.boolean)
+                {
+                    o->write_characters("true", 4);
+                }
+                else
+                {
+                    o->write_characters("false", 5);
+                }
+                return;
+            }
+
+            case value_t::number_integer:
+            {
+                dump_integer(val.m_value.number_integer);
+                return;
+            }
+
+            case value_t::number_unsigned:
+            {
+                dump_integer(val.m_value.number_unsigned);
+                return;
+            }
+
+            case value_t::number_float:
+            {
+                dump_float(val.m_value.number_float);
+                return;
+            }
+
+            case value_t::discarded:
+            {
+                o->write_characters("<discarded>", 11);
+                return;
+            }
+
+            case value_t::null:
+            {
+                o->write_characters("null", 4);
+                return;
+            }
+
+            default:            // LCOV_EXCL_LINE
+                assert(false);  // LCOV_EXCL_LINE
+        }
+    }
+
+  private:
+    /*!
+    @brief dump escaped string
+
+    Escape a string by replacing certain special characters by a sequence of an
+    escape character (backslash) and another character and other control
+    characters by a sequence of "\u" followed by a four-digit hex
+    representation. The escaped string is written to output stream @a o.
+
+    @param[in] s  the string to escape
+    @param[in] ensure_ascii  whether to escape non-ASCII characters with
+                             \uXXXX sequences
+
+    @complexity Linear in the length of string @a s.
+    */
+    void dump_escaped(const string_t& s, const bool ensure_ascii)
+    {
+        std::uint32_t codepoint;
+        std::uint8_t state = UTF8_ACCEPT;
+        std::size_t bytes = 0;  // number of bytes written to string_buffer
+
+        // number of bytes written at the point of the last valid byte
+        std::size_t bytes_after_last_accept = 0;
+        std::size_t undumped_chars = 0;
+
+        for (std::size_t i = 0; i < s.size(); ++i)
+        {
+            const auto byte = static_cast<uint8_t>(s[i]);
+
+            switch (decode(state, codepoint, byte))
+            {
+                case UTF8_ACCEPT:  // decode found a new code point
+                {
+                    switch (codepoint)
+                    {
+                        case 0x08: // backspace
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = 'b';
+                            break;
+                        }
+
+                        case 0x09: // horizontal tab
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = 't';
+                            break;
+                        }
+
+                        case 0x0A: // newline
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = 'n';
+                            break;
+                        }
+
+                        case 0x0C: // formfeed
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = 'f';
+                            break;
+                        }
+
+                        case 0x0D: // carriage return
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = 'r';
+                            break;
+                        }
+
+                        case 0x22: // quotation mark
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = '\"';
+                            break;
+                        }
+
+                        case 0x5C: // reverse solidus
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = '\\';
+                            break;
+                        }
+
+                        default:
+                        {
+                            // escape control characters (0x00..0x1F) or, if
+                            // ensure_ascii parameter is used, non-ASCII characters
+                            if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
+                            {
+                                if (codepoint <= 0xFFFF)
+                                {
+                                    (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
+                                                    static_cast<std::uint16_t>(codepoint));
+                                    bytes += 6;
+                                }
+                                else
+                                {
+                                    (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
+                                                    static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
+                                                    static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
+                                    bytes += 12;
+                                }
+                            }
+                            else
+                            {
+                                // copy byte to buffer (all previous bytes
+                                // been copied have in default case above)
+                                string_buffer[bytes++] = s[i];
+                            }
+                            break;
+                        }
+                    }
+
+                    // write buffer and reset index; there must be 13 bytes
+                    // left, as this is the maximal number of bytes to be
+                    // written ("\uxxxx\uxxxx\0") for one code point
+                    if (string_buffer.size() - bytes < 13)
+                    {
+                        o->write_characters(string_buffer.data(), bytes);
+                        bytes = 0;
+                    }
+
+                    // remember the byte position of this accept
+                    bytes_after_last_accept = bytes;
+                    undumped_chars = 0;
+                    break;
+                }
+
+                case UTF8_REJECT:  // decode found invalid UTF-8 byte
+                {
+                    switch (error_handler)
+                    {
+                        case error_handler_t::strict:
+                        {
+                            std::string sn(3, '\0');
+                            (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
+                            JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
+                        }
+
+                        case error_handler_t::ignore:
+                        case error_handler_t::replace:
+                        {
+                            // in case we saw this character the first time, we
+                            // would like to read it again, because the byte
+                            // may be OK for itself, but just not OK for the
+                            // previous sequence
+                            if (undumped_chars > 0)
+                            {
+                                --i;
+                            }
+
+                            // reset length buffer to the last accepted index;
+                            // thus removing/ignoring the invalid characters
+                            bytes = bytes_after_last_accept;
+
+                            if (error_handler == error_handler_t::replace)
+                            {
+                                // add a replacement character
+                                if (ensure_ascii)
+                                {
+                                    string_buffer[bytes++] = '\\';
+                                    string_buffer[bytes++] = 'u';
+                                    string_buffer[bytes++] = 'f';
+                                    string_buffer[bytes++] = 'f';
+                                    string_buffer[bytes++] = 'f';
+                                    string_buffer[bytes++] = 'd';
+                                }
+                                else
+                                {
+                                    string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
+                                    string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
+                                    string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
+                                }
+
+                                // write buffer and reset index; there must be 13 bytes
+                                // left, as this is the maximal number of bytes to be
+                                // written ("\uxxxx\uxxxx\0") for one code point
+                                if (string_buffer.size() - bytes < 13)
+                                {
+                                    o->write_characters(string_buffer.data(), bytes);
+                                    bytes = 0;
+                                }
+
+                                bytes_after_last_accept = bytes;
+                            }
+
+                            undumped_chars = 0;
+
+                            // continue processing the string
+                            state = UTF8_ACCEPT;
+                            break;
+                        }
+
+                        default:            // LCOV_EXCL_LINE
+                            assert(false);  // LCOV_EXCL_LINE
+                    }
+                    break;
+                }
+
+                default:  // decode found yet incomplete multi-byte code point
+                {
+                    if (not ensure_ascii)
+                    {
+                        // code point will not be escaped - copy byte to buffer
+                        string_buffer[bytes++] = s[i];
+                    }
+                    ++undumped_chars;
+                    break;
+                }
+            }
+        }
+
+        // we finished processing the string
+        if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
+        {
+            // write buffer
+            if (bytes > 0)
+            {
+                o->write_characters(string_buffer.data(), bytes);
+            }
+        }
+        else
+        {
+            // we finish reading, but do not accept: string was incomplete
+            switch (error_handler)
+            {
+                case error_handler_t::strict:
+                {
+                    std::string sn(3, '\0');
+                    (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
+                    JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
+                }
+
+                case error_handler_t::ignore:
+                {
+                    // write all accepted bytes
+                    o->write_characters(string_buffer.data(), bytes_after_last_accept);
+                    break;
+                }
+
+                case error_handler_t::replace:
+                {
+                    // write all accepted bytes
+                    o->write_characters(string_buffer.data(), bytes_after_last_accept);
+                    // add a replacement character
+                    if (ensure_ascii)
+                    {
+                        o->write_characters("\\ufffd", 6);
+                    }
+                    else
+                    {
+                        o->write_characters("\xEF\xBF\xBD", 3);
+                    }
+                    break;
+                }
+
+                default:            // LCOV_EXCL_LINE
+                    assert(false);  // LCOV_EXCL_LINE
+            }
+        }
+    }
+
+    /*!
+    @brief count digits
+
+    Count the number of decimal (base 10) digits for an input unsigned integer.
+
+    @param[in] x  unsigned integer number to count its digits
+    @return    number of decimal digits
+    */
+    inline unsigned int count_digits(number_unsigned_t x) noexcept
+    {
+        unsigned int n_digits = 1;
+        for (;;)
+        {
+            if (x < 10)
+            {
+                return n_digits;
+            }
+            if (x < 100)
+            {
+                return n_digits + 1;
+            }
+            if (x < 1000)
+            {
+                return n_digits + 2;
+            }
+            if (x < 10000)
+            {
+                return n_digits + 3;
+            }
+            x = x / 10000u;
+            n_digits += 4;
+        }
+    }
+
+    /*!
+    @brief dump an integer
+
+    Dump a given integer to output stream @a o. Works internally with
+    @a number_buffer.
+
+    @param[in] x  integer number (signed or unsigned) to dump
+    @tparam NumberType either @a number_integer_t or @a number_unsigned_t
+    */
+    template<typename NumberType, detail::enable_if_t<
+                 std::is_same<NumberType, number_unsigned_t>::value or
+                 std::is_same<NumberType, number_integer_t>::value,
+                 int> = 0>
+    void dump_integer(NumberType x)
+    {
+        static constexpr std::array<std::array<char, 2>, 100> digits_to_99
+        {
+            {
+                {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
+                {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
+                {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
+                {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
+                {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
+                {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
+                {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
+                {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
+                {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
+                {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
+            }
+        };
+
+        // special case for "0"
+        if (x == 0)
+        {
+            o->write_character('0');
+            return;
+        }
+
+        // use a pointer to fill the buffer
+        auto buffer_ptr = number_buffer.begin();
+
+        const bool is_negative = std::is_same<NumberType, number_integer_t>::value and not(x >= 0); // see issue #755
+        number_unsigned_t abs_value;
+
+        unsigned int n_chars;
+
+        if (is_negative)
+        {
+            *buffer_ptr = '-';
+            abs_value = remove_sign(x);
+
+            // account one more byte for the minus sign
+            n_chars = 1 + count_digits(abs_value);
+        }
+        else
+        {
+            abs_value = static_cast<number_unsigned_t>(x);
+            n_chars = count_digits(abs_value);
+        }
+
+        // spare 1 byte for '\0'
+        assert(n_chars < number_buffer.size() - 1);
+
+        // jump to the end to generate the string from backward
+        // so we later avoid reversing the result
+        buffer_ptr += n_chars;
+
+        // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
+        // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
+        while (abs_value >= 100)
+        {
+            const auto digits_index = static_cast<unsigned>((abs_value % 100));
+            abs_value /= 100;
+            *(--buffer_ptr) = digits_to_99[digits_index][1];
+            *(--buffer_ptr) = digits_to_99[digits_index][0];
+        }
+
+        if (abs_value >= 10)
+        {
+            const auto digits_index = static_cast<unsigned>(abs_value);
+            *(--buffer_ptr) = digits_to_99[digits_index][1];
+            *(--buffer_ptr) = digits_to_99[digits_index][0];
+        }
+        else
+        {
+            *(--buffer_ptr) = static_cast<char>('0' + abs_value);
+        }
+
+        o->write_characters(number_buffer.data(), n_chars);
+    }
+
+    /*!
+    @brief dump a floating-point number
+
+    Dump a given floating-point number to output stream @a o. Works internally
+    with @a number_buffer.
+
+    @param[in] x  floating-point number to dump
+    */
+    void dump_float(number_float_t x)
+    {
+        // NaN / inf
+        if (not std::isfinite(x))
+        {
+            o->write_characters("null", 4);
+            return;
+        }
+
+        // If number_float_t is an IEEE-754 single or double precision number,
+        // use the Grisu2 algorithm to produce short numbers which are
+        // guaranteed to round-trip, using strtof and strtod, resp.
+        //
+        // NB: The test below works if <long double> == <double>.
+        static constexpr bool is_ieee_single_or_double
+            = (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 24 and std::numeric_limits<number_float_t>::max_exponent == 128) or
+              (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 53 and std::numeric_limits<number_float_t>::max_exponent == 1024);
+
+        dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
+    }
+
+    void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
+    {
+        char* begin = number_buffer.data();
+        char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
+
+        o->write_characters(begin, static_cast<size_t>(end - begin));
+    }
+
+    void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
+    {
+        // get number of digits for a float -> text -> float round-trip
+        static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
+
+        // the actual conversion
+        std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
+
+        // negative value indicates an error
+        assert(len > 0);
+        // check if buffer was large enough
+        assert(static_cast<std::size_t>(len) < number_buffer.size());
+
+        // erase thousands separator
+        if (thousands_sep != '\0')
+        {
+            const auto end = std::remove(number_buffer.begin(),
+                                         number_buffer.begin() + len, thousands_sep);
+            std::fill(end, number_buffer.end(), '\0');
+            assert((end - number_buffer.begin()) <= len);
+            len = (end - number_buffer.begin());
+        }
+
+        // convert decimal point to '.'
+        if (decimal_point != '\0' and decimal_point != '.')
+        {
+            const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
+            if (dec_pos != number_buffer.end())
+            {
+                *dec_pos = '.';
+            }
+        }
+
+        o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
+
+        // determine if need to append ".0"
+        const bool value_is_int_like =
+            std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
+                         [](char c)
+        {
+            return c == '.' or c == 'e';
+        });
+
+        if (value_is_int_like)
+        {
+            o->write_characters(".0", 2);
+        }
+    }
+
+    /*!
+    @brief check whether a string is UTF-8 encoded
+
+    The function checks each byte of a string whether it is UTF-8 encoded. The
+    result of the check is stored in the @a state parameter. The function must
+    be called initially with state 0 (accept). State 1 means the string must
+    be rejected, because the current byte is not allowed. If the string is
+    completely processed, but the state is non-zero, the string ended
+    prematurely; that is, the last byte indicated more bytes should have
+    followed.
+
+    @param[in,out] state  the state of the decoding
+    @param[in,out] codep  codepoint (valid only if resulting state is UTF8_ACCEPT)
+    @param[in] byte       next byte to decode
+    @return               new state
+
+    @note The function has been edited: a std::array is used.
+
+    @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
+    @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
+    */
+    static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
+    {
+        static const std::array<std::uint8_t, 400> utf8d =
+        {
+            {
+                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F
+                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F
+                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F
+                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F
+                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F
+                7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF
+                8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF
+                0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
+                0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
+                0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
+                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2
+                1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4
+                1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6
+                1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8
+            }
+        };
+
+        const std::uint8_t type = utf8d[byte];
+
+        codep = (state != UTF8_ACCEPT)
+                ? (byte & 0x3fu) | (codep << 6u)
+                : (0xFFu >> type) & (byte);
+
+        state = utf8d[256u + state * 16u + type];
+        return state;
+    }
+
+    /*
+     * Overload to make the compiler happy while it is instantiating
+     * dump_integer for number_unsigned_t.
+     * Must never be called.
+     */
+    number_unsigned_t remove_sign(number_unsigned_t x)
+    {
+        assert(false); // LCOV_EXCL_LINE
+        return x; // LCOV_EXCL_LINE
+    }
+
+    /*
+     * Helper function for dump_integer
+     *
+     * This function takes a negative signed integer and returns its absolute
+     * value as unsigned integer. The plus/minus shuffling is necessary as we can
+     * not directly remove the sign of an arbitrary signed integer as the
+     * absolute values of INT_MIN and INT_MAX are usually not the same. See
+     * #1708 for details.
+     */
+    inline number_unsigned_t remove_sign(number_integer_t x) noexcept
+    {
+        assert(x < 0 and x < (std::numeric_limits<number_integer_t>::max)());
+        return static_cast<number_unsigned_t>(-(x + 1)) + 1;
+    }
+
+  private:
+    /// the output of the serializer
+    output_adapter_t<char> o = nullptr;
+
+    /// a (hopefully) large enough character buffer
+    std::array<char, 64> number_buffer{{}};
+
+    /// the locale
+    const std::lconv* loc = nullptr;
+    /// the locale's thousand separator character
+    const char thousands_sep = '\0';
+    /// the locale's decimal point character
+    const char decimal_point = '\0';
+
+    /// string buffer
+    std::array<char, 512> string_buffer{{}};
+
+    /// the indentation character
+    const char indent_char;
+    /// the indentation string
+    string_t indent_string;
+
+    /// error_handler how to react on decoding errors
+    const error_handler_t error_handler;
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/value_t.hpp>
+
+// #include <nlohmann/json_fwd.hpp>
+
+
+/*!
+@brief namespace for Niels Lohmann
+@see https://github.com/nlohmann
+@since version 1.0.0
+*/
+namespace nlohmann
+{
+
+/*!
+@brief a class to store JSON values
+
+@tparam ObjectType type for JSON objects (`std::map` by default; will be used
+in @ref object_t)
+@tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
+in @ref array_t)
+@tparam StringType type for JSON strings and object keys (`std::string` by
+default; will be used in @ref string_t)
+@tparam BooleanType type for JSON booleans (`bool` by default; will be used
+in @ref boolean_t)
+@tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
+default; will be used in @ref number_integer_t)
+@tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
+`uint64_t` by default; will be used in @ref number_unsigned_t)
+@tparam NumberFloatType type for JSON floating-point numbers (`double` by
+default; will be used in @ref number_float_t)
+@tparam AllocatorType type of the allocator to use (`std::allocator` by
+default)
+@tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
+and `from_json()` (@ref adl_serializer by default)
+
+@requirement The class satisfies the following concept requirements:
+- Basic
+ - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
+   JSON values can be default constructed. The result will be a JSON null
+   value.
+ - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
+   A JSON value can be constructed from an rvalue argument.
+ - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
+   A JSON value can be copy-constructed from an lvalue expression.
+ - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
+   A JSON value van be assigned from an rvalue argument.
+ - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
+   A JSON value can be copy-assigned from an lvalue expression.
+ - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
+   JSON values can be destructed.
+- Layout
+ - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
+   JSON values have
+   [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
+   All non-static data members are private and standard layout types, the
+   class has no virtual functions or (virtual) base classes.
+- Library-wide
+ - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
+   JSON values can be compared with `==`, see @ref
+   operator==(const_reference,const_reference).
+ - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
+   JSON values can be compared with `<`, see @ref
+   operator<(const_reference,const_reference).
+ - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
+   Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
+   other compatible types, using unqualified function call @ref swap().
+ - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
+   JSON values can be compared against `std::nullptr_t` objects which are used
+   to model the `null` value.
+- Container
+ - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
+   JSON values can be used like STL containers and provide iterator access.
+ - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
+   JSON values can be used like STL containers and provide reverse iterator
+   access.
+
+@invariant The member variables @a m_value and @a m_type have the following
+relationship:
+- If `m_type == value_t::object`, then `m_value.object != nullptr`.
+- If `m_type == value_t::array`, then `m_value.array != nullptr`.
+- If `m_type == value_t::string`, then `m_value.string != nullptr`.
+The invariants are checked by member function assert_invariant().
+
+@internal
+@note ObjectType trick from https://stackoverflow.com/a/9860911
+@endinternal
+
+@see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
+Format](http://rfc7159.net/rfc7159)
+
+@since version 1.0.0
+
+@nosubgrouping
+*/
+NLOHMANN_BASIC_JSON_TPL_DECLARATION
+class basic_json
+{
+  private:
+    template<detail::value_t> friend struct detail::external_constructor;
+    friend ::nlohmann::json_pointer<basic_json>;
+    friend ::nlohmann::detail::parser<basic_json>;
+    friend ::nlohmann::detail::serializer<basic_json>;
+    template<typename BasicJsonType>
+    friend class ::nlohmann::detail::iter_impl;
+    template<typename BasicJsonType, typename CharType>
+    friend class ::nlohmann::detail::binary_writer;
+    template<typename BasicJsonType, typename SAX>
+    friend class ::nlohmann::detail::binary_reader;
+    template<typename BasicJsonType>
+    friend class ::nlohmann::detail::json_sax_dom_parser;
+    template<typename BasicJsonType>
+    friend class ::nlohmann::detail::json_sax_dom_callback_parser;
+
+    /// workaround type for MSVC
+    using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
+
+    // convenience aliases for types residing in namespace detail;
+    using lexer = ::nlohmann::detail::lexer<basic_json>;
+    using parser = ::nlohmann::detail::parser<basic_json>;
+
+    using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
+    template<typename BasicJsonType>
+    using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
+    template<typename BasicJsonType>
+    using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
+    template<typename Iterator>
+    using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
+    template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
+
+    template<typename CharType>
+    using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
+
+    using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
+    template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
+
+    using serializer = ::nlohmann::detail::serializer<basic_json>;
+
+  public:
+    using value_t = detail::value_t;
+    /// JSON Pointer, see @ref nlohmann::json_pointer
+    using json_pointer = ::nlohmann::json_pointer<basic_json>;
+    template<typename T, typename SFINAE>
+    using json_serializer = JSONSerializer<T, SFINAE>;
+    /// how to treat decoding errors
+    using error_handler_t = detail::error_handler_t;
+    /// helper type for initializer lists of basic_json values
+    using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
+
+    using input_format_t = detail::input_format_t;
+    /// SAX interface type, see @ref nlohmann::json_sax
+    using json_sax_t = json_sax<basic_json>;
+
+    ////////////////
+    // exceptions //
+    ////////////////
+
+    /// @name exceptions
+    /// Classes to implement user-defined exceptions.
+    /// @{
+
+    /// @copydoc detail::exception
+    using exception = detail::exception;
+    /// @copydoc detail::parse_error
+    using parse_error = detail::parse_error;
+    /// @copydoc detail::invalid_iterator
+    using invalid_iterator = detail::invalid_iterator;
+    /// @copydoc detail::type_error
+    using type_error = detail::type_error;
+    /// @copydoc detail::out_of_range
+    using out_of_range = detail::out_of_range;
+    /// @copydoc detail::other_error
+    using other_error = detail::other_error;
+
+    /// @}
+
+
+    /////////////////////
+    // container types //
+    /////////////////////
+
+    /// @name container types
+    /// The canonic container types to use @ref basic_json like any other STL
+    /// container.
+    /// @{
+
+    /// the type of elements in a basic_json container
+    using value_type = basic_json;
+
+    /// the type of an element reference
+    using reference = value_type&;
+    /// the type of an element const reference
+    using const_reference = const value_type&;
+
+    /// a type to represent differences between iterators
+    using difference_type = std::ptrdiff_t;
+    /// a type to represent container sizes
+    using size_type = std::size_t;
+
+    /// the allocator type
+    using allocator_type = AllocatorType<basic_json>;
+
+    /// the type of an element pointer
+    using pointer = typename std::allocator_traits<allocator_type>::pointer;
+    /// the type of an element const pointer
+    using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
+
+    /// an iterator for a basic_json container
+    using iterator = iter_impl<basic_json>;
+    /// a const iterator for a basic_json container
+    using const_iterator = iter_impl<const basic_json>;
+    /// a reverse iterator for a basic_json container
+    using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
+    /// a const reverse iterator for a basic_json container
+    using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
+
+    /// @}
+
+
+    /*!
+    @brief returns the allocator associated with the container
+    */
+    static allocator_type get_allocator()
+    {
+        return allocator_type();
+    }
+
+    /*!
+    @brief returns version information on the library
+
+    This function returns a JSON object with information about the library,
+    including the version number and information on the platform and compiler.
+
+    @return JSON object holding version information
+    key         | description
+    ----------- | ---------------
+    `compiler`  | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version).
+    `copyright` | The copyright line for the library as string.
+    `name`      | The name of the library as string.
+    `platform`  | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
+    `url`       | The URL of the project as string.
+    `version`   | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string).
+
+    @liveexample{The following code shows an example output of the `meta()`
+    function.,meta}
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes to any JSON value.
+
+    @complexity Constant.
+
+    @since 2.1.0
+    */
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json meta()
+    {
+        basic_json result;
+
+        result["copyright"] = "(C) 2013-2017 Niels Lohmann";
+        result["name"] = "JSON for Modern C++";
+        result["url"] = "https://github.com/nlohmann/json";
+        result["version"]["string"] =
+            std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
+            std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
+            std::to_string(NLOHMANN_JSON_VERSION_PATCH);
+        result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
+        result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
+        result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
+
+#ifdef _WIN32
+        result["platform"] = "win32";
+#elif defined __linux__
+        result["platform"] = "linux";
+#elif defined __APPLE__
+        result["platform"] = "apple";
+#elif defined __unix__
+        result["platform"] = "unix";
+#else
+        result["platform"] = "unknown";
+#endif
+
+#if defined(__ICC) || defined(__INTEL_COMPILER)
+        result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
+#elif defined(__clang__)
+        result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
+#elif defined(__GNUC__) || defined(__GNUG__)
+        result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
+#elif defined(__HP_cc) || defined(__HP_aCC)
+        result["compiler"] = "hp"
+#elif defined(__IBMCPP__)
+        result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
+#elif defined(_MSC_VER)
+        result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
+#elif defined(__PGI)
+        result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
+#elif defined(__SUNPRO_CC)
+        result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
+#else
+        result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
+#endif
+
+#ifdef __cplusplus
+        result["compiler"]["c++"] = std::to_string(__cplusplus);
+#else
+        result["compiler"]["c++"] = "unknown";
+#endif
+        return result;
+    }
+
+
+    ///////////////////////////
+    // JSON value data types //
+    ///////////////////////////
+
+    /// @name JSON value data types
+    /// The data types to store a JSON value. These types are derived from
+    /// the template arguments passed to class @ref basic_json.
+    /// @{
+
+#if defined(JSON_HAS_CPP_14)
+    // Use transparent comparator if possible, combined with perfect forwarding
+    // on find() and count() calls prevents unnecessary string construction.
+    using object_comparator_t = std::less<>;
+#else
+    using object_comparator_t = std::less<StringType>;
+#endif
+
+    /*!
+    @brief a type for an object
+
+    [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
+    > An object is an unordered collection of zero or more name/value pairs,
+    > where a name is a string and a value is a string, number, boolean, null,
+    > object, or array.
+
+    To store objects in C++, a type is defined by the template parameters
+    described below.
+
+    @tparam ObjectType  the container to store objects (e.g., `std::map` or
+    `std::unordered_map`)
+    @tparam StringType the type of the keys or names (e.g., `std::string`).
+    The comparison function `std::less<StringType>` is used to order elements
+    inside the container.
+    @tparam AllocatorType the allocator to use for objects (e.g.,
+    `std::allocator`)
+
+    #### Default type
+
+    With the default values for @a ObjectType (`std::map`), @a StringType
+    (`std::string`), and @a AllocatorType (`std::allocator`), the default
+    value for @a object_t is:
+
+    @code {.cpp}
+    std::map<
+      std::string, // key_type
+      basic_json, // value_type
+      std::less<std::string>, // key_compare
+      std::allocator<std::pair<const std::string, basic_json>> // allocator_type
+    >
+    @endcode
+
+    #### Behavior
+
+    The choice of @a object_t influences the behavior of the JSON class. With
+    the default type, objects have the following behavior:
+
+    - When all names are unique, objects will be interoperable in the sense
+      that all software implementations receiving that object will agree on
+      the name-value mappings.
+    - When the names within an object are not unique, it is unspecified which
+      one of the values for a given key will be chosen. For instance,
+      `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
+      `{"key": 2}`.
+    - Internally, name/value pairs are stored in lexicographical order of the
+      names. Objects will also be serialized (see @ref dump) in this order.
+      For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
+      and serialized as `{"a": 2, "b": 1}`.
+    - When comparing objects, the order of the name/value pairs is irrelevant.
+      This makes objects interoperable in the sense that they will not be
+      affected by these differences. For instance, `{"b": 1, "a": 2}` and
+      `{"a": 2, "b": 1}` will be treated as equal.
+
+    #### Limits
+
+    [RFC 7159](http://rfc7159.net/rfc7159) specifies:
+    > An implementation may set limits on the maximum depth of nesting.
+
+    In this class, the object's limit of nesting is not explicitly constrained.
+    However, a maximum depth of nesting may be introduced by the compiler or
+    runtime environment. A theoretical limit can be queried by calling the
+    @ref max_size function of a JSON object.
+
+    #### Storage
+
+    Objects are stored as pointers in a @ref basic_json type. That is, for any
+    access to object values, a pointer of type `object_t*` must be
+    dereferenced.
+
+    @sa @ref array_t -- type for an array value
+
+    @since version 1.0.0
+
+    @note The order name/value pairs are added to the object is *not*
+    preserved by the library. Therefore, iterating an object may return
+    name/value pairs in a different order than they were originally stored. In
+    fact, keys will be traversed in alphabetical order as `std::map` with
+    `std::less` is used by default. Please note this behavior conforms to [RFC
+    7159](http://rfc7159.net/rfc7159), because any order implements the
+    specified "unordered" nature of JSON objects.
+    */
+    using object_t = ObjectType<StringType,
+          basic_json,
+          object_comparator_t,
+          AllocatorType<std::pair<const StringType,
+          basic_json>>>;
+
+    /*!
+    @brief a type for an array
+
+    [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
+    > An array is an ordered sequence of zero or more values.
+
+    To store objects in C++, a type is defined by the template parameters
+    explained below.
+
+    @tparam ArrayType  container type to store arrays (e.g., `std::vector` or
+    `std::list`)
+    @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
+
+    #### Default type
+
+    With the default values for @a ArrayType (`std::vector`) and @a
+    AllocatorType (`std::allocator`), the default value for @a array_t is:
+
+    @code {.cpp}
+    std::vector<
+      basic_json, // value_type
+      std::allocator<basic_json> // allocator_type
+    >
+    @endcode
+
+    #### Limits
+
+    [RFC 7159](http://rfc7159.net/rfc7159) specifies:
+    > An implementation may set limits on the maximum depth of nesting.
+
+    In this class, the array's limit of nesting is not explicitly constrained.
+    However, a maximum depth of nesting may be introduced by the compiler or
+    runtime environment. A theoretical limit can be queried by calling the
+    @ref max_size function of a JSON array.
+
+    #### Storage
+
+    Arrays are stored as pointers in a @ref basic_json type. That is, for any
+    access to array values, a pointer of type `array_t*` must be dereferenced.
+
+    @sa @ref object_t -- type for an object value
+
+    @since version 1.0.0
+    */
+    using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
+
+    /*!
+    @brief a type for a string
+
+    [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
+    > A string is a sequence of zero or more Unicode characters.
+
+    To store objects in C++, a type is defined by the template parameter
+    described below. Unicode values are split by the JSON class into
+    byte-sized characters during deserialization.
+
+    @tparam StringType  the container to store strings (e.g., `std::string`).
+    Note this container is used for keys/names in objects, see @ref object_t.
+
+    #### Default type
+
+    With the default values for @a StringType (`std::string`), the default
+    value for @a string_t is:
+
+    @code {.cpp}
+    std::string
+    @endcode
+
+    #### Encoding
+
+    Strings are stored in UTF-8 encoding. Therefore, functions like
+    `std::string::size()` or `std::string::length()` return the number of
+    bytes in the string rather than the number of characters or glyphs.
+
+    #### String comparison
+
+    [RFC 7159](http://rfc7159.net/rfc7159) states:
+    > Software implementations are typically required to test names of object
+    > members for equality. Implementations that transform the textual
+    > representation into sequences of Unicode code units and then perform the
+    > comparison numerically, code unit by code unit, are interoperable in the
+    > sense that implementations will agree in all cases on equality or
+    > inequality of two strings. For example, implementations that compare
+    > strings with escaped characters unconverted may incorrectly find that
+    > `"a\\b"` and `"a\u005Cb"` are not equal.
+
+    This implementation is interoperable as it does compare strings code unit
+    by code unit.
+
+    #### Storage
+
+    String values are stored as pointers in a @ref basic_json type. That is,
+    for any access to string values, a pointer of type `string_t*` must be
+    dereferenced.
+
+    @since version 1.0.0
+    */
+    using string_t = StringType;
+
+    /*!
+    @brief a type for a boolean
+
+    [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
+    type which differentiates the two literals `true` and `false`.
+
+    To store objects in C++, a type is defined by the template parameter @a
+    BooleanType which chooses the type to use.
+
+    #### Default type
+
+    With the default values for @a BooleanType (`bool`), the default value for
+    @a boolean_t is:
+
+    @code {.cpp}
+    bool
+    @endcode
+
+    #### Storage
+
+    Boolean values are stored directly inside a @ref basic_json type.
+
+    @since version 1.0.0
+    */
+    using boolean_t = BooleanType;
+
+    /*!
+    @brief a type for a number (integer)
+
+    [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
+    > The representation of numbers is similar to that used in most
+    > programming languages. A number is represented in base 10 using decimal
+    > digits. It contains an integer component that may be prefixed with an
+    > optional minus sign, which may be followed by a fraction part and/or an
+    > exponent part. Leading zeros are not allowed. (...) Numeric values that
+    > cannot be represented in the grammar below (such as Infinity and NaN)
+    > are not permitted.
+
+    This description includes both integer and floating-point numbers.
+    However, C++ allows more precise storage if it is known whether the number
+    is a signed integer, an unsigned integer or a floating-point number.
+    Therefore, three different types, @ref number_integer_t, @ref
+    number_unsigned_t and @ref number_float_t are used.
+
+    To store integer numbers in C++, a type is defined by the template
+    parameter @a NumberIntegerType which chooses the type to use.
+
+    #### Default type
+
+    With the default values for @a NumberIntegerType (`int64_t`), the default
+    value for @a number_integer_t is:
+
+    @code {.cpp}
+    int64_t
+    @endcode
+
+    #### Default behavior
+
+    - The restrictions about leading zeros is not enforced in C++. Instead,
+      leading zeros in integer literals lead to an interpretation as octal
+      number. Internally, the value will be stored as decimal number. For
+      instance, the C++ integer literal `010` will be serialized to `8`.
+      During deserialization, leading zeros yield an error.
+    - Not-a-number (NaN) values will be serialized to `null`.
+
+    #### Limits
+
+    [RFC 7159](http://rfc7159.net/rfc7159) specifies:
+    > An implementation may set limits on the range and precision of numbers.
+
+    When the default type is used, the maximal integer number that can be
+    stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
+    that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
+    that are out of range will yield over/underflow when used in a
+    constructor. During deserialization, too large or small integer numbers
+    will be automatically be stored as @ref number_unsigned_t or @ref
+    number_float_t.
+
+    [RFC 7159](http://rfc7159.net/rfc7159) further states:
+    > Note that when such software is used, numbers that are integers and are
+    > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
+    > that implementations will agree exactly on their numeric values.
+
+    As this range is a subrange of the exactly supported range [INT64_MIN,
+    INT64_MAX], this class's integer type is interoperable.
+
+    #### Storage
+
+    Integer number values are stored directly inside a @ref basic_json type.
+
+    @sa @ref number_float_t -- type for number values (floating-point)
+
+    @sa @ref number_unsigned_t -- type for number values (unsigned integer)
+
+    @since version 1.0.0
+    */
+    using number_integer_t = NumberIntegerType;
+
+    /*!
+    @brief a type for a number (unsigned)
+
+    [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
+    > The representation of numbers is similar to that used in most
+    > programming languages. A number is represented in base 10 using decimal
+    > digits. It contains an integer component that may be prefixed with an
+    > optional minus sign, which may be followed by a fraction part and/or an
+    > exponent part. Leading zeros are not allowed. (...) Numeric values that
+    > cannot be represented in the grammar below (such as Infinity and NaN)
+    > are not permitted.
+
+    This description includes both integer and floating-point numbers.
+    However, C++ allows more precise storage if it is known whether the number
+    is a signed integer, an unsigned integer or a floating-point number.
+    Therefore, three different types, @ref number_integer_t, @ref
+    number_unsigned_t and @ref number_float_t are used.
+
+    To store unsigned integer numbers in C++, a type is defined by the
+    template parameter @a NumberUnsignedType which chooses the type to use.
+
+    #### Default type
+
+    With the default values for @a NumberUnsignedType (`uint64_t`), the
+    default value for @a number_unsigned_t is:
+
+    @code {.cpp}
+    uint64_t
+    @endcode
+
+    #### Default behavior
+
+    - The restrictions about leading zeros is not enforced in C++. Instead,
+      leading zeros in integer literals lead to an interpretation as octal
+      number. Internally, the value will be stored as decimal number. For
+      instance, the C++ integer literal `010` will be serialized to `8`.
+      During deserialization, leading zeros yield an error.
+    - Not-a-number (NaN) values will be serialized to `null`.
+
+    #### Limits
+
+    [RFC 7159](http://rfc7159.net/rfc7159) specifies:
+    > An implementation may set limits on the range and precision of numbers.
+
+    When the default type is used, the maximal integer number that can be
+    stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
+    number that can be stored is `0`. Integer numbers that are out of range
+    will yield over/underflow when used in a constructor. During
+    deserialization, too large or small integer numbers will be automatically
+    be stored as @ref number_integer_t or @ref number_float_t.
+
+    [RFC 7159](http://rfc7159.net/rfc7159) further states:
+    > Note that when such software is used, numbers that are integers and are
+    > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
+    > that implementations will agree exactly on their numeric values.
+
+    As this range is a subrange (when considered in conjunction with the
+    number_integer_t type) of the exactly supported range [0, UINT64_MAX],
+    this class's integer type is interoperable.
+
+    #### Storage
+
+    Integer number values are stored directly inside a @ref basic_json type.
+
+    @sa @ref number_float_t -- type for number values (floating-point)
+    @sa @ref number_integer_t -- type for number values (integer)
+
+    @since version 2.0.0
+    */
+    using number_unsigned_t = NumberUnsignedType;
+
+    /*!
+    @brief a type for a number (floating-point)
+
+    [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
+    > The representation of numbers is similar to that used in most
+    > programming languages. A number is represented in base 10 using decimal
+    > digits. It contains an integer component that may be prefixed with an
+    > optional minus sign, which may be followed by a fraction part and/or an
+    > exponent part. Leading zeros are not allowed. (...) Numeric values that
+    > cannot be represented in the grammar below (such as Infinity and NaN)
+    > are not permitted.
+
+    This description includes both integer and floating-point numbers.
+    However, C++ allows more precise storage if it is known whether the number
+    is a signed integer, an unsigned integer or a floating-point number.
+    Therefore, three different types, @ref number_integer_t, @ref
+    number_unsigned_t and @ref number_float_t are used.
+
+    To store floating-point numbers in C++, a type is defined by the template
+    parameter @a NumberFloatType which chooses the type to use.
+
+    #### Default type
+
+    With the default values for @a NumberFloatType (`double`), the default
+    value for @a number_float_t is:
+
+    @code {.cpp}
+    double
+    @endcode
+
+    #### Default behavior
+
+    - The restrictions about leading zeros is not enforced in C++. Instead,
+      leading zeros in floating-point literals will be ignored. Internally,
+      the value will be stored as decimal number. For instance, the C++
+      floating-point literal `01.2` will be serialized to `1.2`. During
+      deserialization, leading zeros yield an error.
+    - Not-a-number (NaN) values will be serialized to `null`.
+
+    #### Limits
+
+    [RFC 7159](http://rfc7159.net/rfc7159) states:
+    > This specification allows implementations to set limits on the range and
+    > precision of numbers accepted. Since software that implements IEEE
+    > 754-2008 binary64 (double precision) numbers is generally available and
+    > widely used, good interoperability can be achieved by implementations
+    > that expect no more precision or range than these provide, in the sense
+    > that implementations will approximate JSON numbers within the expected
+    > precision.
+
+    This implementation does exactly follow this approach, as it uses double
+    precision floating-point numbers. Note values smaller than
+    `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
+    will be stored as NaN internally and be serialized to `null`.
+
+    #### Storage
+
+    Floating-point number values are stored directly inside a @ref basic_json
+    type.
+
+    @sa @ref number_integer_t -- type for number values (integer)
+
+    @sa @ref number_unsigned_t -- type for number values (unsigned integer)
+
+    @since version 1.0.0
+    */
+    using number_float_t = NumberFloatType;
+
+    /// @}
+
+  private:
+
+    /// helper for exception-safe object creation
+    template<typename T, typename... Args>
+    JSON_HEDLEY_RETURNS_NON_NULL
+    static T* create(Args&& ... args)
+    {
+        AllocatorType<T> alloc;
+        using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
+
+        auto deleter = [&](T * object)
+        {
+            AllocatorTraits::deallocate(alloc, object, 1);
+        };
+        std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
+        AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
+        assert(object != nullptr);
+        return object.release();
+    }
+
+    ////////////////////////
+    // JSON value storage //
+    ////////////////////////
+
+    /*!
+    @brief a JSON value
+
+    The actual storage for a JSON value of the @ref basic_json class. This
+    union combines the different storage types for the JSON value types
+    defined in @ref value_t.
+
+    JSON type | value_t type    | used type
+    --------- | --------------- | ------------------------
+    object    | object          | pointer to @ref object_t
+    array     | array           | pointer to @ref array_t
+    string    | string          | pointer to @ref string_t
+    boolean   | boolean         | @ref boolean_t
+    number    | number_integer  | @ref number_integer_t
+    number    | number_unsigned | @ref number_unsigned_t
+    number    | number_float    | @ref number_float_t
+    null      | null            | *no value is stored*
+
+    @note Variable-length types (objects, arrays, and strings) are stored as
+    pointers. The size of the union should not exceed 64 bits if the default
+    value types are used.
+
+    @since version 1.0.0
+    */
+    union json_value
+    {
+        /// object (stored with pointer to save storage)
+        object_t* object;
+        /// array (stored with pointer to save storage)
+        array_t* array;
+        /// string (stored with pointer to save storage)
+        string_t* string;
+        /// boolean
+        boolean_t boolean;
+        /// number (integer)
+        number_integer_t number_integer;
+        /// number (unsigned integer)
+        number_unsigned_t number_unsigned;
+        /// number (floating-point)
+        number_float_t number_float;
+
+        /// default constructor (for null values)
+        json_value() = default;
+        /// constructor for booleans
+        json_value(boolean_t v) noexcept : boolean(v) {}
+        /// constructor for numbers (integer)
+        json_value(number_integer_t v) noexcept : number_integer(v) {}
+        /// constructor for numbers (unsigned)
+        json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
+        /// constructor for numbers (floating-point)
+        json_value(number_float_t v) noexcept : number_float(v) {}
+        /// constructor for empty values of a given type
+        json_value(value_t t)
+        {
+            switch (t)
+            {
+                case value_t::object:
+                {
+                    object = create<object_t>();
+                    break;
+                }
+
+                case value_t::array:
+                {
+                    array = create<array_t>();
+                    break;
+                }
+
+                case value_t::string:
+                {
+                    string = create<string_t>("");
+                    break;
+                }
+
+                case value_t::boolean:
+                {
+                    boolean = boolean_t(false);
+                    break;
+                }
+
+                case value_t::number_integer:
+                {
+                    number_integer = number_integer_t(0);
+                    break;
+                }
+
+                case value_t::number_unsigned:
+                {
+                    number_unsigned = number_unsigned_t(0);
+                    break;
+                }
+
+                case value_t::number_float:
+                {
+                    number_float = number_float_t(0.0);
+                    break;
+                }
+
+                case value_t::null:
+                {
+                    object = nullptr;  // silence warning, see #821
+                    break;
+                }
+
+                default:
+                {
+                    object = nullptr;  // silence warning, see #821
+                    if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
+                    {
+                        JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.7.3")); // LCOV_EXCL_LINE
+                    }
+                    break;
+                }
+            }
+        }
+
+        /// constructor for strings
+        json_value(const string_t& value)
+        {
+            string = create<string_t>(value);
+        }
+
+        /// constructor for rvalue strings
+        json_value(string_t&& value)
+        {
+            string = create<string_t>(std::move(value));
+        }
+
+        /// constructor for objects
+        json_value(const object_t& value)
+        {
+            object = create<object_t>(value);
+        }
+
+        /// constructor for rvalue objects
+        json_value(object_t&& value)
+        {
+            object = create<object_t>(std::move(value));
+        }
+
+        /// constructor for arrays
+        json_value(const array_t& value)
+        {
+            array = create<array_t>(value);
+        }
+
+        /// constructor for rvalue arrays
+        json_value(array_t&& value)
+        {
+            array = create<array_t>(std::move(value));
+        }
+
+        void destroy(value_t t) noexcept
+        {
+            // flatten the current json_value to a heap-allocated stack
+            std::vector<basic_json> stack;
+
+            // move the top-level items to stack
+            if (t == value_t::array)
+            {
+                stack.reserve(array->size());
+                std::move(array->begin(), array->end(), std::back_inserter(stack));
+            }
+            else if (t == value_t::object)
+            {
+                stack.reserve(object->size());
+                for (auto&& it : *object)
+                {
+                    stack.push_back(std::move(it.second));
+                }
+            }
+
+            while (not stack.empty())
+            {
+                // move the last item to local variable to be processed
+                basic_json current_item(std::move(stack.back()));
+                stack.pop_back();
+
+                // if current_item is array/object, move
+                // its children to the stack to be processed later
+                if (current_item.is_array())
+                {
+                    std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(),
+                              std::back_inserter(stack));
+
+                    current_item.m_value.array->clear();
+                }
+                else if (current_item.is_object())
+                {
+                    for (auto&& it : *current_item.m_value.object)
+                    {
+                        stack.push_back(std::move(it.second));
+                    }
+
+                    current_item.m_value.object->clear();
+                }
+
+                // it's now safe that current_item get destructed
+                // since it doesn't have any children
+            }
+
+            switch (t)
+            {
+                case value_t::object:
+                {
+                    AllocatorType<object_t> alloc;
+                    std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
+                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
+                    break;
+                }
+
+                case value_t::array:
+                {
+                    AllocatorType<array_t> alloc;
+                    std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
+                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
+                    break;
+                }
+
+                case value_t::string:
+                {
+                    AllocatorType<string_t> alloc;
+                    std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
+                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
+                    break;
+                }
+
+                default:
+                {
+                    break;
+                }
+            }
+        }
+    };
+
+    /*!
+    @brief checks the class invariants
+
+    This function asserts the class invariants. It needs to be called at the
+    end of every constructor to make sure that created objects respect the
+    invariant. Furthermore, it has to be called each time the type of a JSON
+    value is changed, because the invariant expresses a relationship between
+    @a m_type and @a m_value.
+    */
+    void assert_invariant() const noexcept
+    {
+        assert(m_type != value_t::object or m_value.object != nullptr);
+        assert(m_type != value_t::array or m_value.array != nullptr);
+        assert(m_type != value_t::string or m_value.string != nullptr);
+    }
+
+  public:
+    //////////////////////////
+    // JSON parser callback //
+    //////////////////////////
+
+    /*!
+    @brief parser event types
+
+    The parser callback distinguishes the following events:
+    - `object_start`: the parser read `{` and started to process a JSON object
+    - `key`: the parser read a key of a value in an object
+    - `object_end`: the parser read `}` and finished processing a JSON object
+    - `array_start`: the parser read `[` and started to process a JSON array
+    - `array_end`: the parser read `]` and finished processing a JSON array
+    - `value`: the parser finished reading a JSON value
+
+    @image html callback_events.png "Example when certain parse events are triggered"
+
+    @sa @ref parser_callback_t for more information and examples
+    */
+    using parse_event_t = typename parser::parse_event_t;
+
+    /*!
+    @brief per-element parser callback type
+
+    With a parser callback function, the result of parsing a JSON text can be
+    influenced. When passed to @ref parse, it is called on certain events
+    (passed as @ref parse_event_t via parameter @a event) with a set recursion
+    depth @a depth and context JSON value @a parsed. The return value of the
+    callback function is a boolean indicating whether the element that emitted
+    the callback shall be kept or not.
+
+    We distinguish six scenarios (determined by the event type) in which the
+    callback function can be called. The following table describes the values
+    of the parameters @a depth, @a event, and @a parsed.
+
+    parameter @a event | description | parameter @a depth | parameter @a parsed
+    ------------------ | ----------- | ------------------ | -------------------
+    parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded
+    parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key
+    parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object
+    parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded
+    parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array
+    parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
+
+    @image html callback_events.png "Example when certain parse events are triggered"
+
+    Discarding a value (i.e., returning `false`) has different effects
+    depending on the context in which function was called:
+
+    - Discarded values in structured types are skipped. That is, the parser
+      will behave as if the discarded value was never read.
+    - In case a value outside a structured type is skipped, it is replaced
+      with `null`. This case happens if the top-level element is skipped.
+
+    @param[in] depth  the depth of the recursion during parsing
+
+    @param[in] event  an event of type parse_event_t indicating the context in
+    the callback function has been called
+
+    @param[in,out] parsed  the current intermediate parse result; note that
+    writing to this value has no effect for parse_event_t::key events
+
+    @return Whether the JSON value which called the function during parsing
+    should be kept (`true`) or not (`false`). In the latter case, it is either
+    skipped completely or replaced by an empty discarded object.
+
+    @sa @ref parse for examples
+
+    @since version 1.0.0
+    */
+    using parser_callback_t = typename parser::parser_callback_t;
+
+    //////////////////
+    // constructors //
+    //////////////////
+
+    /// @name constructors and destructors
+    /// Constructors of class @ref basic_json, copy/move constructor, copy
+    /// assignment, static functions creating objects, and the destructor.
+    /// @{
+
+    /*!
+    @brief create an empty value with a given type
+
+    Create an empty JSON value with a given type. The value will be default
+    initialized with an empty value which depends on the type:
+
+    Value type  | initial value
+    ----------- | -------------
+    null        | `null`
+    boolean     | `false`
+    string      | `""`
+    number      | `0`
+    object      | `{}`
+    array       | `[]`
+
+    @param[in] v  the type of the value to create
+
+    @complexity Constant.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes to any JSON value.
+
+    @liveexample{The following code shows the constructor for different @ref
+    value_t values,basic_json__value_t}
+
+    @sa @ref clear() -- restores the postcondition of this constructor
+
+    @since version 1.0.0
+    */
+    basic_json(const value_t v)
+        : m_type(v), m_value(v)
+    {
+        assert_invariant();
+    }
+
+    /*!
+    @brief create a null object
+
+    Create a `null` JSON value. It either takes a null pointer as parameter
+    (explicitly creating `null`) or no parameter (implicitly creating `null`).
+    The passed null pointer itself is not read -- it is only used to choose
+    the right constructor.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this constructor never throws
+    exceptions.
+
+    @liveexample{The following code shows the constructor with and without a
+    null pointer parameter.,basic_json__nullptr_t}
+
+    @since version 1.0.0
+    */
+    basic_json(std::nullptr_t = nullptr) noexcept
+        : basic_json(value_t::null)
+    {
+        assert_invariant();
+    }
+
+    /*!
+    @brief create a JSON value
+
+    This is a "catch all" constructor for all compatible JSON types; that is,
+    types for which a `to_json()` method exists. The constructor forwards the
+    parameter @a val to that method (to `json_serializer<U>::to_json` method
+    with `U = uncvref_t<CompatibleType>`, to be exact).
+
+    Template type @a CompatibleType includes, but is not limited to, the
+    following types:
+    - **arrays**: @ref array_t and all kinds of compatible containers such as
+      `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
+      `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
+      `std::multiset`, and `std::unordered_multiset` with a `value_type` from
+      which a @ref basic_json value can be constructed.
+    - **objects**: @ref object_t and all kinds of compatible associative
+      containers such as `std::map`, `std::unordered_map`, `std::multimap`,
+      and `std::unordered_multimap` with a `key_type` compatible to
+      @ref string_t and a `value_type` from which a @ref basic_json value can
+      be constructed.
+    - **strings**: @ref string_t, string literals, and all compatible string
+      containers can be used.
+    - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
+      @ref number_float_t, and all convertible number types such as `int`,
+      `size_t`, `int64_t`, `float` or `double` can be used.
+    - **boolean**: @ref boolean_t / `bool` can be used.
+
+    See the examples below.
+
+    @tparam CompatibleType a type such that:
+    - @a CompatibleType is not derived from `std::istream`,
+    - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
+         constructors),
+    - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
+    - @a CompatibleType is not a @ref basic_json nested type (e.g.,
+         @ref json_pointer, @ref iterator, etc ...)
+    - @ref @ref json_serializer<U> has a
+         `to_json(basic_json_t&, CompatibleType&&)` method
+
+    @tparam U = `uncvref_t<CompatibleType>`
+
+    @param[in] val the value to be forwarded to the respective constructor
+
+    @complexity Usually linear in the size of the passed @a val, also
+                depending on the implementation of the called `to_json()`
+                method.
+
+    @exceptionsafety Depends on the called constructor. For types directly
+    supported by the library (i.e., all types for which no `to_json()` function
+    was provided), strong guarantee holds: if an exception is thrown, there are
+    no changes to any JSON value.
+
+    @liveexample{The following code shows the constructor with several
+    compatible types.,basic_json__CompatibleType}
+
+    @since version 2.1.0
+    */
+    template <typename CompatibleType,
+              typename U = detail::uncvref_t<CompatibleType>,
+              detail::enable_if_t<
+                  not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
+    basic_json(CompatibleType && val) noexcept(noexcept(
+                JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
+                                           std::forward<CompatibleType>(val))))
+    {
+        JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
+        assert_invariant();
+    }
+
+    /*!
+    @brief create a JSON value from an existing one
+
+    This is a constructor for existing @ref basic_json types.
+    It does not hijack copy/move constructors, since the parameter has different
+    template arguments than the current ones.
+
+    The constructor tries to convert the internal @ref m_value of the parameter.
+
+    @tparam BasicJsonType a type such that:
+    - @a BasicJsonType is a @ref basic_json type.
+    - @a BasicJsonType has different template arguments than @ref basic_json_t.
+
+    @param[in] val the @ref basic_json value to be converted.
+
+    @complexity Usually linear in the size of the passed @a val, also
+                depending on the implementation of the called `to_json()`
+                method.
+
+    @exceptionsafety Depends on the called constructor. For types directly
+    supported by the library (i.e., all types for which no `to_json()` function
+    was provided), strong guarantee holds: if an exception is thrown, there are
+    no changes to any JSON value.
+
+    @since version 3.2.0
+    */
+    template <typename BasicJsonType,
+              detail::enable_if_t<
+                  detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
+    basic_json(const BasicJsonType& val)
+    {
+        using other_boolean_t = typename BasicJsonType::boolean_t;
+        using other_number_float_t = typename BasicJsonType::number_float_t;
+        using other_number_integer_t = typename BasicJsonType::number_integer_t;
+        using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+        using other_string_t = typename BasicJsonType::string_t;
+        using other_object_t = typename BasicJsonType::object_t;
+        using other_array_t = typename BasicJsonType::array_t;
+
+        switch (val.type())
+        {
+            case value_t::boolean:
+                JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
+                break;
+            case value_t::number_float:
+                JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
+                break;
+            case value_t::number_integer:
+                JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
+                break;
+            case value_t::number_unsigned:
+                JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
+                break;
+            case value_t::string:
+                JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
+                break;
+            case value_t::object:
+                JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
+                break;
+            case value_t::array:
+                JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
+                break;
+            case value_t::null:
+                *this = nullptr;
+                break;
+            case value_t::discarded:
+                m_type = value_t::discarded;
+                break;
+            default:            // LCOV_EXCL_LINE
+                assert(false);  // LCOV_EXCL_LINE
+        }
+        assert_invariant();
+    }
+
+    /*!
+    @brief create a container (array or object) from an initializer list
+
+    Creates a JSON value of type array or object from the passed initializer
+    list @a init. In case @a type_deduction is `true` (default), the type of
+    the JSON value to be created is deducted from the initializer list @a init
+    according to the following rules:
+
+    1. If the list is empty, an empty JSON object value `{}` is created.
+    2. If the list consists of pairs whose first element is a string, a JSON
+       object value is created where the first elements of the pairs are
+       treated as keys and the second elements are as values.
+    3. In all other cases, an array is created.
+
+    The rules aim to create the best fit between a C++ initializer list and
+    JSON values. The rationale is as follows:
+
+    1. The empty initializer list is written as `{}` which is exactly an empty
+       JSON object.
+    2. C++ has no way of describing mapped types other than to list a list of
+       pairs. As JSON requires that keys must be of type string, rule 2 is the
+       weakest constraint one can pose on initializer lists to interpret them
+       as an object.
+    3. In all other cases, the initializer list could not be interpreted as
+       JSON object type, so interpreting it as JSON array type is safe.
+
+    With the rules described above, the following JSON values cannot be
+    expressed by an initializer list:
+
+    - the empty array (`[]`): use @ref array(initializer_list_t)
+      with an empty initializer list in this case
+    - arrays whose elements satisfy rule 2: use @ref
+      array(initializer_list_t) with the same initializer list
+      in this case
+
+    @note When used without parentheses around an empty initializer list, @ref
+    basic_json() is called instead of this function, yielding the JSON null
+    value.
+
+    @param[in] init  initializer list with JSON values
+
+    @param[in] type_deduction internal parameter; when set to `true`, the type
+    of the JSON value is deducted from the initializer list @a init; when set
+    to `false`, the type provided via @a manual_type is forced. This mode is
+    used by the functions @ref array(initializer_list_t) and
+    @ref object(initializer_list_t).
+
+    @param[in] manual_type internal parameter; when @a type_deduction is set
+    to `false`, the created JSON value will use the provided type (only @ref
+    value_t::array and @ref value_t::object are valid); when @a type_deduction
+    is set to `true`, this parameter has no effect
+
+    @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
+    `value_t::object`, but @a init contains an element which is not a pair
+    whose first element is a string. In this case, the constructor could not
+    create an object. If @a type_deduction would have be `true`, an array
+    would have been created. See @ref object(initializer_list_t)
+    for an example.
+
+    @complexity Linear in the size of the initializer list @a init.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes to any JSON value.
+
+    @liveexample{The example below shows how JSON values are created from
+    initializer lists.,basic_json__list_init_t}
+
+    @sa @ref array(initializer_list_t) -- create a JSON array
+    value from an initializer list
+    @sa @ref object(initializer_list_t) -- create a JSON object
+    value from an initializer list
+
+    @since version 1.0.0
+    */
+    basic_json(initializer_list_t init,
+               bool type_deduction = true,
+               value_t manual_type = value_t::array)
+    {
+        // check if each element is an array with two elements whose first
+        // element is a string
+        bool is_an_object = std::all_of(init.begin(), init.end(),
+                                        [](const detail::json_ref<basic_json>& element_ref)
+        {
+            return element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string();
+        });
+
+        // adjust type if type deduction is not wanted
+        if (not type_deduction)
+        {
+            // if array is wanted, do not create an object though possible
+            if (manual_type == value_t::array)
+            {
+                is_an_object = false;
+            }
+
+            // if object is wanted but impossible, throw an exception
+            if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object and not is_an_object))
+            {
+                JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
+            }
+        }
+
+        if (is_an_object)
+        {
+            // the initializer list is a list of pairs -> create object
+            m_type = value_t::object;
+            m_value = value_t::object;
+
+            std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
+            {
+                auto element = element_ref.moved_or_copied();
+                m_value.object->emplace(
+                    std::move(*((*element.m_value.array)[0].m_value.string)),
+                    std::move((*element.m_value.array)[1]));
+            });
+        }
+        else
+        {
+            // the initializer list describes an array -> create array
+            m_type = value_t::array;
+            m_value.array = create<array_t>(init.begin(), init.end());
+        }
+
+        assert_invariant();
+    }
+
+    /*!
+    @brief explicitly create an array from an initializer list
+
+    Creates a JSON array value from a given initializer list. That is, given a
+    list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
+    initializer list is empty, the empty array `[]` is created.
+
+    @note This function is only needed to express two edge cases that cannot
+    be realized with the initializer list constructor (@ref
+    basic_json(initializer_list_t, bool, value_t)). These cases
+    are:
+    1. creating an array whose elements are all pairs whose first element is a
+    string -- in this case, the initializer list constructor would create an
+    object, taking the first elements as keys
+    2. creating an empty array -- passing the empty initializer list to the
+    initializer list constructor yields an empty object
+
+    @param[in] init  initializer list with JSON values to create an array from
+    (optional)
+
+    @return JSON array value
+
+    @complexity Linear in the size of @a init.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes to any JSON value.
+
+    @liveexample{The following code shows an example for the `array`
+    function.,array}
+
+    @sa @ref basic_json(initializer_list_t, bool, value_t) --
+    create a JSON value from an initializer list
+    @sa @ref object(initializer_list_t) -- create a JSON object
+    value from an initializer list
+
+    @since version 1.0.0
+    */
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json array(initializer_list_t init = {})
+    {
+        return basic_json(init, false, value_t::array);
+    }
+
+    /*!
+    @brief explicitly create an object from an initializer list
+
+    Creates a JSON object value from a given initializer list. The initializer
+    lists elements must be pairs, and their first elements must be strings. If
+    the initializer list is empty, the empty object `{}` is created.
+
+    @note This function is only added for symmetry reasons. In contrast to the
+    related function @ref array(initializer_list_t), there are
+    no cases which can only be expressed by this function. That is, any
+    initializer list @a init can also be passed to the initializer list
+    constructor @ref basic_json(initializer_list_t, bool, value_t).
+
+    @param[in] init  initializer list to create an object from (optional)
+
+    @return JSON object value
+
+    @throw type_error.301 if @a init is not a list of pairs whose first
+    elements are strings. In this case, no object can be created. When such a
+    value is passed to @ref basic_json(initializer_list_t, bool, value_t),
+    an array would have been created from the passed initializer list @a init.
+    See example below.
+
+    @complexity Linear in the size of @a init.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes to any JSON value.
+
+    @liveexample{The following code shows an example for the `object`
+    function.,object}
+
+    @sa @ref basic_json(initializer_list_t, bool, value_t) --
+    create a JSON value from an initializer list
+    @sa @ref array(initializer_list_t) -- create a JSON array
+    value from an initializer list
+
+    @since version 1.0.0
+    */
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json object(initializer_list_t init = {})
+    {
+        return basic_json(init, false, value_t::object);
+    }
+
+    /*!
+    @brief construct an array with count copies of given value
+
+    Constructs a JSON array value by creating @a cnt copies of a passed value.
+    In case @a cnt is `0`, an empty array is created.
+
+    @param[in] cnt  the number of JSON copies of @a val to create
+    @param[in] val  the JSON value to copy
+
+    @post `std::distance(begin(),end()) == cnt` holds.
+
+    @complexity Linear in @a cnt.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes to any JSON value.
+
+    @liveexample{The following code shows examples for the @ref
+    basic_json(size_type\, const basic_json&)
+    constructor.,basic_json__size_type_basic_json}
+
+    @since version 1.0.0
+    */
+    basic_json(size_type cnt, const basic_json& val)
+        : m_type(value_t::array)
+    {
+        m_value.array = create<array_t>(cnt, val);
+        assert_invariant();
+    }
+
+    /*!
+    @brief construct a JSON container given an iterator range
+
+    Constructs the JSON value with the contents of the range `[first, last)`.
+    The semantics depends on the different types a JSON value can have:
+    - In case of a null type, invalid_iterator.206 is thrown.
+    - In case of other primitive types (number, boolean, or string), @a first
+      must be `begin()` and @a last must be `end()`. In this case, the value is
+      copied. Otherwise, invalid_iterator.204 is thrown.
+    - In case of structured types (array, object), the constructor behaves as
+      similar versions for `std::vector` or `std::map`; that is, a JSON array
+      or object is constructed from the values in the range.
+
+    @tparam InputIT an input iterator type (@ref iterator or @ref
+    const_iterator)
+
+    @param[in] first begin of the range to copy from (included)
+    @param[in] last end of the range to copy from (excluded)
+
+    @pre Iterators @a first and @a last must be initialized. **This
+         precondition is enforced with an assertion (see warning).** If
+         assertions are switched off, a violation of this precondition yields
+         undefined behavior.
+
+    @pre Range `[first, last)` is valid. Usually, this precondition cannot be
+         checked efficiently. Only certain edge cases are detected; see the
+         description of the exceptions below. A violation of this precondition
+         yields undefined behavior.
+
+    @warning A precondition is enforced with a runtime assertion that will
+             result in calling `std::abort` if this precondition is not met.
+             Assertions can be disabled by defining `NDEBUG` at compile time.
+             See https://en.cppreference.com/w/cpp/error/assert for more
+             information.
+
+    @throw invalid_iterator.201 if iterators @a first and @a last are not
+    compatible (i.e., do not belong to the same JSON value). In this case,
+    the range `[first, last)` is undefined.
+    @throw invalid_iterator.204 if iterators @a first and @a last belong to a
+    primitive type (number, boolean, or string), but @a first does not point
+    to the first element any more. In this case, the range `[first, last)` is
+    undefined. See example code below.
+    @throw invalid_iterator.206 if iterators @a first and @a last belong to a
+    null value. In this case, the range `[first, last)` is undefined.
+
+    @complexity Linear in distance between @a first and @a last.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes to any JSON value.
+
+    @liveexample{The example below shows several ways to create JSON values by
+    specifying a subrange with iterators.,basic_json__InputIt_InputIt}
+
+    @since version 1.0.0
+    */
+    template<class InputIT, typename std::enable_if<
+                 std::is_same<InputIT, typename basic_json_t::iterator>::value or
+                 std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
+    basic_json(InputIT first, InputIT last)
+    {
+        assert(first.m_object != nullptr);
+        assert(last.m_object != nullptr);
+
+        // make sure iterator fits the current value
+        if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
+        }
+
+        // copy type from first iterator
+        m_type = first.m_object->m_type;
+
+        // check if iterator range is complete for primitive values
+        switch (m_type)
+        {
+            case value_t::boolean:
+            case value_t::number_float:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::string:
+            {
+                if (JSON_HEDLEY_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
+                                         or not last.m_it.primitive_iterator.is_end()))
+                {
+                    JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
+                }
+                break;
+            }
+
+            default:
+                break;
+        }
+
+        switch (m_type)
+        {
+            case value_t::number_integer:
+            {
+                m_value.number_integer = first.m_object->m_value.number_integer;
+                break;
+            }
+
+            case value_t::number_unsigned:
+            {
+                m_value.number_unsigned = first.m_object->m_value.number_unsigned;
+                break;
+            }
+
+            case value_t::number_float:
+            {
+                m_value.number_float = first.m_object->m_value.number_float;
+                break;
+            }
+
+            case value_t::boolean:
+            {
+                m_value.boolean = first.m_object->m_value.boolean;
+                break;
+            }
+
+            case value_t::string:
+            {
+                m_value = *first.m_object->m_value.string;
+                break;
+            }
+
+            case value_t::object:
+            {
+                m_value.object = create<object_t>(first.m_it.object_iterator,
+                                                  last.m_it.object_iterator);
+                break;
+            }
+
+            case value_t::array:
+            {
+                m_value.array = create<array_t>(first.m_it.array_iterator,
+                                                last.m_it.array_iterator);
+                break;
+            }
+
+            default:
+                JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
+                                                    std::string(first.m_object->type_name())));
+        }
+
+        assert_invariant();
+    }
+
+
+    ///////////////////////////////////////
+    // other constructors and destructor //
+    ///////////////////////////////////////
+
+    /// @private
+    basic_json(const detail::json_ref<basic_json>& ref)
+        : basic_json(ref.moved_or_copied())
+    {}
+
+    /*!
+    @brief copy constructor
+
+    Creates a copy of a given JSON value.
+
+    @param[in] other  the JSON value to copy
+
+    @post `*this == other`
+
+    @complexity Linear in the size of @a other.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes to any JSON value.
+
+    @requirement This function helps `basic_json` satisfying the
+    [Container](https://en.cppreference.com/w/cpp/named_req/Container)
+    requirements:
+    - The complexity is linear.
+    - As postcondition, it holds: `other == basic_json(other)`.
+
+    @liveexample{The following code shows an example for the copy
+    constructor.,basic_json__basic_json}
+
+    @since version 1.0.0
+    */
+    basic_json(const basic_json& other)
+        : m_type(other.m_type)
+    {
+        // check of passed value is valid
+        other.assert_invariant();
+
+        switch (m_type)
+        {
+            case value_t::object:
+            {
+                m_value = *other.m_value.object;
+                break;
+            }
+
+            case value_t::array:
+            {
+                m_value = *other.m_value.array;
+                break;
+            }
+
+            case value_t::string:
+            {
+                m_value = *other.m_value.string;
+                break;
+            }
+
+            case value_t::boolean:
+            {
+                m_value = other.m_value.boolean;
+                break;
+            }
+
+            case value_t::number_integer:
+            {
+                m_value = other.m_value.number_integer;
+                break;
+            }
+
+            case value_t::number_unsigned:
+            {
+                m_value = other.m_value.number_unsigned;
+                break;
+            }
+
+            case value_t::number_float:
+            {
+                m_value = other.m_value.number_float;
+                break;
+            }
+
+            default:
+                break;
+        }
+
+        assert_invariant();
+    }
+
+    /*!
+    @brief move constructor
+
+    Move constructor. Constructs a JSON value with the contents of the given
+    value @a other using move semantics. It "steals" the resources from @a
+    other and leaves it as JSON null value.
+
+    @param[in,out] other  value to move to this object
+
+    @post `*this` has the same value as @a other before the call.
+    @post @a other is a JSON null value.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this constructor never throws
+    exceptions.
+
+    @requirement This function helps `basic_json` satisfying the
+    [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
+    requirements.
+
+    @liveexample{The code below shows the move constructor explicitly called
+    via std::move.,basic_json__moveconstructor}
+
+    @since version 1.0.0
+    */
+    basic_json(basic_json&& other) noexcept
+        : m_type(std::move(other.m_type)),
+          m_value(std::move(other.m_value))
+    {
+        // check that passed value is valid
+        other.assert_invariant();
+
+        // invalidate payload
+        other.m_type = value_t::null;
+        other.m_value = {};
+
+        assert_invariant();
+    }
+
+    /*!
+    @brief copy assignment
+
+    Copy assignment operator. Copies a JSON value via the "copy and swap"
+    strategy: It is expressed in terms of the copy constructor, destructor,
+    and the `swap()` member function.
+
+    @param[in] other  value to copy from
+
+    @complexity Linear.
+
+    @requirement This function helps `basic_json` satisfying the
+    [Container](https://en.cppreference.com/w/cpp/named_req/Container)
+    requirements:
+    - The complexity is linear.
+
+    @liveexample{The code below shows and example for the copy assignment. It
+    creates a copy of value `a` which is then swapped with `b`. Finally\, the
+    copy of `a` (which is the null value after the swap) is
+    destroyed.,basic_json__copyassignment}
+
+    @since version 1.0.0
+    */
+    basic_json& operator=(basic_json other) noexcept (
+        std::is_nothrow_move_constructible<value_t>::value and
+        std::is_nothrow_move_assignable<value_t>::value and
+        std::is_nothrow_move_constructible<json_value>::value and
+        std::is_nothrow_move_assignable<json_value>::value
+    )
+    {
+        // check that passed value is valid
+        other.assert_invariant();
+
+        using std::swap;
+        swap(m_type, other.m_type);
+        swap(m_value, other.m_value);
+
+        assert_invariant();
+        return *this;
+    }
+
+    /*!
+    @brief destructor
+
+    Destroys the JSON value and frees all allocated memory.
+
+    @complexity Linear.
+
+    @requirement This function helps `basic_json` satisfying the
+    [Container](https://en.cppreference.com/w/cpp/named_req/Container)
+    requirements:
+    - The complexity is linear.
+    - All stored elements are destroyed and all memory is freed.
+
+    @since version 1.0.0
+    */
+    ~basic_json() noexcept
+    {
+        assert_invariant();
+        m_value.destroy(m_type);
+    }
+
+    /// @}
+
+  public:
+    ///////////////////////
+    // object inspection //
+    ///////////////////////
+
+    /// @name object inspection
+    /// Functions to inspect the type of a JSON value.
+    /// @{
+
+    /*!
+    @brief serialization
+
+    Serialization function for JSON values. The function tries to mimic
+    Python's `json.dumps()` function, and currently supports its @a indent
+    and @a ensure_ascii parameters.
+
+    @param[in] indent If indent is nonnegative, then array elements and object
+    members will be pretty-printed with that indent level. An indent level of
+    `0` will only insert newlines. `-1` (the default) selects the most compact
+    representation.
+    @param[in] indent_char The character to use for indentation if @a indent is
+    greater than `0`. The default is ` ` (space).
+    @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
+    in the output are escaped with `\uXXXX` sequences, and the result consists
+    of ASCII characters only.
+    @param[in] error_handler  how to react on decoding errors; there are three
+    possible values: `strict` (throws and exception in case a decoding error
+    occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
+    and `ignore` (ignore invalid UTF-8 sequences during serialization).
+
+    @return string containing the serialization of the JSON value
+
+    @throw type_error.316 if a string stored inside the JSON value is not
+                          UTF-8 encoded
+
+    @complexity Linear.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes in the JSON value.
+
+    @liveexample{The following example shows the effect of different @a indent\,
+    @a indent_char\, and @a ensure_ascii parameters to the result of the
+    serialization.,dump}
+
+    @see https://docs.python.org/2/library/json.html#json.dump
+
+    @since version 1.0.0; indentation character @a indent_char, option
+           @a ensure_ascii and exceptions added in version 3.0.0; error
+           handlers added in version 3.4.0.
+    */
+    string_t dump(const int indent = -1,
+                  const char indent_char = ' ',
+                  const bool ensure_ascii = false,
+                  const error_handler_t error_handler = error_handler_t::strict) const
+    {
+        string_t result;
+        serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
+
+        if (indent >= 0)
+        {
+            s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
+        }
+        else
+        {
+            s.dump(*this, false, ensure_ascii, 0);
+        }
+
+        return result;
+    }
+
+    /*!
+    @brief return the type of the JSON value (explicit)
+
+    Return the type of the JSON value as a value from the @ref value_t
+    enumeration.
+
+    @return the type of the JSON value
+            Value type                | return value
+            ------------------------- | -------------------------
+            null                      | value_t::null
+            boolean                   | value_t::boolean
+            string                    | value_t::string
+            number (integer)          | value_t::number_integer
+            number (unsigned integer) | value_t::number_unsigned
+            number (floating-point)   | value_t::number_float
+            object                    | value_t::object
+            array                     | value_t::array
+            discarded                 | value_t::discarded
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies `type()` for all JSON
+    types.,type}
+
+    @sa @ref operator value_t() -- return the type of the JSON value (implicit)
+    @sa @ref type_name() -- return the type as string
+
+    @since version 1.0.0
+    */
+    constexpr value_t type() const noexcept
+    {
+        return m_type;
+    }
+
+    /*!
+    @brief return whether type is primitive
+
+    This function returns true if and only if the JSON type is primitive
+    (string, number, boolean, or null).
+
+    @return `true` if type is primitive (string, number, boolean, or null),
+    `false` otherwise.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies `is_primitive()` for all JSON
+    types.,is_primitive}
+
+    @sa @ref is_structured() -- returns whether JSON value is structured
+    @sa @ref is_null() -- returns whether JSON value is `null`
+    @sa @ref is_string() -- returns whether JSON value is a string
+    @sa @ref is_boolean() -- returns whether JSON value is a boolean
+    @sa @ref is_number() -- returns whether JSON value is a number
+
+    @since version 1.0.0
+    */
+    constexpr bool is_primitive() const noexcept
+    {
+        return is_null() or is_string() or is_boolean() or is_number();
+    }
+
+    /*!
+    @brief return whether type is structured
+
+    This function returns true if and only if the JSON type is structured
+    (array or object).
+
+    @return `true` if type is structured (array or object), `false` otherwise.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies `is_structured()` for all JSON
+    types.,is_structured}
+
+    @sa @ref is_primitive() -- returns whether value is primitive
+    @sa @ref is_array() -- returns whether value is an array
+    @sa @ref is_object() -- returns whether value is an object
+
+    @since version 1.0.0
+    */
+    constexpr bool is_structured() const noexcept
+    {
+        return is_array() or is_object();
+    }
+
+    /*!
+    @brief return whether value is null
+
+    This function returns true if and only if the JSON value is null.
+
+    @return `true` if type is null, `false` otherwise.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies `is_null()` for all JSON
+    types.,is_null}
+
+    @since version 1.0.0
+    */
+    constexpr bool is_null() const noexcept
+    {
+        return m_type == value_t::null;
+    }
+
+    /*!
+    @brief return whether value is a boolean
+
+    This function returns true if and only if the JSON value is a boolean.
+
+    @return `true` if type is boolean, `false` otherwise.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies `is_boolean()` for all JSON
+    types.,is_boolean}
+
+    @since version 1.0.0
+    */
+    constexpr bool is_boolean() const noexcept
+    {
+        return m_type == value_t::boolean;
+    }
+
+    /*!
+    @brief return whether value is a number
+
+    This function returns true if and only if the JSON value is a number. This
+    includes both integer (signed and unsigned) and floating-point values.
+
+    @return `true` if type is number (regardless whether integer, unsigned
+    integer or floating-type), `false` otherwise.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies `is_number()` for all JSON
+    types.,is_number}
+
+    @sa @ref is_number_integer() -- check if value is an integer or unsigned
+    integer number
+    @sa @ref is_number_unsigned() -- check if value is an unsigned integer
+    number
+    @sa @ref is_number_float() -- check if value is a floating-point number
+
+    @since version 1.0.0
+    */
+    constexpr bool is_number() const noexcept
+    {
+        return is_number_integer() or is_number_float();
+    }
+
+    /*!
+    @brief return whether value is an integer number
+
+    This function returns true if and only if the JSON value is a signed or
+    unsigned integer number. This excludes floating-point values.
+
+    @return `true` if type is an integer or unsigned integer number, `false`
+    otherwise.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies `is_number_integer()` for all
+    JSON types.,is_number_integer}
+
+    @sa @ref is_number() -- check if value is a number
+    @sa @ref is_number_unsigned() -- check if value is an unsigned integer
+    number
+    @sa @ref is_number_float() -- check if value is a floating-point number
+
+    @since version 1.0.0
+    */
+    constexpr bool is_number_integer() const noexcept
+    {
+        return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
+    }
+
+    /*!
+    @brief return whether value is an unsigned integer number
+
+    This function returns true if and only if the JSON value is an unsigned
+    integer number. This excludes floating-point and signed integer values.
+
+    @return `true` if type is an unsigned integer number, `false` otherwise.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies `is_number_unsigned()` for all
+    JSON types.,is_number_unsigned}
+
+    @sa @ref is_number() -- check if value is a number
+    @sa @ref is_number_integer() -- check if value is an integer or unsigned
+    integer number
+    @sa @ref is_number_float() -- check if value is a floating-point number
+
+    @since version 2.0.0
+    */
+    constexpr bool is_number_unsigned() const noexcept
+    {
+        return m_type == value_t::number_unsigned;
+    }
+
+    /*!
+    @brief return whether value is a floating-point number
+
+    This function returns true if and only if the JSON value is a
+    floating-point number. This excludes signed and unsigned integer values.
+
+    @return `true` if type is a floating-point number, `false` otherwise.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies `is_number_float()` for all
+    JSON types.,is_number_float}
+
+    @sa @ref is_number() -- check if value is number
+    @sa @ref is_number_integer() -- check if value is an integer number
+    @sa @ref is_number_unsigned() -- check if value is an unsigned integer
+    number
+
+    @since version 1.0.0
+    */
+    constexpr bool is_number_float() const noexcept
+    {
+        return m_type == value_t::number_float;
+    }
+
+    /*!
+    @brief return whether value is an object
+
+    This function returns true if and only if the JSON value is an object.
+
+    @return `true` if type is object, `false` otherwise.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies `is_object()` for all JSON
+    types.,is_object}
+
+    @since version 1.0.0
+    */
+    constexpr bool is_object() const noexcept
+    {
+        return m_type == value_t::object;
+    }
+
+    /*!
+    @brief return whether value is an array
+
+    This function returns true if and only if the JSON value is an array.
+
+    @return `true` if type is array, `false` otherwise.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies `is_array()` for all JSON
+    types.,is_array}
+
+    @since version 1.0.0
+    */
+    constexpr bool is_array() const noexcept
+    {
+        return m_type == value_t::array;
+    }
+
+    /*!
+    @brief return whether value is a string
+
+    This function returns true if and only if the JSON value is a string.
+
+    @return `true` if type is string, `false` otherwise.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies `is_string()` for all JSON
+    types.,is_string}
+
+    @since version 1.0.0
+    */
+    constexpr bool is_string() const noexcept
+    {
+        return m_type == value_t::string;
+    }
+
+    /*!
+    @brief return whether value is discarded
+
+    This function returns true if and only if the JSON value was discarded
+    during parsing with a callback function (see @ref parser_callback_t).
+
+    @note This function will always be `false` for JSON values after parsing.
+    That is, discarded values can only occur during parsing, but will be
+    removed when inside a structured value or replaced by null in other cases.
+
+    @return `true` if type is discarded, `false` otherwise.
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies `is_discarded()` for all JSON
+    types.,is_discarded}
+
+    @since version 1.0.0
+    */
+    constexpr bool is_discarded() const noexcept
+    {
+        return m_type == value_t::discarded;
+    }
+
+    /*!
+    @brief return the type of the JSON value (implicit)
+
+    Implicitly return the type of the JSON value as a value from the @ref
+    value_t enumeration.
+
+    @return the type of the JSON value
+
+    @complexity Constant.
+
+    @exceptionsafety No-throw guarantee: this member function never throws
+    exceptions.
+
+    @liveexample{The following code exemplifies the @ref value_t operator for
+    all JSON types.,operator__value_t}
+
+    @sa @ref type() -- return the type of the JSON value (explicit)
+    @sa @ref type_name() -- return the type as string
+
+    @since version 1.0.0
+    */
+    constexpr operator value_t() const noexcept
+    {
+        return m_type;
+    }
+
+    /// @}
+
+  private:
+    //////////////////
+    // value access //
+    //////////////////
+
+    /// get a boolean (explicit)
+    boolean_t get_impl(boolean_t* /*unused*/) const
+    {
+        if (JSON_HEDLEY_LIKELY(is_boolean()))
+        {
+            return m_value.boolean;
+        }
+
+        JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
+    }
+
+    /// get a pointer to the value (object)
+    object_t* get_impl_ptr(object_t* /*unused*/) noexcept
+    {
+        return is_object() ? m_value.object : nullptr;
+    }
+
+    /// get a pointer to the value (object)
+    constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
+    {
+        return is_object() ? m_value.object : nullptr;
+    }
+
+    /// get a pointer to the value (array)
+    array_t* get_impl_ptr(array_t* /*unused*/) noexcept
+    {
+        return is_array() ? m_value.array : nullptr;
+    }
+
+    /// get a pointer to the value (array)
+    constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
+    {
+        return is_array() ? m_value.array : nullptr;
+    }
+
+    /// get a pointer to the value (string)
+    string_t* get_impl_ptr(string_t* /*unused*/) noexcept
+    {
+        return is_string() ? m_value.string : nullptr;
+    }
+
+    /// get a pointer to the value (string)
+    constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
+    {
+        return is_string() ? m_value.string : nullptr;
+    }
+
+    /// get a pointer to the value (boolean)
+    boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
+    {
+        return is_boolean() ? &m_value.boolean : nullptr;
+    }
+
+    /// get a pointer to the value (boolean)
+    constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
+    {
+        return is_boolean() ? &m_value.boolean : nullptr;
+    }
+
+    /// get a pointer to the value (integer number)
+    number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
+    {
+        return is_number_integer() ? &m_value.number_integer : nullptr;
+    }
+
+    /// get a pointer to the value (integer number)
+    constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
+    {
+        return is_number_integer() ? &m_value.number_integer : nullptr;
+    }
+
+    /// get a pointer to the value (unsigned number)
+    number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
+    {
+        return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
+    }
+
+    /// get a pointer to the value (unsigned number)
+    constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
+    {
+        return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
+    }
+
+    /// get a pointer to the value (floating-point number)
+    number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
+    {
+        return is_number_float() ? &m_value.number_float : nullptr;
+    }
+
+    /// get a pointer to the value (floating-point number)
+    constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
+    {
+        return is_number_float() ? &m_value.number_float : nullptr;
+    }
+
+    /*!
+    @brief helper function to implement get_ref()
+
+    This function helps to implement get_ref() without code duplication for
+    const and non-const overloads
+
+    @tparam ThisType will be deduced as `basic_json` or `const basic_json`
+
+    @throw type_error.303 if ReferenceType does not match underlying value
+    type of the current JSON
+    */
+    template<typename ReferenceType, typename ThisType>
+    static ReferenceType get_ref_impl(ThisType& obj)
+    {
+        // delegate the call to get_ptr<>()
+        auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
+
+        if (JSON_HEDLEY_LIKELY(ptr != nullptr))
+        {
+            return *ptr;
+        }
+
+        JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
+    }
+
+  public:
+    /// @name value access
+    /// Direct access to the stored value of a JSON value.
+    /// @{
+
+    /*!
+    @brief get special-case overload
+
+    This overloads avoids a lot of template boilerplate, it can be seen as the
+    identity method
+
+    @tparam BasicJsonType == @ref basic_json
+
+    @return a copy of *this
+
+    @complexity Constant.
+
+    @since version 2.1.0
+    */
+    template<typename BasicJsonType, detail::enable_if_t<
+                 std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
+                 int> = 0>
+    basic_json get() const
+    {
+        return *this;
+    }
+
+    /*!
+    @brief get special-case overload
+
+    This overloads converts the current @ref basic_json in a different
+    @ref basic_json type
+
+    @tparam BasicJsonType == @ref basic_json
+
+    @return a copy of *this, converted into @tparam BasicJsonType
+
+    @complexity Depending on the implementation of the called `from_json()`
+                method.
+
+    @since version 3.2.0
+    */
+    template<typename BasicJsonType, detail::enable_if_t<
+                 not std::is_same<BasicJsonType, basic_json>::value and
+                 detail::is_basic_json<BasicJsonType>::value, int> = 0>
+    BasicJsonType get() const
+    {
+        return *this;
+    }
+
+    /*!
+    @brief get a value (explicit)
+
+    Explicit type conversion between the JSON value and a compatible value
+    which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
+    and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
+    The value is converted by calling the @ref json_serializer<ValueType>
+    `from_json()` method.
+
+    The function is equivalent to executing
+    @code {.cpp}
+    ValueType ret;
+    JSONSerializer<ValueType>::from_json(*this, ret);
+    return ret;
+    @endcode
+
+    This overloads is chosen if:
+    - @a ValueType is not @ref basic_json,
+    - @ref json_serializer<ValueType> has a `from_json()` method of the form
+      `void from_json(const basic_json&, ValueType&)`, and
+    - @ref json_serializer<ValueType> does not have a `from_json()` method of
+      the form `ValueType from_json(const basic_json&)`
+
+    @tparam ValueTypeCV the provided value type
+    @tparam ValueType the returned value type
+
+    @return copy of the JSON value, converted to @a ValueType
+
+    @throw what @ref json_serializer<ValueType> `from_json()` method throws
+
+    @liveexample{The example below shows several conversions from JSON values
+    to other types. There a few things to note: (1) Floating-point numbers can
+    be converted to integers\, (2) A JSON array can be converted to a standard
+    `std::vector<short>`\, (3) A JSON object can be converted to C++
+    associative containers such as `std::unordered_map<std::string\,
+    json>`.,get__ValueType_const}
+
+    @since version 2.1.0
+    */
+    template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
+             detail::enable_if_t <
+                 not detail::is_basic_json<ValueType>::value and
+                 detail::has_from_json<basic_json_t, ValueType>::value and
+                 not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
+                 int> = 0>
+    ValueType get() const noexcept(noexcept(
+                                       JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
+    {
+        // we cannot static_assert on ValueTypeCV being non-const, because
+        // there is support for get<const basic_json_t>(), which is why we
+        // still need the uncvref
+        static_assert(not std::is_reference<ValueTypeCV>::value,
+                      "get() cannot be used with reference types, you might want to use get_ref()");
+        static_assert(std::is_default_constructible<ValueType>::value,
+                      "types must be DefaultConstructible when used with get()");
+
+        ValueType ret;
+        JSONSerializer<ValueType>::from_json(*this, ret);
+        return ret;
+    }
+
+    /*!
+    @brief get a value (explicit); special case
+
+    Explicit type conversion between the JSON value and a compatible value
+    which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
+    and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
+    The value is converted by calling the @ref json_serializer<ValueType>
+    `from_json()` method.
+
+    The function is equivalent to executing
+    @code {.cpp}
+    return JSONSerializer<ValueTypeCV>::from_json(*this);
+    @endcode
+
+    This overloads is chosen if:
+    - @a ValueType is not @ref basic_json and
+    - @ref json_serializer<ValueType> has a `from_json()` method of the form
+      `ValueType from_json(const basic_json&)`
+
+    @note If @ref json_serializer<ValueType> has both overloads of
+    `from_json()`, this one is chosen.
+
+    @tparam ValueTypeCV the provided value type
+    @tparam ValueType the returned value type
+
+    @return copy of the JSON value, converted to @a ValueType
+
+    @throw what @ref json_serializer<ValueType> `from_json()` method throws
+
+    @since version 2.1.0
+    */
+    template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
+             detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
+                                 detail::has_non_default_from_json<basic_json_t, ValueType>::value,
+                                 int> = 0>
+    ValueType get() const noexcept(noexcept(
+                                       JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
+    {
+        static_assert(not std::is_reference<ValueTypeCV>::value,
+                      "get() cannot be used with reference types, you might want to use get_ref()");
+        return JSONSerializer<ValueType>::from_json(*this);
+    }
+
+    /*!
+    @brief get a value (explicit)
+
+    Explicit type conversion between the JSON value and a compatible value.
+    The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
+    `from_json()` method.
+
+    The function is equivalent to executing
+    @code {.cpp}
+    ValueType v;
+    JSONSerializer<ValueType>::from_json(*this, v);
+    @endcode
+
+    This overloads is chosen if:
+    - @a ValueType is not @ref basic_json,
+    - @ref json_serializer<ValueType> has a `from_json()` method of the form
+      `void from_json(const basic_json&, ValueType&)`, and
+
+    @tparam ValueType the input parameter type.
+
+    @return the input parameter, allowing chaining calls.
+
+    @throw what @ref json_serializer<ValueType> `from_json()` method throws
+
+    @liveexample{The example below shows several conversions from JSON values
+    to other types. There a few things to note: (1) Floating-point numbers can
+    be converted to integers\, (2) A JSON array can be converted to a standard
+    `std::vector<short>`\, (3) A JSON object can be converted to C++
+    associative containers such as `std::unordered_map<std::string\,
+    json>`.,get_to}
+
+    @since version 3.3.0
+    */
+    template<typename ValueType,
+             detail::enable_if_t <
+                 not detail::is_basic_json<ValueType>::value and
+                 detail::has_from_json<basic_json_t, ValueType>::value,
+                 int> = 0>
+    ValueType & get_to(ValueType& v) const noexcept(noexcept(
+                JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
+    {
+        JSONSerializer<ValueType>::from_json(*this, v);
+        return v;
+    }
+
+    template <
+        typename T, std::size_t N,
+        typename Array = T (&)[N],
+        detail::enable_if_t <
+            detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
+    Array get_to(T (&v)[N]) const
+    noexcept(noexcept(JSONSerializer<Array>::from_json(
+                          std::declval<const basic_json_t&>(), v)))
+    {
+        JSONSerializer<Array>::from_json(*this, v);
+        return v;
+    }
+
+
+    /*!
+    @brief get a pointer value (implicit)
+
+    Implicit pointer access to the internally stored JSON value. No copies are
+    made.
+
+    @warning Writing data to the pointee of the result yields an undefined
+    state.
+
+    @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
+    object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
+    @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
+    assertion.
+
+    @return pointer to the internally stored JSON value if the requested
+    pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
+
+    @complexity Constant.
+
+    @liveexample{The example below shows how pointers to internal values of a
+    JSON value can be requested. Note that no type conversions are made and a
+    `nullptr` is returned if the value and the requested pointer type does not
+    match.,get_ptr}
+
+    @since version 1.0.0
+    */
+    template<typename PointerType, typename std::enable_if<
+                 std::is_pointer<PointerType>::value, int>::type = 0>
+    auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
+    {
+        // delegate the call to get_impl_ptr<>()
+        return get_impl_ptr(static_cast<PointerType>(nullptr));
+    }
+
+    /*!
+    @brief get a pointer value (implicit)
+    @copydoc get_ptr()
+    */
+    template<typename PointerType, typename std::enable_if<
+                 std::is_pointer<PointerType>::value and
+                 std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
+    constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
+    {
+        // delegate the call to get_impl_ptr<>() const
+        return get_impl_ptr(static_cast<PointerType>(nullptr));
+    }
+
+    /*!
+    @brief get a pointer value (explicit)
+
+    Explicit pointer access to the internally stored JSON value. No copies are
+    made.
+
+    @warning The pointer becomes invalid if the underlying JSON object
+    changes.
+
+    @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
+    object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
+    @ref number_unsigned_t, or @ref number_float_t.
+
+    @return pointer to the internally stored JSON value if the requested
+    pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
+
+    @complexity Constant.
+
+    @liveexample{The example below shows how pointers to internal values of a
+    JSON value can be requested. Note that no type conversions are made and a
+    `nullptr` is returned if the value and the requested pointer type does not
+    match.,get__PointerType}
+
+    @sa @ref get_ptr() for explicit pointer-member access
+
+    @since version 1.0.0
+    */
+    template<typename PointerType, typename std::enable_if<
+                 std::is_pointer<PointerType>::value, int>::type = 0>
+    auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
+    {
+        // delegate the call to get_ptr
+        return get_ptr<PointerType>();
+    }
+
+    /*!
+    @brief get a pointer value (explicit)
+    @copydoc get()
+    */
+    template<typename PointerType, typename std::enable_if<
+                 std::is_pointer<PointerType>::value, int>::type = 0>
+    constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
+    {
+        // delegate the call to get_ptr
+        return get_ptr<PointerType>();
+    }
+
+    /*!
+    @brief get a reference value (implicit)
+
+    Implicit reference access to the internally stored JSON value. No copies
+    are made.
+
+    @warning Writing data to the referee of the result yields an undefined
+    state.
+
+    @tparam ReferenceType reference type; must be a reference to @ref array_t,
+    @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
+    @ref number_float_t. Enforced by static assertion.
+
+    @return reference to the internally stored JSON value if the requested
+    reference type @a ReferenceType fits to the JSON value; throws
+    type_error.303 otherwise
+
+    @throw type_error.303 in case passed type @a ReferenceType is incompatible
+    with the stored JSON value; see example below
+
+    @complexity Constant.
+
+    @liveexample{The example shows several calls to `get_ref()`.,get_ref}
+
+    @since version 1.1.0
+    */
+    template<typename ReferenceType, typename std::enable_if<
+                 std::is_reference<ReferenceType>::value, int>::type = 0>
+    ReferenceType get_ref()
+    {
+        // delegate call to get_ref_impl
+        return get_ref_impl<ReferenceType>(*this);
+    }
+
+    /*!
+    @brief get a reference value (implicit)
+    @copydoc get_ref()
+    */
+    template<typename ReferenceType, typename std::enable_if<
+                 std::is_reference<ReferenceType>::value and
+                 std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
+    ReferenceType get_ref() const
+    {
+        // delegate call to get_ref_impl
+        return get_ref_impl<ReferenceType>(*this);
+    }
+
+    /*!
+    @brief get a value (implicit)
+
+    Implicit type conversion between the JSON value and a compatible value.
+    The call is realized by calling @ref get() const.
+
+    @tparam ValueType non-pointer type compatible to the JSON value, for
+    instance `int` for JSON integer numbers, `bool` for JSON booleans, or
+    `std::vector` types for JSON arrays. The character type of @ref string_t
+    as well as an initializer list of this type is excluded to avoid
+    ambiguities as these types implicitly convert to `std::string`.
+
+    @return copy of the JSON value, converted to type @a ValueType
+
+    @throw type_error.302 in case passed type @a ValueType is incompatible
+    to the JSON value type (e.g., the JSON value is of type boolean, but a
+    string is requested); see example below
+
+    @complexity Linear in the size of the JSON value.
+
+    @liveexample{The example below shows several conversions from JSON values
+    to other types. There a few things to note: (1) Floating-point numbers can
+    be converted to integers\, (2) A JSON array can be converted to a standard
+    `std::vector<short>`\, (3) A JSON object can be converted to C++
+    associative containers such as `std::unordered_map<std::string\,
+    json>`.,operator__ValueType}
+
+    @since version 1.0.0
+    */
+    template < typename ValueType, typename std::enable_if <
+                   not std::is_pointer<ValueType>::value and
+                   not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
+                   not std::is_same<ValueType, typename string_t::value_type>::value and
+                   not detail::is_basic_json<ValueType>::value
+
+#ifndef _MSC_VER  // fix for issue #167 operator<< ambiguity under VS2015
+                   and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
+#if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) and _MSC_VER <= 1914))
+                   and not std::is_same<ValueType, typename std::string_view>::value
+#endif
+#endif
+                   and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
+                   , int >::type = 0 >
+    operator ValueType() const
+    {
+        // delegate the call to get<>() const
+        return get<ValueType>();
+    }
+
+    /// @}
+
+
+    ////////////////////
+    // element access //
+    ////////////////////
+
+    /// @name element access
+    /// Access to the JSON value.
+    /// @{
+
+    /*!
+    @brief access specified array element with bounds checking
+
+    Returns a reference to the element at specified location @a idx, with
+    bounds checking.
+
+    @param[in] idx  index of the element to access
+
+    @return reference to the element at index @a idx
+
+    @throw type_error.304 if the JSON value is not an array; in this case,
+    calling `at` with an index makes no sense. See example below.
+    @throw out_of_range.401 if the index @a idx is out of range of the array;
+    that is, `idx >= size()`. See example below.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes in the JSON value.
+
+    @complexity Constant.
+
+    @since version 1.0.0
+
+    @liveexample{The example below shows how array elements can be read and
+    written using `at()`. It also demonstrates the different exceptions that
+    can be thrown.,at__size_type}
+    */
+    reference at(size_type idx)
+    {
+        // at only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            JSON_TRY
+            {
+                return m_value.array->at(idx);
+            }
+            JSON_CATCH (std::out_of_range&)
+            {
+                // create better exception explanation
+                JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
+            }
+        }
+        else
+        {
+            JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
+        }
+    }
+
+    /*!
+    @brief access specified array element with bounds checking
+
+    Returns a const reference to the element at specified location @a idx,
+    with bounds checking.
+
+    @param[in] idx  index of the element to access
+
+    @return const reference to the element at index @a idx
+
+    @throw type_error.304 if the JSON value is not an array; in this case,
+    calling `at` with an index makes no sense. See example below.
+    @throw out_of_range.401 if the index @a idx is out of range of the array;
+    that is, `idx >= size()`. See example below.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes in the JSON value.
+
+    @complexity Constant.
+
+    @since version 1.0.0
+
+    @liveexample{The example below shows how array elements can be read using
+    `at()`. It also demonstrates the different exceptions that can be thrown.,
+    at__size_type_const}
+    */
+    const_reference at(size_type idx) const
+    {
+        // at only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            JSON_TRY
+            {
+                return m_value.array->at(idx);
+            }
+            JSON_CATCH (std::out_of_range&)
+            {
+                // create better exception explanation
+                JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
+            }
+        }
+        else
+        {
+            JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
+        }
+    }
+
+    /*!
+    @brief access specified object element with bounds checking
+
+    Returns a reference to the element at with specified key @a key, with
+    bounds checking.
+
+    @param[in] key  key of the element to access
+
+    @return reference to the element at key @a key
+
+    @throw type_error.304 if the JSON value is not an object; in this case,
+    calling `at` with a key makes no sense. See example below.
+    @throw out_of_range.403 if the key @a key is is not stored in the object;
+    that is, `find(key) == end()`. See example below.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes in the JSON value.
+
+    @complexity Logarithmic in the size of the container.
+
+    @sa @ref operator[](const typename object_t::key_type&) for unchecked
+    access by reference
+    @sa @ref value() for access by value with a default value
+
+    @since version 1.0.0
+
+    @liveexample{The example below shows how object elements can be read and
+    written using `at()`. It also demonstrates the different exceptions that
+    can be thrown.,at__object_t_key_type}
+    */
+    reference at(const typename object_t::key_type& key)
+    {
+        // at only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            JSON_TRY
+            {
+                return m_value.object->at(key);
+            }
+            JSON_CATCH (std::out_of_range&)
+            {
+                // create better exception explanation
+                JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
+            }
+        }
+        else
+        {
+            JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
+        }
+    }
+
+    /*!
+    @brief access specified object element with bounds checking
+
+    Returns a const reference to the element at with specified key @a key,
+    with bounds checking.
+
+    @param[in] key  key of the element to access
+
+    @return const reference to the element at key @a key
+
+    @throw type_error.304 if the JSON value is not an object; in this case,
+    calling `at` with a key makes no sense. See example below.
+    @throw out_of_range.403 if the key @a key is is not stored in the object;
+    that is, `find(key) == end()`. See example below.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes in the JSON value.
+
+    @complexity Logarithmic in the size of the container.
+
+    @sa @ref operator[](const typename object_t::key_type&) for unchecked
+    access by reference
+    @sa @ref value() for access by value with a default value
+
+    @since version 1.0.0
+
+    @liveexample{The example below shows how object elements can be read using
+    `at()`. It also demonstrates the different exceptions that can be thrown.,
+    at__object_t_key_type_const}
+    */
+    const_reference at(const typename object_t::key_type& key) const
+    {
+        // at only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            JSON_TRY
+            {
+                return m_value.object->at(key);
+            }
+            JSON_CATCH (std::out_of_range&)
+            {
+                // create better exception explanation
+                JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
+            }
+        }
+        else
+        {
+            JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
+        }
+    }
+
+    /*!
+    @brief access specified array element
+
+    Returns a reference to the element at specified location @a idx.
+
+    @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
+    then the array is silently filled up with `null` values to make `idx` a
+    valid reference to the last stored element.
+
+    @param[in] idx  index of the element to access
+
+    @return reference to the element at index @a idx
+
+    @throw type_error.305 if the JSON value is not an array or null; in that
+    cases, using the [] operator with an index makes no sense.
+
+    @complexity Constant if @a idx is in the range of the array. Otherwise
+    linear in `idx - size()`.
+
+    @liveexample{The example below shows how array elements can be read and
+    written using `[]` operator. Note the addition of `null`
+    values.,operatorarray__size_type}
+
+    @since version 1.0.0
+    */
+    reference operator[](size_type idx)
+    {
+        // implicitly convert null value to an empty array
+        if (is_null())
+        {
+            m_type = value_t::array;
+            m_value.array = create<array_t>();
+            assert_invariant();
+        }
+
+        // operator[] only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            // fill up array with null values if given idx is outside range
+            if (idx >= m_value.array->size())
+            {
+                m_value.array->insert(m_value.array->end(),
+                                      idx - m_value.array->size() + 1,
+                                      basic_json());
+            }
+
+            return m_value.array->operator[](idx);
+        }
+
+        JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
+    }
+
+    /*!
+    @brief access specified array element
+
+    Returns a const reference to the element at specified location @a idx.
+
+    @param[in] idx  index of the element to access
+
+    @return const reference to the element at index @a idx
+
+    @throw type_error.305 if the JSON value is not an array; in that case,
+    using the [] operator with an index makes no sense.
+
+    @complexity Constant.
+
+    @liveexample{The example below shows how array elements can be read using
+    the `[]` operator.,operatorarray__size_type_const}
+
+    @since version 1.0.0
+    */
+    const_reference operator[](size_type idx) const
+    {
+        // const operator[] only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            return m_value.array->operator[](idx);
+        }
+
+        JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
+    }
+
+    /*!
+    @brief access specified object element
+
+    Returns a reference to the element at with specified key @a key.
+
+    @note If @a key is not found in the object, then it is silently added to
+    the object and filled with a `null` value to make `key` a valid reference.
+    In case the value was `null` before, it is converted to an object.
+
+    @param[in] key  key of the element to access
+
+    @return reference to the element at key @a key
+
+    @throw type_error.305 if the JSON value is not an object or null; in that
+    cases, using the [] operator with a key makes no sense.
+
+    @complexity Logarithmic in the size of the container.
+
+    @liveexample{The example below shows how object elements can be read and
+    written using the `[]` operator.,operatorarray__key_type}
+
+    @sa @ref at(const typename object_t::key_type&) for access by reference
+    with range checking
+    @sa @ref value() for access by value with a default value
+
+    @since version 1.0.0
+    */
+    reference operator[](const typename object_t::key_type& key)
+    {
+        // implicitly convert null value to an empty object
+        if (is_null())
+        {
+            m_type = value_t::object;
+            m_value.object = create<object_t>();
+            assert_invariant();
+        }
+
+        // operator[] only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            return m_value.object->operator[](key);
+        }
+
+        JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
+    }
+
+    /*!
+    @brief read-only access specified object element
+
+    Returns a const reference to the element at with specified key @a key. No
+    bounds checking is performed.
+
+    @warning If the element with key @a key does not exist, the behavior is
+    undefined.
+
+    @param[in] key  key of the element to access
+
+    @return const reference to the element at key @a key
+
+    @pre The element with key @a key must exist. **This precondition is
+         enforced with an assertion.**
+
+    @throw type_error.305 if the JSON value is not an object; in that case,
+    using the [] operator with a key makes no sense.
+
+    @complexity Logarithmic in the size of the container.
+
+    @liveexample{The example below shows how object elements can be read using
+    the `[]` operator.,operatorarray__key_type_const}
+
+    @sa @ref at(const typename object_t::key_type&) for access by reference
+    with range checking
+    @sa @ref value() for access by value with a default value
+
+    @since version 1.0.0
+    */
+    const_reference operator[](const typename object_t::key_type& key) const
+    {
+        // const operator[] only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            assert(m_value.object->find(key) != m_value.object->end());
+            return m_value.object->find(key)->second;
+        }
+
+        JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
+    }
+
+    /*!
+    @brief access specified object element
+
+    Returns a reference to the element at with specified key @a key.
+
+    @note If @a key is not found in the object, then it is silently added to
+    the object and filled with a `null` value to make `key` a valid reference.
+    In case the value was `null` before, it is converted to an object.
+
+    @param[in] key  key of the element to access
+
+    @return reference to the element at key @a key
+
+    @throw type_error.305 if the JSON value is not an object or null; in that
+    cases, using the [] operator with a key makes no sense.
+
+    @complexity Logarithmic in the size of the container.
+
+    @liveexample{The example below shows how object elements can be read and
+    written using the `[]` operator.,operatorarray__key_type}
+
+    @sa @ref at(const typename object_t::key_type&) for access by reference
+    with range checking
+    @sa @ref value() for access by value with a default value
+
+    @since version 1.1.0
+    */
+    template<typename T>
+    JSON_HEDLEY_NON_NULL(2)
+    reference operator[](T* key)
+    {
+        // implicitly convert null to object
+        if (is_null())
+        {
+            m_type = value_t::object;
+            m_value = value_t::object;
+            assert_invariant();
+        }
+
+        // at only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            return m_value.object->operator[](key);
+        }
+
+        JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
+    }
+
+    /*!
+    @brief read-only access specified object element
+
+    Returns a const reference to the element at with specified key @a key. No
+    bounds checking is performed.
+
+    @warning If the element with key @a key does not exist, the behavior is
+    undefined.
+
+    @param[in] key  key of the element to access
+
+    @return const reference to the element at key @a key
+
+    @pre The element with key @a key must exist. **This precondition is
+         enforced with an assertion.**
+
+    @throw type_error.305 if the JSON value is not an object; in that case,
+    using the [] operator with a key makes no sense.
+
+    @complexity Logarithmic in the size of the container.
+
+    @liveexample{The example below shows how object elements can be read using
+    the `[]` operator.,operatorarray__key_type_const}
+
+    @sa @ref at(const typename object_t::key_type&) for access by reference
+    with range checking
+    @sa @ref value() for access by value with a default value
+
+    @since version 1.1.0
+    */
+    template<typename T>
+    JSON_HEDLEY_NON_NULL(2)
+    const_reference operator[](T* key) const
+    {
+        // at only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            assert(m_value.object->find(key) != m_value.object->end());
+            return m_value.object->find(key)->second;
+        }
+
+        JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
+    }
+
+    /*!
+    @brief access specified object element with default value
+
+    Returns either a copy of an object's element at the specified key @a key
+    or a given default value if no element with key @a key exists.
+
+    The function is basically equivalent to executing
+    @code {.cpp}
+    try {
+        return at(key);
+    } catch(out_of_range) {
+        return default_value;
+    }
+    @endcode
+
+    @note Unlike @ref at(const typename object_t::key_type&), this function
+    does not throw if the given key @a key was not found.
+
+    @note Unlike @ref operator[](const typename object_t::key_type& key), this
+    function does not implicitly add an element to the position defined by @a
+    key. This function is furthermore also applicable to const objects.
+
+    @param[in] key  key of the element to access
+    @param[in] default_value  the value to return if @a key is not found
+
+    @tparam ValueType type compatible to JSON values, for instance `int` for
+    JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
+    JSON arrays. Note the type of the expected value at @a key and the default
+    value @a default_value must be compatible.
+
+    @return copy of the element at key @a key or @a default_value if @a key
+    is not found
+
+    @throw type_error.302 if @a default_value does not match the type of the
+    value at @a key
+    @throw type_error.306 if the JSON value is not an object; in that case,
+    using `value()` with a key makes no sense.
+
+    @complexity Logarithmic in the size of the container.
+
+    @liveexample{The example below shows how object elements can be queried
+    with a default value.,basic_json__value}
+
+    @sa @ref at(const typename object_t::key_type&) for access by reference
+    with range checking
+    @sa @ref operator[](const typename object_t::key_type&) for unchecked
+    access by reference
+
+    @since version 1.0.0
+    */
+    template<class ValueType, typename std::enable_if<
+                 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
+    ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
+    {
+        // at only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            // if key is found, return value and given default value otherwise
+            const auto it = find(key);
+            if (it != end())
+            {
+                return *it;
+            }
+
+            return default_value;
+        }
+
+        JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
+    }
+
+    /*!
+    @brief overload for a default value of type const char*
+    @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
+    */
+    string_t value(const typename object_t::key_type& key, const char* default_value) const
+    {
+        return value(key, string_t(default_value));
+    }
+
+    /*!
+    @brief access specified object element via JSON Pointer with default value
+
+    Returns either a copy of an object's element at the specified key @a key
+    or a given default value if no element with key @a key exists.
+
+    The function is basically equivalent to executing
+    @code {.cpp}
+    try {
+        return at(ptr);
+    } catch(out_of_range) {
+        return default_value;
+    }
+    @endcode
+
+    @note Unlike @ref at(const json_pointer&), this function does not throw
+    if the given key @a key was not found.
+
+    @param[in] ptr  a JSON pointer to the element to access
+    @param[in] default_value  the value to return if @a ptr found no value
+
+    @tparam ValueType type compatible to JSON values, for instance `int` for
+    JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
+    JSON arrays. Note the type of the expected value at @a key and the default
+    value @a default_value must be compatible.
+
+    @return copy of the element at key @a key or @a default_value if @a key
+    is not found
+
+    @throw type_error.302 if @a default_value does not match the type of the
+    value at @a ptr
+    @throw type_error.306 if the JSON value is not an object; in that case,
+    using `value()` with a key makes no sense.
+
+    @complexity Logarithmic in the size of the container.
+
+    @liveexample{The example below shows how object elements can be queried
+    with a default value.,basic_json__value_ptr}
+
+    @sa @ref operator[](const json_pointer&) for unchecked access by reference
+
+    @since version 2.0.2
+    */
+    template<class ValueType, typename std::enable_if<
+                 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
+    ValueType value(const json_pointer& ptr, const ValueType& default_value) const
+    {
+        // at only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            // if pointer resolves a value, return it or use default value
+            JSON_TRY
+            {
+                return ptr.get_checked(this);
+            }
+            JSON_INTERNAL_CATCH (out_of_range&)
+            {
+                return default_value;
+            }
+        }
+
+        JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
+    }
+
+    /*!
+    @brief overload for a default value of type const char*
+    @copydoc basic_json::value(const json_pointer&, ValueType) const
+    */
+    JSON_HEDLEY_NON_NULL(3)
+    string_t value(const json_pointer& ptr, const char* default_value) const
+    {
+        return value(ptr, string_t(default_value));
+    }
+
+    /*!
+    @brief access the first element
+
+    Returns a reference to the first element in the container. For a JSON
+    container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
+
+    @return In case of a structured type (array or object), a reference to the
+    first element is returned. In case of number, string, or boolean values, a
+    reference to the value is returned.
+
+    @complexity Constant.
+
+    @pre The JSON value must not be `null` (would throw `std::out_of_range`)
+    or an empty array or object (undefined behavior, **guarded by
+    assertions**).
+    @post The JSON value remains unchanged.
+
+    @throw invalid_iterator.214 when called on `null` value
+
+    @liveexample{The following code shows an example for `front()`.,front}
+
+    @sa @ref back() -- access the last element
+
+    @since version 1.0.0
+    */
+    reference front()
+    {
+        return *begin();
+    }
+
+    /*!
+    @copydoc basic_json::front()
+    */
+    const_reference front() const
+    {
+        return *cbegin();
+    }
+
+    /*!
+    @brief access the last element
+
+    Returns a reference to the last element in the container. For a JSON
+    container `c`, the expression `c.back()` is equivalent to
+    @code {.cpp}
+    auto tmp = c.end();
+    --tmp;
+    return *tmp;
+    @endcode
+
+    @return In case of a structured type (array or object), a reference to the
+    last element is returned. In case of number, string, or boolean values, a
+    reference to the value is returned.
+
+    @complexity Constant.
+
+    @pre The JSON value must not be `null` (would throw `std::out_of_range`)
+    or an empty array or object (undefined behavior, **guarded by
+    assertions**).
+    @post The JSON value remains unchanged.
+
+    @throw invalid_iterator.214 when called on a `null` value. See example
+    below.
+
+    @liveexample{The following code shows an example for `back()`.,back}
+
+    @sa @ref front() -- access the first element
+
+    @since version 1.0.0
+    */
+    reference back()
+    {
+        auto tmp = end();
+        --tmp;
+        return *tmp;
+    }
+
+    /*!
+    @copydoc basic_json::back()
+    */
+    const_reference back() const
+    {
+        auto tmp = cend();
+        --tmp;
+        return *tmp;
+    }
+
+    /*!
+    @brief remove element given an iterator
+
+    Removes the element specified by iterator @a pos. The iterator @a pos must
+    be valid and dereferenceable. Thus the `end()` iterator (which is valid,
+    but is not dereferenceable) cannot be used as a value for @a pos.
+
+    If called on a primitive type other than `null`, the resulting JSON value
+    will be `null`.
+
+    @param[in] pos iterator to the element to remove
+    @return Iterator following the last removed element. If the iterator @a
+    pos refers to the last element, the `end()` iterator is returned.
+
+    @tparam IteratorType an @ref iterator or @ref const_iterator
+
+    @post Invalidates iterators and references at or after the point of the
+    erase, including the `end()` iterator.
+
+    @throw type_error.307 if called on a `null` value; example: `"cannot use
+    erase() with null"`
+    @throw invalid_iterator.202 if called on an iterator which does not belong
+    to the current JSON value; example: `"iterator does not fit current
+    value"`
+    @throw invalid_iterator.205 if called on a primitive type with invalid
+    iterator (i.e., any iterator which is not `begin()`); example: `"iterator
+    out of range"`
+
+    @complexity The complexity depends on the type:
+    - objects: amortized constant
+    - arrays: linear in distance between @a pos and the end of the container
+    - strings: linear in the length of the string
+    - other types: constant
+
+    @liveexample{The example shows the result of `erase()` for different JSON
+    types.,erase__IteratorType}
+
+    @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
+    the given range
+    @sa @ref erase(const typename object_t::key_type&) -- removes the element
+    from an object at the given key
+    @sa @ref erase(const size_type) -- removes the element from an array at
+    the given index
+
+    @since version 1.0.0
+    */
+    template<class IteratorType, typename std::enable_if<
+                 std::is_same<IteratorType, typename basic_json_t::iterator>::value or
+                 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
+             = 0>
+    IteratorType erase(IteratorType pos)
+    {
+        // make sure iterator fits the current value
+        if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
+        }
+
+        IteratorType result = end();
+
+        switch (m_type)
+        {
+            case value_t::boolean:
+            case value_t::number_float:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::string:
+            {
+                if (JSON_HEDLEY_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
+                {
+                    JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
+                }
+
+                if (is_string())
+                {
+                    AllocatorType<string_t> alloc;
+                    std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
+                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
+                    m_value.string = nullptr;
+                }
+
+                m_type = value_t::null;
+                assert_invariant();
+                break;
+            }
+
+            case value_t::object:
+            {
+                result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
+                break;
+            }
+
+            case value_t::array:
+            {
+                result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
+                break;
+            }
+
+            default:
+                JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
+        }
+
+        return result;
+    }
+
+    /*!
+    @brief remove elements given an iterator range
+
+    Removes the element specified by the range `[first; last)`. The iterator
+    @a first does not need to be dereferenceable if `first == last`: erasing
+    an empty range is a no-op.
+
+    If called on a primitive type other than `null`, the resulting JSON value
+    will be `null`.
+
+    @param[in] first iterator to the beginning of the range to remove
+    @param[in] last iterator past the end of the range to remove
+    @return Iterator following the last removed element. If the iterator @a
+    second refers to the last element, the `end()` iterator is returned.
+
+    @tparam IteratorType an @ref iterator or @ref const_iterator
+
+    @post Invalidates iterators and references at or after the point of the
+    erase, including the `end()` iterator.
+
+    @throw type_error.307 if called on a `null` value; example: `"cannot use
+    erase() with null"`
+    @throw invalid_iterator.203 if called on iterators which does not belong
+    to the current JSON value; example: `"iterators do not fit current value"`
+    @throw invalid_iterator.204 if called on a primitive type with invalid
+    iterators (i.e., if `first != begin()` and `last != end()`); example:
+    `"iterators out of range"`
+
+    @complexity The complexity depends on the type:
+    - objects: `log(size()) + std::distance(first, last)`
+    - arrays: linear in the distance between @a first and @a last, plus linear
+      in the distance between @a last and end of the container
+    - strings: linear in the length of the string
+    - other types: constant
+
+    @liveexample{The example shows the result of `erase()` for different JSON
+    types.,erase__IteratorType_IteratorType}
+
+    @sa @ref erase(IteratorType) -- removes the element at a given position
+    @sa @ref erase(const typename object_t::key_type&) -- removes the element
+    from an object at the given key
+    @sa @ref erase(const size_type) -- removes the element from an array at
+    the given index
+
+    @since version 1.0.0
+    */
+    template<class IteratorType, typename std::enable_if<
+                 std::is_same<IteratorType, typename basic_json_t::iterator>::value or
+                 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
+             = 0>
+    IteratorType erase(IteratorType first, IteratorType last)
+    {
+        // make sure iterator fits the current value
+        if (JSON_HEDLEY_UNLIKELY(this != first.m_object or this != last.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
+        }
+
+        IteratorType result = end();
+
+        switch (m_type)
+        {
+            case value_t::boolean:
+            case value_t::number_float:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::string:
+            {
+                if (JSON_HEDLEY_LIKELY(not first.m_it.primitive_iterator.is_begin()
+                                       or not last.m_it.primitive_iterator.is_end()))
+                {
+                    JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
+                }
+
+                if (is_string())
+                {
+                    AllocatorType<string_t> alloc;
+                    std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
+                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
+                    m_value.string = nullptr;
+                }
+
+                m_type = value_t::null;
+                assert_invariant();
+                break;
+            }
+
+            case value_t::object:
+            {
+                result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
+                                              last.m_it.object_iterator);
+                break;
+            }
+
+            case value_t::array:
+            {
+                result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
+                                             last.m_it.array_iterator);
+                break;
+            }
+
+            default:
+                JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
+        }
+
+        return result;
+    }
+
+    /*!
+    @brief remove element from a JSON object given a key
+
+    Removes elements from a JSON object with the key value @a key.
+
+    @param[in] key value of the elements to remove
+
+    @return Number of elements removed. If @a ObjectType is the default
+    `std::map` type, the return value will always be `0` (@a key was not
+    found) or `1` (@a key was found).
+
+    @post References and iterators to the erased elements are invalidated.
+    Other references and iterators are not affected.
+
+    @throw type_error.307 when called on a type other than JSON object;
+    example: `"cannot use erase() with null"`
+
+    @complexity `log(size()) + count(key)`
+
+    @liveexample{The example shows the effect of `erase()`.,erase__key_type}
+
+    @sa @ref erase(IteratorType) -- removes the element at a given position
+    @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
+    the given range
+    @sa @ref erase(const size_type) -- removes the element from an array at
+    the given index
+
+    @since version 1.0.0
+    */
+    size_type erase(const typename object_t::key_type& key)
+    {
+        // this erase only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            return m_value.object->erase(key);
+        }
+
+        JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
+    }
+
+    /*!
+    @brief remove element from a JSON array given an index
+
+    Removes element from a JSON array at the index @a idx.
+
+    @param[in] idx index of the element to remove
+
+    @throw type_error.307 when called on a type other than JSON object;
+    example: `"cannot use erase() with null"`
+    @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
+    is out of range"`
+
+    @complexity Linear in distance between @a idx and the end of the container.
+
+    @liveexample{The example shows the effect of `erase()`.,erase__size_type}
+
+    @sa @ref erase(IteratorType) -- removes the element at a given position
+    @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
+    the given range
+    @sa @ref erase(const typename object_t::key_type&) -- removes the element
+    from an object at the given key
+
+    @since version 1.0.0
+    */
+    void erase(const size_type idx)
+    {
+        // this erase only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            if (JSON_HEDLEY_UNLIKELY(idx >= size()))
+            {
+                JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
+            }
+
+            m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
+        }
+        else
+        {
+            JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
+        }
+    }
+
+    /// @}
+
+
+    ////////////
+    // lookup //
+    ////////////
+
+    /// @name lookup
+    /// @{
+
+    /*!
+    @brief find an element in a JSON object
+
+    Finds an element in a JSON object with key equivalent to @a key. If the
+    element is not found or the JSON value is not an object, end() is
+    returned.
+
+    @note This method always returns @ref end() when executed on a JSON type
+          that is not an object.
+
+    @param[in] key key value of the element to search for.
+
+    @return Iterator to an element with key equivalent to @a key. If no such
+    element is found or the JSON value is not an object, past-the-end (see
+    @ref end()) iterator is returned.
+
+    @complexity Logarithmic in the size of the JSON object.
+
+    @liveexample{The example shows how `find()` is used.,find__key_type}
+
+    @sa @ref contains(KeyT&&) const -- checks whether a key exists
+
+    @since version 1.0.0
+    */
+    template<typename KeyT>
+    iterator find(KeyT&& key)
+    {
+        auto result = end();
+
+        if (is_object())
+        {
+            result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
+        }
+
+        return result;
+    }
+
+    /*!
+    @brief find an element in a JSON object
+    @copydoc find(KeyT&&)
+    */
+    template<typename KeyT>
+    const_iterator find(KeyT&& key) const
+    {
+        auto result = cend();
+
+        if (is_object())
+        {
+            result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
+        }
+
+        return result;
+    }
+
+    /*!
+    @brief returns the number of occurrences of a key in a JSON object
+
+    Returns the number of elements with key @a key. If ObjectType is the
+    default `std::map` type, the return value will always be `0` (@a key was
+    not found) or `1` (@a key was found).
+
+    @note This method always returns `0` when executed on a JSON type that is
+          not an object.
+
+    @param[in] key key value of the element to count
+
+    @return Number of elements with key @a key. If the JSON value is not an
+    object, the return value will be `0`.
+
+    @complexity Logarithmic in the size of the JSON object.
+
+    @liveexample{The example shows how `count()` is used.,count}
+
+    @since version 1.0.0
+    */
+    template<typename KeyT>
+    size_type count(KeyT&& key) const
+    {
+        // return 0 for all nonobject types
+        return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
+    }
+
+    /*!
+    @brief check the existence of an element in a JSON object
+
+    Check whether an element exists in a JSON object with key equivalent to
+    @a key. If the element is not found or the JSON value is not an object,
+    false is returned.
+
+    @note This method always returns false when executed on a JSON type
+          that is not an object.
+
+    @param[in] key key value to check its existence.
+
+    @return true if an element with specified @a key exists. If no such
+    element with such key is found or the JSON value is not an object,
+    false is returned.
+
+    @complexity Logarithmic in the size of the JSON object.
+
+    @liveexample{The following code shows an example for `contains()`.,contains}
+
+    @sa @ref find(KeyT&&) -- returns an iterator to an object element
+    @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
+
+    @since version 3.6.0
+    */
+    template<typename KeyT, typename std::enable_if<
+                 not std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int>::type = 0>
+    bool contains(KeyT && key) const
+    {
+        return is_object() and m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
+    }
+
+    /*!
+    @brief check the existence of an element in a JSON object given a JSON pointer
+
+    Check whether the given JSON pointer @a ptr can be resolved in the current
+    JSON value.
+
+    @note This method can be executed on any JSON value type.
+
+    @param[in] ptr JSON pointer to check its existence.
+
+    @return true if the JSON pointer can be resolved to a stored value, false
+    otherwise.
+
+    @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
+
+    @throw parse_error.106   if an array index begins with '0'
+    @throw parse_error.109   if an array index was not a number
+
+    @complexity Logarithmic in the size of the JSON object.
+
+    @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
+
+    @sa @ref contains(KeyT &&) const -- checks the existence of a key
+
+    @since version 3.7.0
+    */
+    bool contains(const json_pointer& ptr) const
+    {
+        return ptr.contains(this);
+    }
+
+    /// @}
+
+
+    ///////////////
+    // iterators //
+    ///////////////
+
+    /// @name iterators
+    /// @{
+
+    /*!
+    @brief returns an iterator to the first element
+
+    Returns an iterator to the first element.
+
+    @image html range-begin-end.svg "Illustration from cppreference.com"
+
+    @return iterator to the first element
+
+    @complexity Constant.
+
+    @requirement This function helps `basic_json` satisfying the
+    [Container](https://en.cppreference.com/w/cpp/named_req/Container)
+    requirements:
+    - The complexity is constant.
+
+    @liveexample{The following code shows an example for `begin()`.,begin}
+
+    @sa @ref cbegin() -- returns a const iterator to the beginning
+    @sa @ref end() -- returns an iterator to the end
+    @sa @ref cend() -- returns a const iterator to the end
+
+    @since version 1.0.0
+    */
+    iterator begin() noexcept
+    {
+        iterator result(this);
+        result.set_begin();
+        return result;
+    }
+
+    /*!
+    @copydoc basic_json::cbegin()
+    */
+    const_iterator begin() const noexcept
+    {
+        return cbegin();
+    }
+
+    /*!
+    @brief returns a const iterator to the first element
+
+    Returns a const iterator to the first element.
+
+    @image html range-begin-end.svg "Illustration from cppreference.com"
+
+    @return const iterator to the first element
+
+    @complexity Constant.
+
+    @requirement This function helps `basic_json` satisfying the
+    [Container](https://en.cppreference.com/w/cpp/named_req/Container)
+    requirements:
+    - The complexity is constant.
+    - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
+
+    @liveexample{The following code shows an example for `cbegin()`.,cbegin}
+
+    @sa @ref begin() -- returns an iterator to the beginning
+    @sa @ref end() -- returns an iterator to the end
+    @sa @ref cend() -- returns a const iterator to the end
+
+    @since version 1.0.0
+    */
+    const_iterator cbegin() const noexcept
+    {
+        const_iterator result(this);
+        result.set_begin();
+        return result;
+    }
+
+    /*!
+    @brief returns an iterator to one past the last element
+
+    Returns an iterator to one past the last element.
+
+    @image html range-begin-end.svg "Illustration from cppreference.com"
+
+    @return iterator one past the last element
+
+    @complexity Constant.
+
+    @requirement This function helps `basic_json` satisfying the
+    [Container](https://en.cppreference.com/w/cpp/named_req/Container)
+    requirements:
+    - The complexity is constant.
+
+    @liveexample{The following code shows an example for `end()`.,end}
+
+    @sa @ref cend() -- returns a const iterator to the end
+    @sa @ref begin() -- returns an iterator to the beginning
+    @sa @ref cbegin() -- returns a const iterator to the beginning
+
+    @since version 1.0.0
+    */
+    iterator end() noexcept
+    {
+        iterator result(this);
+        result.set_end();
+        return result;
+    }
+
+    /*!
+    @copydoc basic_json::cend()
+    */
+    const_iterator end() const noexcept
+    {
+        return cend();
+    }
+
+    /*!
+    @brief returns a const iterator to one past the last element
+
+    Returns a const iterator to one past the last element.
+
+    @image html range-begin-end.svg "Illustration from cppreference.com"
+
+    @return const iterator one past the last element
+
+    @complexity Constant.
+
+    @requirement This function helps `basic_json` satisfying the
+    [Container](https://en.cppreference.com/w/cpp/named_req/Container)
+    requirements:
+    - The complexity is constant.
+    - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
+
+    @liveexample{The following code shows an example for `cend()`.,cend}
+
+    @sa @ref end() -- returns an iterator to the end
+    @sa @ref begin() -- returns an iterator to the beginning
+    @sa @ref cbegin() -- returns a const iterator to the beginning
+
+    @since version 1.0.0
+    */
+    const_iterator cend() const noexcept
+    {
+        const_iterator result(this);
+        result.set_end();
+        return result;
+    }
+
+    /*!
+    @brief returns an iterator to the reverse-beginning
+
+    Returns an iterator to the reverse-beginning; that is, the last element.
+
+    @image html range-rbegin-rend.svg "Illustration from cppreference.com"
+
+    @complexity Constant.
+
+    @requirement This function helps `basic_json` satisfying the
+    [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
+    requirements:
+    - The complexity is constant.
+    - Has the semantics of `reverse_iterator(end())`.
+
+    @liveexample{The following code shows an example for `rbegin()`.,rbegin}
+
+    @sa @ref crbegin() -- returns a const reverse iterator to the beginning
+    @sa @ref rend() -- returns a reverse iterator to the end
+    @sa @ref crend() -- returns a const reverse iterator to the end
+
+    @since version 1.0.0
+    */
+    reverse_iterator rbegin() noexcept
+    {
+        return reverse_iterator(end());
+    }
+
+    /*!
+    @copydoc basic_json::crbegin()
+    */
+    const_reverse_iterator rbegin() const noexcept
+    {
+        return crbegin();
+    }
+
+    /*!
+    @brief returns an iterator to the reverse-end
+
+    Returns an iterator to the reverse-end; that is, one before the first
+    element.
+
+    @image html range-rbegin-rend.svg "Illustration from cppreference.com"
+
+    @complexity Constant.
+
+    @requirement This function helps `basic_json` satisfying the
+    [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
+    requirements:
+    - The complexity is constant.
+    - Has the semantics of `reverse_iterator(begin())`.
+
+    @liveexample{The following code shows an example for `rend()`.,rend}
+
+    @sa @ref crend() -- returns a const reverse iterator to the end
+    @sa @ref rbegin() -- returns a reverse iterator to the beginning
+    @sa @ref crbegin() -- returns a const reverse iterator to the beginning
+
+    @since version 1.0.0
+    */
+    reverse_iterator rend() noexcept
+    {
+        return reverse_iterator(begin());
+    }
+
+    /*!
+    @copydoc basic_json::crend()
+    */
+    const_reverse_iterator rend() const noexcept
+    {
+        return crend();
+    }
+
+    /*!
+    @brief returns a const reverse iterator to the last element
+
+    Returns a const iterator to the reverse-beginning; that is, the last
+    element.
+
+    @image html range-rbegin-rend.svg "Illustration from cppreference.com"
+
+    @complexity Constant.
+
+    @requirement This function helps `basic_json` satisfying the
+    [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
+    requirements:
+    - The complexity is constant.
+    - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
+
+    @liveexample{The following code shows an example for `crbegin()`.,crbegin}
+
+    @sa @ref rbegin() -- returns a reverse iterator to the beginning
+    @sa @ref rend() -- returns a reverse iterator to the end
+    @sa @ref crend() -- returns a const reverse iterator to the end
+
+    @since version 1.0.0
+    */
+    const_reverse_iterator crbegin() const noexcept
+    {
+        return const_reverse_iterator(cend());
+    }
+
+    /*!
+    @brief returns a const reverse iterator to one before the first
+
+    Returns a const reverse iterator to the reverse-end; that is, one before
+    the first element.
+
+    @image html range-rbegin-rend.svg "Illustration from cppreference.com"
+
+    @complexity Constant.
+
+    @requirement This function helps `basic_json` satisfying the
+    [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
+    requirements:
+    - The complexity is constant.
+    - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
+
+    @liveexample{The following code shows an example for `crend()`.,crend}
+
+    @sa @ref rend() -- returns a reverse iterator to the end
+    @sa @ref rbegin() -- returns a reverse iterator to the beginning
+    @sa @ref crbegin() -- returns a const reverse iterator to the beginning
+
+    @since version 1.0.0
+    */
+    const_reverse_iterator crend() const noexcept
+    {
+        return const_reverse_iterator(cbegin());
+    }
+
+  public:
+    /*!
+    @brief wrapper to access iterator member functions in range-based for
+
+    This function allows to access @ref iterator::key() and @ref
+    iterator::value() during range-based for loops. In these loops, a
+    reference to the JSON values is returned, so there is no access to the
+    underlying iterator.
+
+    For loop without iterator_wrapper:
+
+    @code{cpp}
+    for (auto it = j_object.begin(); it != j_object.end(); ++it)
+    {
+        std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
+    }
+    @endcode
+
+    Range-based for loop without iterator proxy:
+
+    @code{cpp}
+    for (auto it : j_object)
+    {
+        // "it" is of type json::reference and has no key() member
+        std::cout << "value: " << it << '\n';
+    }
+    @endcode
+
+    Range-based for loop with iterator proxy:
+
+    @code{cpp}
+    for (auto it : json::iterator_wrapper(j_object))
+    {
+        std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
+    }
+    @endcode
+
+    @note When iterating over an array, `key()` will return the index of the
+          element as string (see example).
+
+    @param[in] ref  reference to a JSON value
+    @return iteration proxy object wrapping @a ref with an interface to use in
+            range-based for loops
+
+    @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes in the JSON value.
+
+    @complexity Constant.
+
+    @note The name of this function is not yet final and may change in the
+    future.
+
+    @deprecated This stream operator is deprecated and will be removed in
+                future 4.0.0 of the library. Please use @ref items() instead;
+                that is, replace `json::iterator_wrapper(j)` with `j.items()`.
+    */
+    JSON_HEDLEY_DEPRECATED(3.1.0)
+    static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
+    {
+        return ref.items();
+    }
+
+    /*!
+    @copydoc iterator_wrapper(reference)
+    */
+    JSON_HEDLEY_DEPRECATED(3.1.0)
+    static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
+    {
+        return ref.items();
+    }
+
+    /*!
+    @brief helper to access iterator member functions in range-based for
+
+    This function allows to access @ref iterator::key() and @ref
+    iterator::value() during range-based for loops. In these loops, a
+    reference to the JSON values is returned, so there is no access to the
+    underlying iterator.
+
+    For loop without `items()` function:
+
+    @code{cpp}
+    for (auto it = j_object.begin(); it != j_object.end(); ++it)
+    {
+        std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
+    }
+    @endcode
+
+    Range-based for loop without `items()` function:
+
+    @code{cpp}
+    for (auto it : j_object)
+    {
+        // "it" is of type json::reference and has no key() member
+        std::cout << "value: " << it << '\n';
+    }
+    @endcode
+
+    Range-based for loop with `items()` function:
+
+    @code{cpp}
+    for (auto& el : j_object.items())
+    {
+        std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
+    }
+    @endcode
+
+    The `items()` function also allows to use
+    [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
+    (C++17):
+
+    @code{cpp}
+    for (auto& [key, val] : j_object.items())
+    {
+        std::cout << "key: " << key << ", value:" << val << '\n';
+    }
+    @endcode
+
+    @note When iterating over an array, `key()` will return the index of the
+          element as string (see example). For primitive types (e.g., numbers),
+          `key()` returns an empty string.
+
+    @return iteration proxy object wrapping @a ref with an interface to use in
+            range-based for loops
+
+    @liveexample{The following code shows how the function is used.,items}
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes in the JSON value.
+
+    @complexity Constant.
+
+    @since version 3.1.0, structured bindings support since 3.5.0.
+    */
+    iteration_proxy<iterator> items() noexcept
+    {
+        return iteration_proxy<iterator>(*this);
+    }
+
+    /*!
+    @copydoc items()
+    */
+    iteration_proxy<const_iterator> items() const noexcept
+    {
+        return iteration_proxy<const_iterator>(*this);
+    }
+
+    /// @}
+
+
+    //////////////
+    // capacity //
+    //////////////
+
+    /// @name capacity
+    /// @{
+
+    /*!
+    @brief checks whether the container is empty.
+
+    Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
+
+    @return The return value depends on the different types and is
+            defined as follows:
+            Value type  | return value
+            ----------- | -------------
+            null        | `true`
+            boolean     | `false`
+            string      | `false`
+            number      | `false`
+            object      | result of function `object_t::empty()`
+            array       | result of function `array_t::empty()`
+
+    @liveexample{The following code uses `empty()` to check if a JSON
+    object contains any elements.,empty}
+
+    @complexity Constant, as long as @ref array_t and @ref object_t satisfy
+    the Container concept; that is, their `empty()` functions have constant
+    complexity.
+
+    @iterators No changes.
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+
+    @note This function does not return whether a string stored as JSON value
+    is empty - it returns whether the JSON container itself is empty which is
+    false in the case of a string.
+
+    @requirement This function helps `basic_json` satisfying the
+    [Container](https://en.cppreference.com/w/cpp/named_req/Container)
+    requirements:
+    - The complexity is constant.
+    - Has the semantics of `begin() == end()`.
+
+    @sa @ref size() -- returns the number of elements
+
+    @since version 1.0.0
+    */
+    bool empty() const noexcept
+    {
+        switch (m_type)
+        {
+            case value_t::null:
+            {
+                // null values are empty
+                return true;
+            }
+
+            case value_t::array:
+            {
+                // delegate call to array_t::empty()
+                return m_value.array->empty();
+            }
+
+            case value_t::object:
+            {
+                // delegate call to object_t::empty()
+                return m_value.object->empty();
+            }
+
+            default:
+            {
+                // all other types are nonempty
+                return false;
+            }
+        }
+    }
+
+    /*!
+    @brief returns the number of elements
+
+    Returns the number of elements in a JSON value.
+
+    @return The return value depends on the different types and is
+            defined as follows:
+            Value type  | return value
+            ----------- | -------------
+            null        | `0`
+            boolean     | `1`
+            string      | `1`
+            number      | `1`
+            object      | result of function object_t::size()
+            array       | result of function array_t::size()
+
+    @liveexample{The following code calls `size()` on the different value
+    types.,size}
+
+    @complexity Constant, as long as @ref array_t and @ref object_t satisfy
+    the Container concept; that is, their size() functions have constant
+    complexity.
+
+    @iterators No changes.
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+
+    @note This function does not return the length of a string stored as JSON
+    value - it returns the number of elements in the JSON value which is 1 in
+    the case of a string.
+
+    @requirement This function helps `basic_json` satisfying the
+    [Container](https://en.cppreference.com/w/cpp/named_req/Container)
+    requirements:
+    - The complexity is constant.
+    - Has the semantics of `std::distance(begin(), end())`.
+
+    @sa @ref empty() -- checks whether the container is empty
+    @sa @ref max_size() -- returns the maximal number of elements
+
+    @since version 1.0.0
+    */
+    size_type size() const noexcept
+    {
+        switch (m_type)
+        {
+            case value_t::null:
+            {
+                // null values are empty
+                return 0;
+            }
+
+            case value_t::array:
+            {
+                // delegate call to array_t::size()
+                return m_value.array->size();
+            }
+
+            case value_t::object:
+            {
+                // delegate call to object_t::size()
+                return m_value.object->size();
+            }
+
+            default:
+            {
+                // all other types have size 1
+                return 1;
+            }
+        }
+    }
+
+    /*!
+    @brief returns the maximum possible number of elements
+
+    Returns the maximum number of elements a JSON value is able to hold due to
+    system or library implementation limitations, i.e. `std::distance(begin(),
+    end())` for the JSON value.
+
+    @return The return value depends on the different types and is
+            defined as follows:
+            Value type  | return value
+            ----------- | -------------
+            null        | `0` (same as `size()`)
+            boolean     | `1` (same as `size()`)
+            string      | `1` (same as `size()`)
+            number      | `1` (same as `size()`)
+            object      | result of function `object_t::max_size()`
+            array       | result of function `array_t::max_size()`
+
+    @liveexample{The following code calls `max_size()` on the different value
+    types. Note the output is implementation specific.,max_size}
+
+    @complexity Constant, as long as @ref array_t and @ref object_t satisfy
+    the Container concept; that is, their `max_size()` functions have constant
+    complexity.
+
+    @iterators No changes.
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+
+    @requirement This function helps `basic_json` satisfying the
+    [Container](https://en.cppreference.com/w/cpp/named_req/Container)
+    requirements:
+    - The complexity is constant.
+    - Has the semantics of returning `b.size()` where `b` is the largest
+      possible JSON value.
+
+    @sa @ref size() -- returns the number of elements
+
+    @since version 1.0.0
+    */
+    size_type max_size() const noexcept
+    {
+        switch (m_type)
+        {
+            case value_t::array:
+            {
+                // delegate call to array_t::max_size()
+                return m_value.array->max_size();
+            }
+
+            case value_t::object:
+            {
+                // delegate call to object_t::max_size()
+                return m_value.object->max_size();
+            }
+
+            default:
+            {
+                // all other types have max_size() == size()
+                return size();
+            }
+        }
+    }
+
+    /// @}
+
+
+    ///////////////
+    // modifiers //
+    ///////////////
+
+    /// @name modifiers
+    /// @{
+
+    /*!
+    @brief clears the contents
+
+    Clears the content of a JSON value and resets it to the default value as
+    if @ref basic_json(value_t) would have been called with the current value
+    type from @ref type():
+
+    Value type  | initial value
+    ----------- | -------------
+    null        | `null`
+    boolean     | `false`
+    string      | `""`
+    number      | `0`
+    object      | `{}`
+    array       | `[]`
+
+    @post Has the same effect as calling
+    @code {.cpp}
+    *this = basic_json(type());
+    @endcode
+
+    @liveexample{The example below shows the effect of `clear()` to different
+    JSON types.,clear}
+
+    @complexity Linear in the size of the JSON value.
+
+    @iterators All iterators, pointers and references related to this container
+               are invalidated.
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+
+    @sa @ref basic_json(value_t) -- constructor that creates an object with the
+        same value than calling `clear()`
+
+    @since version 1.0.0
+    */
+    void clear() noexcept
+    {
+        switch (m_type)
+        {
+            case value_t::number_integer:
+            {
+                m_value.number_integer = 0;
+                break;
+            }
+
+            case value_t::number_unsigned:
+            {
+                m_value.number_unsigned = 0;
+                break;
+            }
+
+            case value_t::number_float:
+            {
+                m_value.number_float = 0.0;
+                break;
+            }
+
+            case value_t::boolean:
+            {
+                m_value.boolean = false;
+                break;
+            }
+
+            case value_t::string:
+            {
+                m_value.string->clear();
+                break;
+            }
+
+            case value_t::array:
+            {
+                m_value.array->clear();
+                break;
+            }
+
+            case value_t::object:
+            {
+                m_value.object->clear();
+                break;
+            }
+
+            default:
+                break;
+        }
+    }
+
+    /*!
+    @brief add an object to an array
+
+    Appends the given element @a val to the end of the JSON value. If the
+    function is called on a JSON null value, an empty array is created before
+    appending @a val.
+
+    @param[in] val the value to add to the JSON array
+
+    @throw type_error.308 when called on a type other than JSON array or
+    null; example: `"cannot use push_back() with number"`
+
+    @complexity Amortized constant.
+
+    @liveexample{The example shows how `push_back()` and `+=` can be used to
+    add elements to a JSON array. Note how the `null` value was silently
+    converted to a JSON array.,push_back}
+
+    @since version 1.0.0
+    */
+    void push_back(basic_json&& val)
+    {
+        // push_back only works for null objects or arrays
+        if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
+        {
+            JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
+        }
+
+        // transform null object into an array
+        if (is_null())
+        {
+            m_type = value_t::array;
+            m_value = value_t::array;
+            assert_invariant();
+        }
+
+        // add element to array (move semantics)
+        m_value.array->push_back(std::move(val));
+        // invalidate object: mark it null so we do not call the destructor
+        // cppcheck-suppress accessMoved
+        val.m_type = value_t::null;
+    }
+
+    /*!
+    @brief add an object to an array
+    @copydoc push_back(basic_json&&)
+    */
+    reference operator+=(basic_json&& val)
+    {
+        push_back(std::move(val));
+        return *this;
+    }
+
+    /*!
+    @brief add an object to an array
+    @copydoc push_back(basic_json&&)
+    */
+    void push_back(const basic_json& val)
+    {
+        // push_back only works for null objects or arrays
+        if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
+        {
+            JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
+        }
+
+        // transform null object into an array
+        if (is_null())
+        {
+            m_type = value_t::array;
+            m_value = value_t::array;
+            assert_invariant();
+        }
+
+        // add element to array
+        m_value.array->push_back(val);
+    }
+
+    /*!
+    @brief add an object to an array
+    @copydoc push_back(basic_json&&)
+    */
+    reference operator+=(const basic_json& val)
+    {
+        push_back(val);
+        return *this;
+    }
+
+    /*!
+    @brief add an object to an object
+
+    Inserts the given element @a val to the JSON object. If the function is
+    called on a JSON null value, an empty object is created before inserting
+    @a val.
+
+    @param[in] val the value to add to the JSON object
+
+    @throw type_error.308 when called on a type other than JSON object or
+    null; example: `"cannot use push_back() with number"`
+
+    @complexity Logarithmic in the size of the container, O(log(`size()`)).
+
+    @liveexample{The example shows how `push_back()` and `+=` can be used to
+    add elements to a JSON object. Note how the `null` value was silently
+    converted to a JSON object.,push_back__object_t__value}
+
+    @since version 1.0.0
+    */
+    void push_back(const typename object_t::value_type& val)
+    {
+        // push_back only works for null objects or objects
+        if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
+        {
+            JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
+        }
+
+        // transform null object into an object
+        if (is_null())
+        {
+            m_type = value_t::object;
+            m_value = value_t::object;
+            assert_invariant();
+        }
+
+        // add element to array
+        m_value.object->insert(val);
+    }
+
+    /*!
+    @brief add an object to an object
+    @copydoc push_back(const typename object_t::value_type&)
+    */
+    reference operator+=(const typename object_t::value_type& val)
+    {
+        push_back(val);
+        return *this;
+    }
+
+    /*!
+    @brief add an object to an object
+
+    This function allows to use `push_back` with an initializer list. In case
+
+    1. the current value is an object,
+    2. the initializer list @a init contains only two elements, and
+    3. the first element of @a init is a string,
+
+    @a init is converted into an object element and added using
+    @ref push_back(const typename object_t::value_type&). Otherwise, @a init
+    is converted to a JSON value and added using @ref push_back(basic_json&&).
+
+    @param[in] init  an initializer list
+
+    @complexity Linear in the size of the initializer list @a init.
+
+    @note This function is required to resolve an ambiguous overload error,
+          because pairs like `{"key", "value"}` can be both interpreted as
+          `object_t::value_type` or `std::initializer_list<basic_json>`, see
+          https://github.com/nlohmann/json/issues/235 for more information.
+
+    @liveexample{The example shows how initializer lists are treated as
+    objects when possible.,push_back__initializer_list}
+    */
+    void push_back(initializer_list_t init)
+    {
+        if (is_object() and init.size() == 2 and (*init.begin())->is_string())
+        {
+            basic_json&& key = init.begin()->moved_or_copied();
+            push_back(typename object_t::value_type(
+                          std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
+        }
+        else
+        {
+            push_back(basic_json(init));
+        }
+    }
+
+    /*!
+    @brief add an object to an object
+    @copydoc push_back(initializer_list_t)
+    */
+    reference operator+=(initializer_list_t init)
+    {
+        push_back(init);
+        return *this;
+    }
+
+    /*!
+    @brief add an object to an array
+
+    Creates a JSON value from the passed parameters @a args to the end of the
+    JSON value. If the function is called on a JSON null value, an empty array
+    is created before appending the value created from @a args.
+
+    @param[in] args arguments to forward to a constructor of @ref basic_json
+    @tparam Args compatible types to create a @ref basic_json object
+
+    @return reference to the inserted element
+
+    @throw type_error.311 when called on a type other than JSON array or
+    null; example: `"cannot use emplace_back() with number"`
+
+    @complexity Amortized constant.
+
+    @liveexample{The example shows how `push_back()` can be used to add
+    elements to a JSON array. Note how the `null` value was silently converted
+    to a JSON array.,emplace_back}
+
+    @since version 2.0.8, returns reference since 3.7.0
+    */
+    template<class... Args>
+    reference emplace_back(Args&& ... args)
+    {
+        // emplace_back only works for null objects or arrays
+        if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
+        {
+            JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
+        }
+
+        // transform null object into an array
+        if (is_null())
+        {
+            m_type = value_t::array;
+            m_value = value_t::array;
+            assert_invariant();
+        }
+
+        // add element to array (perfect forwarding)
+#ifdef JSON_HAS_CPP_17
+        return m_value.array->emplace_back(std::forward<Args>(args)...);
+#else
+        m_value.array->emplace_back(std::forward<Args>(args)...);
+        return m_value.array->back();
+#endif
+    }
+
+    /*!
+    @brief add an object to an object if key does not exist
+
+    Inserts a new element into a JSON object constructed in-place with the
+    given @a args if there is no element with the key in the container. If the
+    function is called on a JSON null value, an empty object is created before
+    appending the value created from @a args.
+
+    @param[in] args arguments to forward to a constructor of @ref basic_json
+    @tparam Args compatible types to create a @ref basic_json object
+
+    @return a pair consisting of an iterator to the inserted element, or the
+            already-existing element if no insertion happened, and a bool
+            denoting whether the insertion took place.
+
+    @throw type_error.311 when called on a type other than JSON object or
+    null; example: `"cannot use emplace() with number"`
+
+    @complexity Logarithmic in the size of the container, O(log(`size()`)).
+
+    @liveexample{The example shows how `emplace()` can be used to add elements
+    to a JSON object. Note how the `null` value was silently converted to a
+    JSON object. Further note how no value is added if there was already one
+    value stored with the same key.,emplace}
+
+    @since version 2.0.8
+    */
+    template<class... Args>
+    std::pair<iterator, bool> emplace(Args&& ... args)
+    {
+        // emplace only works for null objects or arrays
+        if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
+        {
+            JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
+        }
+
+        // transform null object into an object
+        if (is_null())
+        {
+            m_type = value_t::object;
+            m_value = value_t::object;
+            assert_invariant();
+        }
+
+        // add element to array (perfect forwarding)
+        auto res = m_value.object->emplace(std::forward<Args>(args)...);
+        // create result iterator and set iterator to the result of emplace
+        auto it = begin();
+        it.m_it.object_iterator = res.first;
+
+        // return pair of iterator and boolean
+        return {it, res.second};
+    }
+
+    /// Helper for insertion of an iterator
+    /// @note: This uses std::distance to support GCC 4.8,
+    ///        see https://github.com/nlohmann/json/pull/1257
+    template<typename... Args>
+    iterator insert_iterator(const_iterator pos, Args&& ... args)
+    {
+        iterator result(this);
+        assert(m_value.array != nullptr);
+
+        auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
+        m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
+        result.m_it.array_iterator = m_value.array->begin() + insert_pos;
+
+        // This could have been written as:
+        // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
+        // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
+
+        return result;
+    }
+
+    /*!
+    @brief inserts element
+
+    Inserts element @a val before iterator @a pos.
+
+    @param[in] pos iterator before which the content will be inserted; may be
+    the end() iterator
+    @param[in] val element to insert
+    @return iterator pointing to the inserted @a val.
+
+    @throw type_error.309 if called on JSON values other than arrays;
+    example: `"cannot use insert() with string"`
+    @throw invalid_iterator.202 if @a pos is not an iterator of *this;
+    example: `"iterator does not fit current value"`
+
+    @complexity Constant plus linear in the distance between @a pos and end of
+    the container.
+
+    @liveexample{The example shows how `insert()` is used.,insert}
+
+    @since version 1.0.0
+    */
+    iterator insert(const_iterator pos, const basic_json& val)
+    {
+        // insert only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            // check if iterator pos fits to this JSON value
+            if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
+            {
+                JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
+            }
+
+            // insert to array and return iterator
+            return insert_iterator(pos, val);
+        }
+
+        JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
+    }
+
+    /*!
+    @brief inserts element
+    @copydoc insert(const_iterator, const basic_json&)
+    */
+    iterator insert(const_iterator pos, basic_json&& val)
+    {
+        return insert(pos, val);
+    }
+
+    /*!
+    @brief inserts elements
+
+    Inserts @a cnt copies of @a val before iterator @a pos.
+
+    @param[in] pos iterator before which the content will be inserted; may be
+    the end() iterator
+    @param[in] cnt number of copies of @a val to insert
+    @param[in] val element to insert
+    @return iterator pointing to the first element inserted, or @a pos if
+    `cnt==0`
+
+    @throw type_error.309 if called on JSON values other than arrays; example:
+    `"cannot use insert() with string"`
+    @throw invalid_iterator.202 if @a pos is not an iterator of *this;
+    example: `"iterator does not fit current value"`
+
+    @complexity Linear in @a cnt plus linear in the distance between @a pos
+    and end of the container.
+
+    @liveexample{The example shows how `insert()` is used.,insert__count}
+
+    @since version 1.0.0
+    */
+    iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
+    {
+        // insert only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            // check if iterator pos fits to this JSON value
+            if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
+            {
+                JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
+            }
+
+            // insert to array and return iterator
+            return insert_iterator(pos, cnt, val);
+        }
+
+        JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
+    }
+
+    /*!
+    @brief inserts elements
+
+    Inserts elements from range `[first, last)` before iterator @a pos.
+
+    @param[in] pos iterator before which the content will be inserted; may be
+    the end() iterator
+    @param[in] first begin of the range of elements to insert
+    @param[in] last end of the range of elements to insert
+
+    @throw type_error.309 if called on JSON values other than arrays; example:
+    `"cannot use insert() with string"`
+    @throw invalid_iterator.202 if @a pos is not an iterator of *this;
+    example: `"iterator does not fit current value"`
+    @throw invalid_iterator.210 if @a first and @a last do not belong to the
+    same JSON value; example: `"iterators do not fit"`
+    @throw invalid_iterator.211 if @a first or @a last are iterators into
+    container for which insert is called; example: `"passed iterators may not
+    belong to container"`
+
+    @return iterator pointing to the first element inserted, or @a pos if
+    `first==last`
+
+    @complexity Linear in `std::distance(first, last)` plus linear in the
+    distance between @a pos and end of the container.
+
+    @liveexample{The example shows how `insert()` is used.,insert__range}
+
+    @since version 1.0.0
+    */
+    iterator insert(const_iterator pos, const_iterator first, const_iterator last)
+    {
+        // insert only works for arrays
+        if (JSON_HEDLEY_UNLIKELY(not is_array()))
+        {
+            JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
+        }
+
+        // check if iterator pos fits to this JSON value
+        if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
+        {
+            JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
+        }
+
+        // check if range iterators belong to the same JSON object
+        if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
+        }
+
+        if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
+        {
+            JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
+        }
+
+        // insert to array and return iterator
+        return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
+    }
+
+    /*!
+    @brief inserts elements
+
+    Inserts elements from initializer list @a ilist before iterator @a pos.
+
+    @param[in] pos iterator before which the content will be inserted; may be
+    the end() iterator
+    @param[in] ilist initializer list to insert the values from
+
+    @throw type_error.309 if called on JSON values other than arrays; example:
+    `"cannot use insert() with string"`
+    @throw invalid_iterator.202 if @a pos is not an iterator of *this;
+    example: `"iterator does not fit current value"`
+
+    @return iterator pointing to the first element inserted, or @a pos if
+    `ilist` is empty
+
+    @complexity Linear in `ilist.size()` plus linear in the distance between
+    @a pos and end of the container.
+
+    @liveexample{The example shows how `insert()` is used.,insert__ilist}
+
+    @since version 1.0.0
+    */
+    iterator insert(const_iterator pos, initializer_list_t ilist)
+    {
+        // insert only works for arrays
+        if (JSON_HEDLEY_UNLIKELY(not is_array()))
+        {
+            JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
+        }
+
+        // check if iterator pos fits to this JSON value
+        if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
+        {
+            JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
+        }
+
+        // insert to array and return iterator
+        return insert_iterator(pos, ilist.begin(), ilist.end());
+    }
+
+    /*!
+    @brief inserts elements
+
+    Inserts elements from range `[first, last)`.
+
+    @param[in] first begin of the range of elements to insert
+    @param[in] last end of the range of elements to insert
+
+    @throw type_error.309 if called on JSON values other than objects; example:
+    `"cannot use insert() with string"`
+    @throw invalid_iterator.202 if iterator @a first or @a last does does not
+    point to an object; example: `"iterators first and last must point to
+    objects"`
+    @throw invalid_iterator.210 if @a first and @a last do not belong to the
+    same JSON value; example: `"iterators do not fit"`
+
+    @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
+    of elements to insert.
+
+    @liveexample{The example shows how `insert()` is used.,insert__range_object}
+
+    @since version 3.0.0
+    */
+    void insert(const_iterator first, const_iterator last)
+    {
+        // insert only works for objects
+        if (JSON_HEDLEY_UNLIKELY(not is_object()))
+        {
+            JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
+        }
+
+        // check if range iterators belong to the same JSON object
+        if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
+        }
+
+        // passed iterators must belong to objects
+        if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()))
+        {
+            JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
+        }
+
+        m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
+    }
+
+    /*!
+    @brief updates a JSON object from another object, overwriting existing keys
+
+    Inserts all values from JSON object @a j and overwrites existing keys.
+
+    @param[in] j  JSON object to read values from
+
+    @throw type_error.312 if called on JSON values other than objects; example:
+    `"cannot use update() with string"`
+
+    @complexity O(N*log(size() + N)), where N is the number of elements to
+                insert.
+
+    @liveexample{The example shows how `update()` is used.,update}
+
+    @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
+
+    @since version 3.0.0
+    */
+    void update(const_reference j)
+    {
+        // implicitly convert null value to an empty object
+        if (is_null())
+        {
+            m_type = value_t::object;
+            m_value.object = create<object_t>();
+            assert_invariant();
+        }
+
+        if (JSON_HEDLEY_UNLIKELY(not is_object()))
+        {
+            JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
+        }
+        if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
+        {
+            JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
+        }
+
+        for (auto it = j.cbegin(); it != j.cend(); ++it)
+        {
+            m_value.object->operator[](it.key()) = it.value();
+        }
+    }
+
+    /*!
+    @brief updates a JSON object from another object, overwriting existing keys
+
+    Inserts all values from from range `[first, last)` and overwrites existing
+    keys.
+
+    @param[in] first begin of the range of elements to insert
+    @param[in] last end of the range of elements to insert
+
+    @throw type_error.312 if called on JSON values other than objects; example:
+    `"cannot use update() with string"`
+    @throw invalid_iterator.202 if iterator @a first or @a last does does not
+    point to an object; example: `"iterators first and last must point to
+    objects"`
+    @throw invalid_iterator.210 if @a first and @a last do not belong to the
+    same JSON value; example: `"iterators do not fit"`
+
+    @complexity O(N*log(size() + N)), where N is the number of elements to
+                insert.
+
+    @liveexample{The example shows how `update()` is used__range.,update}
+
+    @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
+
+    @since version 3.0.0
+    */
+    void update(const_iterator first, const_iterator last)
+    {
+        // implicitly convert null value to an empty object
+        if (is_null())
+        {
+            m_type = value_t::object;
+            m_value.object = create<object_t>();
+            assert_invariant();
+        }
+
+        if (JSON_HEDLEY_UNLIKELY(not is_object()))
+        {
+            JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
+        }
+
+        // check if range iterators belong to the same JSON object
+        if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
+        }
+
+        // passed iterators must belong to objects
+        if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()
+                                 or not last.m_object->is_object()))
+        {
+            JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
+        }
+
+        for (auto it = first; it != last; ++it)
+        {
+            m_value.object->operator[](it.key()) = it.value();
+        }
+    }
+
+    /*!
+    @brief exchanges the values
+
+    Exchanges the contents of the JSON value with those of @a other. Does not
+    invoke any move, copy, or swap operations on individual elements. All
+    iterators and references remain valid. The past-the-end iterator is
+    invalidated.
+
+    @param[in,out] other JSON value to exchange the contents with
+
+    @complexity Constant.
+
+    @liveexample{The example below shows how JSON values can be swapped with
+    `swap()`.,swap__reference}
+
+    @since version 1.0.0
+    */
+    void swap(reference other) noexcept (
+        std::is_nothrow_move_constructible<value_t>::value and
+        std::is_nothrow_move_assignable<value_t>::value and
+        std::is_nothrow_move_constructible<json_value>::value and
+        std::is_nothrow_move_assignable<json_value>::value
+    )
+    {
+        std::swap(m_type, other.m_type);
+        std::swap(m_value, other.m_value);
+        assert_invariant();
+    }
+
+    /*!
+    @brief exchanges the values
+
+    Exchanges the contents of a JSON array with those of @a other. Does not
+    invoke any move, copy, or swap operations on individual elements. All
+    iterators and references remain valid. The past-the-end iterator is
+    invalidated.
+
+    @param[in,out] other array to exchange the contents with
+
+    @throw type_error.310 when JSON value is not an array; example: `"cannot
+    use swap() with string"`
+
+    @complexity Constant.
+
+    @liveexample{The example below shows how arrays can be swapped with
+    `swap()`.,swap__array_t}
+
+    @since version 1.0.0
+    */
+    void swap(array_t& other)
+    {
+        // swap only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            std::swap(*(m_value.array), other);
+        }
+        else
+        {
+            JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
+        }
+    }
+
+    /*!
+    @brief exchanges the values
+
+    Exchanges the contents of a JSON object with those of @a other. Does not
+    invoke any move, copy, or swap operations on individual elements. All
+    iterators and references remain valid. The past-the-end iterator is
+    invalidated.
+
+    @param[in,out] other object to exchange the contents with
+
+    @throw type_error.310 when JSON value is not an object; example:
+    `"cannot use swap() with string"`
+
+    @complexity Constant.
+
+    @liveexample{The example below shows how objects can be swapped with
+    `swap()`.,swap__object_t}
+
+    @since version 1.0.0
+    */
+    void swap(object_t& other)
+    {
+        // swap only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            std::swap(*(m_value.object), other);
+        }
+        else
+        {
+            JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
+        }
+    }
+
+    /*!
+    @brief exchanges the values
+
+    Exchanges the contents of a JSON string with those of @a other. Does not
+    invoke any move, copy, or swap operations on individual elements. All
+    iterators and references remain valid. The past-the-end iterator is
+    invalidated.
+
+    @param[in,out] other string to exchange the contents with
+
+    @throw type_error.310 when JSON value is not a string; example: `"cannot
+    use swap() with boolean"`
+
+    @complexity Constant.
+
+    @liveexample{The example below shows how strings can be swapped with
+    `swap()`.,swap__string_t}
+
+    @since version 1.0.0
+    */
+    void swap(string_t& other)
+    {
+        // swap only works for strings
+        if (JSON_HEDLEY_LIKELY(is_string()))
+        {
+            std::swap(*(m_value.string), other);
+        }
+        else
+        {
+            JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
+        }
+    }
+
+    /// @}
+
+  public:
+    //////////////////////////////////////////
+    // lexicographical comparison operators //
+    //////////////////////////////////////////
+
+    /// @name lexicographical comparison operators
+    /// @{
+
+    /*!
+    @brief comparison: equal
+
+    Compares two JSON values for equality according to the following rules:
+    - Two JSON values are equal if (1) they are from the same type and (2)
+      their stored values are the same according to their respective
+      `operator==`.
+    - Integer and floating-point numbers are automatically converted before
+      comparison. Note than two NaN values are always treated as unequal.
+    - Two JSON null values are equal.
+
+    @note Floating-point inside JSON values numbers are compared with
+    `json::number_float_t::operator==` which is `double::operator==` by
+    default. To compare floating-point while respecting an epsilon, an alternative
+    [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
+    could be used, for instance
+    @code {.cpp}
+    template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
+    inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
+    {
+        return std::abs(a - b) <= epsilon;
+    }
+    @endcode
+
+    @note NaN values never compare equal to themselves or to other NaN values.
+
+    @param[in] lhs  first JSON value to consider
+    @param[in] rhs  second JSON value to consider
+    @return whether the values @a lhs and @a rhs are equal
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+
+    @complexity Linear.
+
+    @liveexample{The example demonstrates comparing several JSON
+    types.,operator__equal}
+
+    @since version 1.0.0
+    */
+    friend bool operator==(const_reference lhs, const_reference rhs) noexcept
+    {
+        const auto lhs_type = lhs.type();
+        const auto rhs_type = rhs.type();
+
+        if (lhs_type == rhs_type)
+        {
+            switch (lhs_type)
+            {
+                case value_t::array:
+                    return *lhs.m_value.array == *rhs.m_value.array;
+
+                case value_t::object:
+                    return *lhs.m_value.object == *rhs.m_value.object;
+
+                case value_t::null:
+                    return true;
+
+                case value_t::string:
+                    return *lhs.m_value.string == *rhs.m_value.string;
+
+                case value_t::boolean:
+                    return lhs.m_value.boolean == rhs.m_value.boolean;
+
+                case value_t::number_integer:
+                    return lhs.m_value.number_integer == rhs.m_value.number_integer;
+
+                case value_t::number_unsigned:
+                    return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
+
+                case value_t::number_float:
+                    return lhs.m_value.number_float == rhs.m_value.number_float;
+
+                default:
+                    return false;
+            }
+        }
+        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
+        {
+            return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
+        }
+        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
+        {
+            return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
+        }
+        else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
+        {
+            return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
+        }
+        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
+        {
+            return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
+        }
+        else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
+        {
+            return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
+        }
+        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
+        {
+            return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
+        }
+
+        return false;
+    }
+
+    /*!
+    @brief comparison: equal
+    @copydoc operator==(const_reference, const_reference)
+    */
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
+    {
+        return lhs == basic_json(rhs);
+    }
+
+    /*!
+    @brief comparison: equal
+    @copydoc operator==(const_reference, const_reference)
+    */
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
+    {
+        return basic_json(lhs) == rhs;
+    }
+
+    /*!
+    @brief comparison: not equal
+
+    Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
+
+    @param[in] lhs  first JSON value to consider
+    @param[in] rhs  second JSON value to consider
+    @return whether the values @a lhs and @a rhs are not equal
+
+    @complexity Linear.
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+
+    @liveexample{The example demonstrates comparing several JSON
+    types.,operator__notequal}
+
+    @since version 1.0.0
+    */
+    friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
+    {
+        return not (lhs == rhs);
+    }
+
+    /*!
+    @brief comparison: not equal
+    @copydoc operator!=(const_reference, const_reference)
+    */
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
+    {
+        return lhs != basic_json(rhs);
+    }
+
+    /*!
+    @brief comparison: not equal
+    @copydoc operator!=(const_reference, const_reference)
+    */
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
+    {
+        return basic_json(lhs) != rhs;
+    }
+
+    /*!
+    @brief comparison: less than
+
+    Compares whether one JSON value @a lhs is less than another JSON value @a
+    rhs according to the following rules:
+    - If @a lhs and @a rhs have the same type, the values are compared using
+      the default `<` operator.
+    - Integer and floating-point numbers are automatically converted before
+      comparison
+    - In case @a lhs and @a rhs have different types, the values are ignored
+      and the order of the types is considered, see
+      @ref operator<(const value_t, const value_t).
+
+    @param[in] lhs  first JSON value to consider
+    @param[in] rhs  second JSON value to consider
+    @return whether @a lhs is less than @a rhs
+
+    @complexity Linear.
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+
+    @liveexample{The example demonstrates comparing several JSON
+    types.,operator__less}
+
+    @since version 1.0.0
+    */
+    friend bool operator<(const_reference lhs, const_reference rhs) noexcept
+    {
+        const auto lhs_type = lhs.type();
+        const auto rhs_type = rhs.type();
+
+        if (lhs_type == rhs_type)
+        {
+            switch (lhs_type)
+            {
+                case value_t::array:
+                    // note parentheses are necessary, see
+                    // https://github.com/nlohmann/json/issues/1530
+                    return (*lhs.m_value.array) < (*rhs.m_value.array);
+
+                case value_t::object:
+                    return (*lhs.m_value.object) < (*rhs.m_value.object);
+
+                case value_t::null:
+                    return false;
+
+                case value_t::string:
+                    return (*lhs.m_value.string) < (*rhs.m_value.string);
+
+                case value_t::boolean:
+                    return (lhs.m_value.boolean) < (rhs.m_value.boolean);
+
+                case value_t::number_integer:
+                    return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
+
+                case value_t::number_unsigned:
+                    return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
+
+                case value_t::number_float:
+                    return (lhs.m_value.number_float) < (rhs.m_value.number_float);
+
+                default:
+                    return false;
+            }
+        }
+        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
+        {
+            return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
+        }
+        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
+        {
+            return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
+        }
+        else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
+        {
+            return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
+        }
+        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
+        {
+            return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
+        }
+        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
+        {
+            return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
+        }
+        else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
+        {
+            return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
+        }
+
+        // We only reach this line if we cannot compare values. In that case,
+        // we compare types. Note we have to call the operator explicitly,
+        // because MSVC has problems otherwise.
+        return operator<(lhs_type, rhs_type);
+    }
+
+    /*!
+    @brief comparison: less than
+    @copydoc operator<(const_reference, const_reference)
+    */
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
+    {
+        return lhs < basic_json(rhs);
+    }
+
+    /*!
+    @brief comparison: less than
+    @copydoc operator<(const_reference, const_reference)
+    */
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
+    {
+        return basic_json(lhs) < rhs;
+    }
+
+    /*!
+    @brief comparison: less than or equal
+
+    Compares whether one JSON value @a lhs is less than or equal to another
+    JSON value by calculating `not (rhs < lhs)`.
+
+    @param[in] lhs  first JSON value to consider
+    @param[in] rhs  second JSON value to consider
+    @return whether @a lhs is less than or equal to @a rhs
+
+    @complexity Linear.
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+
+    @liveexample{The example demonstrates comparing several JSON
+    types.,operator__greater}
+
+    @since version 1.0.0
+    */
+    friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
+    {
+        return not (rhs < lhs);
+    }
+
+    /*!
+    @brief comparison: less than or equal
+    @copydoc operator<=(const_reference, const_reference)
+    */
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
+    {
+        return lhs <= basic_json(rhs);
+    }
+
+    /*!
+    @brief comparison: less than or equal
+    @copydoc operator<=(const_reference, const_reference)
+    */
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
+    {
+        return basic_json(lhs) <= rhs;
+    }
+
+    /*!
+    @brief comparison: greater than
+
+    Compares whether one JSON value @a lhs is greater than another
+    JSON value by calculating `not (lhs <= rhs)`.
+
+    @param[in] lhs  first JSON value to consider
+    @param[in] rhs  second JSON value to consider
+    @return whether @a lhs is greater than to @a rhs
+
+    @complexity Linear.
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+
+    @liveexample{The example demonstrates comparing several JSON
+    types.,operator__lessequal}
+
+    @since version 1.0.0
+    */
+    friend bool operator>(const_reference lhs, const_reference rhs) noexcept
+    {
+        return not (lhs <= rhs);
+    }
+
+    /*!
+    @brief comparison: greater than
+    @copydoc operator>(const_reference, const_reference)
+    */
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
+    {
+        return lhs > basic_json(rhs);
+    }
+
+    /*!
+    @brief comparison: greater than
+    @copydoc operator>(const_reference, const_reference)
+    */
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
+    {
+        return basic_json(lhs) > rhs;
+    }
+
+    /*!
+    @brief comparison: greater than or equal
+
+    Compares whether one JSON value @a lhs is greater than or equal to another
+    JSON value by calculating `not (lhs < rhs)`.
+
+    @param[in] lhs  first JSON value to consider
+    @param[in] rhs  second JSON value to consider
+    @return whether @a lhs is greater than or equal to @a rhs
+
+    @complexity Linear.
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+
+    @liveexample{The example demonstrates comparing several JSON
+    types.,operator__greaterequal}
+
+    @since version 1.0.0
+    */
+    friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
+    {
+        return not (lhs < rhs);
+    }
+
+    /*!
+    @brief comparison: greater than or equal
+    @copydoc operator>=(const_reference, const_reference)
+    */
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
+    {
+        return lhs >= basic_json(rhs);
+    }
+
+    /*!
+    @brief comparison: greater than or equal
+    @copydoc operator>=(const_reference, const_reference)
+    */
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
+    {
+        return basic_json(lhs) >= rhs;
+    }
+
+    /// @}
+
+    ///////////////////
+    // serialization //
+    ///////////////////
+
+    /// @name serialization
+    /// @{
+
+    /*!
+    @brief serialize to stream
+
+    Serialize the given JSON value @a j to the output stream @a o. The JSON
+    value will be serialized using the @ref dump member function.
+
+    - The indentation of the output can be controlled with the member variable
+      `width` of the output stream @a o. For instance, using the manipulator
+      `std::setw(4)` on @a o sets the indentation level to `4` and the
+      serialization result is the same as calling `dump(4)`.
+
+    - The indentation character can be controlled with the member variable
+      `fill` of the output stream @a o. For instance, the manipulator
+      `std::setfill('\\t')` sets indentation to use a tab character rather than
+      the default space character.
+
+    @param[in,out] o  stream to serialize to
+    @param[in] j  JSON value to serialize
+
+    @return the stream @a o
+
+    @throw type_error.316 if a string stored inside the JSON value is not
+                          UTF-8 encoded
+
+    @complexity Linear.
+
+    @liveexample{The example below shows the serialization with different
+    parameters to `width` to adjust the indentation level.,operator_serialize}
+
+    @since version 1.0.0; indentation character added in version 3.0.0
+    */
+    friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
+    {
+        // read width member and use it as indentation parameter if nonzero
+        const bool pretty_print = o.width() > 0;
+        const auto indentation = pretty_print ? o.width() : 0;
+
+        // reset width to 0 for subsequent calls to this stream
+        o.width(0);
+
+        // do the actual serialization
+        serializer s(detail::output_adapter<char>(o), o.fill());
+        s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
+        return o;
+    }
+
+    /*!
+    @brief serialize to stream
+    @deprecated This stream operator is deprecated and will be removed in
+                future 4.0.0 of the library. Please use
+                @ref operator<<(std::ostream&, const basic_json&)
+                instead; that is, replace calls like `j >> o;` with `o << j;`.
+    @since version 1.0.0; deprecated since version 3.0.0
+    */
+    JSON_HEDLEY_DEPRECATED(3.0.0)
+    friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
+    {
+        return o << j;
+    }
+
+    /// @}
+
+
+    /////////////////////
+    // deserialization //
+    /////////////////////
+
+    /// @name deserialization
+    /// @{
+
+    /*!
+    @brief deserialize from a compatible input
+
+    This function reads from a compatible input. Examples are:
+    - an array of 1-byte values
+    - strings with character/literal type with size of 1 byte
+    - input streams
+    - container with contiguous storage of 1-byte values. Compatible container
+      types include `std::vector`, `std::string`, `std::array`,
+      `std::valarray`, and `std::initializer_list`. Furthermore, C-style
+      arrays can be used with `std::begin()`/`std::end()`. User-defined
+      containers can be used as long as they implement random-access iterators
+      and a contiguous storage.
+
+    @pre Each element of the container has a size of 1 byte. Violating this
+    precondition yields undefined behavior. **This precondition is enforced
+    with a static assertion.**
+
+    @pre The container storage is contiguous. Violating this precondition
+    yields undefined behavior. **This precondition is enforced with an
+    assertion.**
+
+    @warning There is no way to enforce all preconditions at compile-time. If
+             the function is called with a noncompliant container and with
+             assertions switched off, the behavior is undefined and will most
+             likely yield segmentation violation.
+
+    @param[in] i  input to read from
+    @param[in] cb  a parser callback function of type @ref parser_callback_t
+    which is used to control the deserialization by filtering unwanted values
+    (optional)
+    @param[in] allow_exceptions  whether to throw exceptions in case of a
+    parse error (optional, true by default)
+
+    @return deserialized JSON value; in case of a parse error and
+            @a allow_exceptions set to `false`, the return value will be
+            value_t::discarded.
+
+    @throw parse_error.101 if a parse error occurs; example: `""unexpected end
+    of input; expected string literal""`
+    @throw parse_error.102 if to_unicode fails or surrogate error
+    @throw parse_error.103 if to_unicode fails
+
+    @complexity Linear in the length of the input. The parser is a predictive
+    LL(1) parser. The complexity can be higher if the parser callback function
+    @a cb has a super-linear complexity.
+
+    @note A UTF-8 byte order mark is silently ignored.
+
+    @liveexample{The example below demonstrates the `parse()` function reading
+    from an array.,parse__array__parser_callback_t}
+
+    @liveexample{The example below demonstrates the `parse()` function with
+    and without callback function.,parse__string__parser_callback_t}
+
+    @liveexample{The example below demonstrates the `parse()` function with
+    and without callback function.,parse__istream__parser_callback_t}
+
+    @liveexample{The example below demonstrates the `parse()` function reading
+    from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
+
+    @since version 2.0.3 (contiguous containers)
+    */
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json parse(detail::input_adapter&& i,
+                            const parser_callback_t cb = nullptr,
+                            const bool allow_exceptions = true)
+    {
+        basic_json result;
+        parser(i, cb, allow_exceptions).parse(true, result);
+        return result;
+    }
+
+    static bool accept(detail::input_adapter&& i)
+    {
+        return parser(i).accept(true);
+    }
+
+    /*!
+    @brief generate SAX events
+
+    The SAX event lister must follow the interface of @ref json_sax.
+
+    This function reads from a compatible input. Examples are:
+    - an array of 1-byte values
+    - strings with character/literal type with size of 1 byte
+    - input streams
+    - container with contiguous storage of 1-byte values. Compatible container
+      types include `std::vector`, `std::string`, `std::array`,
+      `std::valarray`, and `std::initializer_list`. Furthermore, C-style
+      arrays can be used with `std::begin()`/`std::end()`. User-defined
+      containers can be used as long as they implement random-access iterators
+      and a contiguous storage.
+
+    @pre Each element of the container has a size of 1 byte. Violating this
+    precondition yields undefined behavior. **This precondition is enforced
+    with a static assertion.**
+
+    @pre The container storage is contiguous. Violating this precondition
+    yields undefined behavior. **This precondition is enforced with an
+    assertion.**
+
+    @warning There is no way to enforce all preconditions at compile-time. If
+             the function is called with a noncompliant container and with
+             assertions switched off, the behavior is undefined and will most
+             likely yield segmentation violation.
+
+    @param[in] i  input to read from
+    @param[in,out] sax  SAX event listener
+    @param[in] format  the format to parse (JSON, CBOR, MessagePack, or UBJSON)
+    @param[in] strict  whether the input has to be consumed completely
+
+    @return return value of the last processed SAX event
+
+    @throw parse_error.101 if a parse error occurs; example: `""unexpected end
+    of input; expected string literal""`
+    @throw parse_error.102 if to_unicode fails or surrogate error
+    @throw parse_error.103 if to_unicode fails
+
+    @complexity Linear in the length of the input. The parser is a predictive
+    LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
+    a super-linear complexity.
+
+    @note A UTF-8 byte order mark is silently ignored.
+
+    @liveexample{The example below demonstrates the `sax_parse()` function
+    reading from string and processing the events with a user-defined SAX
+    event consumer.,sax_parse}
+
+    @since version 3.2.0
+    */
+    template <typename SAX>
+    JSON_HEDLEY_NON_NULL(2)
+    static bool sax_parse(detail::input_adapter&& i, SAX* sax,
+                          input_format_t format = input_format_t::json,
+                          const bool strict = true)
+    {
+        assert(sax);
+        return format == input_format_t::json
+               ? parser(std::move(i)).sax_parse(sax, strict)
+               : detail::binary_reader<basic_json, SAX>(std::move(i)).sax_parse(format, sax, strict);
+    }
+
+    /*!
+    @brief deserialize from an iterator range with contiguous storage
+
+    This function reads from an iterator range of a container with contiguous
+    storage of 1-byte values. Compatible container types include
+    `std::vector`, `std::string`, `std::array`, `std::valarray`, and
+    `std::initializer_list`. Furthermore, C-style arrays can be used with
+    `std::begin()`/`std::end()`. User-defined containers can be used as long
+    as they implement random-access iterators and a contiguous storage.
+
+    @pre The iterator range is contiguous. Violating this precondition yields
+    undefined behavior. **This precondition is enforced with an assertion.**
+    @pre Each element in the range has a size of 1 byte. Violating this
+    precondition yields undefined behavior. **This precondition is enforced
+    with a static assertion.**
+
+    @warning There is no way to enforce all preconditions at compile-time. If
+             the function is called with noncompliant iterators and with
+             assertions switched off, the behavior is undefined and will most
+             likely yield segmentation violation.
+
+    @tparam IteratorType iterator of container with contiguous storage
+    @param[in] first  begin of the range to parse (included)
+    @param[in] last  end of the range to parse (excluded)
+    @param[in] cb  a parser callback function of type @ref parser_callback_t
+    which is used to control the deserialization by filtering unwanted values
+    (optional)
+    @param[in] allow_exceptions  whether to throw exceptions in case of a
+    parse error (optional, true by default)
+
+    @return deserialized JSON value; in case of a parse error and
+            @a allow_exceptions set to `false`, the return value will be
+            value_t::discarded.
+
+    @throw parse_error.101 in case of an unexpected token
+    @throw parse_error.102 if to_unicode fails or surrogate error
+    @throw parse_error.103 if to_unicode fails
+
+    @complexity Linear in the length of the input. The parser is a predictive
+    LL(1) parser. The complexity can be higher if the parser callback function
+    @a cb has a super-linear complexity.
+
+    @note A UTF-8 byte order mark is silently ignored.
+
+    @liveexample{The example below demonstrates the `parse()` function reading
+    from an iterator range.,parse__iteratortype__parser_callback_t}
+
+    @since version 2.0.3
+    */
+    template<class IteratorType, typename std::enable_if<
+                 std::is_base_of<
+                     std::random_access_iterator_tag,
+                     typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
+    static basic_json parse(IteratorType first, IteratorType last,
+                            const parser_callback_t cb = nullptr,
+                            const bool allow_exceptions = true)
+    {
+        basic_json result;
+        parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
+        return result;
+    }
+
+    template<class IteratorType, typename std::enable_if<
+                 std::is_base_of<
+                     std::random_access_iterator_tag,
+                     typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
+    static bool accept(IteratorType first, IteratorType last)
+    {
+        return parser(detail::input_adapter(first, last)).accept(true);
+    }
+
+    template<class IteratorType, class SAX, typename std::enable_if<
+                 std::is_base_of<
+                     std::random_access_iterator_tag,
+                     typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
+    JSON_HEDLEY_NON_NULL(3)
+    static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
+    {
+        return parser(detail::input_adapter(first, last)).sax_parse(sax);
+    }
+
+    /*!
+    @brief deserialize from stream
+    @deprecated This stream operator is deprecated and will be removed in
+                version 4.0.0 of the library. Please use
+                @ref operator>>(std::istream&, basic_json&)
+                instead; that is, replace calls like `j << i;` with `i >> j;`.
+    @since version 1.0.0; deprecated since version 3.0.0
+    */
+    JSON_HEDLEY_DEPRECATED(3.0.0)
+    friend std::istream& operator<<(basic_json& j, std::istream& i)
+    {
+        return operator>>(i, j);
+    }
+
+    /*!
+    @brief deserialize from stream
+
+    Deserializes an input stream to a JSON value.
+
+    @param[in,out] i  input stream to read a serialized JSON value from
+    @param[in,out] j  JSON value to write the deserialized input to
+
+    @throw parse_error.101 in case of an unexpected token
+    @throw parse_error.102 if to_unicode fails or surrogate error
+    @throw parse_error.103 if to_unicode fails
+
+    @complexity Linear in the length of the input. The parser is a predictive
+    LL(1) parser.
+
+    @note A UTF-8 byte order mark is silently ignored.
+
+    @liveexample{The example below shows how a JSON value is constructed by
+    reading a serialization from a stream.,operator_deserialize}
+
+    @sa parse(std::istream&, const parser_callback_t) for a variant with a
+    parser callback function to filter values while parsing
+
+    @since version 1.0.0
+    */
+    friend std::istream& operator>>(std::istream& i, basic_json& j)
+    {
+        parser(detail::input_adapter(i)).parse(false, j);
+        return i;
+    }
+
+    /// @}
+
+    ///////////////////////////
+    // convenience functions //
+    ///////////////////////////
+
+    /*!
+    @brief return the type as string
+
+    Returns the type name as string to be used in error messages - usually to
+    indicate that a function was called on a wrong JSON type.
+
+    @return a string representation of a the @a m_type member:
+            Value type  | return value
+            ----------- | -------------
+            null        | `"null"`
+            boolean     | `"boolean"`
+            string      | `"string"`
+            number      | `"number"` (for all number types)
+            object      | `"object"`
+            array       | `"array"`
+            discarded   | `"discarded"`
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+
+    @complexity Constant.
+
+    @liveexample{The following code exemplifies `type_name()` for all JSON
+    types.,type_name}
+
+    @sa @ref type() -- return the type of the JSON value
+    @sa @ref operator value_t() -- return the type of the JSON value (implicit)
+
+    @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
+    since 3.0.0
+    */
+    JSON_HEDLEY_RETURNS_NON_NULL
+    const char* type_name() const noexcept
+    {
+        {
+            switch (m_type)
+            {
+                case value_t::null:
+                    return "null";
+                case value_t::object:
+                    return "object";
+                case value_t::array:
+                    return "array";
+                case value_t::string:
+                    return "string";
+                case value_t::boolean:
+                    return "boolean";
+                case value_t::discarded:
+                    return "discarded";
+                default:
+                    return "number";
+            }
+        }
+    }
+
+
+  private:
+    //////////////////////
+    // member variables //
+    //////////////////////
+
+    /// the type of the current element
+    value_t m_type = value_t::null;
+
+    /// the value of the current element
+    json_value m_value = {};
+
+    //////////////////////////////////////////
+    // binary serialization/deserialization //
+    //////////////////////////////////////////
+
+    /// @name binary serialization/deserialization support
+    /// @{
+
+  public:
+    /*!
+    @brief create a CBOR serialization of a given JSON value
+
+    Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
+    Binary Object Representation) serialization format. CBOR is a binary
+    serialization format which aims to be more compact than JSON itself, yet
+    more efficient to parse.
+
+    The library uses the following mapping from JSON values types to
+    CBOR types according to the CBOR specification (RFC 7049):
+
+    JSON value type | value/range                                | CBOR type                          | first byte
+    --------------- | ------------------------------------------ | ---------------------------------- | ---------------
+    null            | `null`                                     | Null                               | 0xF6
+    boolean         | `true`                                     | True                               | 0xF5
+    boolean         | `false`                                    | False                              | 0xF4
+    number_integer  | -9223372036854775808..-2147483649          | Negative integer (8 bytes follow)  | 0x3B
+    number_integer  | -2147483648..-32769                        | Negative integer (4 bytes follow)  | 0x3A
+    number_integer  | -32768..-129                               | Negative integer (2 bytes follow)  | 0x39
+    number_integer  | -128..-25                                  | Negative integer (1 byte follow)   | 0x38
+    number_integer  | -24..-1                                    | Negative integer                   | 0x20..0x37
+    number_integer  | 0..23                                      | Integer                            | 0x00..0x17
+    number_integer  | 24..255                                    | Unsigned integer (1 byte follow)   | 0x18
+    number_integer  | 256..65535                                 | Unsigned integer (2 bytes follow)  | 0x19
+    number_integer  | 65536..4294967295                          | Unsigned integer (4 bytes follow)  | 0x1A
+    number_integer  | 4294967296..18446744073709551615           | Unsigned integer (8 bytes follow)  | 0x1B
+    number_unsigned | 0..23                                      | Integer                            | 0x00..0x17
+    number_unsigned | 24..255                                    | Unsigned integer (1 byte follow)   | 0x18
+    number_unsigned | 256..65535                                 | Unsigned integer (2 bytes follow)  | 0x19
+    number_unsigned | 65536..4294967295                          | Unsigned integer (4 bytes follow)  | 0x1A
+    number_unsigned | 4294967296..18446744073709551615           | Unsigned integer (8 bytes follow)  | 0x1B
+    number_float    | *any value*                                | Double-Precision Float             | 0xFB
+    string          | *length*: 0..23                            | UTF-8 string                       | 0x60..0x77
+    string          | *length*: 23..255                          | UTF-8 string (1 byte follow)       | 0x78
+    string          | *length*: 256..65535                       | UTF-8 string (2 bytes follow)      | 0x79
+    string          | *length*: 65536..4294967295                | UTF-8 string (4 bytes follow)      | 0x7A
+    string          | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow)      | 0x7B
+    array           | *size*: 0..23                              | array                              | 0x80..0x97
+    array           | *size*: 23..255                            | array (1 byte follow)              | 0x98
+    array           | *size*: 256..65535                         | array (2 bytes follow)             | 0x99
+    array           | *size*: 65536..4294967295                  | array (4 bytes follow)             | 0x9A
+    array           | *size*: 4294967296..18446744073709551615   | array (8 bytes follow)             | 0x9B
+    object          | *size*: 0..23                              | map                                | 0xA0..0xB7
+    object          | *size*: 23..255                            | map (1 byte follow)                | 0xB8
+    object          | *size*: 256..65535                         | map (2 bytes follow)               | 0xB9
+    object          | *size*: 65536..4294967295                  | map (4 bytes follow)               | 0xBA
+    object          | *size*: 4294967296..18446744073709551615   | map (8 bytes follow)               | 0xBB
+
+    @note The mapping is **complete** in the sense that any JSON value type
+          can be converted to a CBOR value.
+
+    @note If NaN or Infinity are stored inside a JSON number, they are
+          serialized properly. This behavior differs from the @ref dump()
+          function which serializes NaN or Infinity to `null`.
+
+    @note The following CBOR types are not used in the conversion:
+          - byte strings (0x40..0x5F)
+          - UTF-8 strings terminated by "break" (0x7F)
+          - arrays terminated by "break" (0x9F)
+          - maps terminated by "break" (0xBF)
+          - date/time (0xC0..0xC1)
+          - bignum (0xC2..0xC3)
+          - decimal fraction (0xC4)
+          - bigfloat (0xC5)
+          - tagged items (0xC6..0xD4, 0xD8..0xDB)
+          - expected conversions (0xD5..0xD7)
+          - simple values (0xE0..0xF3, 0xF8)
+          - undefined (0xF7)
+          - half and single-precision floats (0xF9-0xFA)
+          - break (0xFF)
+
+    @param[in] j  JSON value to serialize
+    @return MessagePack serialization as byte vector
+
+    @complexity Linear in the size of the JSON value @a j.
+
+    @liveexample{The example shows the serialization of a JSON value to a byte
+    vector in CBOR format.,to_cbor}
+
+    @sa http://cbor.io
+    @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
+        analogous deserialization
+    @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
+    @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
+             related UBJSON format
+
+    @since version 2.0.9
+    */
+    static std::vector<uint8_t> to_cbor(const basic_json& j)
+    {
+        std::vector<uint8_t> result;
+        to_cbor(j, result);
+        return result;
+    }
+
+    static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
+    {
+        binary_writer<uint8_t>(o).write_cbor(j);
+    }
+
+    static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
+    {
+        binary_writer<char>(o).write_cbor(j);
+    }
+
+    /*!
+    @brief create a MessagePack serialization of a given JSON value
+
+    Serializes a given JSON value @a j to a byte vector using the MessagePack
+    serialization format. MessagePack is a binary serialization format which
+    aims to be more compact than JSON itself, yet more efficient to parse.
+
+    The library uses the following mapping from JSON values types to
+    MessagePack types according to the MessagePack specification:
+
+    JSON value type | value/range                       | MessagePack type | first byte
+    --------------- | --------------------------------- | ---------------- | ----------
+    null            | `null`                            | nil              | 0xC0
+    boolean         | `true`                            | true             | 0xC3
+    boolean         | `false`                           | false            | 0xC2
+    number_integer  | -9223372036854775808..-2147483649 | int64            | 0xD3
+    number_integer  | -2147483648..-32769               | int32            | 0xD2
+    number_integer  | -32768..-129                      | int16            | 0xD1
+    number_integer  | -128..-33                         | int8             | 0xD0
+    number_integer  | -32..-1                           | negative fixint  | 0xE0..0xFF
+    number_integer  | 0..127                            | positive fixint  | 0x00..0x7F
+    number_integer  | 128..255                          | uint 8           | 0xCC
+    number_integer  | 256..65535                        | uint 16          | 0xCD
+    number_integer  | 65536..4294967295                 | uint 32          | 0xCE
+    number_integer  | 4294967296..18446744073709551615  | uint 64          | 0xCF
+    number_unsigned | 0..127                            | positive fixint  | 0x00..0x7F
+    number_unsigned | 128..255                          | uint 8           | 0xCC
+    number_unsigned | 256..65535                        | uint 16          | 0xCD
+    number_unsigned | 65536..4294967295                 | uint 32          | 0xCE
+    number_unsigned | 4294967296..18446744073709551615  | uint 64          | 0xCF
+    number_float    | *any value*                       | float 64         | 0xCB
+    string          | *length*: 0..31                   | fixstr           | 0xA0..0xBF
+    string          | *length*: 32..255                 | str 8            | 0xD9
+    string          | *length*: 256..65535              | str 16           | 0xDA
+    string          | *length*: 65536..4294967295       | str 32           | 0xDB
+    array           | *size*: 0..15                     | fixarray         | 0x90..0x9F
+    array           | *size*: 16..65535                 | array 16         | 0xDC
+    array           | *size*: 65536..4294967295         | array 32         | 0xDD
+    object          | *size*: 0..15                     | fix map          | 0x80..0x8F
+    object          | *size*: 16..65535                 | map 16           | 0xDE
+    object          | *size*: 65536..4294967295         | map 32           | 0xDF
+
+    @note The mapping is **complete** in the sense that any JSON value type
+          can be converted to a MessagePack value.
+
+    @note The following values can **not** be converted to a MessagePack value:
+          - strings with more than 4294967295 bytes
+          - arrays with more than 4294967295 elements
+          - objects with more than 4294967295 elements
+
+    @note The following MessagePack types are not used in the conversion:
+          - bin 8 - bin 32 (0xC4..0xC6)
+          - ext 8 - ext 32 (0xC7..0xC9)
+          - float 32 (0xCA)
+          - fixext 1 - fixext 16 (0xD4..0xD8)
+
+    @note Any MessagePack output created @ref to_msgpack can be successfully
+          parsed by @ref from_msgpack.
+
+    @note If NaN or Infinity are stored inside a JSON number, they are
+          serialized properly. This behavior differs from the @ref dump()
+          function which serializes NaN or Infinity to `null`.
+
+    @param[in] j  JSON value to serialize
+    @return MessagePack serialization as byte vector
+
+    @complexity Linear in the size of the JSON value @a j.
+
+    @liveexample{The example shows the serialization of a JSON value to a byte
+    vector in MessagePack format.,to_msgpack}
+
+    @sa http://msgpack.org
+    @sa @ref from_msgpack for the analogous deserialization
+    @sa @ref to_cbor(const basic_json& for the related CBOR format
+    @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
+             related UBJSON format
+
+    @since version 2.0.9
+    */
+    static std::vector<uint8_t> to_msgpack(const basic_json& j)
+    {
+        std::vector<uint8_t> result;
+        to_msgpack(j, result);
+        return result;
+    }
+
+    static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
+    {
+        binary_writer<uint8_t>(o).write_msgpack(j);
+    }
+
+    static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
+    {
+        binary_writer<char>(o).write_msgpack(j);
+    }
+
+    /*!
+    @brief create a UBJSON serialization of a given JSON value
+
+    Serializes a given JSON value @a j to a byte vector using the UBJSON
+    (Universal Binary JSON) serialization format. UBJSON aims to be more compact
+    than JSON itself, yet more efficient to parse.
+
+    The library uses the following mapping from JSON values types to
+    UBJSON types according to the UBJSON specification:
+
+    JSON value type | value/range                       | UBJSON type | marker
+    --------------- | --------------------------------- | ----------- | ------
+    null            | `null`                            | null        | `Z`
+    boolean         | `true`                            | true        | `T`
+    boolean         | `false`                           | false       | `F`
+    number_integer  | -9223372036854775808..-2147483649 | int64       | `L`
+    number_integer  | -2147483648..-32769               | int32       | `l`
+    number_integer  | -32768..-129                      | int16       | `I`
+    number_integer  | -128..127                         | int8        | `i`
+    number_integer  | 128..255                          | uint8       | `U`
+    number_integer  | 256..32767                        | int16       | `I`
+    number_integer  | 32768..2147483647                 | int32       | `l`
+    number_integer  | 2147483648..9223372036854775807   | int64       | `L`
+    number_unsigned | 0..127                            | int8        | `i`
+    number_unsigned | 128..255                          | uint8       | `U`
+    number_unsigned | 256..32767                        | int16       | `I`
+    number_unsigned | 32768..2147483647                 | int32       | `l`
+    number_unsigned | 2147483648..9223372036854775807   | int64       | `L`
+    number_float    | *any value*                       | float64     | `D`
+    string          | *with shortest length indicator*  | string      | `S`
+    array           | *see notes on optimized format*   | array       | `[`
+    object          | *see notes on optimized format*   | map         | `{`
+
+    @note The mapping is **complete** in the sense that any JSON value type
+          can be converted to a UBJSON value.
+
+    @note The following values can **not** be converted to a UBJSON value:
+          - strings with more than 9223372036854775807 bytes (theoretical)
+          - unsigned integer numbers above 9223372036854775807
+
+    @note The following markers are not used in the conversion:
+          - `Z`: no-op values are not created.
+          - `C`: single-byte strings are serialized with `S` markers.
+
+    @note Any UBJSON output created @ref to_ubjson can be successfully parsed
+          by @ref from_ubjson.
+
+    @note If NaN or Infinity are stored inside a JSON number, they are
+          serialized properly. This behavior differs from the @ref dump()
+          function which serializes NaN or Infinity to `null`.
+
+    @note The optimized formats for containers are supported: Parameter
+          @a use_size adds size information to the beginning of a container and
+          removes the closing marker. Parameter @a use_type further checks
+          whether all elements of a container have the same type and adds the
+          type marker to the beginning of the container. The @a use_type
+          parameter must only be used together with @a use_size = true. Note
+          that @a use_size = true alone may result in larger representations -
+          the benefit of this parameter is that the receiving side is
+          immediately informed on the number of elements of the container.
+
+    @param[in] j  JSON value to serialize
+    @param[in] use_size  whether to add size annotations to container types
+    @param[in] use_type  whether to add type annotations to container types
+                         (must be combined with @a use_size = true)
+    @return UBJSON serialization as byte vector
+
+    @complexity Linear in the size of the JSON value @a j.
+
+    @liveexample{The example shows the serialization of a JSON value to a byte
+    vector in UBJSON format.,to_ubjson}
+
+    @sa http://ubjson.org
+    @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
+        analogous deserialization
+    @sa @ref to_cbor(const basic_json& for the related CBOR format
+    @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
+
+    @since version 3.1.0
+    */
+    static std::vector<uint8_t> to_ubjson(const basic_json& j,
+                                          const bool use_size = false,
+                                          const bool use_type = false)
+    {
+        std::vector<uint8_t> result;
+        to_ubjson(j, result, use_size, use_type);
+        return result;
+    }
+
+    static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
+                          const bool use_size = false, const bool use_type = false)
+    {
+        binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
+    }
+
+    static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
+                          const bool use_size = false, const bool use_type = false)
+    {
+        binary_writer<char>(o).write_ubjson(j, use_size, use_type);
+    }
+
+
+    /*!
+    @brief Serializes the given JSON object `j` to BSON and returns a vector
+           containing the corresponding BSON-representation.
+
+    BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
+    stored as a single entity (a so-called document).
+
+    The library uses the following mapping from JSON values types to BSON types:
+
+    JSON value type | value/range                       | BSON type   | marker
+    --------------- | --------------------------------- | ----------- | ------
+    null            | `null`                            | null        | 0x0A
+    boolean         | `true`, `false`                   | boolean     | 0x08
+    number_integer  | -9223372036854775808..-2147483649 | int64       | 0x12
+    number_integer  | -2147483648..2147483647           | int32       | 0x10
+    number_integer  | 2147483648..9223372036854775807   | int64       | 0x12
+    number_unsigned | 0..2147483647                     | int32       | 0x10
+    number_unsigned | 2147483648..9223372036854775807   | int64       | 0x12
+    number_unsigned | 9223372036854775808..18446744073709551615| --   | --
+    number_float    | *any value*                       | double      | 0x01
+    string          | *any value*                       | string      | 0x02
+    array           | *any value*                       | document    | 0x04
+    object          | *any value*                       | document    | 0x03
+
+    @warning The mapping is **incomplete**, since only JSON-objects (and things
+    contained therein) can be serialized to BSON.
+    Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
+    and the keys may not contain U+0000, since they are serialized a
+    zero-terminated c-strings.
+
+    @throw out_of_range.407  if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
+    @throw out_of_range.409  if a key in `j` contains a NULL (U+0000)
+    @throw type_error.317    if `!j.is_object()`
+
+    @pre The input `j` is required to be an object: `j.is_object() == true`.
+
+    @note Any BSON output created via @ref to_bson can be successfully parsed
+          by @ref from_bson.
+
+    @param[in] j  JSON value to serialize
+    @return BSON serialization as byte vector
+
+    @complexity Linear in the size of the JSON value @a j.
+
+    @liveexample{The example shows the serialization of a JSON value to a byte
+    vector in BSON format.,to_bson}
+
+    @sa http://bsonspec.org/spec.html
+    @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
+        analogous deserialization
+    @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
+             related UBJSON format
+    @sa @ref to_cbor(const basic_json&) for the related CBOR format
+    @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
+    */
+    static std::vector<uint8_t> to_bson(const basic_json& j)
+    {
+        std::vector<uint8_t> result;
+        to_bson(j, result);
+        return result;
+    }
+
+    /*!
+    @brief Serializes the given JSON object `j` to BSON and forwards the
+           corresponding BSON-representation to the given output_adapter `o`.
+    @param j The JSON object to convert to BSON.
+    @param o The output adapter that receives the binary BSON representation.
+    @pre The input `j` shall be an object: `j.is_object() == true`
+    @sa @ref to_bson(const basic_json&)
+    */
+    static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
+    {
+        binary_writer<uint8_t>(o).write_bson(j);
+    }
+
+    /*!
+    @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
+    */
+    static void to_bson(const basic_json& j, detail::output_adapter<char> o)
+    {
+        binary_writer<char>(o).write_bson(j);
+    }
+
+
+    /*!
+    @brief create a JSON value from an input in CBOR format
+
+    Deserializes a given input @a i to a JSON value using the CBOR (Concise
+    Binary Object Representation) serialization format.
+
+    The library maps CBOR types to JSON value types as follows:
+
+    CBOR type              | JSON value type | first byte
+    ---------------------- | --------------- | ----------
+    Integer                | number_unsigned | 0x00..0x17
+    Unsigned integer       | number_unsigned | 0x18
+    Unsigned integer       | number_unsigned | 0x19
+    Unsigned integer       | number_unsigned | 0x1A
+    Unsigned integer       | number_unsigned | 0x1B
+    Negative integer       | number_integer  | 0x20..0x37
+    Negative integer       | number_integer  | 0x38
+    Negative integer       | number_integer  | 0x39
+    Negative integer       | number_integer  | 0x3A
+    Negative integer       | number_integer  | 0x3B
+    Negative integer       | number_integer  | 0x40..0x57
+    UTF-8 string           | string          | 0x60..0x77
+    UTF-8 string           | string          | 0x78
+    UTF-8 string           | string          | 0x79
+    UTF-8 string           | string          | 0x7A
+    UTF-8 string           | string          | 0x7B
+    UTF-8 string           | string          | 0x7F
+    array                  | array           | 0x80..0x97
+    array                  | array           | 0x98
+    array                  | array           | 0x99
+    array                  | array           | 0x9A
+    array                  | array           | 0x9B
+    array                  | array           | 0x9F
+    map                    | object          | 0xA0..0xB7
+    map                    | object          | 0xB8
+    map                    | object          | 0xB9
+    map                    | object          | 0xBA
+    map                    | object          | 0xBB
+    map                    | object          | 0xBF
+    False                  | `false`         | 0xF4
+    True                   | `true`          | 0xF5
+    Null                   | `null`          | 0xF6
+    Half-Precision Float   | number_float    | 0xF9
+    Single-Precision Float | number_float    | 0xFA
+    Double-Precision Float | number_float    | 0xFB
+
+    @warning The mapping is **incomplete** in the sense that not all CBOR
+             types can be converted to a JSON value. The following CBOR types
+             are not supported and will yield parse errors (parse_error.112):
+             - byte strings (0x40..0x5F)
+             - date/time (0xC0..0xC1)
+             - bignum (0xC2..0xC3)
+             - decimal fraction (0xC4)
+             - bigfloat (0xC5)
+             - tagged items (0xC6..0xD4, 0xD8..0xDB)
+             - expected conversions (0xD5..0xD7)
+             - simple values (0xE0..0xF3, 0xF8)
+             - undefined (0xF7)
+
+    @warning CBOR allows map keys of any type, whereas JSON only allows
+             strings as keys in object values. Therefore, CBOR maps with keys
+             other than UTF-8 strings are rejected (parse_error.113).
+
+    @note Any CBOR output created @ref to_cbor can be successfully parsed by
+          @ref from_cbor.
+
+    @param[in] i  an input in CBOR format convertible to an input adapter
+    @param[in] strict  whether to expect the input to be consumed until EOF
+                       (true by default)
+    @param[in] allow_exceptions  whether to throw exceptions in case of a
+    parse error (optional, true by default)
+
+    @return deserialized JSON value; in case of a parse error and
+            @a allow_exceptions set to `false`, the return value will be
+            value_t::discarded.
+
+    @throw parse_error.110 if the given input ends prematurely or the end of
+    file was not reached when @a strict was set to true
+    @throw parse_error.112 if unsupported features from CBOR were
+    used in the given input @a v or if the input is not valid CBOR
+    @throw parse_error.113 if a string was expected as map key, but not found
+
+    @complexity Linear in the size of the input @a i.
+
+    @liveexample{The example shows the deserialization of a byte vector in CBOR
+    format to a JSON value.,from_cbor}
+
+    @sa http://cbor.io
+    @sa @ref to_cbor(const basic_json&) for the analogous serialization
+    @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
+        related MessagePack format
+    @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
+        related UBJSON format
+
+    @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
+           consume input adapters, removed start_index parameter, and added
+           @a strict parameter since 3.0.0; added @a allow_exceptions parameter
+           since 3.2.0
+    */
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_cbor(detail::input_adapter&& i,
+                                const bool strict = true,
+                                const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::cbor, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /*!
+    @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
+    */
+    template<typename A1, typename A2,
+             detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_cbor(A1 && a1, A2 && a2,
+                                const bool strict = true,
+                                const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::cbor, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /*!
+    @brief create a JSON value from an input in MessagePack format
+
+    Deserializes a given input @a i to a JSON value using the MessagePack
+    serialization format.
+
+    The library maps MessagePack types to JSON value types as follows:
+
+    MessagePack type | JSON value type | first byte
+    ---------------- | --------------- | ----------
+    positive fixint  | number_unsigned | 0x00..0x7F
+    fixmap           | object          | 0x80..0x8F
+    fixarray         | array           | 0x90..0x9F
+    fixstr           | string          | 0xA0..0xBF
+    nil              | `null`          | 0xC0
+    false            | `false`         | 0xC2
+    true             | `true`          | 0xC3
+    float 32         | number_float    | 0xCA
+    float 64         | number_float    | 0xCB
+    uint 8           | number_unsigned | 0xCC
+    uint 16          | number_unsigned | 0xCD
+    uint 32          | number_unsigned | 0xCE
+    uint 64          | number_unsigned | 0xCF
+    int 8            | number_integer  | 0xD0
+    int 16           | number_integer  | 0xD1
+    int 32           | number_integer  | 0xD2
+    int 64           | number_integer  | 0xD3
+    str 8            | string          | 0xD9
+    str 16           | string          | 0xDA
+    str 32           | string          | 0xDB
+    array 16         | array           | 0xDC
+    array 32         | array           | 0xDD
+    map 16           | object          | 0xDE
+    map 32           | object          | 0xDF
+    negative fixint  | number_integer  | 0xE0-0xFF
+
+    @warning The mapping is **incomplete** in the sense that not all
+             MessagePack types can be converted to a JSON value. The following
+             MessagePack types are not supported and will yield parse errors:
+              - bin 8 - bin 32 (0xC4..0xC6)
+              - ext 8 - ext 32 (0xC7..0xC9)
+              - fixext 1 - fixext 16 (0xD4..0xD8)
+
+    @note Any MessagePack output created @ref to_msgpack can be successfully
+          parsed by @ref from_msgpack.
+
+    @param[in] i  an input in MessagePack format convertible to an input
+                  adapter
+    @param[in] strict  whether to expect the input to be consumed until EOF
+                       (true by default)
+    @param[in] allow_exceptions  whether to throw exceptions in case of a
+    parse error (optional, true by default)
+
+    @return deserialized JSON value; in case of a parse error and
+            @a allow_exceptions set to `false`, the return value will be
+            value_t::discarded.
+
+    @throw parse_error.110 if the given input ends prematurely or the end of
+    file was not reached when @a strict was set to true
+    @throw parse_error.112 if unsupported features from MessagePack were
+    used in the given input @a i or if the input is not valid MessagePack
+    @throw parse_error.113 if a string was expected as map key, but not found
+
+    @complexity Linear in the size of the input @a i.
+
+    @liveexample{The example shows the deserialization of a byte vector in
+    MessagePack format to a JSON value.,from_msgpack}
+
+    @sa http://msgpack.org
+    @sa @ref to_msgpack(const basic_json&) for the analogous serialization
+    @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
+        related CBOR format
+    @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
+        the related UBJSON format
+    @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
+        the related BSON format
+
+    @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
+           consume input adapters, removed start_index parameter, and added
+           @a strict parameter since 3.0.0; added @a allow_exceptions parameter
+           since 3.2.0
+    */
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_msgpack(detail::input_adapter&& i,
+                                   const bool strict = true,
+                                   const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::msgpack, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /*!
+    @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
+    */
+    template<typename A1, typename A2,
+             detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_msgpack(A1 && a1, A2 && a2,
+                                   const bool strict = true,
+                                   const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::msgpack, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /*!
+    @brief create a JSON value from an input in UBJSON format
+
+    Deserializes a given input @a i to a JSON value using the UBJSON (Universal
+    Binary JSON) serialization format.
+
+    The library maps UBJSON types to JSON value types as follows:
+
+    UBJSON type | JSON value type                         | marker
+    ----------- | --------------------------------------- | ------
+    no-op       | *no value, next value is read*          | `N`
+    null        | `null`                                  | `Z`
+    false       | `false`                                 | `F`
+    true        | `true`                                  | `T`
+    float32     | number_float                            | `d`
+    float64     | number_float                            | `D`
+    uint8       | number_unsigned                         | `U`
+    int8        | number_integer                          | `i`
+    int16       | number_integer                          | `I`
+    int32       | number_integer                          | `l`
+    int64       | number_integer                          | `L`
+    string      | string                                  | `S`
+    char        | string                                  | `C`
+    array       | array (optimized values are supported)  | `[`
+    object      | object (optimized values are supported) | `{`
+
+    @note The mapping is **complete** in the sense that any UBJSON value can
+          be converted to a JSON value.
+
+    @param[in] i  an input in UBJSON format convertible to an input adapter
+    @param[in] strict  whether to expect the input to be consumed until EOF
+                       (true by default)
+    @param[in] allow_exceptions  whether to throw exceptions in case of a
+    parse error (optional, true by default)
+
+    @return deserialized JSON value; in case of a parse error and
+            @a allow_exceptions set to `false`, the return value will be
+            value_t::discarded.
+
+    @throw parse_error.110 if the given input ends prematurely or the end of
+    file was not reached when @a strict was set to true
+    @throw parse_error.112 if a parse error occurs
+    @throw parse_error.113 if a string could not be parsed successfully
+
+    @complexity Linear in the size of the input @a i.
+
+    @liveexample{The example shows the deserialization of a byte vector in
+    UBJSON format to a JSON value.,from_ubjson}
+
+    @sa http://ubjson.org
+    @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
+             analogous serialization
+    @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
+        related CBOR format
+    @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
+        the related MessagePack format
+    @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
+        the related BSON format
+
+    @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
+    */
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_ubjson(detail::input_adapter&& i,
+                                  const bool strict = true,
+                                  const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::ubjson, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /*!
+    @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
+    */
+    template<typename A1, typename A2,
+             detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_ubjson(A1 && a1, A2 && a2,
+                                  const bool strict = true,
+                                  const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::ubjson, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /*!
+    @brief Create a JSON value from an input in BSON format
+
+    Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
+    serialization format.
+
+    The library maps BSON record types to JSON value types as follows:
+
+    BSON type       | BSON marker byte | JSON value type
+    --------------- | ---------------- | ---------------------------
+    double          | 0x01             | number_float
+    string          | 0x02             | string
+    document        | 0x03             | object
+    array           | 0x04             | array
+    binary          | 0x05             | still unsupported
+    undefined       | 0x06             | still unsupported
+    ObjectId        | 0x07             | still unsupported
+    boolean         | 0x08             | boolean
+    UTC Date-Time   | 0x09             | still unsupported
+    null            | 0x0A             | null
+    Regular Expr.   | 0x0B             | still unsupported
+    DB Pointer      | 0x0C             | still unsupported
+    JavaScript Code | 0x0D             | still unsupported
+    Symbol          | 0x0E             | still unsupported
+    JavaScript Code | 0x0F             | still unsupported
+    int32           | 0x10             | number_integer
+    Timestamp       | 0x11             | still unsupported
+    128-bit decimal float | 0x13       | still unsupported
+    Max Key         | 0x7F             | still unsupported
+    Min Key         | 0xFF             | still unsupported
+
+    @warning The mapping is **incomplete**. The unsupported mappings
+             are indicated in the table above.
+
+    @param[in] i  an input in BSON format convertible to an input adapter
+    @param[in] strict  whether to expect the input to be consumed until EOF
+                       (true by default)
+    @param[in] allow_exceptions  whether to throw exceptions in case of a
+    parse error (optional, true by default)
+
+    @return deserialized JSON value; in case of a parse error and
+            @a allow_exceptions set to `false`, the return value will be
+            value_t::discarded.
+
+    @throw parse_error.114 if an unsupported BSON record type is encountered
+
+    @complexity Linear in the size of the input @a i.
+
+    @liveexample{The example shows the deserialization of a byte vector in
+    BSON format to a JSON value.,from_bson}
+
+    @sa http://bsonspec.org/spec.html
+    @sa @ref to_bson(const basic_json&) for the analogous serialization
+    @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
+        related CBOR format
+    @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
+        the related MessagePack format
+    @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
+        related UBJSON format
+    */
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_bson(detail::input_adapter&& i,
+                                const bool strict = true,
+                                const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::bson, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /*!
+    @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
+    */
+    template<typename A1, typename A2,
+             detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_bson(A1 && a1, A2 && a2,
+                                const bool strict = true,
+                                const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::bson, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+
+
+    /// @}
+
+    //////////////////////////
+    // JSON Pointer support //
+    //////////////////////////
+
+    /// @name JSON Pointer functions
+    /// @{
+
+    /*!
+    @brief access specified element via JSON Pointer
+
+    Uses a JSON pointer to retrieve a reference to the respective JSON value.
+    No bound checking is performed. Similar to @ref operator[](const typename
+    object_t::key_type&), `null` values are created in arrays and objects if
+    necessary.
+
+    In particular:
+    - If the JSON pointer points to an object key that does not exist, it
+      is created an filled with a `null` value before a reference to it
+      is returned.
+    - If the JSON pointer points to an array index that does not exist, it
+      is created an filled with a `null` value before a reference to it
+      is returned. All indices between the current maximum and the given
+      index are also filled with `null`.
+    - The special value `-` is treated as a synonym for the index past the
+      end.
+
+    @param[in] ptr  a JSON pointer
+
+    @return reference to the element pointed to by @a ptr
+
+    @complexity Constant.
+
+    @throw parse_error.106   if an array index begins with '0'
+    @throw parse_error.109   if an array index was not a number
+    @throw out_of_range.404  if the JSON pointer can not be resolved
+
+    @liveexample{The behavior is shown in the example.,operatorjson_pointer}
+
+    @since version 2.0.0
+    */
+    reference operator[](const json_pointer& ptr)
+    {
+        return ptr.get_unchecked(this);
+    }
+
+    /*!
+    @brief access specified element via JSON Pointer
+
+    Uses a JSON pointer to retrieve a reference to the respective JSON value.
+    No bound checking is performed. The function does not change the JSON
+    value; no `null` values are created. In particular, the special value
+    `-` yields an exception.
+
+    @param[in] ptr  JSON pointer to the desired element
+
+    @return const reference to the element pointed to by @a ptr
+
+    @complexity Constant.
+
+    @throw parse_error.106   if an array index begins with '0'
+    @throw parse_error.109   if an array index was not a number
+    @throw out_of_range.402  if the array index '-' is used
+    @throw out_of_range.404  if the JSON pointer can not be resolved
+
+    @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
+
+    @since version 2.0.0
+    */
+    const_reference operator[](const json_pointer& ptr) const
+    {
+        return ptr.get_unchecked(this);
+    }
+
+    /*!
+    @brief access specified element via JSON Pointer
+
+    Returns a reference to the element at with specified JSON pointer @a ptr,
+    with bounds checking.
+
+    @param[in] ptr  JSON pointer to the desired element
+
+    @return reference to the element pointed to by @a ptr
+
+    @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
+    begins with '0'. See example below.
+
+    @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
+    is not a number. See example below.
+
+    @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
+    is out of range. See example below.
+
+    @throw out_of_range.402 if the array index '-' is used in the passed JSON
+    pointer @a ptr. As `at` provides checked access (and no elements are
+    implicitly inserted), the index '-' is always invalid. See example below.
+
+    @throw out_of_range.403 if the JSON pointer describes a key of an object
+    which cannot be found. See example below.
+
+    @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
+    See example below.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes in the JSON value.
+
+    @complexity Constant.
+
+    @since version 2.0.0
+
+    @liveexample{The behavior is shown in the example.,at_json_pointer}
+    */
+    reference at(const json_pointer& ptr)
+    {
+        return ptr.get_checked(this);
+    }
+
+    /*!
+    @brief access specified element via JSON Pointer
+
+    Returns a const reference to the element at with specified JSON pointer @a
+    ptr, with bounds checking.
+
+    @param[in] ptr  JSON pointer to the desired element
+
+    @return reference to the element pointed to by @a ptr
+
+    @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
+    begins with '0'. See example below.
+
+    @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
+    is not a number. See example below.
+
+    @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
+    is out of range. See example below.
+
+    @throw out_of_range.402 if the array index '-' is used in the passed JSON
+    pointer @a ptr. As `at` provides checked access (and no elements are
+    implicitly inserted), the index '-' is always invalid. See example below.
+
+    @throw out_of_range.403 if the JSON pointer describes a key of an object
+    which cannot be found. See example below.
+
+    @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
+    See example below.
+
+    @exceptionsafety Strong guarantee: if an exception is thrown, there are no
+    changes in the JSON value.
+
+    @complexity Constant.
+
+    @since version 2.0.0
+
+    @liveexample{The behavior is shown in the example.,at_json_pointer_const}
+    */
+    const_reference at(const json_pointer& ptr) const
+    {
+        return ptr.get_checked(this);
+    }
+
+    /*!
+    @brief return flattened JSON value
+
+    The function creates a JSON object whose keys are JSON pointers (see [RFC
+    6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
+    primitive. The original JSON value can be restored using the @ref
+    unflatten() function.
+
+    @return an object that maps JSON pointers to primitive values
+
+    @note Empty objects and arrays are flattened to `null` and will not be
+          reconstructed correctly by the @ref unflatten() function.
+
+    @complexity Linear in the size the JSON value.
+
+    @liveexample{The following code shows how a JSON object is flattened to an
+    object whose keys consist of JSON pointers.,flatten}
+
+    @sa @ref unflatten() for the reverse function
+
+    @since version 2.0.0
+    */
+    basic_json flatten() const
+    {
+        basic_json result(value_t::object);
+        json_pointer::flatten("", *this, result);
+        return result;
+    }
+
+    /*!
+    @brief unflatten a previously flattened JSON value
+
+    The function restores the arbitrary nesting of a JSON value that has been
+    flattened before using the @ref flatten() function. The JSON value must
+    meet certain constraints:
+    1. The value must be an object.
+    2. The keys must be JSON pointers (see
+       [RFC 6901](https://tools.ietf.org/html/rfc6901))
+    3. The mapped values must be primitive JSON types.
+
+    @return the original JSON from a flattened version
+
+    @note Empty objects and arrays are flattened by @ref flatten() to `null`
+          values and can not unflattened to their original type. Apart from
+          this example, for a JSON value `j`, the following is always true:
+          `j == j.flatten().unflatten()`.
+
+    @complexity Linear in the size the JSON value.
+
+    @throw type_error.314  if value is not an object
+    @throw type_error.315  if object values are not primitive
+
+    @liveexample{The following code shows how a flattened JSON object is
+    unflattened into the original nested JSON object.,unflatten}
+
+    @sa @ref flatten() for the reverse function
+
+    @since version 2.0.0
+    */
+    basic_json unflatten() const
+    {
+        return json_pointer::unflatten(*this);
+    }
+
+    /// @}
+
+    //////////////////////////
+    // JSON Patch functions //
+    //////////////////////////
+
+    /// @name JSON Patch functions
+    /// @{
+
+    /*!
+    @brief applies a JSON patch
+
+    [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
+    expressing a sequence of operations to apply to a JSON) document. With
+    this function, a JSON Patch is applied to the current JSON value by
+    executing all operations from the patch.
+
+    @param[in] json_patch  JSON patch document
+    @return patched document
+
+    @note The application of a patch is atomic: Either all operations succeed
+          and the patched document is returned or an exception is thrown. In
+          any case, the original value is not changed: the patch is applied
+          to a copy of the value.
+
+    @throw parse_error.104 if the JSON patch does not consist of an array of
+    objects
+
+    @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
+    attributes are missing); example: `"operation add must have member path"`
+
+    @throw out_of_range.401 if an array index is out of range.
+
+    @throw out_of_range.403 if a JSON pointer inside the patch could not be
+    resolved successfully in the current JSON value; example: `"key baz not
+    found"`
+
+    @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
+    "move")
+
+    @throw other_error.501 if "test" operation was unsuccessful
+
+    @complexity Linear in the size of the JSON value and the length of the
+    JSON patch. As usually only a fraction of the JSON value is affected by
+    the patch, the complexity can usually be neglected.
+
+    @liveexample{The following code shows how a JSON patch is applied to a
+    value.,patch}
+
+    @sa @ref diff -- create a JSON patch by comparing two JSON values
+
+    @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
+    @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
+
+    @since version 2.0.0
+    */
+    basic_json patch(const basic_json& json_patch) const
+    {
+        // make a working copy to apply the patch to
+        basic_json result = *this;
+
+        // the valid JSON Patch operations
+        enum class patch_operations {add, remove, replace, move, copy, test, invalid};
+
+        const auto get_op = [](const std::string & op)
+        {
+            if (op == "add")
+            {
+                return patch_operations::add;
+            }
+            if (op == "remove")
+            {
+                return patch_operations::remove;
+            }
+            if (op == "replace")
+            {
+                return patch_operations::replace;
+            }
+            if (op == "move")
+            {
+                return patch_operations::move;
+            }
+            if (op == "copy")
+            {
+                return patch_operations::copy;
+            }
+            if (op == "test")
+            {
+                return patch_operations::test;
+            }
+
+            return patch_operations::invalid;
+        };
+
+        // wrapper for "add" operation; add value at ptr
+        const auto operation_add = [&result](json_pointer & ptr, basic_json val)
+        {
+            // adding to the root of the target document means replacing it
+            if (ptr.empty())
+            {
+                result = val;
+                return;
+            }
+
+            // make sure the top element of the pointer exists
+            json_pointer top_pointer = ptr.top();
+            if (top_pointer != ptr)
+            {
+                result.at(top_pointer);
+            }
+
+            // get reference to parent of JSON pointer ptr
+            const auto last_path = ptr.back();
+            ptr.pop_back();
+            basic_json& parent = result[ptr];
+
+            switch (parent.m_type)
+            {
+                case value_t::null:
+                case value_t::object:
+                {
+                    // use operator[] to add value
+                    parent[last_path] = val;
+                    break;
+                }
+
+                case value_t::array:
+                {
+                    if (last_path == "-")
+                    {
+                        // special case: append to back
+                        parent.push_back(val);
+                    }
+                    else
+                    {
+                        const auto idx = json_pointer::array_index(last_path);
+                        if (JSON_HEDLEY_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
+                        {
+                            // avoid undefined behavior
+                            JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
+                        }
+
+                        // default case: insert add offset
+                        parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
+                    }
+                    break;
+                }
+
+                // if there exists a parent it cannot be primitive
+                default:            // LCOV_EXCL_LINE
+                    assert(false);  // LCOV_EXCL_LINE
+            }
+        };
+
+        // wrapper for "remove" operation; remove value at ptr
+        const auto operation_remove = [&result](json_pointer & ptr)
+        {
+            // get reference to parent of JSON pointer ptr
+            const auto last_path = ptr.back();
+            ptr.pop_back();
+            basic_json& parent = result.at(ptr);
+
+            // remove child
+            if (parent.is_object())
+            {
+                // perform range check
+                auto it = parent.find(last_path);
+                if (JSON_HEDLEY_LIKELY(it != parent.end()))
+                {
+                    parent.erase(it);
+                }
+                else
+                {
+                    JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
+                }
+            }
+            else if (parent.is_array())
+            {
+                // note erase performs range check
+                parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
+            }
+        };
+
+        // type check: top level value must be an array
+        if (JSON_HEDLEY_UNLIKELY(not json_patch.is_array()))
+        {
+            JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
+        }
+
+        // iterate and apply the operations
+        for (const auto& val : json_patch)
+        {
+            // wrapper to get a value for an operation
+            const auto get_value = [&val](const std::string & op,
+                                          const std::string & member,
+                                          bool string_type) -> basic_json &
+            {
+                // find value
+                auto it = val.m_value.object->find(member);
+
+                // context-sensitive error message
+                const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
+
+                // check if desired value is present
+                if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
+                {
+                    JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
+                }
+
+                // check if result is of type string
+                if (JSON_HEDLEY_UNLIKELY(string_type and not it->second.is_string()))
+                {
+                    JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
+                }
+
+                // no error: return value
+                return it->second;
+            };
+
+            // type check: every element of the array must be an object
+            if (JSON_HEDLEY_UNLIKELY(not val.is_object()))
+            {
+                JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
+            }
+
+            // collect mandatory members
+            const std::string op = get_value("op", "op", true);
+            const std::string path = get_value(op, "path", true);
+            json_pointer ptr(path);
+
+            switch (get_op(op))
+            {
+                case patch_operations::add:
+                {
+                    operation_add(ptr, get_value("add", "value", false));
+                    break;
+                }
+
+                case patch_operations::remove:
+                {
+                    operation_remove(ptr);
+                    break;
+                }
+
+                case patch_operations::replace:
+                {
+                    // the "path" location must exist - use at()
+                    result.at(ptr) = get_value("replace", "value", false);
+                    break;
+                }
+
+                case patch_operations::move:
+                {
+                    const std::string from_path = get_value("move", "from", true);
+                    json_pointer from_ptr(from_path);
+
+                    // the "from" location must exist - use at()
+                    basic_json v = result.at(from_ptr);
+
+                    // The move operation is functionally identical to a
+                    // "remove" operation on the "from" location, followed
+                    // immediately by an "add" operation at the target
+                    // location with the value that was just removed.
+                    operation_remove(from_ptr);
+                    operation_add(ptr, v);
+                    break;
+                }
+
+                case patch_operations::copy:
+                {
+                    const std::string from_path = get_value("copy", "from", true);
+                    const json_pointer from_ptr(from_path);
+
+                    // the "from" location must exist - use at()
+                    basic_json v = result.at(from_ptr);
+
+                    // The copy is functionally identical to an "add"
+                    // operation at the target location using the value
+                    // specified in the "from" member.
+                    operation_add(ptr, v);
+                    break;
+                }
+
+                case patch_operations::test:
+                {
+                    bool success = false;
+                    JSON_TRY
+                    {
+                        // check if "value" matches the one at "path"
+                        // the "path" location must exist - use at()
+                        success = (result.at(ptr) == get_value("test", "value", false));
+                    }
+                    JSON_INTERNAL_CATCH (out_of_range&)
+                    {
+                        // ignore out of range errors: success remains false
+                    }
+
+                    // throw an exception if test fails
+                    if (JSON_HEDLEY_UNLIKELY(not success))
+                    {
+                        JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
+                    }
+
+                    break;
+                }
+
+                default:
+                {
+                    // op must be "add", "remove", "replace", "move", "copy", or
+                    // "test"
+                    JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
+                }
+            }
+        }
+
+        return result;
+    }
+
+    /*!
+    @brief creates a diff as a JSON patch
+
+    Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
+    be changed into the value @a target by calling @ref patch function.
+
+    @invariant For two JSON values @a source and @a target, the following code
+    yields always `true`:
+    @code {.cpp}
+    source.patch(diff(source, target)) == target;
+    @endcode
+
+    @note Currently, only `remove`, `add`, and `replace` operations are
+          generated.
+
+    @param[in] source  JSON value to compare from
+    @param[in] target  JSON value to compare against
+    @param[in] path    helper value to create JSON pointers
+
+    @return a JSON patch to convert the @a source to @a target
+
+    @complexity Linear in the lengths of @a source and @a target.
+
+    @liveexample{The following code shows how a JSON patch is created as a
+    diff for two JSON values.,diff}
+
+    @sa @ref patch -- apply a JSON patch
+    @sa @ref merge_patch -- apply a JSON Merge Patch
+
+    @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
+
+    @since version 2.0.0
+    */
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json diff(const basic_json& source, const basic_json& target,
+                           const std::string& path = "")
+    {
+        // the patch
+        basic_json result(value_t::array);
+
+        // if the values are the same, return empty patch
+        if (source == target)
+        {
+            return result;
+        }
+
+        if (source.type() != target.type())
+        {
+            // different types: replace value
+            result.push_back(
+            {
+                {"op", "replace"}, {"path", path}, {"value", target}
+            });
+            return result;
+        }
+
+        switch (source.type())
+        {
+            case value_t::array:
+            {
+                // first pass: traverse common elements
+                std::size_t i = 0;
+                while (i < source.size() and i < target.size())
+                {
+                    // recursive call to compare array values at index i
+                    auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
+                    result.insert(result.end(), temp_diff.begin(), temp_diff.end());
+                    ++i;
+                }
+
+                // i now reached the end of at least one array
+                // in a second pass, traverse the remaining elements
+
+                // remove my remaining elements
+                const auto end_index = static_cast<difference_type>(result.size());
+                while (i < source.size())
+                {
+                    // add operations in reverse order to avoid invalid
+                    // indices
+                    result.insert(result.begin() + end_index, object(
+                    {
+                        {"op", "remove"},
+                        {"path", path + "/" + std::to_string(i)}
+                    }));
+                    ++i;
+                }
+
+                // add other remaining elements
+                while (i < target.size())
+                {
+                    result.push_back(
+                    {
+                        {"op", "add"},
+                        {"path", path + "/" + std::to_string(i)},
+                        {"value", target[i]}
+                    });
+                    ++i;
+                }
+
+                break;
+            }
+
+            case value_t::object:
+            {
+                // first pass: traverse this object's elements
+                for (auto it = source.cbegin(); it != source.cend(); ++it)
+                {
+                    // escape the key name to be used in a JSON patch
+                    const auto key = json_pointer::escape(it.key());
+
+                    if (target.find(it.key()) != target.end())
+                    {
+                        // recursive call to compare object values at key it
+                        auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
+                        result.insert(result.end(), temp_diff.begin(), temp_diff.end());
+                    }
+                    else
+                    {
+                        // found a key that is not in o -> remove it
+                        result.push_back(object(
+                        {
+                            {"op", "remove"}, {"path", path + "/" + key}
+                        }));
+                    }
+                }
+
+                // second pass: traverse other object's elements
+                for (auto it = target.cbegin(); it != target.cend(); ++it)
+                {
+                    if (source.find(it.key()) == source.end())
+                    {
+                        // found a key that is not in this -> add it
+                        const auto key = json_pointer::escape(it.key());
+                        result.push_back(
+                        {
+                            {"op", "add"}, {"path", path + "/" + key},
+                            {"value", it.value()}
+                        });
+                    }
+                }
+
+                break;
+            }
+
+            default:
+            {
+                // both primitive type: replace value
+                result.push_back(
+                {
+                    {"op", "replace"}, {"path", path}, {"value", target}
+                });
+                break;
+            }
+        }
+
+        return result;
+    }
+
+    /// @}
+
+    ////////////////////////////////
+    // JSON Merge Patch functions //
+    ////////////////////////////////
+
+    /// @name JSON Merge Patch functions
+    /// @{
+
+    /*!
+    @brief applies a JSON Merge Patch
+
+    The merge patch format is primarily intended for use with the HTTP PATCH
+    method as a means of describing a set of modifications to a target
+    resource's content. This function applies a merge patch to the current
+    JSON value.
+
+    The function implements the following algorithm from Section 2 of
+    [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
+
+    ```
+    define MergePatch(Target, Patch):
+      if Patch is an Object:
+        if Target is not an Object:
+          Target = {} // Ignore the contents and set it to an empty Object
+        for each Name/Value pair in Patch:
+          if Value is null:
+            if Name exists in Target:
+              remove the Name/Value pair from Target
+          else:
+            Target[Name] = MergePatch(Target[Name], Value)
+        return Target
+      else:
+        return Patch
+    ```
+
+    Thereby, `Target` is the current object; that is, the patch is applied to
+    the current value.
+
+    @param[in] apply_patch  the patch to apply
+
+    @complexity Linear in the lengths of @a patch.
+
+    @liveexample{The following code shows how a JSON Merge Patch is applied to
+    a JSON document.,merge_patch}
+
+    @sa @ref patch -- apply a JSON patch
+    @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
+
+    @since version 3.0.0
+    */
+    void merge_patch(const basic_json& apply_patch)
+    {
+        if (apply_patch.is_object())
+        {
+            if (not is_object())
+            {
+                *this = object();
+            }
+            for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
+            {
+                if (it.value().is_null())
+                {
+                    erase(it.key());
+                }
+                else
+                {
+                    operator[](it.key()).merge_patch(it.value());
+                }
+            }
+        }
+        else
+        {
+            *this = apply_patch;
+        }
+    }
+
+    /// @}
+};
+
+/*!
+@brief user-defined to_string function for JSON values
+
+This function implements a user-defined to_string  for JSON objects.
+
+@param[in] j  a JSON object
+@return a std::string object
+*/
+
+NLOHMANN_BASIC_JSON_TPL_DECLARATION
+std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
+{
+    return j.dump();
+}
+} // namespace nlohmann
+
+///////////////////////
+// nonmember support //
+///////////////////////
+
+// specialization of std::swap, and std::hash
+namespace std
+{
+
+/// hash value for JSON objects
+template<>
+struct hash<nlohmann::json>
+{
+    /*!
+    @brief return a hash value for a JSON object
+
+    @since version 1.0.0
+    */
+    std::size_t operator()(const nlohmann::json& j) const
+    {
+        // a naive hashing via the string representation
+        const auto& h = hash<nlohmann::json::string_t>();
+        return h(j.dump());
+    }
+};
+
+/// specialization for std::less<value_t>
+/// @note: do not remove the space after '<',
+///        see https://github.com/nlohmann/json/pull/679
+template<>
+struct less<::nlohmann::detail::value_t>
+{
+    /*!
+    @brief compare two value_t enum values
+    @since version 3.0.0
+    */
+    bool operator()(nlohmann::detail::value_t lhs,
+                    nlohmann::detail::value_t rhs) const noexcept
+    {
+        return nlohmann::detail::operator<(lhs, rhs);
+    }
+};
+
+/*!
+@brief exchanges the values of two JSON objects
+
+@since version 1.0.0
+*/
+template<>
+inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
+    is_nothrow_move_constructible<nlohmann::json>::value and
+    is_nothrow_move_assignable<nlohmann::json>::value
+)
+{
+    j1.swap(j2);
+}
+
+} // namespace std
+
+/*!
+@brief user-defined string literal for JSON values
+
+This operator implements a user-defined string literal for JSON objects. It
+can be used by adding `"_json"` to a string literal and returns a JSON object
+if no parse error occurred.
+
+@param[in] s  a string representation of a JSON object
+@param[in] n  the length of string @a s
+@return a JSON object
+
+@since version 1.0.0
+*/
+JSON_HEDLEY_NON_NULL(1)
+inline nlohmann::json operator "" _json(const char* s, std::size_t n)
+{
+    return nlohmann::json::parse(s, s + n);
+}
+
+/*!
+@brief user-defined string literal for JSON pointer
+
+This operator implements a user-defined string literal for JSON Pointers. It
+can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
+object if no parse error occurred.
+
+@param[in] s  a string representation of a JSON Pointer
+@param[in] n  the length of string @a s
+@return a JSON pointer object
+
+@since version 2.0.0
+*/
+JSON_HEDLEY_NON_NULL(1)
+inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
+{
+    return nlohmann::json::json_pointer(std::string(s, n));
+}
+
+// #include <nlohmann/detail/macro_unscope.hpp>
+
+
+// restore GCC/clang diagnostic settings
+#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
+    #pragma GCC diagnostic pop
+#endif
+#if defined(__clang__)
+    #pragma GCC diagnostic pop
+#endif
+
+// clean up
+#undef JSON_INTERNAL_CATCH
+#undef JSON_CATCH
+#undef JSON_THROW
+#undef JSON_TRY
+#undef JSON_HAS_CPP_14
+#undef JSON_HAS_CPP_17
+#undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
+#undef NLOHMANN_BASIC_JSON_TPL
+
+// #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
+#undef JSON_HEDLEY_ALWAYS_INLINE
+#undef JSON_HEDLEY_ARM_VERSION
+#undef JSON_HEDLEY_ARM_VERSION_CHECK
+#undef JSON_HEDLEY_ARRAY_PARAM
+#undef JSON_HEDLEY_ASSUME
+#undef JSON_HEDLEY_BEGIN_C_DECLS
+#undef JSON_HEDLEY_C_DECL
+#undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
+#undef JSON_HEDLEY_CLANG_HAS_BUILTIN
+#undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
+#undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
+#undef JSON_HEDLEY_CLANG_HAS_EXTENSION
+#undef JSON_HEDLEY_CLANG_HAS_FEATURE
+#undef JSON_HEDLEY_CLANG_HAS_WARNING
+#undef JSON_HEDLEY_COMPCERT_VERSION
+#undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
+#undef JSON_HEDLEY_CONCAT
+#undef JSON_HEDLEY_CONCAT_EX
+#undef JSON_HEDLEY_CONST
+#undef JSON_HEDLEY_CONST_CAST
+#undef JSON_HEDLEY_CONSTEXPR
+#undef JSON_HEDLEY_CPP_CAST
+#undef JSON_HEDLEY_CRAY_VERSION
+#undef JSON_HEDLEY_CRAY_VERSION_CHECK
+#undef JSON_HEDLEY_DEPRECATED
+#undef JSON_HEDLEY_DEPRECATED_FOR
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
+#undef JSON_HEDLEY_DIAGNOSTIC_POP
+#undef JSON_HEDLEY_DIAGNOSTIC_PUSH
+#undef JSON_HEDLEY_DMC_VERSION
+#undef JSON_HEDLEY_DMC_VERSION_CHECK
+#undef JSON_HEDLEY_EMPTY_BASES
+#undef JSON_HEDLEY_EMSCRIPTEN_VERSION
+#undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
+#undef JSON_HEDLEY_END_C_DECLS
+#undef JSON_HEDLEY_FALL_THROUGH
+#undef JSON_HEDLEY_FLAGS
+#undef JSON_HEDLEY_FLAGS_CAST
+#undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
+#undef JSON_HEDLEY_GCC_HAS_BUILTIN
+#undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
+#undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
+#undef JSON_HEDLEY_GCC_HAS_EXTENSION
+#undef JSON_HEDLEY_GCC_HAS_FEATURE
+#undef JSON_HEDLEY_GCC_HAS_WARNING
+#undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
+#undef JSON_HEDLEY_GCC_VERSION
+#undef JSON_HEDLEY_GCC_VERSION_CHECK
+#undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
+#undef JSON_HEDLEY_GNUC_HAS_BUILTIN
+#undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
+#undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
+#undef JSON_HEDLEY_GNUC_HAS_EXTENSION
+#undef JSON_HEDLEY_GNUC_HAS_FEATURE
+#undef JSON_HEDLEY_GNUC_HAS_WARNING
+#undef JSON_HEDLEY_GNUC_VERSION
+#undef JSON_HEDLEY_GNUC_VERSION_CHECK
+#undef JSON_HEDLEY_HAS_ATTRIBUTE
+#undef JSON_HEDLEY_HAS_BUILTIN
+#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
+#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
+#undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
+#undef JSON_HEDLEY_HAS_EXTENSION
+#undef JSON_HEDLEY_HAS_FEATURE
+#undef JSON_HEDLEY_HAS_WARNING
+#undef JSON_HEDLEY_IAR_VERSION
+#undef JSON_HEDLEY_IAR_VERSION_CHECK
+#undef JSON_HEDLEY_IBM_VERSION
+#undef JSON_HEDLEY_IBM_VERSION_CHECK
+#undef JSON_HEDLEY_IMPORT
+#undef JSON_HEDLEY_INLINE
+#undef JSON_HEDLEY_INTEL_VERSION
+#undef JSON_HEDLEY_INTEL_VERSION_CHECK
+#undef JSON_HEDLEY_IS_CONSTANT
+#undef JSON_HEDLEY_IS_CONSTEXPR_
+#undef JSON_HEDLEY_LIKELY
+#undef JSON_HEDLEY_MALLOC
+#undef JSON_HEDLEY_MESSAGE
+#undef JSON_HEDLEY_MSVC_VERSION
+#undef JSON_HEDLEY_MSVC_VERSION_CHECK
+#undef JSON_HEDLEY_NEVER_INLINE
+#undef JSON_HEDLEY_NO_ESCAPE
+#undef JSON_HEDLEY_NON_NULL
+#undef JSON_HEDLEY_NO_RETURN
+#undef JSON_HEDLEY_NO_THROW
+#undef JSON_HEDLEY_NULL
+#undef JSON_HEDLEY_PELLES_VERSION
+#undef JSON_HEDLEY_PELLES_VERSION_CHECK
+#undef JSON_HEDLEY_PGI_VERSION
+#undef JSON_HEDLEY_PGI_VERSION_CHECK
+#undef JSON_HEDLEY_PREDICT
+#undef JSON_HEDLEY_PRINTF_FORMAT
+#undef JSON_HEDLEY_PRIVATE
+#undef JSON_HEDLEY_PUBLIC
+#undef JSON_HEDLEY_PURE
+#undef JSON_HEDLEY_REINTERPRET_CAST
+#undef JSON_HEDLEY_REQUIRE
+#undef JSON_HEDLEY_REQUIRE_CONSTEXPR
+#undef JSON_HEDLEY_REQUIRE_MSG
+#undef JSON_HEDLEY_RESTRICT
+#undef JSON_HEDLEY_RETURNS_NON_NULL
+#undef JSON_HEDLEY_SENTINEL
+#undef JSON_HEDLEY_STATIC_ASSERT
+#undef JSON_HEDLEY_STATIC_CAST
+#undef JSON_HEDLEY_STRINGIFY
+#undef JSON_HEDLEY_STRINGIFY_EX
+#undef JSON_HEDLEY_SUNPRO_VERSION
+#undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
+#undef JSON_HEDLEY_TINYC_VERSION
+#undef JSON_HEDLEY_TINYC_VERSION_CHECK
+#undef JSON_HEDLEY_TI_VERSION
+#undef JSON_HEDLEY_TI_VERSION_CHECK
+#undef JSON_HEDLEY_UNAVAILABLE
+#undef JSON_HEDLEY_UNLIKELY
+#undef JSON_HEDLEY_UNPREDICTABLE
+#undef JSON_HEDLEY_UNREACHABLE
+#undef JSON_HEDLEY_UNREACHABLE_RETURN
+#undef JSON_HEDLEY_VERSION
+#undef JSON_HEDLEY_VERSION_DECODE_MAJOR
+#undef JSON_HEDLEY_VERSION_DECODE_MINOR
+#undef JSON_HEDLEY_VERSION_DECODE_REVISION
+#undef JSON_HEDLEY_VERSION_ENCODE
+#undef JSON_HEDLEY_WARNING
+#undef JSON_HEDLEY_WARN_UNUSED_RESULT
+
+
+
+#endif  // INCLUDE_NLOHMANN_JSON_HPP_

+ 2819 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/external/mpark/variant.hpp

@@ -0,0 +1,2819 @@
+// MPark.Variant
+//
+// Copyright Michael Park, 2015-2017
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
+
+#ifndef MPARK_VARIANT_HPP
+#define MPARK_VARIANT_HPP
+
+/*
+   variant synopsis
+
+namespace std {
+
+  // 20.7.2, class template variant
+  template <class... Types>
+  class variant {
+  public:
+
+    // 20.7.2.1, constructors
+    constexpr variant() noexcept(see below);
+    variant(const variant&);
+    variant(variant&&) noexcept(see below);
+
+    template <class T> constexpr variant(T&&) noexcept(see below);
+
+    template <class T, class... Args>
+    constexpr explicit variant(in_place_type_t<T>, Args&&...);
+
+    template <class T, class U, class... Args>
+    constexpr explicit variant(
+        in_place_type_t<T>, initializer_list<U>, Args&&...);
+
+    template <size_t I, class... Args>
+    constexpr explicit variant(in_place_index_t<I>, Args&&...);
+
+    template <size_t I, class U, class... Args>
+    constexpr explicit variant(
+        in_place_index_t<I>, initializer_list<U>, Args&&...);
+
+    // 20.7.2.2, destructor
+    ~variant();
+
+    // 20.7.2.3, assignment
+    variant& operator=(const variant&);
+    variant& operator=(variant&&) noexcept(see below);
+
+    template <class T> variant& operator=(T&&) noexcept(see below);
+
+    // 20.7.2.4, modifiers
+    template <class T, class... Args>
+    T& emplace(Args&&...);
+
+    template <class T, class U, class... Args>
+    T& emplace(initializer_list<U>, Args&&...);
+
+    template <size_t I, class... Args>
+    variant_alternative<I, variant>& emplace(Args&&...);
+
+    template <size_t I, class U, class...  Args>
+    variant_alternative<I, variant>& emplace(initializer_list<U>, Args&&...);
+
+    // 20.7.2.5, value status
+    constexpr bool valueless_by_exception() const noexcept;
+    constexpr size_t index() const noexcept;
+
+    // 20.7.2.6, swap
+    void swap(variant&) noexcept(see below);
+  };
+
+  // 20.7.3, variant helper classes
+  template <class T> struct variant_size; // undefined
+
+  template <class T>
+  constexpr size_t variant_size_v = variant_size<T>::value;
+
+  template <class T> struct variant_size<const T>;
+  template <class T> struct variant_size<volatile T>;
+  template <class T> struct variant_size<const volatile T>;
+
+  template <class... Types>
+  struct variant_size<variant<Types...>>;
+
+  template <size_t I, class T> struct variant_alternative; // undefined
+
+  template <size_t I, class T>
+  using variant_alternative_t = typename variant_alternative<I, T>::type;
+
+  template <size_t I, class T> struct variant_alternative<I, const T>;
+  template <size_t I, class T> struct variant_alternative<I, volatile T>;
+  template <size_t I, class T> struct variant_alternative<I, const volatile T>;
+
+  template <size_t I, class... Types>
+  struct variant_alternative<I, variant<Types...>>;
+
+  constexpr size_t variant_npos = -1;
+
+  // 20.7.4, value access
+  template <class T, class... Types>
+  constexpr bool holds_alternative(const variant<Types...>&) noexcept;
+
+  template <size_t I, class... Types>
+  constexpr variant_alternative_t<I, variant<Types...>>&
+  get(variant<Types...>&);
+
+  template <size_t I, class... Types>
+  constexpr variant_alternative_t<I, variant<Types...>>&&
+  get(variant<Types...>&&);
+
+  template <size_t I, class... Types>
+  constexpr variant_alternative_t<I, variant<Types...>> const&
+  get(const variant<Types...>&);
+
+  template <size_t I, class... Types>
+  constexpr variant_alternative_t<I, variant<Types...>> const&&
+  get(const variant<Types...>&&);
+
+  template <class T, class...  Types>
+  constexpr T& get(variant<Types...>&);
+
+  template <class T, class... Types>
+  constexpr T&& get(variant<Types...>&&);
+
+  template <class T, class... Types>
+  constexpr const T& get(const variant<Types...>&);
+
+  template <class T, class... Types>
+  constexpr const T&& get(const variant<Types...>&&);
+
+  template <size_t I, class... Types>
+  constexpr add_pointer_t<variant_alternative_t<I, variant<Types...>>>
+  get_if(variant<Types...>*) noexcept;
+
+  template <size_t I, class... Types>
+  constexpr add_pointer_t<const variant_alternative_t<I, variant<Types...>>>
+  get_if(const variant<Types...>*) noexcept;
+
+  template <class T, class... Types>
+  constexpr add_pointer_t<T>
+  get_if(variant<Types...>*) noexcept;
+
+  template <class T, class... Types>
+  constexpr add_pointer_t<const T>
+  get_if(const variant<Types...>*) noexcept;
+
+  // 20.7.5, relational operators
+  template <class... Types>
+  constexpr bool operator==(const variant<Types...>&, const variant<Types...>&);
+
+  template <class... Types>
+  constexpr bool operator!=(const variant<Types...>&, const variant<Types...>&);
+
+  template <class... Types>
+  constexpr bool operator<(const variant<Types...>&, const variant<Types...>&);
+
+  template <class... Types>
+  constexpr bool operator>(const variant<Types...>&, const variant<Types...>&);
+
+  template <class... Types>
+  constexpr bool operator<=(const variant<Types...>&, const variant<Types...>&);
+
+  template <class... Types>
+  constexpr bool operator>=(const variant<Types...>&, const variant<Types...>&);
+
+  // 20.7.6, visitation
+  template <class Visitor, class... Variants>
+  constexpr see below visit(Visitor&&, Variants&&...);
+
+  // 20.7.7, class monostate
+  struct monostate;
+
+  // 20.7.8, monostate relational operators
+  constexpr bool operator<(monostate, monostate) noexcept;
+  constexpr bool operator>(monostate, monostate) noexcept;
+  constexpr bool operator<=(monostate, monostate) noexcept;
+  constexpr bool operator>=(monostate, monostate) noexcept;
+  constexpr bool operator==(monostate, monostate) noexcept;
+  constexpr bool operator!=(monostate, monostate) noexcept;
+
+  // 20.7.9, specialized algorithms
+  template <class... Types>
+  void swap(variant<Types...>&, variant<Types...>&) noexcept(see below);
+
+  // 20.7.10, class bad_variant_access
+  class bad_variant_access;
+
+  // 20.7.11, hash support
+  template <class T> struct hash;
+  template <class... Types> struct hash<variant<Types...>>;
+  template <> struct hash<monostate>;
+
+} // namespace std
+
+*/
+
+#include <cstddef>
+#include <exception>
+#include <functional>
+#include <initializer_list>
+#include <new>
+#include <type_traits>
+#include <utility>
+
+// MPark.Variant
+//
+// Copyright Michael Park, 2015-2017
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
+
+#ifndef MPARK_CONFIG_HPP
+#define MPARK_CONFIG_HPP
+
+// MSVC 2015 Update 3.
+#if __cplusplus < 201103L && (!defined(_MSC_VER) || _MSC_FULL_VER < 190024210)
+#error "MPark.Variant requires C++11 support."
+#endif
+
+#ifndef __has_attribute
+#define __has_attribute(x) 0
+#endif
+
+#ifndef __has_builtin
+#define __has_builtin(x) 0
+#endif
+
+#ifndef __has_include
+#define __has_include(x) 0
+#endif
+
+#ifndef __has_feature
+#define __has_feature(x) 0
+#endif
+
+#if __has_attribute(always_inline) || defined(__GNUC__)
+#define MPARK_ALWAYS_INLINE __attribute__((__always_inline__)) inline
+#elif defined(_MSC_VER)
+#define MPARK_ALWAYS_INLINE __forceinline
+#else
+#define MPARK_ALWAYS_INLINE inline
+#endif
+
+#if __has_builtin(__builtin_addressof) || \
+    (defined(__GNUC__) && __GNUC__ >= 7) || defined(_MSC_VER)
+#define MPARK_BUILTIN_ADDRESSOF
+#endif
+
+#if __has_builtin(__builtin_unreachable) || defined(__GNUC__)
+#define MPARK_BUILTIN_UNREACHABLE __builtin_unreachable()
+#elif defined(_MSC_VER)
+#define MPARK_BUILTIN_UNREACHABLE __assume(false)
+#else
+#define MPARK_BUILTIN_UNREACHABLE
+#endif
+
+#if __has_builtin(__type_pack_element)
+#define MPARK_TYPE_PACK_ELEMENT
+#endif
+
+#if defined(__cpp_constexpr) && __cpp_constexpr >= 200704 && \
+    !(defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 9)
+#define MPARK_CPP11_CONSTEXPR
+#endif
+
+#if defined(__cpp_constexpr) && __cpp_constexpr >= 201304
+#define MPARK_CPP14_CONSTEXPR
+#endif
+
+#if __has_feature(cxx_exceptions) || defined(__cpp_exceptions) || \
+    (defined(_MSC_VER) && defined(_CPPUNWIND))
+#define MPARK_EXCEPTIONS
+#endif
+
+#if defined(__cpp_generic_lambdas) || defined(_MSC_VER)
+#define MPARK_GENERIC_LAMBDAS
+#endif
+
+#if defined(__cpp_lib_integer_sequence)
+#define MPARK_INTEGER_SEQUENCE
+#endif
+
+#if defined(__cpp_return_type_deduction) || defined(_MSC_VER)
+#define MPARK_RETURN_TYPE_DEDUCTION
+#endif
+
+#if defined(__cpp_lib_transparent_operators) || defined(_MSC_VER)
+#define MPARK_TRANSPARENT_OPERATORS
+#endif
+
+#if defined(__cpp_variable_templates) || defined(_MSC_VER)
+#define MPARK_VARIABLE_TEMPLATES
+#endif
+
+#if !defined(__GLIBCXX__) || __has_include(<codecvt>)  // >= libstdc++-5
+#define MPARK_TRIVIALITY_TYPE_TRAITS
+#define MPARK_INCOMPLETE_TYPE_TRAITS
+#endif
+
+#endif  // MPARK_CONFIG_HPP
+
+// MPark.Variant
+//
+// Copyright Michael Park, 2015-2017
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
+
+#ifndef MPARK_IN_PLACE_HPP
+#define MPARK_IN_PLACE_HPP
+
+#include <cstddef>
+
+
+namespace mpark {
+
+  struct in_place_t { explicit in_place_t() = default; };
+
+  template <std::size_t I>
+  struct in_place_index_t { explicit in_place_index_t() = default; };
+
+  template <typename T>
+  struct in_place_type_t { explicit in_place_type_t() = default; };
+
+#ifdef MPARK_VARIABLE_TEMPLATES
+  constexpr in_place_t in_place{};
+
+  template <std::size_t I> constexpr in_place_index_t<I> in_place_index{};
+
+  template <typename T> constexpr in_place_type_t<T> in_place_type{};
+#endif
+
+}  // namespace mpark
+
+#endif  // MPARK_IN_PLACE_HPP
+
+// MPark.Variant
+//
+// Copyright Michael Park, 2015-2017
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
+
+#ifndef MPARK_LIB_HPP
+#define MPARK_LIB_HPP
+
+#include <memory>
+#include <functional>
+#include <type_traits>
+#include <utility>
+
+
+#define MPARK_RETURN(...) \
+  noexcept(noexcept(__VA_ARGS__)) -> decltype(__VA_ARGS__) { return __VA_ARGS__; }
+
+namespace mpark {
+  namespace lib {
+    template <typename T>
+    struct identity { using type = T; };
+
+    inline namespace cpp14 {
+      template <typename T, std::size_t N>
+      struct array {
+        constexpr const T &operator[](std::size_t index) const {
+          return data[index];
+        }
+
+        T data[N == 0 ? 1 : N];
+      };
+
+      template <typename T>
+      using add_pointer_t = typename std::add_pointer<T>::type;
+
+      template <typename... Ts>
+      using common_type_t = typename std::common_type<Ts...>::type;
+
+      template <typename T>
+      using decay_t = typename std::decay<T>::type;
+
+      template <bool B, typename T = void>
+      using enable_if_t = typename std::enable_if<B, T>::type;
+
+      template <typename T>
+      using remove_const_t = typename std::remove_const<T>::type;
+
+      template <typename T>
+      using remove_reference_t = typename std::remove_reference<T>::type;
+
+      template <typename T>
+      inline constexpr T &&forward(remove_reference_t<T> &t) noexcept {
+        return static_cast<T &&>(t);
+      }
+
+      template <typename T>
+      inline constexpr T &&forward(remove_reference_t<T> &&t) noexcept {
+        static_assert(!std::is_lvalue_reference<T>::value,
+                      "can not forward an rvalue as an lvalue");
+        return static_cast<T &&>(t);
+      }
+
+      template <typename T>
+      inline constexpr remove_reference_t<T> &&move(T &&t) noexcept {
+        return static_cast<remove_reference_t<T> &&>(t);
+      }
+
+#ifdef MPARK_INTEGER_SEQUENCE
+      using std::integer_sequence;
+      using std::index_sequence;
+      using std::make_index_sequence;
+      using std::index_sequence_for;
+#else
+      template <typename T, T... Is>
+      struct integer_sequence {
+        using value_type = T;
+        static constexpr std::size_t size() noexcept { return sizeof...(Is); }
+      };
+
+      template <std::size_t... Is>
+      using index_sequence = integer_sequence<std::size_t, Is...>;
+
+      template <typename Lhs, typename Rhs>
+      struct make_index_sequence_concat;
+
+      template <std::size_t... Lhs, std::size_t... Rhs>
+      struct make_index_sequence_concat<index_sequence<Lhs...>,
+                                        index_sequence<Rhs...>>
+          : identity<index_sequence<Lhs..., (sizeof...(Lhs) + Rhs)...>> {};
+
+      template <std::size_t N>
+      struct make_index_sequence_impl;
+
+      template <std::size_t N>
+      using make_index_sequence = typename make_index_sequence_impl<N>::type;
+
+      template <std::size_t N>
+      struct make_index_sequence_impl
+          : make_index_sequence_concat<make_index_sequence<N / 2>,
+                                       make_index_sequence<N - (N / 2)>> {};
+
+      template <>
+      struct make_index_sequence_impl<0> : identity<index_sequence<>> {};
+
+      template <>
+      struct make_index_sequence_impl<1> : identity<index_sequence<0>> {};
+
+      template <typename... Ts>
+      using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
+#endif
+
+      // <functional>
+#ifdef MPARK_TRANSPARENT_OPERATORS
+      using equal_to = std::equal_to<>;
+#else
+      struct equal_to {
+        template <typename Lhs, typename Rhs>
+        inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const
+          MPARK_RETURN(lib::forward<Lhs>(lhs) == lib::forward<Rhs>(rhs))
+      };
+#endif
+
+#ifdef MPARK_TRANSPARENT_OPERATORS
+      using not_equal_to = std::not_equal_to<>;
+#else
+      struct not_equal_to {
+        template <typename Lhs, typename Rhs>
+        inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const
+          MPARK_RETURN(lib::forward<Lhs>(lhs) != lib::forward<Rhs>(rhs))
+      };
+#endif
+
+#ifdef MPARK_TRANSPARENT_OPERATORS
+      using less = std::less<>;
+#else
+      struct less {
+        template <typename Lhs, typename Rhs>
+        inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const
+          MPARK_RETURN(lib::forward<Lhs>(lhs) < lib::forward<Rhs>(rhs))
+      };
+#endif
+
+#ifdef MPARK_TRANSPARENT_OPERATORS
+      using greater = std::greater<>;
+#else
+      struct greater {
+        template <typename Lhs, typename Rhs>
+        inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const
+          MPARK_RETURN(lib::forward<Lhs>(lhs) > lib::forward<Rhs>(rhs))
+      };
+#endif
+
+#ifdef MPARK_TRANSPARENT_OPERATORS
+      using less_equal = std::less_equal<>;
+#else
+      struct less_equal {
+        template <typename Lhs, typename Rhs>
+        inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const
+          MPARK_RETURN(lib::forward<Lhs>(lhs) <= lib::forward<Rhs>(rhs))
+      };
+#endif
+
+#ifdef MPARK_TRANSPARENT_OPERATORS
+      using greater_equal = std::greater_equal<>;
+#else
+      struct greater_equal {
+        template <typename Lhs, typename Rhs>
+        inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const
+          MPARK_RETURN(lib::forward<Lhs>(lhs) >= lib::forward<Rhs>(rhs))
+      };
+#endif
+    }  // namespace cpp14
+
+    inline namespace cpp17 {
+
+      // <type_traits>
+      template <bool B>
+      using bool_constant = std::integral_constant<bool, B>;
+
+      template <typename...>
+      struct voider : identity<void> {};
+
+      template <typename... Ts>
+      using void_t = typename voider<Ts...>::type;
+
+      namespace detail {
+        namespace swappable {
+
+          using std::swap;
+
+          template <typename T>
+          struct is_swappable {
+            private:
+            template <typename U,
+                      typename = decltype(swap(std::declval<U &>(),
+                                               std::declval<U &>()))>
+            inline static std::true_type test(int);
+
+            template <typename U>
+            inline static std::false_type test(...);
+
+            public:
+            static constexpr bool value = decltype(test<T>(0))::value;
+          };
+
+          template <bool IsSwappable, typename T>
+          struct is_nothrow_swappable {
+            static constexpr bool value =
+                noexcept(swap(std::declval<T &>(), std::declval<T &>()));
+          };
+
+          template <typename T>
+          struct is_nothrow_swappable<false, T> : std::false_type {};
+
+        }  // namespace swappable
+      }  // namespace detail
+
+      using detail::swappable::is_swappable;
+
+      template <typename T>
+      using is_nothrow_swappable =
+          detail::swappable::is_nothrow_swappable<is_swappable<T>::value, T>;
+
+      // <functional>
+      namespace detail {
+
+        template <typename T>
+        struct is_reference_wrapper : std::false_type {};
+
+        template <typename T>
+        struct is_reference_wrapper<std::reference_wrapper<T>>
+            : std::true_type {};
+
+        template <bool, int>
+        struct Invoke;
+
+        template <>
+        struct Invoke<true /* pmf */, 0 /* is_base_of */> {
+          template <typename R, typename T, typename Arg, typename... Args>
+          inline static constexpr auto invoke(R T::*pmf, Arg &&arg, Args &&... args)
+            MPARK_RETURN((lib::forward<Arg>(arg).*pmf)(lib::forward<Args>(args)...))
+        };
+
+        template <>
+        struct Invoke<true /* pmf */, 1 /* is_reference_wrapper */> {
+          template <typename R, typename T, typename Arg, typename... Args>
+          inline static constexpr auto invoke(R T::*pmf, Arg &&arg, Args &&... args)
+            MPARK_RETURN((lib::forward<Arg>(arg).get().*pmf)(lib::forward<Args>(args)...))
+        };
+
+        template <>
+        struct Invoke<true /* pmf */, 2 /* otherwise */> {
+          template <typename R, typename T, typename Arg, typename... Args>
+          inline static constexpr auto invoke(R T::*pmf, Arg &&arg, Args &&... args)
+            MPARK_RETURN(((*lib::forward<Arg>(arg)).*pmf)(lib::forward<Args>(args)...))
+        };
+
+        template <>
+        struct Invoke<false /* pmo */, 0 /* is_base_of */> {
+          template <typename R, typename T, typename Arg>
+          inline static constexpr auto invoke(R T::*pmo, Arg &&arg)
+            MPARK_RETURN(lib::forward<Arg>(arg).*pmo)
+        };
+
+        template <>
+        struct Invoke<false /* pmo */, 1 /* is_reference_wrapper */> {
+          template <typename R, typename T, typename Arg>
+          inline static constexpr auto invoke(R T::*pmo, Arg &&arg)
+            MPARK_RETURN(lib::forward<Arg>(arg).get().*pmo)
+        };
+
+        template <>
+        struct Invoke<false /* pmo */, 2 /* otherwise */> {
+          template <typename R, typename T, typename Arg>
+          inline static constexpr auto invoke(R T::*pmo, Arg &&arg)
+              MPARK_RETURN((*lib::forward<Arg>(arg)).*pmo)
+        };
+
+        template <typename R, typename T, typename Arg, typename... Args>
+        inline constexpr auto invoke(R T::*f, Arg &&arg, Args &&... args)
+          MPARK_RETURN(
+              Invoke<std::is_function<R>::value,
+                     (std::is_base_of<T, lib::decay_t<Arg>>::value
+                          ? 0
+                          : is_reference_wrapper<lib::decay_t<Arg>>::value
+                                ? 1
+                                : 2)>::invoke(f,
+                                              lib::forward<Arg>(arg),
+                                              lib::forward<Args>(args)...))
+
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4100)
+#endif
+        template <typename F, typename... Args>
+        inline constexpr auto invoke(F &&f, Args &&... args)
+          MPARK_RETURN(lib::forward<F>(f)(lib::forward<Args>(args)...))
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+      }  // namespace detail
+
+      template <typename F, typename... Args>
+      inline constexpr auto invoke(F &&f, Args &&... args)
+        MPARK_RETURN(detail::invoke(lib::forward<F>(f),
+                                    lib::forward<Args>(args)...))
+
+      namespace detail {
+
+        template <typename Void, typename, typename...>
+        struct invoke_result {};
+
+        template <typename F, typename... Args>
+        struct invoke_result<void_t<decltype(lib::invoke(
+                                 std::declval<F>(), std::declval<Args>()...))>,
+                             F,
+                             Args...>
+            : identity<decltype(
+                  lib::invoke(std::declval<F>(), std::declval<Args>()...))> {};
+
+      }  // namespace detail
+
+      template <typename F, typename... Args>
+      using invoke_result = detail::invoke_result<void, F, Args...>;
+
+      template <typename F, typename... Args>
+      using invoke_result_t = typename invoke_result<F, Args...>::type;
+
+      namespace detail {
+
+        template <typename Void, typename, typename...>
+        struct is_invocable : std::false_type {};
+
+        template <typename F, typename... Args>
+        struct is_invocable<void_t<invoke_result_t<F, Args...>>, F, Args...>
+            : std::true_type {};
+
+        template <typename Void, typename, typename, typename...>
+        struct is_invocable_r : std::false_type {};
+
+        template <typename R, typename F, typename... Args>
+        struct is_invocable_r<void_t<invoke_result_t<F, Args...>>,
+                              R,
+                              F,
+                              Args...>
+            : std::is_convertible<invoke_result_t<F, Args...>, R> {};
+
+      }  // namespace detail
+
+      template <typename F, typename... Args>
+      using is_invocable = detail::is_invocable<void, F, Args...>;
+
+      template <typename R, typename F, typename... Args>
+      using is_invocable_r = detail::is_invocable_r<void, R, F, Args...>;
+
+      namespace detail {
+
+        template <bool Invocable, typename F, typename... Args>
+        struct is_nothrow_invocable {
+          static constexpr bool value =
+              noexcept(lib::invoke(std::declval<F>(), std::declval<Args>()...));
+        };
+
+        template <typename F, typename... Args>
+        struct is_nothrow_invocable<false, F, Args...> : std::false_type {};
+
+        template <bool Invocable, typename R, typename F, typename... Args>
+        struct is_nothrow_invocable_r {
+          private:
+          inline static R impl() {
+            return lib::invoke(std::declval<F>(), std::declval<Args>()...);
+          }
+
+          public:
+          static constexpr bool value = noexcept(impl());
+        };
+
+        template <typename R, typename F, typename... Args>
+        struct is_nothrow_invocable_r<false, R, F, Args...> : std::false_type {};
+
+      }  // namespace detail
+
+      template <typename F, typename... Args>
+      using is_nothrow_invocable = detail::
+          is_nothrow_invocable<is_invocable<F, Args...>::value, F, Args...>;
+
+      template <typename R, typename F, typename... Args>
+      using is_nothrow_invocable_r =
+          detail::is_nothrow_invocable_r<is_invocable_r<R, F, Args...>::value,
+                                         R,
+                                         F,
+                                         Args...>;
+
+      // <memory>
+#ifdef MPARK_BUILTIN_ADDRESSOF
+      template <typename T>
+      inline constexpr T *addressof(T &arg) noexcept {
+        return __builtin_addressof(arg);
+      }
+#else
+      namespace detail {
+
+        namespace has_addressof_impl {
+
+          struct fail;
+
+          template <typename T>
+          inline fail operator&(T &&);
+
+          template <typename T>
+          inline static constexpr bool impl() {
+            return (std::is_class<T>::value || std::is_union<T>::value) &&
+                   !std::is_same<decltype(&std::declval<T &>()), fail>::value;
+          }
+
+        }  // namespace has_addressof_impl
+
+        template <typename T>
+        using has_addressof = bool_constant<has_addressof_impl::impl<T>()>;
+
+        template <typename T>
+        inline constexpr T *addressof(T &arg, std::true_type) noexcept {
+          return std::addressof(arg);
+        }
+
+        template <typename T>
+        inline constexpr T *addressof(T &arg, std::false_type) noexcept {
+          return &arg;
+        }
+
+      }  // namespace detail
+
+      template <typename T>
+      inline constexpr T *addressof(T &arg) noexcept {
+        return detail::addressof(arg, detail::has_addressof<T>{});
+      }
+#endif
+
+      template <typename T>
+      inline constexpr T *addressof(const T &&) = delete;
+
+    }  // namespace cpp17
+
+    template <typename T>
+    struct remove_all_extents : identity<T> {};
+
+    template <typename T, std::size_t N>
+    struct remove_all_extents<array<T, N>> : remove_all_extents<T> {};
+
+    template <typename T>
+    using remove_all_extents_t = typename remove_all_extents<T>::type;
+
+    template <std::size_t N>
+    using size_constant = std::integral_constant<std::size_t, N>;
+
+    template <std::size_t I, typename T>
+    struct indexed_type : size_constant<I> { using type = T; };
+
+    template <bool... Bs>
+    using all = std::is_same<integer_sequence<bool, true, Bs...>,
+                             integer_sequence<bool, Bs..., true>>;
+
+#ifdef MPARK_TYPE_PACK_ELEMENT
+    template <std::size_t I, typename... Ts>
+    using type_pack_element_t = __type_pack_element<I, Ts...>;
+#else
+    template <std::size_t I, typename... Ts>
+    struct type_pack_element_impl {
+      private:
+      template <typename>
+      struct set;
+
+      template <std::size_t... Is>
+      struct set<index_sequence<Is...>> : indexed_type<Is, Ts>... {};
+
+      template <typename T>
+      inline static std::enable_if<true, T> impl(indexed_type<I, T>);
+
+      inline static std::enable_if<false> impl(...);
+
+      public:
+      using type = decltype(impl(set<index_sequence_for<Ts...>>{}));
+    };
+
+    template <std::size_t I, typename... Ts>
+    using type_pack_element = typename type_pack_element_impl<I, Ts...>::type;
+
+    template <std::size_t I, typename... Ts>
+    using type_pack_element_t = typename type_pack_element<I, Ts...>::type;
+#endif
+
+#ifdef MPARK_TRIVIALITY_TYPE_TRAITS
+    using std::is_trivially_copy_constructible;
+    using std::is_trivially_move_constructible;
+    using std::is_trivially_copy_assignable;
+    using std::is_trivially_move_assignable;
+#else
+    template <typename T>
+    struct is_trivially_copy_constructible
+        : bool_constant<
+              std::is_copy_constructible<T>::value && __has_trivial_copy(T)> {};
+
+    template <typename T>
+    struct is_trivially_move_constructible : bool_constant<__is_trivial(T)> {};
+
+    template <typename T>
+    struct is_trivially_copy_assignable
+        : bool_constant<
+              std::is_copy_assignable<T>::value && __has_trivial_assign(T)> {};
+
+    template <typename T>
+    struct is_trivially_move_assignable : bool_constant<__is_trivial(T)> {};
+#endif
+
+    template <typename T, bool>
+    struct dependent_type : T {};
+
+    template <typename Is, std::size_t J>
+    struct push_back;
+
+    template <typename Is, std::size_t J>
+    using push_back_t = typename push_back<Is, J>::type;
+
+    template <std::size_t... Is, std::size_t J>
+    struct push_back<index_sequence<Is...>, J> {
+      using type = index_sequence<Is..., J>;
+    };
+
+  }  // namespace lib
+}  // namespace mpark
+
+#undef MPARK_RETURN
+
+#endif  // MPARK_LIB_HPP
+
+
+namespace mpark {
+
+#ifdef MPARK_RETURN_TYPE_DEDUCTION
+
+#define AUTO auto
+#define AUTO_RETURN(...) { return __VA_ARGS__; }
+
+#define AUTO_REFREF auto &&
+#define AUTO_REFREF_RETURN(...) { return __VA_ARGS__; }
+
+#define DECLTYPE_AUTO decltype(auto)
+#define DECLTYPE_AUTO_RETURN(...) { return __VA_ARGS__; }
+
+#else
+
+#define AUTO auto
+#define AUTO_RETURN(...) \
+  -> lib::decay_t<decltype(__VA_ARGS__)> { return __VA_ARGS__; }
+
+#define AUTO_REFREF auto
+#define AUTO_REFREF_RETURN(...)                                           \
+  -> decltype((__VA_ARGS__)) {                                            \
+    static_assert(std::is_reference<decltype((__VA_ARGS__))>::value, ""); \
+    return __VA_ARGS__;                                                   \
+  }
+
+#define DECLTYPE_AUTO auto
+#define DECLTYPE_AUTO_RETURN(...) \
+  -> decltype(__VA_ARGS__) { return __VA_ARGS__; }
+
+#endif
+
+  class bad_variant_access : public std::exception {
+    public:
+    virtual const char *what() const noexcept override { return "bad_variant_access"; }
+  };
+
+  [[noreturn]] inline void throw_bad_variant_access() {
+#ifdef MPARK_EXCEPTIONS
+    throw bad_variant_access{};
+#else
+    std::terminate();
+    MPARK_BUILTIN_UNREACHABLE;
+#endif
+  }
+
+  template <typename... Ts>
+  class variant;
+
+  template <typename T>
+  struct variant_size;
+
+#ifdef MPARK_VARIABLE_TEMPLATES
+  template <typename T>
+  constexpr std::size_t variant_size_v = variant_size<T>::value;
+#endif
+
+  template <typename T>
+  struct variant_size<const T> : variant_size<T> {};
+
+  template <typename T>
+  struct variant_size<volatile T> : variant_size<T> {};
+
+  template <typename T>
+  struct variant_size<const volatile T> : variant_size<T> {};
+
+  template <typename... Ts>
+  struct variant_size<variant<Ts...>> : lib::size_constant<sizeof...(Ts)> {};
+
+  template <std::size_t I, typename T>
+  struct variant_alternative;
+
+  template <std::size_t I, typename T>
+  using variant_alternative_t = typename variant_alternative<I, T>::type;
+
+  template <std::size_t I, typename T>
+  struct variant_alternative<I, const T>
+      : std::add_const<variant_alternative_t<I, T>> {};
+
+  template <std::size_t I, typename T>
+  struct variant_alternative<I, volatile T>
+      : std::add_volatile<variant_alternative_t<I, T>> {};
+
+  template <std::size_t I, typename T>
+  struct variant_alternative<I, const volatile T>
+      : std::add_cv<variant_alternative_t<I, T>> {};
+
+  template <std::size_t I, typename... Ts>
+  struct variant_alternative<I, variant<Ts...>> {
+    static_assert(I < sizeof...(Ts),
+                  "index out of bounds in `std::variant_alternative<>`");
+    using type = lib::type_pack_element_t<I, Ts...>;
+  };
+
+  constexpr std::size_t variant_npos = static_cast<std::size_t>(-1);
+
+  namespace detail {
+
+    constexpr std::size_t not_found = static_cast<std::size_t>(-1);
+    constexpr std::size_t ambiguous = static_cast<std::size_t>(-2);
+
+#ifdef MPARK_CPP14_CONSTEXPR
+    template <typename T, typename... Ts>
+    inline constexpr std::size_t find_index() {
+      constexpr lib::array<bool, sizeof...(Ts)> matches = {
+          {std::is_same<T, Ts>::value...}
+      };
+      std::size_t result = not_found;
+      for (std::size_t i = 0; i < sizeof...(Ts); ++i) {
+        if (matches[i]) {
+          if (result != not_found) {
+            return ambiguous;
+          }
+          result = i;
+        }
+      }
+      return result;
+    }
+#else
+    inline constexpr std::size_t find_index_impl(std::size_t result,
+                                                 std::size_t) {
+      return result;
+    }
+
+    template <typename... Bs>
+    inline constexpr std::size_t find_index_impl(std::size_t result,
+                                                 std::size_t idx,
+                                                 bool b,
+                                                 Bs... bs) {
+      return b ? (result != not_found ? ambiguous
+                                      : find_index_impl(idx, idx + 1, bs...))
+               : find_index_impl(result, idx + 1, bs...);
+    }
+
+    template <typename T, typename... Ts>
+    inline constexpr std::size_t find_index() {
+      return find_index_impl(not_found, 0, std::is_same<T, Ts>::value...);
+    }
+#endif
+
+    template <std::size_t I>
+    using find_index_sfinae_impl =
+        lib::enable_if_t<I != not_found && I != ambiguous,
+                         lib::size_constant<I>>;
+
+    template <typename T, typename... Ts>
+    using find_index_sfinae = find_index_sfinae_impl<find_index<T, Ts...>()>;
+
+    template <std::size_t I>
+    struct find_index_checked_impl : lib::size_constant<I> {
+      static_assert(I != not_found, "the specified type is not found.");
+      static_assert(I != ambiguous, "the specified type is ambiguous.");
+    };
+
+    template <typename T, typename... Ts>
+    using find_index_checked = find_index_checked_impl<find_index<T, Ts...>()>;
+
+    struct valueless_t {};
+
+    enum class Trait { TriviallyAvailable, Available, Unavailable };
+
+    template <typename T,
+              template <typename> class IsTriviallyAvailable,
+              template <typename> class IsAvailable>
+    inline constexpr Trait trait() {
+      return IsTriviallyAvailable<T>::value
+                 ? Trait::TriviallyAvailable
+                 : IsAvailable<T>::value ? Trait::Available
+                                         : Trait::Unavailable;
+    }
+
+#ifdef MPARK_CPP14_CONSTEXPR
+    template <typename... Traits>
+    inline constexpr Trait common_trait(Traits... traits_) {
+      Trait result = Trait::TriviallyAvailable;
+      lib::array<Trait, sizeof...(Traits)> traits = {{traits_...}};
+      for (std::size_t i = 0; i < sizeof...(Traits); ++i) {
+        Trait t = traits[i];
+        if (static_cast<int>(t) > static_cast<int>(result)) {
+          result = t;
+        }
+      }
+      return result;
+    }
+#else
+    inline constexpr Trait common_trait_impl(Trait result) { return result; }
+
+    template <typename... Traits>
+    inline constexpr Trait common_trait_impl(Trait result,
+                                             Trait t,
+                                             Traits... ts) {
+      return static_cast<int>(t) > static_cast<int>(result)
+                 ? common_trait_impl(t, ts...)
+                 : common_trait_impl(result, ts...);
+    }
+
+    template <typename... Traits>
+    inline constexpr Trait common_trait(Traits... ts) {
+      return common_trait_impl(Trait::TriviallyAvailable, ts...);
+    }
+#endif
+
+    template <typename... Ts>
+    struct traits {
+      static constexpr Trait copy_constructible_trait =
+          common_trait(trait<Ts,
+                             lib::is_trivially_copy_constructible,
+                             std::is_copy_constructible>()...);
+
+      static constexpr Trait move_constructible_trait =
+          common_trait(trait<Ts,
+                             lib::is_trivially_move_constructible,
+                             std::is_move_constructible>()...);
+
+      static constexpr Trait copy_assignable_trait =
+          common_trait(copy_constructible_trait,
+                       trait<Ts,
+                             lib::is_trivially_copy_assignable,
+                             std::is_copy_assignable>()...);
+
+      static constexpr Trait move_assignable_trait =
+          common_trait(move_constructible_trait,
+                       trait<Ts,
+                             lib::is_trivially_move_assignable,
+                             std::is_move_assignable>()...);
+
+      static constexpr Trait destructible_trait =
+          common_trait(trait<Ts,
+                             std::is_trivially_destructible,
+                             std::is_destructible>()...);
+    };
+
+    namespace access {
+
+      struct recursive_union {
+#ifdef MPARK_RETURN_TYPE_DEDUCTION
+        template <typename V>
+        inline static constexpr auto &&get_alt(V &&v, in_place_index_t<0>) {
+          return lib::forward<V>(v).head_;
+        }
+
+        template <typename V, std::size_t I>
+        inline static constexpr auto &&get_alt(V &&v, in_place_index_t<I>) {
+          return get_alt(lib::forward<V>(v).tail_, in_place_index_t<I - 1>{});
+        }
+#else
+        template <std::size_t I, bool Dummy = true>
+        struct get_alt_impl {
+          template <typename V>
+          inline constexpr AUTO_REFREF operator()(V &&v) const
+            AUTO_REFREF_RETURN(get_alt_impl<I - 1>{}(lib::forward<V>(v).tail_))
+        };
+
+        template <bool Dummy>
+        struct get_alt_impl<0, Dummy> {
+          template <typename V>
+          inline constexpr AUTO_REFREF operator()(V &&v) const
+            AUTO_REFREF_RETURN(lib::forward<V>(v).head_)
+        };
+
+        template <typename V, std::size_t I>
+        inline static constexpr AUTO_REFREF get_alt(V &&v, in_place_index_t<I>)
+          AUTO_REFREF_RETURN(get_alt_impl<I>{}(lib::forward<V>(v)))
+#endif
+      };
+
+      struct base {
+        template <std::size_t I, typename V>
+        inline static constexpr AUTO_REFREF get_alt(V &&v)
+#ifdef _MSC_VER
+          AUTO_REFREF_RETURN(recursive_union::get_alt(
+              lib::forward<V>(v).data_, in_place_index_t<I>{}))
+#else
+          AUTO_REFREF_RETURN(recursive_union::get_alt(
+              data(lib::forward<V>(v)), in_place_index_t<I>{}))
+#endif
+      };
+
+      struct variant {
+        template <std::size_t I, typename V>
+        inline static constexpr AUTO_REFREF get_alt(V &&v)
+          AUTO_REFREF_RETURN(base::get_alt<I>(lib::forward<V>(v).impl_))
+      };
+
+    }  // namespace access
+
+    namespace visitation {
+
+#if defined(MPARK_CPP14_CONSTEXPR) && !defined(_MSC_VER)
+#define MPARK_VARIANT_SWITCH_VISIT
+#endif
+
+      struct base {
+        template <typename Visitor, typename... Vs>
+        using dispatch_result_t = decltype(
+            lib::invoke(std::declval<Visitor>(),
+                        access::base::get_alt<0>(std::declval<Vs>())...));
+
+        template <typename Expected>
+        struct expected {
+          template <typename Actual>
+          inline static constexpr bool but_got() {
+            return std::is_same<Expected, Actual>::value;
+          }
+        };
+
+        template <typename Expected, typename Actual>
+        struct visit_return_type_check {
+          static_assert(
+              expected<Expected>::template but_got<Actual>(),
+              "`visit` requires the visitor to have a single return type");
+
+          template <typename Visitor, typename... Alts>
+          inline static constexpr DECLTYPE_AUTO invoke(Visitor &&visitor,
+                                                       Alts &&... alts)
+            DECLTYPE_AUTO_RETURN(lib::invoke(lib::forward<Visitor>(visitor),
+                                             lib::forward<Alts>(alts)...))
+        };
+
+#ifdef MPARK_VARIANT_SWITCH_VISIT
+        template <bool B, typename R, typename... ITs>
+        struct dispatcher;
+
+        template <typename R, typename... ITs>
+        struct dispatcher<false, R, ITs...> {
+          template <std::size_t B, typename F, typename... Vs>
+          MPARK_ALWAYS_INLINE static constexpr R dispatch(
+              F &&, typename ITs::type &&..., Vs &&...) {
+            MPARK_BUILTIN_UNREACHABLE;
+          }
+
+          template <std::size_t I, typename F, typename... Vs>
+          MPARK_ALWAYS_INLINE static constexpr R dispatch_case(F &&, Vs &&...) {
+            MPARK_BUILTIN_UNREACHABLE;
+          }
+
+          template <std::size_t B, typename F, typename... Vs>
+          MPARK_ALWAYS_INLINE static constexpr R dispatch_at(std::size_t,
+                                                             F &&,
+                                                             Vs &&...) {
+            MPARK_BUILTIN_UNREACHABLE;
+          }
+        };
+
+        template <typename R, typename... ITs>
+        struct dispatcher<true, R, ITs...> {
+          template <std::size_t B, typename F>
+          MPARK_ALWAYS_INLINE static constexpr R dispatch(
+              F &&f, typename ITs::type &&... visited_vs) {
+            using Expected = R;
+            using Actual = decltype(lib::invoke(
+                lib::forward<F>(f),
+                access::base::get_alt<ITs::value>(
+                    lib::forward<typename ITs::type>(visited_vs))...));
+            return visit_return_type_check<Expected, Actual>::invoke(
+                lib::forward<F>(f),
+                access::base::get_alt<ITs::value>(
+                    lib::forward<typename ITs::type>(visited_vs))...);
+          }
+
+          template <std::size_t B, typename F, typename V, typename... Vs>
+          MPARK_ALWAYS_INLINE static constexpr R dispatch(
+              F &&f, typename ITs::type &&... visited_vs, V &&v, Vs &&... vs) {
+#define MPARK_DISPATCH(I)                                                   \
+  dispatcher<(I < lib::decay_t<V>::size()),                                 \
+             R,                                                             \
+             ITs...,                                                        \
+             lib::indexed_type<I, V>>::                                     \
+      template dispatch<0>(lib::forward<F>(f),                              \
+                           lib::forward<typename ITs::type>(visited_vs)..., \
+                           lib::forward<V>(v),                              \
+                           lib::forward<Vs>(vs)...)
+
+#define MPARK_DEFAULT(I)                                                      \
+  dispatcher<(I < lib::decay_t<V>::size()), R, ITs...>::template dispatch<I>( \
+      lib::forward<F>(f),                                                     \
+      lib::forward<typename ITs::type>(visited_vs)...,                        \
+      lib::forward<V>(v),                                                     \
+      lib::forward<Vs>(vs)...)
+
+            switch (v.index()) {
+              case B + 0: return MPARK_DISPATCH(B + 0);
+              case B + 1: return MPARK_DISPATCH(B + 1);
+              case B + 2: return MPARK_DISPATCH(B + 2);
+              case B + 3: return MPARK_DISPATCH(B + 3);
+              case B + 4: return MPARK_DISPATCH(B + 4);
+              case B + 5: return MPARK_DISPATCH(B + 5);
+              case B + 6: return MPARK_DISPATCH(B + 6);
+              case B + 7: return MPARK_DISPATCH(B + 7);
+              case B + 8: return MPARK_DISPATCH(B + 8);
+              case B + 9: return MPARK_DISPATCH(B + 9);
+              case B + 10: return MPARK_DISPATCH(B + 10);
+              case B + 11: return MPARK_DISPATCH(B + 11);
+              case B + 12: return MPARK_DISPATCH(B + 12);
+              case B + 13: return MPARK_DISPATCH(B + 13);
+              case B + 14: return MPARK_DISPATCH(B + 14);
+              case B + 15: return MPARK_DISPATCH(B + 15);
+              case B + 16: return MPARK_DISPATCH(B + 16);
+              case B + 17: return MPARK_DISPATCH(B + 17);
+              case B + 18: return MPARK_DISPATCH(B + 18);
+              case B + 19: return MPARK_DISPATCH(B + 19);
+              case B + 20: return MPARK_DISPATCH(B + 20);
+              case B + 21: return MPARK_DISPATCH(B + 21);
+              case B + 22: return MPARK_DISPATCH(B + 22);
+              case B + 23: return MPARK_DISPATCH(B + 23);
+              case B + 24: return MPARK_DISPATCH(B + 24);
+              case B + 25: return MPARK_DISPATCH(B + 25);
+              case B + 26: return MPARK_DISPATCH(B + 26);
+              case B + 27: return MPARK_DISPATCH(B + 27);
+              case B + 28: return MPARK_DISPATCH(B + 28);
+              case B + 29: return MPARK_DISPATCH(B + 29);
+              case B + 30: return MPARK_DISPATCH(B + 30);
+              case B + 31: return MPARK_DISPATCH(B + 31);
+              default: return MPARK_DEFAULT(B + 32);
+            }
+
+#undef MPARK_DEFAULT
+#undef MPARK_DISPATCH
+          }
+
+          template <std::size_t I, typename F, typename... Vs>
+          MPARK_ALWAYS_INLINE static constexpr R dispatch_case(F &&f,
+                                                               Vs &&... vs) {
+            using Expected = R;
+            using Actual = decltype(
+                lib::invoke(lib::forward<F>(f),
+                            access::base::get_alt<I>(lib::forward<Vs>(vs))...));
+            return visit_return_type_check<Expected, Actual>::invoke(
+                lib::forward<F>(f),
+                access::base::get_alt<I>(lib::forward<Vs>(vs))...);
+          }
+
+          template <std::size_t B, typename F, typename V, typename... Vs>
+          MPARK_ALWAYS_INLINE static constexpr R dispatch_at(std::size_t index,
+                                                             F &&f,
+                                                             V &&v,
+                                                             Vs &&... vs) {
+            static_assert(lib::all<(lib::decay_t<V>::size() ==
+                                    lib::decay_t<Vs>::size())...>::value,
+                          "all of the variants must be the same size.");
+#define MPARK_DISPATCH_AT(I)                                               \
+  dispatcher<(I < lib::decay_t<V>::size()), R>::template dispatch_case<I>( \
+      lib::forward<F>(f), lib::forward<V>(v), lib::forward<Vs>(vs)...)
+
+#define MPARK_DEFAULT(I)                                                 \
+  dispatcher<(I < lib::decay_t<V>::size()), R>::template dispatch_at<I>( \
+      index, lib::forward<F>(f), lib::forward<V>(v), lib::forward<Vs>(vs)...)
+
+            switch (index) {
+              case B + 0: return MPARK_DISPATCH_AT(B + 0);
+              case B + 1: return MPARK_DISPATCH_AT(B + 1);
+              case B + 2: return MPARK_DISPATCH_AT(B + 2);
+              case B + 3: return MPARK_DISPATCH_AT(B + 3);
+              case B + 4: return MPARK_DISPATCH_AT(B + 4);
+              case B + 5: return MPARK_DISPATCH_AT(B + 5);
+              case B + 6: return MPARK_DISPATCH_AT(B + 6);
+              case B + 7: return MPARK_DISPATCH_AT(B + 7);
+              case B + 8: return MPARK_DISPATCH_AT(B + 8);
+              case B + 9: return MPARK_DISPATCH_AT(B + 9);
+              case B + 10: return MPARK_DISPATCH_AT(B + 10);
+              case B + 11: return MPARK_DISPATCH_AT(B + 11);
+              case B + 12: return MPARK_DISPATCH_AT(B + 12);
+              case B + 13: return MPARK_DISPATCH_AT(B + 13);
+              case B + 14: return MPARK_DISPATCH_AT(B + 14);
+              case B + 15: return MPARK_DISPATCH_AT(B + 15);
+              case B + 16: return MPARK_DISPATCH_AT(B + 16);
+              case B + 17: return MPARK_DISPATCH_AT(B + 17);
+              case B + 18: return MPARK_DISPATCH_AT(B + 18);
+              case B + 19: return MPARK_DISPATCH_AT(B + 19);
+              case B + 20: return MPARK_DISPATCH_AT(B + 20);
+              case B + 21: return MPARK_DISPATCH_AT(B + 21);
+              case B + 22: return MPARK_DISPATCH_AT(B + 22);
+              case B + 23: return MPARK_DISPATCH_AT(B + 23);
+              case B + 24: return MPARK_DISPATCH_AT(B + 24);
+              case B + 25: return MPARK_DISPATCH_AT(B + 25);
+              case B + 26: return MPARK_DISPATCH_AT(B + 26);
+              case B + 27: return MPARK_DISPATCH_AT(B + 27);
+              case B + 28: return MPARK_DISPATCH_AT(B + 28);
+              case B + 29: return MPARK_DISPATCH_AT(B + 29);
+              case B + 30: return MPARK_DISPATCH_AT(B + 30);
+              case B + 31: return MPARK_DISPATCH_AT(B + 31);
+              default: return MPARK_DEFAULT(B + 32);
+            }
+
+#undef MPARK_DEFAULT
+#undef MPARK_DISPATCH_AT
+          }
+        };
+#else
+        template <typename T>
+        inline static constexpr const T &at(const T &elem) noexcept {
+          return elem;
+        }
+
+        template <typename T, std::size_t N, typename... Is>
+        inline static constexpr const lib::remove_all_extents_t<T> &at(
+            const lib::array<T, N> &elems, std::size_t i, Is... is) noexcept {
+          return at(elems[i], is...);
+        }
+
+        template <typename F, typename... Fs>
+        inline static constexpr lib::array<lib::decay_t<F>, sizeof...(Fs) + 1>
+        make_farray(F &&f, Fs &&... fs) {
+          return {{lib::forward<F>(f), lib::forward<Fs>(fs)...}};
+        }
+
+        template <typename F, typename... Vs>
+        struct make_fmatrix_impl {
+
+          template <std::size_t... Is>
+          inline static constexpr dispatch_result_t<F, Vs...> dispatch(
+              F &&f, Vs &&... vs) {
+            using Expected = dispatch_result_t<F, Vs...>;
+            using Actual = decltype(lib::invoke(
+                lib::forward<F>(f),
+                access::base::get_alt<Is>(lib::forward<Vs>(vs))...));
+            return visit_return_type_check<Expected, Actual>::invoke(
+                lib::forward<F>(f),
+                access::base::get_alt<Is>(lib::forward<Vs>(vs))...);
+          }
+
+#ifdef MPARK_RETURN_TYPE_DEDUCTION
+          template <std::size_t... Is>
+          inline static constexpr auto impl(lib::index_sequence<Is...>) {
+            return &dispatch<Is...>;
+          }
+
+          template <typename Is, std::size_t... Js, typename... Ls>
+          inline static constexpr auto impl(Is,
+                                            lib::index_sequence<Js...>,
+                                            Ls... ls) {
+            return make_farray(impl(lib::push_back_t<Is, Js>{}, ls...)...);
+          }
+#else
+          template <typename...>
+          struct impl;
+
+          template <std::size_t... Is>
+          struct impl<lib::index_sequence<Is...>> {
+            inline constexpr AUTO operator()() const
+              AUTO_RETURN(&dispatch<Is...>)
+          };
+
+          template <typename Is, std::size_t... Js, typename... Ls>
+          struct impl<Is, lib::index_sequence<Js...>, Ls...> {
+            inline constexpr AUTO operator()() const
+              AUTO_RETURN(
+                  make_farray(impl<lib::push_back_t<Is, Js>, Ls...>{}()...))
+          };
+#endif
+        };
+
+#ifdef MPARK_RETURN_TYPE_DEDUCTION
+        template <typename F, typename... Vs>
+        inline static constexpr auto make_fmatrix() {
+          return make_fmatrix_impl<F, Vs...>::impl(
+              lib::index_sequence<>{},
+              lib::make_index_sequence<lib::decay_t<Vs>::size()>{}...);
+        }
+#else
+        template <typename F, typename... Vs>
+        inline static constexpr AUTO make_fmatrix()
+          AUTO_RETURN(
+              typename make_fmatrix_impl<F, Vs...>::template impl<
+                  lib::index_sequence<>,
+                  lib::make_index_sequence<lib::decay_t<Vs>::size()>...>{}())
+#endif
+
+        template <typename F, typename... Vs>
+        struct make_fdiagonal_impl {
+          template <std::size_t I>
+          inline static constexpr dispatch_result_t<F, Vs...> dispatch(
+              F &&f, Vs &&... vs) {
+            using Expected = dispatch_result_t<F, Vs...>;
+            using Actual = decltype(
+                lib::invoke(lib::forward<F>(f),
+                            access::base::get_alt<I>(lib::forward<Vs>(vs))...));
+            return visit_return_type_check<Expected, Actual>::invoke(
+                lib::forward<F>(f),
+                access::base::get_alt<I>(lib::forward<Vs>(vs))...);
+          }
+
+          template <std::size_t... Is>
+          inline static constexpr AUTO impl(lib::index_sequence<Is...>)
+            AUTO_RETURN(make_farray(&dispatch<Is>...))
+        };
+
+        template <typename F, typename V, typename... Vs>
+        inline static constexpr auto make_fdiagonal()
+            -> decltype(make_fdiagonal_impl<F, V, Vs...>::impl(
+                lib::make_index_sequence<lib::decay_t<V>::size()>{})) {
+          static_assert(lib::all<(lib::decay_t<V>::size() ==
+                                  lib::decay_t<Vs>::size())...>::value,
+                        "all of the variants must be the same size.");
+          return make_fdiagonal_impl<F, V, Vs...>::impl(
+              lib::make_index_sequence<lib::decay_t<V>::size()>{});
+        }
+#endif
+      };
+
+#if !defined(MPARK_VARIANT_SWITCH_VISIT) && \
+    (!defined(_MSC_VER) || _MSC_VER >= 1910)
+      template <typename F, typename... Vs>
+      using fmatrix_t = decltype(base::make_fmatrix<F, Vs...>());
+
+      template <typename F, typename... Vs>
+      struct fmatrix {
+        static constexpr fmatrix_t<F, Vs...> value =
+            base::make_fmatrix<F, Vs...>();
+      };
+
+      template <typename F, typename... Vs>
+      constexpr fmatrix_t<F, Vs...> fmatrix<F, Vs...>::value;
+
+      template <typename F, typename... Vs>
+      using fdiagonal_t = decltype(base::make_fdiagonal<F, Vs...>());
+
+      template <typename F, typename... Vs>
+      struct fdiagonal {
+        static constexpr fdiagonal_t<F, Vs...> value =
+            base::make_fdiagonal<F, Vs...>();
+      };
+
+      template <typename F, typename... Vs>
+      constexpr fdiagonal_t<F, Vs...> fdiagonal<F, Vs...>::value;
+#endif
+
+      struct alt {
+        template <typename Visitor, typename... Vs>
+        inline static constexpr DECLTYPE_AUTO visit_alt(Visitor &&visitor,
+                                                        Vs &&... vs)
+#ifdef MPARK_VARIANT_SWITCH_VISIT
+          DECLTYPE_AUTO_RETURN(
+              base::dispatcher<
+                  true,
+                  base::dispatch_result_t<Visitor,
+                                          decltype(as_base(
+                                              lib::forward<Vs>(vs)))...>>::
+                  template dispatch<0>(lib::forward<Visitor>(visitor),
+                                       as_base(lib::forward<Vs>(vs))...))
+#elif !defined(_MSC_VER) || _MSC_VER >= 1910
+          DECLTYPE_AUTO_RETURN(base::at(
+              fmatrix<Visitor &&,
+                      decltype(as_base(lib::forward<Vs>(vs)))...>::value,
+              vs.index()...)(lib::forward<Visitor>(visitor),
+                             as_base(lib::forward<Vs>(vs))...))
+#else
+          DECLTYPE_AUTO_RETURN(base::at(
+              base::make_fmatrix<Visitor &&,
+                      decltype(as_base(lib::forward<Vs>(vs)))...>(),
+              vs.index()...)(lib::forward<Visitor>(visitor),
+                             as_base(lib::forward<Vs>(vs))...))
+#endif
+
+        template <typename Visitor, typename... Vs>
+        inline static constexpr DECLTYPE_AUTO visit_alt_at(std::size_t index,
+                                                           Visitor &&visitor,
+                                                           Vs &&... vs)
+#ifdef MPARK_VARIANT_SWITCH_VISIT
+          DECLTYPE_AUTO_RETURN(
+              base::dispatcher<
+                  true,
+                  base::dispatch_result_t<Visitor,
+                                          decltype(as_base(
+                                              lib::forward<Vs>(vs)))...>>::
+                  template dispatch_at<0>(index,
+                                          lib::forward<Visitor>(visitor),
+                                          as_base(lib::forward<Vs>(vs))...))
+#elif !defined(_MSC_VER) || _MSC_VER >= 1910
+          DECLTYPE_AUTO_RETURN(base::at(
+              fdiagonal<Visitor &&,
+                        decltype(as_base(lib::forward<Vs>(vs)))...>::value,
+              index)(lib::forward<Visitor>(visitor),
+                     as_base(lib::forward<Vs>(vs))...))
+#else
+          DECLTYPE_AUTO_RETURN(base::at(
+              base::make_fdiagonal<Visitor &&,
+                        decltype(as_base(lib::forward<Vs>(vs)))...>(),
+              index)(lib::forward<Visitor>(visitor),
+                     as_base(lib::forward<Vs>(vs))...))
+#endif
+      };
+
+      struct variant {
+        private:
+        template <typename Visitor>
+        struct visitor {
+          template <typename... Values>
+          inline static constexpr bool does_not_handle() {
+            return lib::is_invocable<Visitor, Values...>::value;
+          }
+        };
+
+        template <typename Visitor, typename... Values>
+        struct visit_exhaustiveness_check {
+          static_assert(visitor<Visitor>::template does_not_handle<Values...>(),
+                        "`visit` requires the visitor to be exhaustive.");
+
+          inline static constexpr DECLTYPE_AUTO invoke(Visitor &&visitor,
+                                                       Values &&... values)
+            DECLTYPE_AUTO_RETURN(lib::invoke(lib::forward<Visitor>(visitor),
+                                             lib::forward<Values>(values)...))
+        };
+
+        template <typename Visitor>
+        struct value_visitor {
+          Visitor &&visitor_;
+
+          template <typename... Alts>
+          inline constexpr DECLTYPE_AUTO operator()(Alts &&... alts) const
+            DECLTYPE_AUTO_RETURN(
+                visit_exhaustiveness_check<
+                    Visitor,
+                    decltype((lib::forward<Alts>(alts).value))...>::
+                    invoke(lib::forward<Visitor>(visitor_),
+                           lib::forward<Alts>(alts).value...))
+        };
+
+        template <typename Visitor>
+        inline static constexpr AUTO make_value_visitor(Visitor &&visitor)
+          AUTO_RETURN(value_visitor<Visitor>{lib::forward<Visitor>(visitor)})
+
+        public:
+        template <typename Visitor, typename... Vs>
+        inline static constexpr DECLTYPE_AUTO visit_alt(Visitor &&visitor,
+                                                        Vs &&... vs)
+          DECLTYPE_AUTO_RETURN(alt::visit_alt(lib::forward<Visitor>(visitor),
+                                              lib::forward<Vs>(vs).impl_...))
+
+        template <typename Visitor, typename... Vs>
+        inline static constexpr DECLTYPE_AUTO visit_alt_at(std::size_t index,
+                                                           Visitor &&visitor,
+                                                           Vs &&... vs)
+          DECLTYPE_AUTO_RETURN(
+              alt::visit_alt_at(index,
+                                lib::forward<Visitor>(visitor),
+                                lib::forward<Vs>(vs).impl_...))
+
+        template <typename Visitor, typename... Vs>
+        inline static constexpr DECLTYPE_AUTO visit_value(Visitor &&visitor,
+                                                          Vs &&... vs)
+          DECLTYPE_AUTO_RETURN(
+              visit_alt(make_value_visitor(lib::forward<Visitor>(visitor)),
+                        lib::forward<Vs>(vs)...))
+
+        template <typename Visitor, typename... Vs>
+        inline static constexpr DECLTYPE_AUTO visit_value_at(std::size_t index,
+                                                             Visitor &&visitor,
+                                                             Vs &&... vs)
+          DECLTYPE_AUTO_RETURN(
+              visit_alt_at(index,
+                           make_value_visitor(lib::forward<Visitor>(visitor)),
+                           lib::forward<Vs>(vs)...))
+      };
+
+    }  // namespace visitation
+
+    template <std::size_t Index, typename T>
+    struct alt {
+      using value_type = T;
+
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4244)
+#endif
+      template <typename... Args>
+      inline explicit constexpr alt(in_place_t, Args &&... args)
+          : value(lib::forward<Args>(args)...) {}
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+
+      T value;
+    };
+
+    template <Trait DestructibleTrait, std::size_t Index, typename... Ts>
+    union recursive_union;
+
+    template <Trait DestructibleTrait, std::size_t Index>
+    union recursive_union<DestructibleTrait, Index> {};
+
+#define MPARK_VARIANT_RECURSIVE_UNION(destructible_trait, destructor)      \
+  template <std::size_t Index, typename T, typename... Ts>                 \
+  union recursive_union<destructible_trait, Index, T, Ts...> {             \
+    public:                                                                \
+    inline explicit constexpr recursive_union(valueless_t) noexcept        \
+        : dummy_{} {}                                                      \
+                                                                           \
+    template <typename... Args>                                            \
+    inline explicit constexpr recursive_union(in_place_index_t<0>,         \
+                                              Args &&... args)             \
+        : head_(in_place_t{}, lib::forward<Args>(args)...) {}              \
+                                                                           \
+    template <std::size_t I, typename... Args>                             \
+    inline explicit constexpr recursive_union(in_place_index_t<I>,         \
+                                              Args &&... args)             \
+        : tail_(in_place_index_t<I - 1>{}, lib::forward<Args>(args)...) {} \
+                                                                           \
+    recursive_union(const recursive_union &) = default;                    \
+    recursive_union(recursive_union &&) = default;                         \
+                                                                           \
+    destructor                                                             \
+                                                                           \
+    recursive_union &operator=(const recursive_union &) = default;         \
+    recursive_union &operator=(recursive_union &&) = default;              \
+                                                                           \
+    private:                                                               \
+    char dummy_;                                                           \
+    alt<Index, T> head_;                                                   \
+    recursive_union<destructible_trait, Index + 1, Ts...> tail_;           \
+                                                                           \
+    friend struct access::recursive_union;                                 \
+  }
+
+    MPARK_VARIANT_RECURSIVE_UNION(Trait::TriviallyAvailable,
+                                  ~recursive_union() = default;);
+    MPARK_VARIANT_RECURSIVE_UNION(Trait::Available,
+                                  ~recursive_union() {});
+    MPARK_VARIANT_RECURSIVE_UNION(Trait::Unavailable,
+                                  ~recursive_union() = delete;);
+
+#undef MPARK_VARIANT_RECURSIVE_UNION
+
+    using index_t = unsigned int;
+
+    template <Trait DestructibleTrait, typename... Ts>
+    class base {
+      public:
+      inline explicit constexpr base(valueless_t tag) noexcept
+          : data_(tag), index_(static_cast<index_t>(-1)) {}
+
+      template <std::size_t I, typename... Args>
+      inline explicit constexpr base(in_place_index_t<I>, Args &&... args)
+          : data_(in_place_index_t<I>{}, lib::forward<Args>(args)...),
+            index_(I) {}
+
+      inline constexpr bool valueless_by_exception() const noexcept {
+        return index_ == static_cast<index_t>(-1);
+      }
+
+      inline constexpr std::size_t index() const noexcept {
+        return valueless_by_exception() ? variant_npos : index_;
+      }
+
+      protected:
+      using data_t = recursive_union<DestructibleTrait, 0, Ts...>;
+
+      friend inline constexpr base &as_base(base &b) { return b; }
+      friend inline constexpr const base &as_base(const base &b) { return b; }
+      friend inline constexpr base &&as_base(base &&b) { return lib::move(b); }
+      friend inline constexpr const base &&as_base(const base &&b) { return lib::move(b); }
+
+      friend inline constexpr data_t &data(base &b) { return b.data_; }
+      friend inline constexpr const data_t &data(const base &b) { return b.data_; }
+      friend inline constexpr data_t &&data(base &&b) { return lib::move(b).data_; }
+      friend inline constexpr const data_t &&data(const base &&b) { return lib::move(b).data_; }
+
+      inline static constexpr std::size_t size() { return sizeof...(Ts); }
+
+      data_t data_;
+      index_t index_;
+
+      friend struct access::base;
+      friend struct visitation::base;
+    };
+
+    struct dtor {
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4100)
+#endif
+      template <typename Alt>
+      inline void operator()(Alt &alt) const noexcept { alt.~Alt(); }
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+    };
+
+#if !defined(_MSC_VER) || _MSC_VER >= 1910
+#define MPARK_INHERITING_CTOR(type, base) using base::base;
+#else
+#define MPARK_INHERITING_CTOR(type, base)         \
+  template <typename... Args>                     \
+  inline explicit constexpr type(Args &&... args) \
+      : base(lib::forward<Args>(args)...) {}
+#endif
+
+    template <typename Traits, Trait = Traits::destructible_trait>
+    class destructor;
+
+#define MPARK_VARIANT_DESTRUCTOR(destructible_trait, definition, destroy) \
+  template <typename... Ts>                                               \
+  class destructor<traits<Ts...>, destructible_trait>                     \
+      : public base<destructible_trait, Ts...> {                          \
+    using super = base<destructible_trait, Ts...>;                        \
+                                                                          \
+    public:                                                               \
+    MPARK_INHERITING_CTOR(destructor, super)                              \
+    using super::operator=;                                               \
+                                                                          \
+    destructor(const destructor &) = default;                             \
+    destructor(destructor &&) = default;                                  \
+    definition                                                            \
+    destructor &operator=(const destructor &) = default;                  \
+    destructor &operator=(destructor &&) = default;                       \
+                                                                          \
+    protected:                                                            \
+    destroy                                                               \
+  }
+
+    MPARK_VARIANT_DESTRUCTOR(
+        Trait::TriviallyAvailable,
+        ~destructor() = default;,
+        inline void destroy() noexcept {
+          this->index_ = static_cast<index_t>(-1);
+        });
+
+    MPARK_VARIANT_DESTRUCTOR(
+        Trait::Available,
+        ~destructor() { destroy(); },
+        inline void destroy() noexcept {
+          if (!this->valueless_by_exception()) {
+            visitation::alt::visit_alt(dtor{}, *this);
+          }
+          this->index_ = static_cast<index_t>(-1);
+        });
+
+    MPARK_VARIANT_DESTRUCTOR(
+        Trait::Unavailable,
+        ~destructor() = delete;,
+        inline void destroy() noexcept = delete;);
+
+#undef MPARK_VARIANT_DESTRUCTOR
+
+    template <typename Traits>
+    class constructor : public destructor<Traits> {
+      using super = destructor<Traits>;
+
+      public:
+      MPARK_INHERITING_CTOR(constructor, super)
+      using super::operator=;
+
+      protected:
+#ifndef MPARK_GENERIC_LAMBDAS
+      struct ctor {
+        template <typename LhsAlt, typename RhsAlt>
+        inline void operator()(LhsAlt &lhs_alt, RhsAlt &&rhs_alt) const {
+          constructor::construct_alt(lhs_alt,
+                                     lib::forward<RhsAlt>(rhs_alt).value);
+        }
+      };
+#endif
+
+      template <std::size_t I, typename T, typename... Args>
+      inline static T &construct_alt(alt<I, T> &a, Args &&... args) {
+        auto *result = ::new (static_cast<void *>(lib::addressof(a)))
+            alt<I, T>(in_place_t{}, lib::forward<Args>(args)...);
+        return result->value;
+      }
+
+      template <typename Rhs>
+      inline static void generic_construct(constructor &lhs, Rhs &&rhs) {
+        lhs.destroy();
+        if (!rhs.valueless_by_exception()) {
+          visitation::alt::visit_alt_at(
+              rhs.index(),
+#ifdef MPARK_GENERIC_LAMBDAS
+              [](auto &lhs_alt, auto &&rhs_alt) {
+                constructor::construct_alt(
+                    lhs_alt, lib::forward<decltype(rhs_alt)>(rhs_alt).value);
+              }
+#else
+              ctor{}
+#endif
+              ,
+              lhs,
+              lib::forward<Rhs>(rhs));
+          lhs.index_ = rhs.index_;
+        }
+      }
+    };
+
+    template <typename Traits, Trait = Traits::move_constructible_trait>
+    class move_constructor;
+
+#define MPARK_VARIANT_MOVE_CONSTRUCTOR(move_constructible_trait, definition) \
+  template <typename... Ts>                                                  \
+  class move_constructor<traits<Ts...>, move_constructible_trait>            \
+      : public constructor<traits<Ts...>> {                                  \
+    using super = constructor<traits<Ts...>>;                                \
+                                                                             \
+    public:                                                                  \
+    MPARK_INHERITING_CTOR(move_constructor, super)                           \
+    using super::operator=;                                                  \
+                                                                             \
+    move_constructor(const move_constructor &) = default;                    \
+    definition                                                               \
+    ~move_constructor() = default;                                           \
+    move_constructor &operator=(const move_constructor &) = default;         \
+    move_constructor &operator=(move_constructor &&) = default;              \
+  }
+
+    MPARK_VARIANT_MOVE_CONSTRUCTOR(
+        Trait::TriviallyAvailable,
+        move_constructor(move_constructor &&that) = default;);
+
+    MPARK_VARIANT_MOVE_CONSTRUCTOR(
+        Trait::Available,
+        move_constructor(move_constructor &&that) noexcept(
+            lib::all<std::is_nothrow_move_constructible<Ts>::value...>::value)
+            : move_constructor(valueless_t{}) {
+          this->generic_construct(*this, lib::move(that));
+        });
+
+    MPARK_VARIANT_MOVE_CONSTRUCTOR(
+        Trait::Unavailable,
+        move_constructor(move_constructor &&) = delete;);
+
+#undef MPARK_VARIANT_MOVE_CONSTRUCTOR
+
+    template <typename Traits, Trait = Traits::copy_constructible_trait>
+    class copy_constructor;
+
+#define MPARK_VARIANT_COPY_CONSTRUCTOR(copy_constructible_trait, definition) \
+  template <typename... Ts>                                                  \
+  class copy_constructor<traits<Ts...>, copy_constructible_trait>            \
+      : public move_constructor<traits<Ts...>> {                             \
+    using super = move_constructor<traits<Ts...>>;                           \
+                                                                             \
+    public:                                                                  \
+    MPARK_INHERITING_CTOR(copy_constructor, super)                           \
+    using super::operator=;                                                  \
+                                                                             \
+    definition                                                               \
+    copy_constructor(copy_constructor &&) = default;                         \
+    ~copy_constructor() = default;                                           \
+    copy_constructor &operator=(const copy_constructor &) = default;         \
+    copy_constructor &operator=(copy_constructor &&) = default;              \
+  }
+
+    MPARK_VARIANT_COPY_CONSTRUCTOR(
+        Trait::TriviallyAvailable,
+        copy_constructor(const copy_constructor &that) = default;);
+
+    MPARK_VARIANT_COPY_CONSTRUCTOR(
+        Trait::Available,
+        copy_constructor(const copy_constructor &that)
+            : copy_constructor(valueless_t{}) {
+          this->generic_construct(*this, that);
+        });
+
+    MPARK_VARIANT_COPY_CONSTRUCTOR(
+        Trait::Unavailable,
+        copy_constructor(const copy_constructor &) = delete;);
+
+#undef MPARK_VARIANT_COPY_CONSTRUCTOR
+
+    template <typename Traits>
+    class assignment : public copy_constructor<Traits> {
+      using super = copy_constructor<Traits>;
+
+      public:
+      MPARK_INHERITING_CTOR(assignment, super)
+      using super::operator=;
+
+      template <std::size_t I, typename... Args>
+      inline /* auto & */ auto emplace(Args &&... args)
+          -> decltype(this->construct_alt(access::base::get_alt<I>(*this),
+                                          lib::forward<Args>(args)...)) {
+        this->destroy();
+        auto &result = this->construct_alt(access::base::get_alt<I>(*this),
+                                           lib::forward<Args>(args)...);
+        this->index_ = I;
+        return result;
+      }
+
+      protected:
+#ifndef MPARK_GENERIC_LAMBDAS
+      template <typename That>
+      struct assigner {
+        template <typename ThisAlt, typename ThatAlt>
+        inline void operator()(ThisAlt &this_alt, ThatAlt &&that_alt) const {
+          self->assign_alt(this_alt, lib::forward<ThatAlt>(that_alt).value);
+        }
+        assignment *self;
+      };
+#endif
+
+      template <std::size_t I, typename T, typename Arg>
+      inline void assign_alt(alt<I, T> &a, Arg &&arg) {
+        if (this->index() == I) {
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4244)
+#endif
+          a.value = lib::forward<Arg>(arg);
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+        } else {
+          struct {
+            void operator()(std::true_type) const {
+              this_->emplace<I>(lib::forward<Arg>(arg_));
+            }
+            void operator()(std::false_type) const {
+              this_->emplace<I>(T(lib::forward<Arg>(arg_)));
+            }
+            assignment *this_;
+            Arg &&arg_;
+          } impl{this, lib::forward<Arg>(arg)};
+          impl(lib::bool_constant<
+                   std::is_nothrow_constructible<T, Arg>::value ||
+                   !std::is_nothrow_move_constructible<T>::value>{});
+        }
+      }
+
+      template <typename That>
+      inline void generic_assign(That &&that) {
+        if (this->valueless_by_exception() && that.valueless_by_exception()) {
+          // do nothing.
+        } else if (that.valueless_by_exception()) {
+          this->destroy();
+        } else {
+          visitation::alt::visit_alt_at(
+              that.index(),
+#ifdef MPARK_GENERIC_LAMBDAS
+              [this](auto &this_alt, auto &&that_alt) {
+                this->assign_alt(
+                    this_alt, lib::forward<decltype(that_alt)>(that_alt).value);
+              }
+#else
+              assigner<That>{this}
+#endif
+              ,
+              *this,
+              lib::forward<That>(that));
+        }
+      }
+    };
+
+    template <typename Traits, Trait = Traits::move_assignable_trait>
+    class move_assignment;
+
+#define MPARK_VARIANT_MOVE_ASSIGNMENT(move_assignable_trait, definition) \
+  template <typename... Ts>                                              \
+  class move_assignment<traits<Ts...>, move_assignable_trait>            \
+      : public assignment<traits<Ts...>> {                               \
+    using super = assignment<traits<Ts...>>;                             \
+                                                                         \
+    public:                                                              \
+    MPARK_INHERITING_CTOR(move_assignment, super)                        \
+    using super::operator=;                                              \
+                                                                         \
+    move_assignment(const move_assignment &) = default;                  \
+    move_assignment(move_assignment &&) = default;                       \
+    ~move_assignment() = default;                                        \
+    move_assignment &operator=(const move_assignment &) = default;       \
+    definition                                                           \
+  }
+
+    MPARK_VARIANT_MOVE_ASSIGNMENT(
+        Trait::TriviallyAvailable,
+        move_assignment &operator=(move_assignment &&that) = default;);
+
+    MPARK_VARIANT_MOVE_ASSIGNMENT(
+        Trait::Available,
+        move_assignment &
+        operator=(move_assignment &&that) noexcept(
+            lib::all<(std::is_nothrow_move_constructible<Ts>::value &&
+                      std::is_nothrow_move_assignable<Ts>::value)...>::value) {
+          this->generic_assign(lib::move(that));
+          return *this;
+        });
+
+    MPARK_VARIANT_MOVE_ASSIGNMENT(
+        Trait::Unavailable,
+        move_assignment &operator=(move_assignment &&) = delete;);
+
+#undef MPARK_VARIANT_MOVE_ASSIGNMENT
+
+    template <typename Traits, Trait = Traits::copy_assignable_trait>
+    class copy_assignment;
+
+#define MPARK_VARIANT_COPY_ASSIGNMENT(copy_assignable_trait, definition) \
+  template <typename... Ts>                                              \
+  class copy_assignment<traits<Ts...>, copy_assignable_trait>            \
+      : public move_assignment<traits<Ts...>> {                          \
+    using super = move_assignment<traits<Ts...>>;                        \
+                                                                         \
+    public:                                                              \
+    MPARK_INHERITING_CTOR(copy_assignment, super)                        \
+    using super::operator=;                                              \
+                                                                         \
+    copy_assignment(const copy_assignment &) = default;                  \
+    copy_assignment(copy_assignment &&) = default;                       \
+    ~copy_assignment() = default;                                        \
+    definition                                                           \
+    copy_assignment &operator=(copy_assignment &&) = default;            \
+  }
+
+    MPARK_VARIANT_COPY_ASSIGNMENT(
+        Trait::TriviallyAvailable,
+        copy_assignment &operator=(const copy_assignment &that) = default;);
+
+    MPARK_VARIANT_COPY_ASSIGNMENT(
+        Trait::Available,
+        copy_assignment &operator=(const copy_assignment &that) {
+          this->generic_assign(that);
+          return *this;
+        });
+
+    MPARK_VARIANT_COPY_ASSIGNMENT(
+        Trait::Unavailable,
+        copy_assignment &operator=(const copy_assignment &) = delete;);
+
+#undef MPARK_VARIANT_COPY_ASSIGNMENT
+
+    template <typename... Ts>
+    class impl : public copy_assignment<traits<Ts...>> {
+      using super = copy_assignment<traits<Ts...>>;
+
+      public:
+      MPARK_INHERITING_CTOR(impl, super)
+      using super::operator=;
+
+      impl(const impl&) = default;
+      impl(impl&&) = default;
+      ~impl() = default;
+      impl &operator=(const impl &) = default;
+      impl &operator=(impl &&) = default;
+
+      template <std::size_t I, typename Arg>
+      inline void assign(Arg &&arg) {
+        this->assign_alt(access::base::get_alt<I>(*this),
+                         lib::forward<Arg>(arg));
+      }
+
+      inline void swap(impl &that) {
+        if (this->valueless_by_exception() && that.valueless_by_exception()) {
+          // do nothing.
+        } else if (this->index() == that.index()) {
+          visitation::alt::visit_alt_at(this->index(),
+#ifdef MPARK_GENERIC_LAMBDAS
+                                        [](auto &this_alt, auto &that_alt) {
+                                          using std::swap;
+                                          swap(this_alt.value,
+                                               that_alt.value);
+                                        }
+#else
+                                        swapper{}
+#endif
+                                        ,
+                                        *this,
+                                        that);
+        } else {
+          impl *lhs = this;
+          impl *rhs = lib::addressof(that);
+          if (lhs->move_nothrow() && !rhs->move_nothrow()) {
+            std::swap(lhs, rhs);
+          }
+          impl tmp(lib::move(*rhs));
+#ifdef MPARK_EXCEPTIONS
+          // EXTENSION: When the move construction of `lhs` into `rhs` throws
+          // and `tmp` is nothrow move constructible then we move `tmp` back
+          // into `rhs` and provide the strong exception safety guarantee.
+          try {
+            this->generic_construct(*rhs, lib::move(*lhs));
+          } catch (...) {
+            if (tmp.move_nothrow()) {
+              this->generic_construct(*rhs, lib::move(tmp));
+            }
+            throw;
+          }
+#else
+          this->generic_construct(*rhs, lib::move(*lhs));
+#endif
+          this->generic_construct(*lhs, lib::move(tmp));
+        }
+      }
+
+      private:
+#ifndef MPARK_GENERIC_LAMBDAS
+      struct swapper {
+        template <typename ThisAlt, typename ThatAlt>
+        inline void operator()(ThisAlt &this_alt, ThatAlt &that_alt) const {
+          using std::swap;
+          swap(this_alt.value, that_alt.value);
+        }
+      };
+#endif
+
+      inline constexpr bool move_nothrow() const {
+        return this->valueless_by_exception() ||
+               lib::array<bool, sizeof...(Ts)>{
+                   {std::is_nothrow_move_constructible<Ts>::value...}
+               }[this->index()];
+      }
+    };
+
+#undef MPARK_INHERITING_CTOR
+
+    template <std::size_t I, typename T>
+    struct overload_leaf {
+      using F = lib::size_constant<I> (*)(T);
+      operator F() const { return nullptr; }
+    };
+
+    template <typename... Ts>
+    struct overload_impl {
+      private:
+      template <typename>
+      struct impl;
+
+      template <std::size_t... Is>
+      struct impl<lib::index_sequence<Is...>> : overload_leaf<Is, Ts>... {};
+
+      public:
+      using type = impl<lib::index_sequence_for<Ts...>>;
+    };
+
+    template <typename... Ts>
+    using overload = typename overload_impl<Ts...>::type;
+
+    template <typename T, typename... Ts>
+    using best_match = lib::invoke_result_t<overload<Ts...>, T &&>;
+
+    template <typename T>
+    struct is_in_place_index : std::false_type {};
+
+    template <std::size_t I>
+    struct is_in_place_index<in_place_index_t<I>> : std::true_type {};
+
+    template <typename T>
+    struct is_in_place_type : std::false_type {};
+
+    template <typename T>
+    struct is_in_place_type<in_place_type_t<T>> : std::true_type {};
+
+  }  // detail
+
+  template <typename... Ts>
+  class variant {
+    static_assert(0 < sizeof...(Ts),
+                  "variant must consist of at least one alternative.");
+
+    static_assert(lib::all<!std::is_array<Ts>::value...>::value,
+                  "variant can not have an array type as an alternative.");
+
+    static_assert(lib::all<!std::is_reference<Ts>::value...>::value,
+                  "variant can not have a reference type as an alternative.");
+
+    static_assert(lib::all<!std::is_void<Ts>::value...>::value,
+                  "variant can not have a void type as an alternative.");
+
+    public:
+    template <
+        typename Front = lib::type_pack_element_t<0, Ts...>,
+        lib::enable_if_t<std::is_default_constructible<Front>::value, int> = 0>
+    inline constexpr variant() noexcept(
+        std::is_nothrow_default_constructible<Front>::value)
+        : impl_(in_place_index_t<0>{}) {}
+
+    variant(const variant &) = default;
+    variant(variant &&) = default;
+
+    template <
+        typename Arg,
+        typename Decayed = lib::decay_t<Arg>,
+        lib::enable_if_t<!std::is_same<Decayed, variant>::value, int> = 0,
+        lib::enable_if_t<!detail::is_in_place_index<Decayed>::value, int> = 0,
+        lib::enable_if_t<!detail::is_in_place_type<Decayed>::value, int> = 0,
+        std::size_t I = detail::best_match<Arg, Ts...>::value,
+        typename T = lib::type_pack_element_t<I, Ts...>,
+        lib::enable_if_t<std::is_constructible<T, Arg>::value, int> = 0>
+    inline constexpr variant(Arg &&arg) noexcept(
+        std::is_nothrow_constructible<T, Arg>::value)
+        : impl_(in_place_index_t<I>{}, lib::forward<Arg>(arg)) {}
+
+    template <
+        std::size_t I,
+        typename... Args,
+        typename T = lib::type_pack_element_t<I, Ts...>,
+        lib::enable_if_t<std::is_constructible<T, Args...>::value, int> = 0>
+    inline explicit constexpr variant(
+        in_place_index_t<I>,
+        Args &&... args) noexcept(std::is_nothrow_constructible<T,
+                                                                Args...>::value)
+        : impl_(in_place_index_t<I>{}, lib::forward<Args>(args)...) {}
+
+    template <
+        std::size_t I,
+        typename Up,
+        typename... Args,
+        typename T = lib::type_pack_element_t<I, Ts...>,
+        lib::enable_if_t<std::is_constructible<T,
+                                               std::initializer_list<Up> &,
+                                               Args...>::value,
+                         int> = 0>
+    inline explicit constexpr variant(
+        in_place_index_t<I>,
+        std::initializer_list<Up> il,
+        Args &&... args) noexcept(std::
+                                      is_nothrow_constructible<
+                                          T,
+                                          std::initializer_list<Up> &,
+                                          Args...>::value)
+        : impl_(in_place_index_t<I>{}, il, lib::forward<Args>(args)...) {}
+
+    template <
+        typename T,
+        typename... Args,
+        std::size_t I = detail::find_index_sfinae<T, Ts...>::value,
+        lib::enable_if_t<std::is_constructible<T, Args...>::value, int> = 0>
+    inline explicit constexpr variant(
+        in_place_type_t<T>,
+        Args &&... args) noexcept(std::is_nothrow_constructible<T,
+                                                                Args...>::value)
+        : impl_(in_place_index_t<I>{}, lib::forward<Args>(args)...) {}
+
+    template <
+        typename T,
+        typename Up,
+        typename... Args,
+        std::size_t I = detail::find_index_sfinae<T, Ts...>::value,
+        lib::enable_if_t<std::is_constructible<T,
+                                               std::initializer_list<Up> &,
+                                               Args...>::value,
+                         int> = 0>
+    inline explicit constexpr variant(
+        in_place_type_t<T>,
+        std::initializer_list<Up> il,
+        Args &&... args) noexcept(std::
+                                      is_nothrow_constructible<
+                                          T,
+                                          std::initializer_list<Up> &,
+                                          Args...>::value)
+        : impl_(in_place_index_t<I>{}, il, lib::forward<Args>(args)...) {}
+
+    ~variant() = default;
+
+    variant &operator=(const variant &) = default;
+    variant &operator=(variant &&) = default;
+
+    template <typename Arg,
+              lib::enable_if_t<!std::is_same<lib::decay_t<Arg>, variant>::value,
+                               int> = 0,
+              std::size_t I = detail::best_match<Arg, Ts...>::value,
+              typename T = lib::type_pack_element_t<I, Ts...>,
+              lib::enable_if_t<(std::is_assignable<T &, Arg>::value &&
+                                std::is_constructible<T, Arg>::value),
+                               int> = 0>
+    inline variant &operator=(Arg &&arg) noexcept(
+        (std::is_nothrow_assignable<T &, Arg>::value &&
+         std::is_nothrow_constructible<T, Arg>::value)) {
+      impl_.template assign<I>(lib::forward<Arg>(arg));
+      return *this;
+    }
+
+    template <
+        std::size_t I,
+        typename... Args,
+        typename T = lib::type_pack_element_t<I, Ts...>,
+        lib::enable_if_t<std::is_constructible<T, Args...>::value, int> = 0>
+    inline T &emplace(Args &&... args) {
+      return impl_.template emplace<I>(lib::forward<Args>(args)...);
+    }
+
+    template <
+        std::size_t I,
+        typename Up,
+        typename... Args,
+        typename T = lib::type_pack_element_t<I, Ts...>,
+        lib::enable_if_t<std::is_constructible<T,
+                                               std::initializer_list<Up> &,
+                                               Args...>::value,
+                         int> = 0>
+    inline T &emplace(std::initializer_list<Up> il, Args &&... args) {
+      return impl_.template emplace<I>(il, lib::forward<Args>(args)...);
+    }
+
+    template <
+        typename T,
+        typename... Args,
+        std::size_t I = detail::find_index_sfinae<T, Ts...>::value,
+        lib::enable_if_t<std::is_constructible<T, Args...>::value, int> = 0>
+    inline T &emplace(Args &&... args) {
+      return impl_.template emplace<I>(lib::forward<Args>(args)...);
+    }
+
+    template <
+        typename T,
+        typename Up,
+        typename... Args,
+        std::size_t I = detail::find_index_sfinae<T, Ts...>::value,
+        lib::enable_if_t<std::is_constructible<T,
+                                               std::initializer_list<Up> &,
+                                               Args...>::value,
+                         int> = 0>
+    inline T &emplace(std::initializer_list<Up> il, Args &&... args) {
+      return impl_.template emplace<I>(il, lib::forward<Args>(args)...);
+    }
+
+    inline constexpr bool valueless_by_exception() const noexcept {
+      return impl_.valueless_by_exception();
+    }
+
+    inline constexpr std::size_t index() const noexcept {
+      return impl_.index();
+    }
+
+    template <bool Dummy = true,
+              lib::enable_if_t<
+                  lib::all<Dummy,
+                           (lib::dependent_type<std::is_move_constructible<Ts>,
+                                                Dummy>::value &&
+                            lib::dependent_type<lib::is_swappable<Ts>,
+                                                Dummy>::value)...>::value,
+                  int> = 0>
+    inline void swap(variant &that) noexcept(
+        lib::all<(std::is_nothrow_move_constructible<Ts>::value &&
+                  lib::is_nothrow_swappable<Ts>::value)...>::value) {
+      impl_.swap(that.impl_);
+    }
+
+    private:
+    detail::impl<Ts...> impl_;
+
+    friend struct detail::access::variant;
+    friend struct detail::visitation::variant;
+  };
+
+  template <std::size_t I, typename... Ts>
+  inline constexpr bool holds_alternative(const variant<Ts...> &v) noexcept {
+    return v.index() == I;
+  }
+
+  template <typename T, typename... Ts>
+  inline constexpr bool holds_alternative(const variant<Ts...> &v) noexcept {
+    return holds_alternative<detail::find_index_checked<T, Ts...>::value>(v);
+  }
+
+  namespace detail {
+    template <std::size_t I, typename V>
+    struct generic_get_impl {
+      constexpr generic_get_impl(int) noexcept {}
+
+      constexpr AUTO_REFREF operator()(V &&v) const
+        AUTO_REFREF_RETURN(
+            access::variant::get_alt<I>(lib::forward<V>(v)).value)
+    };
+
+    template <std::size_t I, typename V>
+    inline constexpr AUTO_REFREF generic_get(V &&v)
+      AUTO_REFREF_RETURN(generic_get_impl<I, V>(
+          holds_alternative<I>(v) ? 0 : (throw_bad_variant_access(), 0))(
+          lib::forward<V>(v)))
+  }  // namespace detail
+
+  template <std::size_t I, typename... Ts>
+  inline constexpr variant_alternative_t<I, variant<Ts...>> &get(
+      variant<Ts...> &v) {
+    return detail::generic_get<I>(v);
+  }
+
+  template <std::size_t I, typename... Ts>
+  inline constexpr variant_alternative_t<I, variant<Ts...>> &&get(
+      variant<Ts...> &&v) {
+    return detail::generic_get<I>(lib::move(v));
+  }
+
+  template <std::size_t I, typename... Ts>
+  inline constexpr const variant_alternative_t<I, variant<Ts...>> &get(
+      const variant<Ts...> &v) {
+    return detail::generic_get<I>(v);
+  }
+
+  template <std::size_t I, typename... Ts>
+  inline constexpr const variant_alternative_t<I, variant<Ts...>> &&get(
+      const variant<Ts...> &&v) {
+    return detail::generic_get<I>(lib::move(v));
+  }
+
+  template <typename T, typename... Ts>
+  inline constexpr T &get(variant<Ts...> &v) {
+    return get<detail::find_index_checked<T, Ts...>::value>(v);
+  }
+
+  template <typename T, typename... Ts>
+  inline constexpr T &&get(variant<Ts...> &&v) {
+    return get<detail::find_index_checked<T, Ts...>::value>(lib::move(v));
+  }
+
+  template <typename T, typename... Ts>
+  inline constexpr const T &get(const variant<Ts...> &v) {
+    return get<detail::find_index_checked<T, Ts...>::value>(v);
+  }
+
+  template <typename T, typename... Ts>
+  inline constexpr const T &&get(const variant<Ts...> &&v) {
+    return get<detail::find_index_checked<T, Ts...>::value>(lib::move(v));
+  }
+
+  namespace detail {
+
+    template <std::size_t I, typename V>
+    inline constexpr /* auto * */ AUTO generic_get_if(V *v) noexcept
+      AUTO_RETURN(v && holds_alternative<I>(*v)
+                      ? lib::addressof(access::variant::get_alt<I>(*v).value)
+                      : nullptr)
+
+  }  // namespace detail
+
+  template <std::size_t I, typename... Ts>
+  inline constexpr lib::add_pointer_t<variant_alternative_t<I, variant<Ts...>>>
+  get_if(variant<Ts...> *v) noexcept {
+    return detail::generic_get_if<I>(v);
+  }
+
+  template <std::size_t I, typename... Ts>
+  inline constexpr lib::add_pointer_t<
+      const variant_alternative_t<I, variant<Ts...>>>
+  get_if(const variant<Ts...> *v) noexcept {
+    return detail::generic_get_if<I>(v);
+  }
+
+  template <typename T, typename... Ts>
+  inline constexpr lib::add_pointer_t<T>
+  get_if(variant<Ts...> *v) noexcept {
+    return get_if<detail::find_index_checked<T, Ts...>::value>(v);
+  }
+
+  template <typename T, typename... Ts>
+  inline constexpr lib::add_pointer_t<const T>
+  get_if(const variant<Ts...> *v) noexcept {
+    return get_if<detail::find_index_checked<T, Ts...>::value>(v);
+  }
+
+  namespace detail {
+    template <typename RelOp>
+    struct convert_to_bool {
+      template <typename Lhs, typename Rhs>
+      inline constexpr bool operator()(Lhs &&lhs, Rhs &&rhs) const {
+        static_assert(std::is_convertible<lib::invoke_result_t<RelOp, Lhs, Rhs>,
+                                          bool>::value,
+                      "relational operators must return a type"
+                      " implicitly convertible to bool");
+        return lib::invoke(
+            RelOp{}, lib::forward<Lhs>(lhs), lib::forward<Rhs>(rhs));
+      }
+    };
+  }  // namespace detail
+
+  template <typename... Ts>
+  inline constexpr bool operator==(const variant<Ts...> &lhs,
+                                   const variant<Ts...> &rhs) {
+    using detail::visitation::variant;
+    using equal_to = detail::convert_to_bool<lib::equal_to>;
+#ifdef MPARK_CPP14_CONSTEXPR
+    if (lhs.index() != rhs.index()) return false;
+    if (lhs.valueless_by_exception()) return true;
+    return variant::visit_value_at(lhs.index(), equal_to{}, lhs, rhs);
+#else
+    return lhs.index() == rhs.index() &&
+           (lhs.valueless_by_exception() ||
+            variant::visit_value_at(lhs.index(), equal_to{}, lhs, rhs));
+#endif
+  }
+
+  template <typename... Ts>
+  inline constexpr bool operator!=(const variant<Ts...> &lhs,
+                                   const variant<Ts...> &rhs) {
+    using detail::visitation::variant;
+    using not_equal_to = detail::convert_to_bool<lib::not_equal_to>;
+#ifdef MPARK_CPP14_CONSTEXPR
+    if (lhs.index() != rhs.index()) return true;
+    if (lhs.valueless_by_exception()) return false;
+    return variant::visit_value_at(lhs.index(), not_equal_to{}, lhs, rhs);
+#else
+    return lhs.index() != rhs.index() ||
+           (!lhs.valueless_by_exception() &&
+            variant::visit_value_at(lhs.index(), not_equal_to{}, lhs, rhs));
+#endif
+  }
+
+  template <typename... Ts>
+  inline constexpr bool operator<(const variant<Ts...> &lhs,
+                                  const variant<Ts...> &rhs) {
+    using detail::visitation::variant;
+    using less = detail::convert_to_bool<lib::less>;
+#ifdef MPARK_CPP14_CONSTEXPR
+    if (rhs.valueless_by_exception()) return false;
+    if (lhs.valueless_by_exception()) return true;
+    if (lhs.index() < rhs.index()) return true;
+    if (lhs.index() > rhs.index()) return false;
+    return variant::visit_value_at(lhs.index(), less{}, lhs, rhs);
+#else
+    return !rhs.valueless_by_exception() &&
+           (lhs.valueless_by_exception() || lhs.index() < rhs.index() ||
+            (lhs.index() == rhs.index() &&
+             variant::visit_value_at(lhs.index(), less{}, lhs, rhs)));
+#endif
+  }
+
+  template <typename... Ts>
+  inline constexpr bool operator>(const variant<Ts...> &lhs,
+                                  const variant<Ts...> &rhs) {
+    using detail::visitation::variant;
+    using greater = detail::convert_to_bool<lib::greater>;
+#ifdef MPARK_CPP14_CONSTEXPR
+    if (lhs.valueless_by_exception()) return false;
+    if (rhs.valueless_by_exception()) return true;
+    if (lhs.index() > rhs.index()) return true;
+    if (lhs.index() < rhs.index()) return false;
+    return variant::visit_value_at(lhs.index(), greater{}, lhs, rhs);
+#else
+    return !lhs.valueless_by_exception() &&
+           (rhs.valueless_by_exception() || lhs.index() > rhs.index() ||
+            (lhs.index() == rhs.index() &&
+             variant::visit_value_at(lhs.index(), greater{}, lhs, rhs)));
+#endif
+  }
+
+  template <typename... Ts>
+  inline constexpr bool operator<=(const variant<Ts...> &lhs,
+                                   const variant<Ts...> &rhs) {
+    using detail::visitation::variant;
+    using less_equal = detail::convert_to_bool<lib::less_equal>;
+#ifdef MPARK_CPP14_CONSTEXPR
+    if (lhs.valueless_by_exception()) return true;
+    if (rhs.valueless_by_exception()) return false;
+    if (lhs.index() < rhs.index()) return true;
+    if (lhs.index() > rhs.index()) return false;
+    return variant::visit_value_at(lhs.index(), less_equal{}, lhs, rhs);
+#else
+    return lhs.valueless_by_exception() ||
+           (!rhs.valueless_by_exception() &&
+            (lhs.index() < rhs.index() ||
+             (lhs.index() == rhs.index() &&
+              variant::visit_value_at(lhs.index(), less_equal{}, lhs, rhs))));
+#endif
+  }
+
+  template <typename... Ts>
+  inline constexpr bool operator>=(const variant<Ts...> &lhs,
+                                   const variant<Ts...> &rhs) {
+    using detail::visitation::variant;
+    using greater_equal = detail::convert_to_bool<lib::greater_equal>;
+#ifdef MPARK_CPP14_CONSTEXPR
+    if (rhs.valueless_by_exception()) return true;
+    if (lhs.valueless_by_exception()) return false;
+    if (lhs.index() > rhs.index()) return true;
+    if (lhs.index() < rhs.index()) return false;
+    return variant::visit_value_at(lhs.index(), greater_equal{}, lhs, rhs);
+#else
+    return rhs.valueless_by_exception() ||
+           (!lhs.valueless_by_exception() &&
+            (lhs.index() > rhs.index() ||
+             (lhs.index() == rhs.index() &&
+              variant::visit_value_at(
+                  lhs.index(), greater_equal{}, lhs, rhs))));
+#endif
+  }
+
+  struct monostate {};
+
+  inline constexpr bool operator<(monostate, monostate) noexcept {
+    return false;
+  }
+
+  inline constexpr bool operator>(monostate, monostate) noexcept {
+    return false;
+  }
+
+  inline constexpr bool operator<=(monostate, monostate) noexcept {
+    return true;
+  }
+
+  inline constexpr bool operator>=(monostate, monostate) noexcept {
+    return true;
+  }
+
+  inline constexpr bool operator==(monostate, monostate) noexcept {
+    return true;
+  }
+
+  inline constexpr bool operator!=(monostate, monostate) noexcept {
+    return false;
+  }
+
+#ifdef MPARK_CPP14_CONSTEXPR
+  namespace detail {
+
+    inline constexpr bool all(std::initializer_list<bool> bs) {
+      for (bool b : bs) {
+        if (!b) {
+          return false;
+        }
+      }
+      return true;
+    }
+
+  }  // namespace detail
+
+  template <typename Visitor, typename... Vs>
+  inline constexpr decltype(auto) visit(Visitor &&visitor, Vs &&... vs) {
+    return (detail::all({!vs.valueless_by_exception()...})
+                ? (void)0
+                : throw_bad_variant_access()),
+           detail::visitation::variant::visit_value(
+               lib::forward<Visitor>(visitor), lib::forward<Vs>(vs)...);
+  }
+#else
+  namespace detail {
+
+    template <std::size_t N>
+    inline constexpr bool all_impl(const lib::array<bool, N> &bs,
+                                   std::size_t idx) {
+      return idx >= N || (bs[idx] && all_impl(bs, idx + 1));
+    }
+
+    template <std::size_t N>
+    inline constexpr bool all(const lib::array<bool, N> &bs) {
+      return all_impl(bs, 0);
+    }
+
+  }  // namespace detail
+
+  template <typename Visitor, typename... Vs>
+  inline constexpr DECLTYPE_AUTO visit(Visitor &&visitor, Vs &&... vs)
+    DECLTYPE_AUTO_RETURN(
+        (detail::all(
+             lib::array<bool, sizeof...(Vs)>{{!vs.valueless_by_exception()...}})
+             ? (void)0
+             : throw_bad_variant_access()),
+        detail::visitation::variant::visit_value(lib::forward<Visitor>(visitor),
+                                                 lib::forward<Vs>(vs)...))
+#endif
+
+  template <typename... Ts>
+  inline auto swap(variant<Ts...> &lhs,
+                   variant<Ts...> &rhs) noexcept(noexcept(lhs.swap(rhs)))
+      -> decltype(lhs.swap(rhs)) {
+    lhs.swap(rhs);
+  }
+
+  namespace detail {
+
+    template <typename T, typename...>
+    using enabled_type = T;
+
+    namespace hash {
+
+      template <typename H, typename K>
+      constexpr bool meets_requirements() noexcept {
+        return std::is_copy_constructible<H>::value &&
+               std::is_move_constructible<H>::value &&
+               lib::is_invocable_r<std::size_t, H, const K &>::value;
+      }
+
+      template <typename K>
+      constexpr bool is_enabled() noexcept {
+        using H = std::hash<K>;
+        return meets_requirements<H, K>() &&
+               std::is_default_constructible<H>::value &&
+               std::is_copy_assignable<H>::value &&
+               std::is_move_assignable<H>::value;
+      }
+
+    }  // namespace hash
+
+  }  // namespace detail
+
+#undef AUTO
+#undef AUTO_RETURN
+
+#undef AUTO_REFREF
+#undef AUTO_REFREF_RETURN
+
+#undef DECLTYPE_AUTO
+#undef DECLTYPE_AUTO_RETURN
+
+}  // namespace mpark
+
+namespace std {
+
+  template <typename... Ts>
+  struct hash<mpark::detail::enabled_type<
+      mpark::variant<Ts...>,
+      mpark::lib::enable_if_t<mpark::lib::all<mpark::detail::hash::is_enabled<
+          mpark::lib::remove_const_t<Ts>>()...>::value>>> {
+    using argument_type = mpark::variant<Ts...>;
+    using result_type = std::size_t;
+
+    inline result_type operator()(const argument_type &v) const {
+      using mpark::detail::visitation::variant;
+      std::size_t result =
+          v.valueless_by_exception()
+              ? 299792458  // Random value chosen by the universe upon creation
+              : variant::visit_alt(
+#ifdef MPARK_GENERIC_LAMBDAS
+                    [](const auto &alt) {
+                      using alt_type = mpark::lib::decay_t<decltype(alt)>;
+                      using value_type = mpark::lib::remove_const_t<
+                          typename alt_type::value_type>;
+                      return hash<value_type>{}(alt.value);
+                    }
+#else
+                    hasher{}
+#endif
+                    ,
+                    v);
+      return hash_combine(result, hash<std::size_t>{}(v.index()));
+    }
+
+    private:
+#ifndef MPARK_GENERIC_LAMBDAS
+    struct hasher {
+      template <typename Alt>
+      inline std::size_t operator()(const Alt &alt) const {
+        using alt_type = mpark::lib::decay_t<Alt>;
+        using value_type =
+            mpark::lib::remove_const_t<typename alt_type::value_type>;
+        return hash<value_type>{}(alt.value);
+      }
+    };
+#endif
+
+    static std::size_t hash_combine(std::size_t lhs, std::size_t rhs) {
+      return lhs ^= rhs + 0x9e3779b9 + (lhs << 6) + (lhs >> 2);
+    }
+  };
+
+  template <>
+  struct hash<mpark::monostate> {
+    using argument_type = mpark::monostate;
+    using result_type = std::size_t;
+
+    inline result_type operator()(const argument_type &) const noexcept {
+      return 66740831;  // return a fundamentally attractive random value.
+    }
+  };
+
+}  // namespace std
+
+#endif  // MPARK_VARIANT_HPP

+ 1831 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm.h

@@ -0,0 +1,1831 @@
+/*
+    FIXME: License, since this header may be distributed independently from
+    other headers.
+*/
+
+#ifndef REALM_H
+#define REALM_H
+
+#include <stddef.h>
+#include <stdint.h>
+#include <stdbool.h>
+
+#if defined(_WIN32) || defined(__CYGWIN__)
+
+#if defined(Realm_EXPORTS)
+// Exporting Win32 symbols
+#define RLM_EXPORT __declspec(dllexport)
+#else
+// Importing Win32 symbols. Note: Clients linking statically should define
+// RLM_NO_DLLIMPORT.
+#if !defined(RLM_NO_DLLIMPORT)
+#define RLM_EXPORT __declspec(dllimport)
+#else
+#define RLM_EXPORT
+#endif // RLM_NO_DLLIMPORT
+#endif // Realm_EXPORTS
+
+#else
+// Not Win32
+#define RLM_EXPORT __attribute__((visibility("default")))
+#endif
+
+#ifdef __cplusplus
+#define RLM_API extern "C" RLM_EXPORT
+#else
+#define RLM_API RLM_EXPORT
+#endif // __cplusplus
+
+
+typedef struct shared_realm realm_t;
+typedef struct realm_schema realm_schema_t;
+typedef struct realm_scheduler realm_scheduler_t;
+typedef struct realm_thread_safe_reference realm_thread_safe_reference_t;
+typedef void (*realm_free_userdata_func_t)(void*);
+typedef void* (*realm_clone_userdata_func_t)(const void*);
+
+/* Accessor types */
+typedef struct realm_object realm_object_t;
+typedef struct realm_list realm_list_t;
+typedef struct realm_set realm_set_t;
+typedef struct realm_dictionary realm_dictionary_t;
+
+/* Query types */
+typedef struct realm_query realm_query_t;
+typedef struct realm_results realm_results_t;
+
+/* Config types */
+typedef struct realm_config realm_config_t;
+typedef struct realm_sync_config realm_sync_config_t;
+typedef bool (*realm_migration_func_t)(void* userdata, realm_t* old_realm, realm_t* new_realm,
+                                       const realm_schema_t* schema);
+typedef bool (*realm_data_initialization_func_t)(void* userdata, realm_t* realm);
+typedef bool (*realm_should_compact_on_launch_func_t)(void* userdata, uint64_t total_bytes, uint64_t used_bytes);
+typedef enum realm_schema_mode {
+    RLM_SCHEMA_MODE_AUTOMATIC,
+    RLM_SCHEMA_MODE_IMMUTABLE,
+    RLM_SCHEMA_MODE_READ_ONLY_ALTERNATIVE,
+    RLM_SCHEMA_MODE_RESET_FILE,
+    RLM_SCHEMA_MODE_ADDITIVE_DISCOVERED,
+    RLM_SCHEMA_MODE_ADDITIVE_EXPLICIT,
+    RLM_SCHEMA_MODE_MANUAL,
+} realm_schema_mode_e;
+
+/* Key types */
+typedef uint32_t realm_class_key_t;
+typedef int64_t realm_property_key_t;
+typedef int64_t realm_object_key_t;
+typedef uint64_t realm_version_t;
+
+static const realm_class_key_t RLM_INVALID_CLASS_KEY = ((uint32_t)-1) >> 1;
+static const realm_property_key_t RLM_INVALID_PROPERTY_KEY = -1;
+static const realm_object_key_t RLM_INVALID_OBJECT_KEY = -1;
+
+/* Value types */
+
+typedef enum realm_value_type {
+    RLM_TYPE_NULL,
+    RLM_TYPE_INT,
+    RLM_TYPE_BOOL,
+    RLM_TYPE_STRING,
+    RLM_TYPE_BINARY,
+    RLM_TYPE_TIMESTAMP,
+    RLM_TYPE_FLOAT,
+    RLM_TYPE_DOUBLE,
+    RLM_TYPE_DECIMAL128,
+    RLM_TYPE_OBJECT_ID,
+    RLM_TYPE_LINK,
+    RLM_TYPE_UUID,
+} realm_value_type_e;
+
+typedef enum realm_schema_validation_mode {
+    RLM_SCHEMA_VALIDATION_BASIC = 0,
+    RLM_SCHEMA_VALIDATION_SYNC = 1,
+    RLM_SCHEMA_VALIDATION_REJECT_EMBEDDED_ORPHANS = 2
+} realm_schema_validation_mode_e;
+
+typedef struct realm_string {
+    const char* data;
+    size_t size;
+} realm_string_t;
+
+typedef struct realm_binary {
+    const uint8_t* data;
+    size_t size;
+} realm_binary_t;
+
+typedef struct realm_timestamp {
+    int64_t seconds;
+    int32_t nanoseconds;
+} realm_timestamp_t;
+
+typedef struct realm_decimal128 {
+    uint64_t w[2];
+} realm_decimal128_t;
+
+typedef struct realm_link {
+    realm_class_key_t target_table;
+    realm_object_key_t target;
+} realm_link_t;
+
+typedef struct realm_object_id {
+    uint8_t bytes[12];
+} realm_object_id_t;
+
+typedef struct realm_uuid {
+    uint8_t bytes[16];
+} realm_uuid_t;
+
+typedef struct realm_value {
+    union {
+        int64_t integer;
+        bool boolean;
+        realm_string_t string;
+        realm_binary_t binary;
+        realm_timestamp_t timestamp;
+        float fnum;
+        double dnum;
+        realm_decimal128_t decimal128;
+        realm_object_id_t object_id;
+        realm_uuid_t uuid;
+
+        realm_link_t link;
+
+        char data[16];
+    };
+    realm_value_type_e type;
+} realm_value_t;
+
+typedef struct realm_version_id {
+    uint64_t version;
+    uint64_t index;
+} realm_version_id_t;
+
+
+/* Error types */
+typedef struct realm_async_error realm_async_error_t;
+typedef enum realm_errno {
+    RLM_ERR_NONE = 0,
+    RLM_ERR_UNKNOWN,
+    RLM_ERR_OTHER_EXCEPTION,
+    RLM_ERR_OUT_OF_MEMORY,
+    RLM_ERR_NOT_CLONABLE,
+
+    RLM_ERR_NOT_IN_A_TRANSACTION,
+    RLM_ERR_WRONG_THREAD,
+
+    RLM_ERR_INVALIDATED_OBJECT,
+    RLM_ERR_INVALID_PROPERTY,
+    RLM_ERR_MISSING_PROPERTY_VALUE,
+    RLM_ERR_PROPERTY_TYPE_MISMATCH,
+    RLM_ERR_MISSING_PRIMARY_KEY,
+    RLM_ERR_UNEXPECTED_PRIMARY_KEY,
+    RLM_ERR_WRONG_PRIMARY_KEY_TYPE,
+    RLM_ERR_MODIFY_PRIMARY_KEY,
+    RLM_ERR_READ_ONLY_PROPERTY,
+    RLM_ERR_PROPERTY_NOT_NULLABLE,
+    RLM_ERR_INVALID_ARGUMENT,
+
+    RLM_ERR_LOGIC,
+    RLM_ERR_NO_SUCH_TABLE,
+    RLM_ERR_NO_SUCH_OBJECT,
+    RLM_ERR_CROSS_TABLE_LINK_TARGET,
+    RLM_ERR_UNSUPPORTED_FILE_FORMAT_VERSION,
+    RLM_ERR_MULTIPLE_SYNC_AGENTS,
+    RLM_ERR_ADDRESS_SPACE_EXHAUSTED,
+    RLM_ERR_MAXIMUM_FILE_SIZE_EXCEEDED,
+    RLM_ERR_OUT_OF_DISK_SPACE,
+    RLM_ERR_KEY_NOT_FOUND,
+    RLM_ERR_COLUMN_NOT_FOUND,
+    RLM_ERR_COLUMN_ALREADY_EXISTS,
+    RLM_ERR_KEY_ALREADY_USED,
+    RLM_ERR_SERIALIZATION_ERROR,
+    RLM_ERR_INVALID_PATH_ERROR,
+    RLM_ERR_DUPLICATE_PRIMARY_KEY_VALUE,
+
+    RLM_ERR_INDEX_OUT_OF_BOUNDS,
+
+    RLM_ERR_INVALID_QUERY_STRING,
+    RLM_ERR_INVALID_QUERY,
+
+    RLM_ERR_CALLBACK = 1000000, /**< A user-provided callback failed. */
+} realm_errno_e;
+
+typedef enum realm_logic_error_kind {
+    RLM_LOGIC_ERR_NONE = 0,
+    RLM_LOGIC_ERR_STRING_TOO_BIG,
+    // ...
+} realm_logic_error_kind_e;
+
+typedef struct realm_error {
+    realm_errno_e error;
+    const char* message;
+    union {
+        int code;
+        realm_logic_error_kind_e logic_error_kind;
+    } kind;
+} realm_error_t;
+
+/* Schema types */
+
+typedef enum realm_column_attr {
+    // Values matching `realm::ColumnAttr`.
+    RLM_COLUMN_ATTR_NONE = 0,
+    RLM_COLUMN_ATTR_INDEXED = 1,
+    RLM_COLUMN_ATTR_UNIQUE = 2,
+    RLM_COLUMN_ATTR_RESERVED = 4,
+    RLM_COLUMN_ATTR_STRONG_LINKS = 8,
+    RLM_COLUMN_ATTR_NULLABLE = 16,
+    RLM_COLUMN_ATTR_LIST = 32,
+    RLM_COLUMN_ATTR_DICTIONARY = 64,
+    RLM_COLUMN_ATTR_COLLECTION = 64 + 32,
+} realm_column_attr_e;
+
+typedef enum realm_property_type {
+    // Values matching `realm::ColumnType`.
+    RLM_PROPERTY_TYPE_INT = 0,
+    RLM_PROPERTY_TYPE_BOOL = 1,
+    RLM_PROPERTY_TYPE_STRING = 2,
+    RLM_PROPERTY_TYPE_BINARY = 4,
+    RLM_PROPERTY_TYPE_MIXED = 6,
+    RLM_PROPERTY_TYPE_TIMESTAMP = 8,
+    RLM_PROPERTY_TYPE_FLOAT = 9,
+    RLM_PROPERTY_TYPE_DOUBLE = 10,
+    RLM_PROPERTY_TYPE_DECIMAL128 = 11,
+    RLM_PROPERTY_TYPE_OBJECT = 12,
+    RLM_PROPERTY_TYPE_LINKING_OBJECTS = 14,
+    RLM_PROPERTY_TYPE_OBJECT_ID = 15,
+    RLM_PROPERTY_TYPE_UUID = 17,
+} realm_property_type_e;
+
+typedef enum realm_collection_type {
+    RLM_COLLECTION_TYPE_NONE = 0,
+    RLM_COLLECTION_TYPE_LIST = 1,
+    RLM_COLLECTION_TYPE_SET = 2,
+    RLM_COLLECTION_TYPE_DICTIONARY = 4,
+} realm_collection_type_e;
+
+typedef struct realm_property_info {
+    const char* name;
+    const char* public_name;
+    realm_property_type_e type;
+    realm_collection_type_e collection_type;
+
+    const char* link_target;
+    const char* link_origin_property_name;
+    realm_property_key_t key;
+    int flags;
+} realm_property_info_t;
+
+typedef struct realm_class_info {
+    const char* name;
+    const char* primary_key;
+    size_t num_properties;
+    size_t num_computed_properties;
+    realm_class_key_t key;
+    int flags;
+} realm_class_info_t;
+
+typedef enum realm_class_flags {
+    RLM_CLASS_NORMAL = 0,
+    RLM_CLASS_EMBEDDED = 1,
+} realm_class_flags_e;
+
+typedef enum realm_property_flags {
+    RLM_PROPERTY_NORMAL = 0,
+    RLM_PROPERTY_NULLABLE = 1,
+    RLM_PROPERTY_PRIMARY_KEY = 2,
+    RLM_PROPERTY_INDEXED = 4,
+} realm_property_flags_e;
+
+
+/* Notification types */
+typedef struct realm_notification_token realm_notification_token_t;
+typedef struct realm_object_changes realm_object_changes_t;
+typedef struct realm_collection_changes realm_collection_changes_t;
+typedef void (*realm_on_object_change_func_t)(void* userdata, const realm_object_changes_t*);
+typedef void (*realm_on_collection_change_func_t)(void* userdata, const realm_collection_changes_t*);
+typedef void (*realm_callback_error_func_t)(void* userdata, const realm_async_error_t*);
+
+/* Scheduler types */
+typedef void (*realm_scheduler_notify_func_t)(void* userdata);
+typedef bool (*realm_scheduler_is_on_thread_func_t)(void* userdata);
+typedef bool (*realm_scheduler_is_same_as_func_t)(const void* userdata1, const void* userdata2);
+typedef bool (*realm_scheduler_can_deliver_notifications_func_t)(void* userdata);
+typedef void (*realm_scheduler_set_notify_callback_func_t)(void* userdata, void* callback_userdata,
+                                                           realm_free_userdata_func_t, realm_scheduler_notify_func_t);
+typedef realm_scheduler_t* (*realm_scheduler_default_factory_func_t)(void* userdata);
+
+/* Sync types */
+typedef void (*realm_sync_upload_completion_func_t)(void* userdata, realm_async_error_t*);
+typedef void (*realm_sync_download_completion_func_t)(void* userdata, realm_async_error_t*);
+typedef void (*realm_sync_connection_state_changed_func_t)(void* userdata, int, int);
+typedef void (*realm_sync_session_state_changed_func_t)(void* userdata, int, int);
+typedef void (*realm_sync_progress_func_t)(void* userdata, size_t transferred, size_t total);
+
+/**
+ * Get the VersionID of the current transaction.
+ *
+ * @param out_found True if version information is available. This requires an available Read or Write transaction.
+ * @param out_version The version of the current transaction. If `out_found` returns False, this returns (0,0).
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_get_version_id(const realm_t*, bool* out_found, realm_version_id_t* out_version);
+
+/**
+ * Get a string representing the version number of the Realm library.
+ *
+ * @return A null-terminated string.
+ */
+RLM_API const char* realm_get_library_version(void);
+
+/**
+ * Get individual components of the version number of the Realm library.
+ *
+ * @param out_major The major version number (X.0.0).
+ * @param out_minor The minor version number (0.X.0).
+ * @param out_patch The patch version number (0.0.X).
+ * @param out_extra The extra version string (0.0.0-X).
+ */
+RLM_API void realm_get_library_version_numbers(int* out_major, int* out_minor, int* out_patch,
+                                               const char** out_extra);
+
+/**
+ * Get the last error that happened on this thread.
+ *
+ * Errors are thread-local. Getting the error must happen on the same thread as
+ * the call that caused the error to occur. The error is specific to the current
+ * thread, and not the Realm instance for which the error occurred.
+ *
+ * Note: The error message in @a err will only be safe to use until the next API
+ *       call is made on the current thread.
+ *
+ * Note: The error is not cleared by subsequent successful calls to this
+ *       function, but it will be overwritten by subsequent failing calls to
+ *       other library functions.
+ *
+ * Note: Calling this function does not clear the current last error.
+ *
+ * This function does not allocate any memory.
+ *
+ * @param err A pointer to a `realm_error_t` struct that will be populated with
+ *            information about the last error, if there is one. May be NULL.
+ * @return True if an error occurred.
+ */
+RLM_API bool realm_get_last_error(realm_error_t* err);
+
+/**
+ * Get information about an async error, potentially coming from another thread.
+ *
+ * This function does not allocate any memory.
+ *
+ * @param err A pointer to a `realm_error_t` struct that will be populated with
+ *            information about the error. May not be NULL.
+ * @see realm_get_last_error()
+ */
+RLM_API void realm_get_async_error(const realm_async_error_t* err, realm_error_t* out_err);
+
+/**
+ * Convert the last error to `realm_async_error_t`, which can safely be passed
+ * between threads.
+ *
+ * Note: This function does not clear the last error.
+ *
+ * @return A non-null pointer if there was an error on this thread.
+ * @see realm_get_last_error()
+ * @see realm_get_async_error()
+ * @see realm_clear_last_error()
+ */
+RLM_API realm_async_error_t* realm_get_last_error_as_async_error(void);
+
+#if defined(__cplusplus)
+/**
+ * Rethrow the last exception.
+ *
+ * Note: This function does not have C linkage, because throwing across language
+ * boundaries is undefined behavior. When called from C code, this should result
+ * in a linker error. When called from C++, `std::rethrow_exception` will be
+ * called to propagate the exception unchanged.
+ */
+RLM_EXPORT void realm_rethrow_last_error(void);
+
+/**
+ * Invoke a function that may throw an exception, and report that exception as
+ * part of the C API error handling mechanism.
+ *
+ * This is used to test translation of exceptions to error codes.
+ *
+ * @return True if no exception was thrown.
+ */
+RLM_EXPORT bool realm_wrap_exceptions(void (*)()) noexcept;
+#endif // __cplusplus
+
+/**
+ * Clear the last error on the calling thread.
+ *
+ * Use this if the system has recovered from an error, e.g. by closing the
+ * offending Realm and reopening it, freeing up resources, or similar.
+ *
+ * @return True if an error was cleared.
+ */
+RLM_API bool realm_clear_last_error(void);
+
+/**
+ * Free any Realm C Wrapper object.
+ *
+ * Note: Any pointer returned from a library function is owned by the caller.
+ *       The caller is responsible for calling `realm_release()`. The only
+ *       exception from this is C++ bridge functions that return `void*`, with
+ *       the prefix `_realm`.
+ *
+ * Note: C++ destructors are typically `noexcept`, so it is likely that an
+ *       exception will crash the process.
+ *
+ * @param ptr A pointer to a Realm C Wrapper object. May be NULL.
+ */
+RLM_API void realm_release(void* ptr);
+
+/**
+ * Clone a Realm C Wrapper object.
+ *
+ * If the object is not clonable, this function fails with RLM_ERR_NOT_CLONABLE.
+ *
+ * @return A pointer to an object of the same type as the input, or NULL if
+ *         cloning failed.
+ */
+RLM_API void* realm_clone(const void*);
+
+/**
+ * Return true if two API objects refer to the same underlying data. Objects
+ * with different types are never equal.
+ *
+ * Note: This function cannot be used with types that have value semantics, only
+ *       opaque types that have object semantics.
+ *
+ *    - `realm_t` objects are identical if they represent the same instance (not
+ *      just if they represent the same file).
+ *    - `realm_schema_t` objects are equal if the represented schemas are equal.
+ *    - `realm_config_t` objects are equal if the configurations are equal.
+ *    - `realm_object_t` objects are identical if they belong to the same realm
+ *      and class, and have the same object key.
+ *    - `realm_list_t` and other collection objects are identical if they come
+ *      from the same object and property.
+ *    - `realm_query_t` objects are never equal.
+ *    - `realm_scheduler_t` objects are equal if they represent the same
+ *      scheduler.
+ *    - Query descriptor objects are equal if they represent equivalent
+ *      descriptors.
+ *    - `realm_async_error_t` objects are equal if they represent the same
+ *      exception instance.
+ *
+ * This function cannot fail.
+ */
+RLM_API bool realm_equals(const void*, const void*);
+
+/**
+ * True if a Realm C Wrapper object is "frozen" (immutable).
+ *
+ * Objects, collections, and results can be frozen. For all other types, this
+ * function always returns false.
+ */
+RLM_API bool realm_is_frozen(const void*);
+
+/**
+ * Get a thread-safe reference representing the same underlying object as some
+ * API object.
+ *
+ * The thread safe reference can be passed to a different thread and resolved
+ * against a different `realm_t` instance, which succeeds if the underlying
+ * object still exists.
+ *
+ * The following types can produce thread safe references:
+ *
+ * - `realm_object_t`
+ * - `realm_results_t`
+ * - `realm_list_t`
+ * - `realm_t`
+ *
+ * This does not assume ownership of the object, except for `realm_t`, where the
+ * instance is transferred by value, and must be transferred back to the current
+ * thread to be used. Note that the `realm_thread_safe_reference_t` object must
+ * still be destroyed after having been converted into a `realm_t` object.
+ *
+ * @return A non-null pointer if no exception occurred.
+ */
+RLM_API realm_thread_safe_reference_t* realm_create_thread_safe_reference(const void*);
+
+/**
+ * Allocate a new configuration with default options.
+ */
+RLM_API realm_config_t* realm_config_new(void);
+
+/**
+ * Get the path of the realm being opened.
+ *
+ * This function cannot fail.
+ */
+RLM_API const char* realm_config_get_path(const realm_config_t*);
+
+/**
+ * Set the path of the realm being opened.
+ *
+ * This function aborts when out of memory, but otherwise cannot fail.
+ */
+RLM_API void realm_config_set_path(realm_config_t*, const char* path);
+
+/**
+ * Get the encryption key for the realm.
+ *
+ * The output buffer must be at least 64 bytes.
+ *
+ * @returns The length of the encryption key (0 or 64)
+ */
+RLM_API size_t realm_config_get_encryption_key(const realm_config_t*, uint8_t* out_key);
+
+/**
+ * Set the encryption key for the realm.
+ *
+ * The key must be either 64 bytes long or have length zero (in which case
+ * encryption is disabled).
+ *
+ * This function may fail if the encryption key has the wrong length.
+ */
+RLM_API bool realm_config_set_encryption_key(realm_config_t*, const uint8_t* key, size_t key_size);
+
+/**
+ * Get the schema for this realm.
+ *
+ * Note: The caller obtains ownership of the returned value, and must manually
+ *       free it by calling `realm_release()`.
+ *
+ * @return A schema object, or NULL if the schema is not set (empty).
+ */
+RLM_API realm_schema_t* realm_config_get_schema(const realm_config_t*);
+
+/**
+ * Set the schema object for this realm.
+ *
+ * This does not take ownership of the schema object, and it should be released
+ * afterwards.
+ *
+ * This function aborts when out of memory, but otherwise cannot fail.
+ *
+ * @param schema The schema object. May be NULL, which means an empty schema.
+ */
+RLM_API void realm_config_set_schema(realm_config_t*, const realm_schema_t* schema);
+
+/**
+ * Get the schema version of the schema.
+ *
+ * This function cannot fail.
+ */
+RLM_API uint64_t realm_config_get_schema_version(const realm_config_t*);
+
+/**
+ * Set the schema version of the schema.
+ *
+ * This function cannot fail.
+ */
+RLM_API void realm_config_set_schema_version(realm_config_t*, uint64_t version);
+
+/**
+ * Get the schema mode.
+ *
+ * This function cannot fail.
+ */
+RLM_API realm_schema_mode_e realm_config_get_schema_mode(const realm_config_t*);
+
+/**
+ * Set the schema mode.
+ *
+ * This function cannot fail.
+ */
+RLM_API void realm_config_set_schema_mode(realm_config_t*, realm_schema_mode_e);
+
+/**
+ * Set the migration callback.
+ *
+ * The migration function is called during a migration for schema modes
+ * `RLM_SCHEMA_MODE_AUTOMATIC` and `RLM_SCHEMA_MODE_MANUAL`. The callback is
+ * invoked with a realm instance before the migration and the realm instance
+ * that is currently performing the migration.
+ *
+ * This function cannot fail.
+ */
+RLM_API void realm_config_set_migration_function(realm_config_t*, realm_migration_func_t, void* userdata);
+
+/**
+ * Set the data initialization function.
+ *
+ * The callback is invoked the first time the schema is created, such that the
+ * user can perform one-time initialization of the data in the realm.
+ *
+ * The realm instance passed to the callback is in a write transaction.
+ *
+ * This function cannot fail.
+ */
+RLM_API void realm_config_set_data_initialization_function(realm_config_t*, realm_data_initialization_func_t,
+                                                           void* userdata);
+
+/**
+ * Set the should-compact-on-launch callback.
+ *
+ * The callback is invoked the first time a realm file is opened in this process
+ * to decide whether the realm file should be compacted.
+ *
+ * Note: If another process has the realm file open, it will not be compacted.
+ *
+ * This function cannot fail.
+ */
+RLM_API void realm_config_set_should_compact_on_launch_function(realm_config_t*,
+                                                                realm_should_compact_on_launch_func_t,
+                                                                void* userdata);
+
+/**
+ * True if file format upgrades on open are disabled.
+ *
+ * This function cannot fail.
+ */
+RLM_API bool realm_config_get_disable_format_upgrade(const realm_config_t*);
+
+/**
+ * Disable file format upgrade on open (default: false).
+ *
+ * If a migration is needed to open the realm file with the provided schema, an
+ * error is thrown rather than automatically performing the migration.
+ *
+ * This function cannot fail.
+ */
+RLM_API void realm_config_set_disable_format_upgrade(realm_config_t*, bool);
+
+/**
+ * True if automatic change notifications should be generated.
+ *
+ * This function cannot fail.
+ */
+RLM_API bool realm_config_get_automatic_change_notifications(const realm_config_t*);
+
+/**
+ * Automatically generated change notifications (default: true).
+ *
+ * This function cannot fail.
+ */
+RLM_API void realm_config_set_automatic_change_notifications(realm_config_t*, bool);
+
+/**
+ * The scheduler which this realm should be bound to (default: NULL).
+ *
+ * If NULL, the realm will be bound to the default scheduler for the current thread.
+ *
+ * This function aborts when out of memory, but otherwise cannot fail.
+ */
+RLM_API void realm_config_set_scheduler(realm_config_t*, const realm_scheduler_t*);
+
+/**
+ * Sync configuration for this realm (default: NULL).
+ *
+ * This function aborts when out of memory, but otherwise cannot fail.
+ */
+RLM_API void realm_config_set_sync_config(realm_config_t*, realm_sync_config_t*);
+
+/**
+ * Get whether the realm file should be forcibly initialized as a synchronized.
+ *
+ * This function cannot fail.
+ */
+RLM_API bool realm_config_get_force_sync_history(const realm_config_t*);
+
+/**
+ * Force the realm file to be initialized as a synchronized realm, even if no
+ * sync config is provided (default: false).
+ *
+ * This function cannot fail.
+ */
+RLM_API void realm_config_set_force_sync_history(realm_config_t*, bool);
+
+/**
+ * Set the audit interface for the realm (unimplemented).
+ */
+RLM_API bool realm_config_set_audit_factory(realm_config_t*, void*);
+
+/**
+ * Get maximum number of active versions in the realm file allowed before an
+ * exception is thrown.
+ *
+ * This function cannot fail.
+ */
+RLM_API uint64_t realm_config_get_max_number_of_active_versions(const realm_config_t*);
+
+/**
+ * Set maximum number of active versions in the realm file allowed before an
+ * exception is thrown (default: UINT64_MAX).
+ *
+ * This function cannot fail.
+ */
+RLM_API void realm_config_set_max_number_of_active_versions(realm_config_t*, uint64_t);
+
+/**
+ * Create a custom scheduler object from callback functions.
+ *
+ * @param userdata Pointer passed to all callbacks.
+ * @param notify Function to trigger a call to the registered callback on the
+ *               scheduler's event loop. This function must be thread-safe, or
+ *               NULL, in which case the scheduler is considered unable to
+ *               deliver notifications.
+ * @param is_on_thread Function to return true if called from the same thread as
+ *                     the scheduler. This function must be thread-safe.
+ * @param can_deliver_notifications Function to return true if the scheduler can
+ *                                  support `notify()`. This function does not
+ *                                  need to be thread-safe.
+ * @param set_notify_callback Function to accept a callback that will be invoked
+ *                            by `notify()` on the scheduler's event loop. This
+ *                            function does not need to be thread-safe.
+ */
+RLM_API realm_scheduler_t*
+realm_scheduler_new(void* userdata, realm_free_userdata_func_t, realm_scheduler_notify_func_t notify,
+                    realm_scheduler_is_on_thread_func_t is_on_thread, realm_scheduler_is_same_as_func_t is_same_as,
+                    realm_scheduler_can_deliver_notifications_func_t can_deliver_notifications,
+                    realm_scheduler_set_notify_callback_func_t set_notify_callback);
+
+/**
+ * Create an instance of the default scheduler for the current platform,
+ * normally confined to the calling thread.
+ */
+RLM_API realm_scheduler_t* realm_scheduler_make_default(void);
+
+/**
+ * Get the scheduler used by frozen realms. This scheduler does not support
+ * notifications, and does not perform any thread checking.
+ *
+ * This function is thread-safe, and cannot fail.
+ */
+RLM_API const realm_scheduler_t* realm_scheduler_get_frozen(void);
+
+/**
+ * Returns true if there is a default scheduler implementation for the current
+ * platform, or one has been set with `realm_scheduler_set_default_factory()`.
+ *
+ * If there is no default factory, and no scheduler is provided in the config,
+ * `realm_open()` will fail. Note that `realm_scheduler_get_frozen()` always
+ * returns a valid scheduler.
+ *
+ * This function is thread-safe, and cannot fail.
+ */
+RLM_API bool realm_scheduler_has_default_factory(void);
+
+/**
+ * For platforms with no default scheduler implementation, register a factory
+ * function which can produce custom schedulers. If there is a platform-specific
+ * scheduler, this function will fail. If a custom scheduler is desired for
+ * platforms that already have a default scheduler implementation, the caller
+ * must call `realm_open()` with a config that indicates the desired scheduler.
+ *
+ * The provided callback may produce a scheduler by calling
+ * `realm_scheduler_new()`.
+ *
+ * This function is thread-safe, but should generally only be called once.
+ */
+RLM_API bool realm_scheduler_set_default_factory(void* userdata, realm_free_userdata_func_t,
+                                                 realm_scheduler_default_factory_func_t);
+
+/**
+ * Trigger a call to the registered notifier callback on the scheduler's event loop.
+ *
+ * This function is thread-safe.
+ */
+RLM_API void realm_scheduler_notify(realm_scheduler_t*);
+
+/**
+ * Returns true if the caller is currently running on the scheduler's thread.
+ *
+ * This function is thread-safe.
+ */
+RLM_API bool realm_scheduler_is_on_thread(const realm_scheduler_t*);
+
+/**
+ * Returns true if the scheduler is able to deliver notifications.
+ *
+ * A false return value may indicate that notifications are not applicable for
+ * the scheduler, not implementable, or a temporary inability to deliver
+ * notifications.
+ *
+ * This function is not thread-safe.
+ */
+RLM_API bool realm_scheduler_can_deliver_notifications(const realm_scheduler_t*);
+
+/**
+ * Set the callback that will be invoked by `realm_scheduler_notify()`.
+ *
+ * This function is not thread-safe.
+ */
+RLM_API bool realm_scheduler_set_notify_callback(realm_scheduler_t*, void* userdata, realm_free_userdata_func_t,
+                                                 realm_scheduler_notify_func_t);
+
+
+/**
+ * Open a Realm file.
+ *
+ * @param config Realm configuration. If the Realm is already opened on another
+ *               thread, validate that the given configuration is compatible
+ *               with the existing one.
+ * @return If successful, the Realm object. Otherwise, NULL.
+ */
+RLM_API realm_t* realm_open(const realm_config_t* config);
+
+/**
+ * Create a `realm_t` object from a thread-safe reference to the same realm.
+ *
+ * @param tsr Thread-safe reference object created by calling
+ *            `realm_get_thread_safe_reference()` with a `realm_t` instance.
+ * @param scheduler The scheduler to use for the new `realm_t` instance. May be
+ *                  NULL, in which case the default scheduler for the current
+ *                  thread is used.
+ * @return A non-null pointer if no error occurred.
+ */
+RLM_API realm_t* realm_from_thread_safe_reference(realm_thread_safe_reference_t* tsr, realm_scheduler_t* scheduler);
+
+/**
+ * Create a `realm_t*` from a `std::shared_ptr<Realm>*`.
+ *
+ * This is intended as a migration path for users of the C++ Object Store API.
+ *
+ * Call `realm_release()` on the returned `realm_t*` to decrement the refcount
+ * on the inner `std::shared_ptr<Realm>`.
+ *
+ * @param pshared_ptr A pointer to an instance of `std::shared_ptr<Realm>`.
+ * @param n Must be equal to `sizeof(std::shared_ptr<Realm>)`.
+ * @return A `realm_t*` representing the same Realm object as the passed
+ *         `std::shared_ptr<Realm>`.
+ */
+RLM_API realm_t* _realm_from_native_ptr(const void* pshared_ptr, size_t n);
+
+/**
+ * Get a `std::shared_ptr<Realm>` from a `realm_t*`.
+ *
+ * This is intended as a migration path for users of the C++ Object Store API.
+ *
+ * @param pshared_ptr A pointer to an instance of `std::shared_ptr<Realm>`.
+ * @param n Must be equal to `sizeof(std::shared_ptr<Realm>)`.
+ */
+RLM_API void _realm_get_native_ptr(const realm_t*, void* pshared_ptr, size_t n);
+
+/**
+ * Forcibly close a Realm file.
+ *
+ * Note that this invalidates all Realm instances for the same path.
+ *
+ * The Realm will be automatically closed when the last reference is released,
+ * including references to objects within the Realm.
+ *
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_close(realm_t*);
+
+/**
+ * True if the Realm file is closed.
+ *
+ * This function cannot fail.
+ */
+RLM_API bool realm_is_closed(realm_t*);
+
+/**
+ * Begin a read transaction for the Realm file.
+ *
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_begin_read(realm_t*);
+
+/**
+ * Begin a write transaction for the Realm file.
+ *
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_begin_write(realm_t*);
+
+/**
+ * Return true if the realm is in a write transaction.
+ *
+ * This function cannot fail.
+ */
+RLM_API bool realm_is_writable(const realm_t*);
+
+/**
+ * Commit a write transaction.
+ *
+ * @return True if the commit succeeded and no exceptions were thrown.
+ */
+RLM_API bool realm_commit(realm_t*);
+
+/**
+ * Roll back a write transaction.
+ *
+ * @return True if the rollback succeeded and no exceptions were thrown.
+ */
+RLM_API bool realm_rollback(realm_t*);
+
+/**
+ * Refresh the view of the realm file.
+ *
+ * If another process or thread has made changes to the realm file, this causes
+ * those changes to become visible in this realm instance.
+ *
+ * This calls `advance_read()` at the Core layer.
+ *
+ * @return True if the realm was successfully refreshed and no exceptions were
+ *         thrown.
+ */
+RLM_API bool realm_refresh(realm_t*);
+
+/**
+ * Produce a frozen view of this realm.
+ *
+ * @return A non-NULL realm instance representing the frozen state.
+ */
+RLM_API realm_t* realm_freeze(realm_t*);
+
+/**
+ * Vacuum the free space from the realm file, reducing its file size.
+ *
+ * @return True if compaction was successful and no exceptions were thrown.
+ */
+RLM_API bool realm_compact(realm_t*, bool* did_compact);
+
+/**
+ * Create a new schema from classes and their properties.
+ *
+ * Note: This function does not validate the schema.
+ *
+ * Note: `realm_class_key_t` and `realm_property_key_t` values inside
+ *       `realm_class_info_t` and `realm_property_info_t` are unused when
+ *       defining the schema. Call `realm_get_schema()` to obtain the values for
+ *       these fields in an open realm.
+ *
+ * @return True if allocation of the schema structure succeeded.
+ */
+RLM_API realm_schema_t* realm_schema_new(const realm_class_info_t* classes, size_t num_classes,
+                                         const realm_property_info_t** class_properties);
+
+/**
+ * Get the schema for this realm.
+ *
+ * Note: The returned value is allocated by this function, so `realm_release()`
+ *       must be called on it.
+ */
+RLM_API realm_schema_t* realm_get_schema(const realm_t*);
+
+/**
+ * Update the schema of an open realm.
+ *
+ * This is equivalent to calling `realm_update_schema_advanced(realm, schema, 0,
+ * NULL, NULL, NULL, NULL, false)`.
+ */
+RLM_API bool realm_update_schema(realm_t* realm, const realm_schema_t* schema);
+
+/**
+ * Update the schema of an open realm, with options to customize certain steps
+ * of the process.
+ *
+ * @param realm The realm for which the schema should be updated.
+ * @param schema The new schema for the realm. If the schema is the same the
+ *               existing schema, this function does nothing.
+ * @param version The version of the new schema.
+ * @param migration_func Callback to perform the migration. Has no effect if the
+ *                       Realm is opened with `RLM_SCHEMA_MODE_ADDITIVE`.
+ * @param migration_func_userdata Userdata pointer to pass to `migration_func`.
+ * @param data_init_func Callback to perform initialization of the data in the
+ *                       Realm if it is opened for the first time (i.e., it has
+ *                       no previous schema version).
+ * @param data_init_func_userdata Userdata pointer to pass to `data_init_func`.
+ * @param is_in_transaction Pass true if the realm is already in a write
+ *                          transaction. Otherwise, if the migration requires a
+ *                          write transaction, this function will perform the
+ *                          migration in its own write transaction.
+ */
+RLM_API bool realm_update_schema_advanced(realm_t* realm, const realm_schema_t* schema, uint64_t version,
+                                          realm_migration_func_t migration_func, void* migration_func_userdata,
+                                          realm_data_initialization_func_t data_init_func,
+                                          void* data_init_func_userdata, bool is_in_transaction);
+
+/**
+ * Get the `realm::Schema*` pointer for this realm.
+ *
+ * This is intended as a migration path for users of the C++ Object Store API.
+ *
+ * The returned value is owned by the `realm_t` instance, and must not be freed.
+ */
+RLM_API const void* _realm_get_schema_native(const realm_t*);
+
+/**
+ * Validate the schema.
+ *
+ *  @param validation_mode A bitwise combination of values from the
+ *                         enum realm_schema_validation_mode.
+ *
+ * @return True if the schema passed validation. If validation failed,
+ *         `realm_get_last_error()` will produce an error describing the
+ *         validation failure.
+ */
+RLM_API bool realm_schema_validate(const realm_schema_t*, uint64_t validation_mode);
+
+/**
+ * Return the number of classes in the Realm's schema.
+ *
+ * This cannot fail.
+ */
+RLM_API size_t realm_get_num_classes(const realm_t*);
+
+/**
+ * Get the table keys for classes in the schema.
+ *
+ * @param out_keys An array that will contain the keys of each class in the
+ *                 schema. May be NULL, in which case `out_n` can be used to
+ *                 determine the number of classes in the schema.
+ * @param max The maximum number of keys to write to `out_keys`.
+ * @param out_n The actual number of classes. May be NULL.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_get_class_keys(const realm_t*, realm_class_key_t* out_keys, size_t max, size_t* out_n);
+
+/**
+ * Find a by the name of @a name.
+ *
+ * @param name The name of the class.
+ * @param out_found Set to true if the class was found and no error occurred.
+ *                  Otherwise, false. May not be NULL.
+ * @param out_class_info A pointer to a `realm_class_info_t` that will be
+ *                       populated with information about the class. May be
+ *                       NULL.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_find_class(const realm_t*, const char* name, bool* out_found, realm_class_info_t* out_class_info);
+
+/**
+ * Get the class with @a key from the schema.
+ *
+ * Passing an invalid @a key for this schema is considered an error.
+ *
+ * @param key The key of the class, as discovered by `realm_get_class_keys()`.
+ * @param out_class_info A pointer to a `realm_class_info_t` that will be
+ *                       populated with the information of the class. May be
+ *                       NULL, though that's kind of pointless.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_get_class(const realm_t*, realm_class_key_t key, realm_class_info_t* out_class_info);
+
+/**
+ * Get the list of properties for the class with this @a key.
+ *
+ * @param out_properties A pointer to an array of `realm_property_info_t`, which
+ *                       will be populated with the information about the
+ *                       properties. To see all properties, the length of the
+ *                       array should be at least the number of properties in
+ *                       the class, as reported in the sum of persisted and
+ *                       computed properties for the class. May be NULL, in
+ *                       which case this function can be used to discover the
+ *                       number of properties in the class.
+ * @param max The maximum number of entries to write to `out_properties`.
+ * @param out_n The actual number of properties written to `out_properties`.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_get_class_properties(const realm_t*, realm_class_key_t key, realm_property_info_t* out_properties,
+                                        size_t max, size_t* out_n);
+
+/**
+ * Get the property keys for the class with this @a key.
+ *
+ * @param key The class key.
+ * @param out_col_keys An array of property keys. May be NULL, in which case
+ *                     this function can be used to discover the number of
+ *                     properties for this class.
+ * @param max The maximum number of keys to write to `out_col_keys`. Ignored if
+ *            `out_col_keys == NULL`.
+ * @param out_n The actual number of properties written to `out_col_keys` (if
+ *              non-NULL), or number of properties in the class.
+ **/
+RLM_API bool realm_get_property_keys(const realm_t*, realm_class_key_t key, realm_property_key_t* out_col_keys,
+                                     size_t max, size_t* out_n);
+
+
+/**
+ * Find a property by its column key.
+ *
+ * It is an error to pass a property @a key that is not present in this class.
+ *
+ * @param class_key The key of the class.
+ * @param key The column key for the property.
+ * @param out_property_info A pointer to a `realm_property_info_t` that will be
+ *                          populated with information about the property.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_get_property(const realm_t*, realm_class_key_t class_key, realm_property_key_t key,
+                                realm_property_info_t* out_property_info);
+
+/**
+ * Find a property by the internal (non-public) name of @a name.
+ *
+ * @param class_key The table key for the class.
+ * @param name The name of the property.
+ * @param out_found Will be set to true if the property was found. May not be
+ *                  NULL.
+ * @param out_property_info A pointer to a `realm_property_info_t` that will be
+ *                          populated with information about the property. May
+ *                          be NULL.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_find_property(const realm_t*, realm_class_key_t class_key, const char* name, bool* out_found,
+                                 realm_property_info_t* out_property_info);
+
+/**
+ * Find a property with the public name of @a name.
+ *
+ * @param class_key The table key for the class.
+ * @param public_name The public name of the property.
+ * @param out_found Will be set to true if the property was found. May not be
+ *                  NULL.
+ * @param out_property_info A pointer to a `realm_property_info_t` that will be
+ *                          populated with information about the property. May
+ *                          be NULL.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_find_property_by_public_name(const realm_t*, realm_class_key_t class_key, const char* public_name,
+                                                bool* out_found, realm_property_info_t* out_property_info);
+
+/**
+ * Find the primary key property for a class, if it has one.
+ *
+ * @param class_key The table key for this class.
+ * @param out_found Will be set to true if the property was found. May not be
+ *                  NULL.
+ * @param out_property_info A property to a `realm_property_info_t` that will be
+ *                          populated with information about the property, if it
+ *                          was found. May be NULL.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_find_primary_key_property(const realm_t*, realm_class_key_t class_key, bool* out_found,
+                                             realm_property_info_t* out_property_info);
+
+/**
+ * Get the number of objects in a table (class).
+ *
+ * @param out_count A pointer to a `size_t` that will contain the number of
+ *                  objects, if successful.
+ * @return True if the table key was valid for this realm.
+ */
+RLM_API bool realm_get_num_objects(const realm_t*, realm_class_key_t, size_t* out_count);
+
+/**
+ * Get the number of versions found in the Realm file.
+ *
+ * @param out_versions_count A pointer to a `size_t` that will contain the number of
+ *                           versions, if successful.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_get_num_versions(const realm_t*, uint64_t* out_versions_count);
+
+/**
+ * Get an object with a particular object key.
+ *
+ * @param class_key The class key.
+ * @param obj_key The key to the object. Passing a non-existent key is
+ *                considered an error.
+ * @return A non-NULL pointer if no exception occurred.
+ */
+RLM_API realm_object_t* realm_get_object(const realm_t*, realm_class_key_t class_key, realm_object_key_t obj_key);
+
+/**
+ * Find an object with a particular primary key value.
+ *
+ * @param out_found A pointer to a boolean that will be set to true or false if
+ *                  no error occurred.
+ * @return A non-NULL pointer if the object was found and no exception occurred.
+ */
+RLM_API realm_object_t* realm_object_find_with_primary_key(const realm_t*, realm_class_key_t, realm_value_t pk,
+                                                           bool* out_found);
+
+/**
+ * Find all objects in class.
+ *
+ * Note: This is faster than running a query matching all objects (such as
+ *       "TRUEPREDICATE").
+ *
+ * @return A non-NULL pointer if no exception was thrown.
+ */
+RLM_API realm_results_t* realm_object_find_all(const realm_t*, realm_class_key_t);
+
+/**
+ * Create an object in a class without a primary key.
+ *
+ * @return A non-NULL pointer if the object was created successfully.
+ */
+RLM_API realm_object_t* realm_object_create(realm_t*, realm_class_key_t);
+
+/**
+ * Create an object in a class with a primary key.
+ *
+ * @return A non-NULL pointer if the object was created successfully.
+ */
+RLM_API realm_object_t* realm_object_create_with_primary_key(realm_t*, realm_class_key_t, realm_value_t pk);
+
+/**
+ * Delete a realm object.
+ *
+ * Note: This does not call `realm_release()` on the `realm_object_t` instance.
+ *
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_object_delete(realm_object_t*);
+
+RLM_API realm_object_t* _realm_object_from_native_copy(const void* pobj, size_t n);
+RLM_API realm_object_t* _realm_object_from_native_move(void* pobj, size_t n);
+RLM_API const void* _realm_object_get_native_ptr(realm_object_t*);
+
+/**
+ * True if this object still exists in the realm.
+ *
+ * This function cannot fail.
+ */
+RLM_API bool realm_object_is_valid(const realm_object_t*);
+
+/**
+ * Get the key for this object.
+ *
+ * This function cannot fail.
+ */
+RLM_API realm_object_key_t realm_object_get_key(const realm_object_t* object);
+
+/**
+ * Get the table for this object.
+ *
+ * This function cannot fail.
+ */
+RLM_API realm_class_key_t realm_object_get_table(const realm_object_t* object);
+
+/**
+ * Get a `realm_link_t` representing a link to @a object.
+ *
+ * This function cannot fail.
+ */
+RLM_API realm_link_t realm_object_as_link(const realm_object_t* object);
+
+/**
+ * Subscribe to notifications for this object.
+ *
+ * @return A non-null pointer if no exception occurred.
+ */
+RLM_API realm_notification_token_t* realm_object_add_notification_callback(realm_object_t*, void* userdata,
+                                                                           realm_free_userdata_func_t free,
+                                                                           realm_on_object_change_func_t on_change,
+                                                                           realm_callback_error_func_t on_error,
+                                                                           realm_scheduler_t*);
+
+/**
+ * Get an object from a thread-safe reference, potentially originating in a
+ * different `realm_t` instance
+ */
+RLM_API realm_object_t* realm_object_from_thread_safe_reference(const realm_t*, realm_thread_safe_reference_t*);
+
+/**
+ * Get the value for a property.
+ *
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_get_value(const realm_object_t*, realm_property_key_t, realm_value_t* out_value);
+
+/**
+ * Get the values for several properties.
+ *
+ * This is provided as an alternative to calling `realm_get_value()` multiple
+ * times in a row, which is particularly useful for language runtimes where
+ * crossing the native bridge is comparatively expensive. In addition, it
+ * eliminates some parameter validation that would otherwise be repeated for
+ * each call.
+ *
+ * Example use cases:
+ *
+ *  - Extracting all properties of an object for serialization.
+ *  - Converting an object to some in-memory representation.
+ *
+ * @param num_values The number of elements in @a properties and @a out_values.
+ * @param properties The keys for the properties to fetch. May not be NULL.
+ * @param out_values Where to write the property values. If an error occurs,
+ *                   this array may only be partially initialized. May not be
+ *                   NULL.
+ * @return True if no exception occurs.
+ */
+RLM_API bool realm_get_values(const realm_object_t*, size_t num_values, const realm_property_key_t* properties,
+                              realm_value_t* out_values);
+
+/**
+ * Set the value for a property.
+ *
+ * @param new_value The new value for the property.
+ * @param is_default True if this property is being set as part of setting the
+ *                   default values for a new object. This has no effect in
+ *                   non-sync'ed realms.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_set_value(realm_object_t*, realm_property_key_t, realm_value_t new_value, bool is_default);
+
+/**
+ * Set the values for several properties.
+ *
+ * This is provided as an alternative to calling `realm_get_value()` multiple
+ * times in a row, which is particularly useful for language runtimes where
+ * crossing the native bridge is comparatively expensive. In addition, it
+ * eliminates some parameter validation that would otherwise be repeated for
+ * each call.
+ *
+ * Example use cases:
+ *
+ *  - Initializing a new object with default values.
+ *  - Deserializing some in-memory structure into a realm object.
+ *
+ * This operation is "atomic"; if an exception occurs due to invalid input (such
+ * as type mismatch, nullability mismatch, etc.), the object will remain
+ * unmodified.
+ *
+ * @param num_values The number of elements in @a properties and @a values.
+ * @param properties The keys of the properties to set. May not be NULL.
+ * @param values The values to assign to the properties. May not be NULL.
+ * @param is_default True if the properties are being set as part of setting
+ *                   default values for a new object. This has no effect in
+ *                   non-sync'ed realms.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_set_values(realm_object_t*, size_t num_values, const realm_property_key_t* properties,
+                              const realm_value_t* values, bool is_default);
+
+/**
+ * Get a list instance for the property of an object.
+ *
+ * Note: It is up to the caller to call `realm_release()` on the returned list.
+ *
+ * @return A non-null pointer if no exception occurred.
+ */
+RLM_API realm_list_t* realm_get_list(realm_object_t*, realm_property_key_t);
+
+/**
+ * Create a `realm_list_t` from a pointer to a `realm::List`, copy-constructing
+ * the internal representation.
+ *
+ * @param plist A pointer to an instance of `realm::List`.
+ * @param n Must be equal to `sizeof(realm::List)`.
+ * @return A non-null pointer if no exception occurred.
+ */
+RLM_API realm_list_t* _realm_list_from_native_copy(const void* plist, size_t n);
+
+/**
+ * Create a `realm_list_t` from a pointer to a `realm::List`, move-constructing
+ * the internal representation.
+ *
+ * @param plist A pointer to an instance of `realm::List`.
+ * @param n Must be equal to `sizeof(realm::List)`.
+ * @return A non-null pointer if no exception occurred.
+ */
+RLM_API realm_list_t* _realm_list_from_native_move(void* plist, size_t n);
+
+/**
+ * Get the size of a list, in number of elements.
+ *
+ * This function may fail if the object owning the list has been deleted.
+ *
+ * @param out_size Where to put the list size. May be NULL.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_list_size(const realm_list_t*, size_t* out_size);
+
+/**
+ * Get the property that this list came from.
+ *
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_list_get_property(const realm_list_t*, realm_property_info_t* out_property_info);
+
+/**
+ * Get the value at @a index.
+ *
+ * @param out_value The resulting value, if no error occurred. May be NULL,
+ *                  though nonsensical.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_list_get(const realm_list_t*, size_t index, realm_value_t* out_value);
+
+/**
+ * Set the value at @a index.
+ *
+ * @param value The value to set.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_list_set(realm_list_t*, size_t index, realm_value_t value);
+
+/**
+ * Insert @a value at @a index.
+ *
+ * @param value The value to insert.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_list_insert(realm_list_t*, size_t index, realm_value_t value);
+
+/**
+ * Erase the element at @a index.
+ *
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_list_erase(realm_list_t*, size_t index);
+
+/**
+ * Clear a list, removing all elements in the list. In a list of links, this
+ * does *NOT* delete the target objects.
+ *
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_list_clear(realm_list_t*);
+
+/**
+ * In a list of objects, delete all objects in the list and clear the list. In a
+ * list of values, clear the list.
+ *
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_list_remove_all(realm_list_t*);
+
+/**
+ * Replace the contents of a list with values.
+ *
+ * This is equivalent to calling `realm_list_clear()`, and then
+ * `realm_list_insert()` repeatedly.
+ *
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_list_assign(realm_list_t*, const realm_value_t* values, size_t num_values);
+
+/**
+ * Subscribe to notifications for this object.
+ *
+ * @return A non-null pointer if no exception occurred.
+ */
+RLM_API realm_notification_token_t* realm_list_add_notification_callback(realm_list_t*, void* userdata,
+                                                                         realm_free_userdata_func_t free,
+                                                                         realm_on_collection_change_func_t on_change,
+                                                                         realm_callback_error_func_t on_error,
+                                                                         realm_scheduler_t*);
+
+/**
+ * Get an list from a thread-safe reference, potentially originating in a
+ * different `realm_t` instance
+ */
+RLM_API realm_list_t* realm_list_from_thread_safe_reference(const realm_t*, realm_thread_safe_reference_t*);
+
+/**
+ * True if an object notification indicates that the object was deleted.
+ *
+ * This function cannot fail.
+ */
+RLM_API bool realm_object_changes_is_deleted(const realm_object_changes_t*);
+
+/**
+ * Get the number of properties that were modified in an object notification.
+ *
+ * This function cannot fail.
+ */
+RLM_API size_t realm_object_changes_get_num_modified_properties(const realm_object_changes_t*);
+
+/**
+ * Get the column keys for the properties that were modified in an object
+ * notification.
+ *
+ * This function cannot fail.
+ *
+ * @param out_modified Where the column keys should be written. May be NULL.
+ * @param max The maximum number of column keys to write.
+ * @return The number of column keys written to @a out_modified, or the number
+ *         of modified properties if @a out_modified is NULL.
+ */
+RLM_API size_t realm_object_changes_get_modified_properties(const realm_object_changes_t*,
+                                                            realm_property_key_t* out_modified, size_t max);
+
+/**
+ * Get the number of various types of changes in a collection notification.
+ *
+ * @param out_num_deletions The number of deletions. May be NULL.
+ * @param out_num_insertions The number of insertions. May be NULL.
+ * @param out_num_modifications The number of modifications. May be NULL.
+ * @param out_num_moves The number of moved elements. May be NULL.
+ */
+RLM_API void realm_collection_changes_get_num_changes(const realm_collection_changes_t*, size_t* out_num_deletions,
+                                                      size_t* out_num_insertions, size_t* out_num_modifications,
+                                                      size_t* out_num_moves);
+
+/**
+ * Get the number of various types of changes in a collection notification,
+ * suitable for acquiring the change indices as ranges, which is much more
+ * compact in memory than getting the individual indices when multiple adjacent
+ * elements have been modified.
+ *
+ * @param out_num_deletion_ranges The number of deleted ranges. May be NULL.
+ * @param out_num_insertion_ranges The number of inserted ranges. May be NULL.
+ * @param out_num_modification_ranges The number of modified ranges. May be
+ *                                    NULL.
+ * @param out_num_moves The number of moved elements. May be NULL.
+ */
+RLM_API void realm_collection_changes_get_num_ranges(const realm_collection_changes_t*,
+                                                     size_t* out_num_deletion_ranges,
+                                                     size_t* out_num_insertion_ranges,
+                                                     size_t* out_num_modification_ranges, size_t* out_num_moves);
+
+typedef struct realm_collection_move {
+    size_t from;
+    size_t to;
+} realm_collection_move_t;
+
+typedef struct realm_index_range {
+    size_t from;
+    size_t to;
+} realm_index_range_t;
+
+/**
+ * Get the indices of changes in a collection notification.
+ *
+ * Note: For moves, every `from` index will also be present among deletions, and
+ *       every `to` index will also be present among insertions.
+ *
+ * This function cannot fail.
+ *
+ * @param out_deletion_indices Where to put the indices of deleted elements
+ *                             (*before* the deletion happened). May be NULL.
+ * @param max_deletion_indices The max number of indices to write to @a
+ *                             out_deletion_indices.
+ * @param out_insertion_indices Where the put the indices of inserted elements
+ *                              (*after* the insertion happened). May be NULL.
+ * @param max_insertion_indices The max number of indices to write to @a
+ *                              out_insertion_indices.
+ * @param out_modification_indices Where to put the indices of modified elements
+ *                                 (*before* any insertions or deletions of
+ *                                 other elements). May be NULL.
+ * @param max_modification_indices The max number of indices to write to @a
+ *                                 out_modification_indices.
+ * @param out_modification_indices_after Where to put the indices of modified
+ *                                       elements (*after* any insertions or
+ *                                       deletions of other elements). May be
+ *                                       NULL.
+ * @param max_modification_indices_after The max number of indices to write to
+ *                                       @a out_modification_indices_after.
+ * @param out_moves Where to put the pairs of indices of moved elements. May be
+ *                  NULL.
+ * @param max_moves The max number of pairs to write to @a out_moves.
+ */
+RLM_API void realm_collection_changes_get_changes(const realm_collection_changes_t*, size_t* out_deletion_indices,
+                                                  size_t max_deletion_indices, size_t* out_insertion_indices,
+                                                  size_t max_insertion_indices, size_t* out_modification_indices,
+                                                  size_t max_modification_indices,
+                                                  size_t* out_modification_indices_after,
+                                                  size_t max_modification_indices_after,
+                                                  realm_collection_move_t* out_moves, size_t max_moves);
+
+RLM_API void realm_collection_changes_get_ranges(
+    const realm_collection_changes_t*, realm_index_range_t* out_deletion_ranges, size_t max_deletion_ranges,
+    realm_index_range_t* out_insertion_ranges, size_t max_insertion_ranges,
+    realm_index_range_t* out_modification_ranges, size_t max_modification_ranges,
+    realm_index_range_t* out_modification_ranges_after, size_t max_modification_ranges_after,
+    realm_collection_move_t* out_moves, size_t max_moves);
+
+RLM_API realm_set_t* _realm_set_from_native_copy(const void* pset, size_t n);
+RLM_API realm_set_t* _realm_set_from_native_move(void* pset, size_t n);
+RLM_API realm_set_t* realm_get_set(const realm_object_t*, realm_property_key_t);
+RLM_API size_t realm_set_size(const realm_set_t*);
+RLM_API bool realm_set_get(const realm_set_t*, size_t index, realm_value_t* out_value);
+RLM_API bool realm_set_find(const realm_set_t*, realm_value_t value, size_t* out_index);
+RLM_API bool realm_set_insert(realm_set_t*, realm_value_t value, size_t out_index);
+RLM_API bool realm_set_erase(realm_set_t*, realm_value_t value, bool* out_erased);
+RLM_API bool realm_set_clear(realm_set_t*);
+RLM_API bool realm_set_assign(realm_set_t*, realm_value_t values, size_t num_values);
+RLM_API realm_notification_token_t* realm_set_add_notification_callback(realm_object_t*, void* userdata,
+                                                                        realm_free_userdata_func_t free,
+                                                                        realm_on_collection_change_func_t on_change,
+                                                                        realm_callback_error_func_t on_error,
+                                                                        realm_scheduler_t*);
+
+
+RLM_API realm_dictionary_t* _realm_dictionary_from_native_copy(const void* pdict, size_t n);
+RLM_API realm_dictionary_t* _realm_dictionary_from_native_move(void* pdict, size_t n);
+RLM_API realm_dictionary_t* realm_get_dictionary(const realm_object_t*, realm_property_key_t);
+RLM_API size_t realm_dictionary_size(const realm_dictionary_t*);
+RLM_API bool realm_dictionary_get(const realm_dictionary_t*, realm_value_t key, realm_value_t* out_value,
+                                  bool* out_found);
+RLM_API bool realm_dictionary_insert(realm_dictionary_t*, realm_value_t key, realm_value_t value, bool* out_inserted,
+                                     size_t* out_index);
+RLM_API bool realm_dictionary_erase(realm_dictionary_t*, realm_value_t key, bool* out_erased);
+RLM_API bool realm_dictionary_clear(realm_dictionary_t*);
+typedef realm_value_t realm_key_value_pair_t[2];
+RLM_API bool realm_dictionary_assign(realm_dictionary_t*, const realm_key_value_pair_t* pairs, size_t num_pairs);
+RLM_API realm_notification_token_t*
+realm_dictionary_add_notification_callback(realm_object_t*, void* userdata, realm_free_userdata_func_t free,
+                                           realm_on_collection_change_func_t on_change,
+                                           realm_callback_error_func_t on_error, realm_scheduler_t*);
+
+/**
+ * Parse a query string and bind it to a table.
+ *
+ * If the query failed to parse, the parser error is available from
+ * `realm_get_last_error()`.
+ *
+ * @param target_table The table on which to run this query.
+ * @param query_string A zero-terminated string in the Realm Query Language,
+ *                     optionally containing argument placeholders (`$0`, `$1`,
+ *                     etc.).
+ * @param num_args The number of arguments for this query.
+ * @param args A pointer to a list of argument values.
+ * @return A non-null pointer if the query was successfully parsed and no
+ *         exception occurred.
+ */
+RLM_API realm_query_t* realm_query_parse(const realm_t*, realm_class_key_t target_table, const char* query_string,
+                                         size_t num_args, const realm_value_t* args);
+
+/**
+ * Parse a query string and bind it to a list.
+ *
+ * If the query failed to parse, the parser error is available from
+ * `realm_get_last_error()`.
+ *
+ * @param target_list The list on which to run this query.
+ * @param query_string A string in the Realm Query Language, optionally
+ *                     containing argument placeholders (`$0`, `$1`, etc.).
+ * @param num_args The number of arguments for this query.
+ * @param args A pointer to a list of argument values.
+ * @return A non-null pointer if the query was successfully parsed and no
+ *         exception occurred.
+ */
+RLM_API realm_query_t* realm_query_parse_for_list(const realm_list_t* target_list, const char* query_string,
+                                                  size_t num_args, const realm_value_t* args);
+
+/**
+ * Parse a query string and bind it to another query result.
+ *
+ * If the query failed to parse, the parser error is available from
+ * `realm_get_last_error()`.
+ *
+ * @param target_results The results on which to run this query.
+ * @param query_string A zero-terminated string in the Realm Query Language,
+ *                     optionally containing argument placeholders (`$0`, `$1`,
+ *                     etc.).
+ * @param num_args The number of arguments for this query.
+ * @param args A pointer to a list of argument values.
+ * @return A non-null pointer if the query was successfully parsed and no
+ *         exception occurred.
+ */
+RLM_API realm_query_t* realm_query_parse_for_results(const realm_results_t* target_results, const char* query_string,
+                                                     size_t num_args, const realm_value_t* args);
+
+/**
+ * Count the number of objects found by this query.
+ */
+RLM_API bool realm_query_count(const realm_query_t*, size_t* out_count);
+
+/**
+ * Return the first object matched by this query.
+ *
+ * Note: This function can only produce objects, not values. Use the
+ *       `realm_results_t` returned by `realm_query_find_all()` to retrieve
+ *       values from a list of primitive values.
+ *
+ * @param out_value Where to write the result, if any object matched the query.
+ *                  May be NULL.
+ * @param out_found Where to write whether the object was found. May be NULL.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_query_find_first(realm_query_t*, realm_value_t* out_value, bool* out_found);
+
+/**
+ * Produce a results object for this query.
+ *
+ * Note: This does not actually run the query until the results are accessed in
+ *       some way.
+ *
+ * @return A non-null pointer if no exception occurred.
+ */
+RLM_API realm_results_t* realm_query_find_all(realm_query_t*);
+
+/**
+ * Delete all objects matched by a query.
+ */
+RLM_API bool realm_query_delete_all(const realm_query_t*);
+
+/**
+ * Count the number of results.
+ *
+ * If the result is "live" (not a snapshot), this may rerun the query if things
+ * have changed.
+ *
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_results_count(realm_results_t*, size_t* out_count);
+
+/**
+ * Get the matching element at @a index in the results.
+ *
+ * If the result is "live" (not a snapshot), this may rerun the query if things
+ * have changed.
+ *
+ * Note: The bound returned by `realm_results_count()` for a non-snapshot result
+ *       is not a reliable way to iterate over elements in the result, because
+ *       the result will be live-updated if changes are made in each iteration
+ *       that may change the number of query results or even change the
+ *       ordering. In other words, this method should probably only be used with
+ *       snapshot results.
+ *
+ * @return True if no exception occurred (including out-of-bounds).
+ */
+RLM_API bool realm_results_get(realm_results_t*, size_t index, realm_value_t* out_value);
+
+/**
+ * Get the matching object at @a index in the results.
+ *
+ * If the result is "live" (not a snapshot), this may rerun the query if things
+ * have changed.
+ *
+ * Note: The bound returned by `realm_results_count()` for a non-snapshot result
+ *       is not a reliable way to iterate over elements in the result, because
+ *       the result will be live-updated if changes are made in each iteration
+ *       that may change the number of query results or even change the
+ *       ordering. In other words, this method should probably only be used with
+ *       snapshot results.
+ *
+ * @return An instance of `realm_object_t` if no exception occurred.
+ */
+RLM_API realm_object_t* realm_results_get_object(realm_results_t*, size_t index);
+
+/**
+ * Delete all objects in the result.
+ *
+ * If the result if "live" (not a snapshot), this may rerun the query if things
+ * have changed.
+ *
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_results_delete_all(realm_results_t*);
+
+/**
+ * Return a snapshot of the results that never automatically updates.
+ *
+ * The returned result is suitable for use with `realm_results_count()` +
+ * `realm_results_get()`.
+ */
+RLM_API realm_results_t* realm_results_snapshot(const realm_results_t*);
+
+/**
+ * Map the results into a frozen realm instance.
+ */
+RLM_API realm_results_t* realm_results_freeze(const realm_results_t*, const realm_t* frozen_realm);
+
+/**
+ * Compute the minimum value of a property in the results.
+ *
+ * @param out_min Where to write the result, if there were matching rows.
+ * @param out_found Set to true if there are matching rows.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_results_min(realm_results_t*, realm_property_key_t, realm_value_t* out_min, bool* out_found);
+
+/**
+ * Compute the maximum value of a property in the results.
+ *
+ * @param out_max Where to write the result, if there were matching rows.
+ * @param out_found Set to true if there are matching rows.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_results_max(realm_results_t*, realm_property_key_t, realm_value_t* out_max, bool* out_found);
+
+/**
+ * Compute the sum value of a property in the results.
+ *
+ * @param out_sum Where to write the result. Zero if no rows matched.
+ * @param out_found Set to true if there are matching rows.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_results_sum(realm_results_t*, realm_property_key_t, realm_value_t* out_sum, bool* out_found);
+
+/**
+ * Compute the average value of a property in the results.
+ *
+ * Note: For numeric columns, the average is always converted to double.
+ *
+ * @param out_average Where to write the result.
+ * @param out_found Set to true if there are matching rows.
+ * @return True if no exception occurred.
+ */
+RLM_API bool realm_results_average(realm_results_t*, realm_property_key_t, realm_value_t* out_average,
+                                   bool* out_found);
+
+RLM_API realm_notification_token_t* realm_results_add_notification_callback(realm_results_t*, void* userdata,
+                                                                            realm_free_userdata_func_t,
+                                                                            realm_on_collection_change_func_t,
+                                                                            realm_callback_error_func_t,
+                                                                            realm_scheduler_t*);
+
+/**
+ * Get an results object from a thread-safe reference, potentially originating
+ * in a different `realm_t` instance
+ */
+RLM_API realm_results_t* realm_results_from_thread_safe_reference(const realm_t*, realm_thread_safe_reference_t*);
+
+#endif // REALM_H

+ 32 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm.hpp

@@ -0,0 +1,32 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_HPP
+#define REALM_HPP
+
+#include <realm/db.hpp>
+#include <realm/obj.hpp>
+#include <realm/list.hpp>
+#include <realm/set.hpp>
+#include <realm/dictionary.hpp>
+#include <realm/table_view.hpp>
+#include <realm/query.hpp>
+#include <realm/query_engine.hpp>
+#include <realm/query_expression.hpp>
+
+#endif // REALM_HPP

+ 608 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/alloc.hpp

@@ -0,0 +1,608 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ALLOC_HPP
+#define REALM_ALLOC_HPP
+
+#include <cstdint>
+#include <cstddef>
+#include <atomic>
+
+#include <realm/util/features.h>
+#include <realm/util/terminate.hpp>
+#include <realm/util/assert.hpp>
+#include <realm/util/file.hpp>
+#include <realm/exceptions.hpp>
+#include <realm/util/safe_int_ops.hpp>
+#include <realm/node_header.hpp>
+#include <realm/util/file_mapper.hpp>
+
+// Temporary workaround for
+// https://developercommunity.visualstudio.com/content/problem/994075/64-bit-atomic-load-ices-cl-1924-with-o2-ob1.html
+#if defined REALM_ARCHITECTURE_X86_32 && defined REALM_WINDOWS
+#define REALM_WORKAROUND_MSVC_BUG REALM_NOINLINE
+#else
+#define REALM_WORKAROUND_MSVC_BUG
+#endif
+
+namespace realm {
+
+class Allocator;
+
+using ref_type = size_t;
+
+int_fast64_t from_ref(ref_type) noexcept;
+ref_type to_ref(int_fast64_t) noexcept;
+int64_t to_int64(size_t value) noexcept;
+
+class MemRef {
+public:
+    MemRef() noexcept;
+    ~MemRef() noexcept;
+
+    MemRef(char* addr, ref_type ref, Allocator& alloc) noexcept;
+    MemRef(ref_type ref, Allocator& alloc) noexcept;
+
+    char* get_addr() const;
+    ref_type get_ref() const;
+    void set_ref(ref_type ref);
+    void set_addr(char* addr);
+
+private:
+    char* m_addr;
+    ref_type m_ref;
+#if REALM_ENABLE_MEMDEBUG
+    // Allocator that created m_ref. Used to verify that the ref is valid whenever you call
+    // get_ref()/get_addr and that it e.g. has not been free'ed
+    const Allocator* m_alloc = nullptr;
+#endif
+};
+
+
+/// The common interface for Realm allocators.
+///
+/// A Realm allocator must associate a 'ref' to each allocated
+/// object and be able to efficiently map any 'ref' to the
+/// corresponding memory address. The 'ref' is an integer and it must
+/// always be divisible by 8. Also, a value of zero is used to
+/// indicate a null-reference, and must therefore never be returned by
+/// Allocator::alloc().
+///
+/// The purpose of the 'refs' is to decouple the memory reference from
+/// the actual address and thereby allowing objects to be relocated in
+/// memory without having to modify stored references.
+///
+/// \sa SlabAlloc
+class Allocator {
+public:
+    /// The specified size must be divisible by 8, and must not be
+    /// zero.
+    ///
+    /// \throw std::bad_alloc If insufficient memory was available.
+    MemRef alloc(size_t size);
+
+    /// Calls do_realloc().
+    ///
+    /// Note: The underscore has been added because the name `realloc`
+    /// would conflict with a macro on the Windows platform.
+    MemRef realloc_(ref_type, const char* addr, size_t old_size, size_t new_size);
+
+    /// Calls do_free().
+    ///
+    /// Note: The underscore has been added because the name `free
+    /// would conflict with a macro on the Windows platform.
+    void free_(ref_type, const char* addr) noexcept;
+
+    /// Shorthand for free_(mem.get_ref(), mem.get_addr()).
+    void free_(MemRef mem) noexcept;
+
+    /// Calls do_translate().
+    char* translate(ref_type ref) const noexcept;
+
+    /// Returns true if, and only if the object at the specified 'ref'
+    /// is in the immutable part of the memory managed by this
+    /// allocator. The method by which some objects become part of the
+    /// immuatble part is entirely up to the class that implements
+    /// this interface.
+    bool is_read_only(ref_type) const noexcept;
+
+    void set_read_only(bool ro)
+    {
+        m_is_read_only = ro;
+    }
+    /// Returns a simple allocator that can be used with free-standing
+    /// Realm objects (such as a free-standing table). A
+    /// free-standing object is one that is not part of a Group, and
+    /// therefore, is not part of an actual database.
+    static Allocator& get_default() noexcept;
+
+    virtual ~Allocator() noexcept;
+
+    // Disable copying. Copying an allocator can produce double frees.
+    Allocator(const Allocator&) = delete;
+    Allocator& operator=(const Allocator&) = delete;
+
+    virtual void verify() const = 0;
+
+#ifdef REALM_DEBUG
+    /// Terminate the program precisely when the specified 'ref' is
+    /// freed (or reallocated). You can use this to detect whether the
+    /// ref is freed (or reallocated), and even to get a stacktrace at
+    /// the point where it happens. Call watch(0) to stop watching
+    /// that ref.
+    void watch(ref_type ref)
+    {
+        m_debug_watch = ref;
+    }
+#endif
+
+    struct MappedFile;
+
+    static constexpr size_t section_size() noexcept
+    {
+        return 1 << section_shift;
+    }
+
+protected:
+    constexpr static int section_shift = 26;
+
+    std::atomic<size_t> m_baseline; // Separation line between immutable and mutable refs.
+
+    ref_type m_debug_watch = 0;
+
+    // The following logically belongs in the slab allocator, but is placed
+    // here to optimize a critical path:
+
+    // The ref translation splits the full ref-space (both below and above baseline)
+    // into equal chunks.
+    struct RefTranslation {
+        char* mapping_addr;
+        uint64_t cookie;
+        std::atomic<size_t> lowest_possible_xover_offset = 0;
+
+        // member 'xover_mapping_addr' is used for memory synchronization of the fields
+        // 'xover_mapping_base' and 'xover_encrypted_mapping'. It also imposes an ordering
+        // on 'lowest_possible_xover_offset' such that once a non-null value of 'xover_mapping_addr'
+        // has been acquired, 'lowest_possible_xover_offset' will never change.
+        std::atomic<char*> xover_mapping_addr = nullptr;
+        size_t xover_mapping_base = 0;
+#if REALM_ENABLE_ENCRYPTION
+        util::EncryptedFileMapping* encrypted_mapping = nullptr;
+        util::EncryptedFileMapping* xover_encrypted_mapping = nullptr;
+#endif
+        explicit RefTranslation(char* addr)
+            : mapping_addr(addr)
+            , cookie(0x1234567890)
+        {
+        }
+        RefTranslation()
+            : RefTranslation(nullptr)
+        {
+        }
+        ~RefTranslation()
+        {
+            cookie = 0xdeadbeefdeadbeef;
+        }
+        RefTranslation& operator=(const RefTranslation& from)
+        {
+            if (&from != this) {
+                mapping_addr = from.mapping_addr;
+#if REALM_ENABLE_ENCRYPTION
+                encrypted_mapping = from.encrypted_mapping;
+#endif
+                const auto local_xover_mapping_addr = from.xover_mapping_addr.load(std::memory_order_acquire);
+
+                // This must be loaded after xover_mapping_addr to ensure it isn't stale.
+                lowest_possible_xover_offset.store(from.lowest_possible_xover_offset, std::memory_order_relaxed);
+
+                if (local_xover_mapping_addr) {
+                    xover_mapping_base = from.xover_mapping_base;
+#if REALM_ENABLE_ENCRYPTION
+                    xover_encrypted_mapping = from.xover_encrypted_mapping;
+#endif
+                    xover_mapping_addr.store(local_xover_mapping_addr, std::memory_order_release);
+                }
+            }
+            return *this;
+        }
+    };
+    // This pointer may be changed concurrently with access, so make sure it is
+    // atomic!
+    std::atomic<RefTranslation*> m_ref_translation_ptr;
+
+    /// The specified size must be divisible by 8, and must not be
+    /// zero.
+    ///
+    /// \throw std::bad_alloc If insufficient memory was available.
+    virtual MemRef do_alloc(const size_t size) = 0;
+
+    /// The specified size must be divisible by 8, and must not be
+    /// zero.
+    ///
+    /// The default version of this function simply allocates a new
+    /// chunk of memory, copies over the old contents, and then frees
+    /// the old chunk.
+    ///
+    /// \throw std::bad_alloc If insufficient memory was available.
+    virtual MemRef do_realloc(ref_type, char* addr, size_t old_size, size_t new_size) = 0;
+
+    /// Release the specified chunk of memory.
+    virtual void do_free(ref_type, char* addr) = 0;
+
+    /// Map the specified \a ref to the corresponding memory
+    /// address. Note that if is_read_only(ref) returns true, then the
+    /// referenced object is to be considered immutable, and it is
+    /// then entirely the responsibility of the caller that the memory
+    /// is not modified by way of the returned memory pointer.
+    virtual char* do_translate(ref_type ref) const noexcept = 0;
+    char* translate_critical(RefTranslation*, ref_type ref) const noexcept;
+    char* translate_less_critical(RefTranslation*, ref_type ref) const noexcept;
+    virtual void get_or_add_xover_mapping(RefTranslation&, size_t, size_t, size_t) = 0;
+    Allocator() noexcept;
+    size_t get_section_index(size_t pos) const noexcept;
+    inline size_t get_section_base(size_t index) const noexcept;
+
+
+    // The following counters are used to ensure accessor refresh,
+    // and allows us to report many errors related to attempts to
+    // access data which is no longer current.
+    //
+    // * storage_versioning: monotonically increasing counter
+    //   bumped whenever the underlying storage layout is changed,
+    //   or if the owning accessor have been detached.
+    // * content_versioning: monotonically increasing counter
+    //   bumped whenever the data is changed. Used to detect
+    //   if queries are stale.
+    // * instance_versioning: monotonically increasing counter
+    //   used to detect if the allocator (and owning structure, e.g. Table)
+    //   is recycled. Mismatch on this counter will cause accesors
+    //   lower in the hierarchy to throw if access is attempted.
+    std::atomic<uint_fast64_t> m_content_versioning_counter;
+
+    std::atomic<uint_fast64_t> m_storage_versioning_counter;
+
+    std::atomic<uint_fast64_t> m_instance_versioning_counter;
+
+    inline uint_fast64_t get_storage_version(uint64_t instance_version)
+    {
+        if (instance_version != m_instance_versioning_counter) {
+            throw LogicError(LogicError::detached_accessor);
+        }
+        return m_storage_versioning_counter.load(std::memory_order_acquire);
+    }
+
+public:
+    inline uint_fast64_t get_storage_version()
+    {
+        return m_storage_versioning_counter.load(std::memory_order_acquire);
+    }
+
+protected:
+    inline void bump_storage_version() noexcept
+    {
+        m_storage_versioning_counter.fetch_add(1, std::memory_order_acq_rel);
+    }
+
+public:
+    REALM_WORKAROUND_MSVC_BUG inline uint_fast64_t get_content_version() noexcept
+    {
+        return m_content_versioning_counter.load(std::memory_order_acquire);
+    }
+
+protected:
+    inline uint_fast64_t bump_content_version() noexcept
+    {
+        return m_content_versioning_counter.fetch_add(1, std::memory_order_acq_rel) + 1;
+    }
+
+    REALM_WORKAROUND_MSVC_BUG inline uint_fast64_t get_instance_version() noexcept
+    {
+        return m_instance_versioning_counter.load(std::memory_order_relaxed);
+    }
+
+    inline void bump_instance_version() noexcept
+    {
+        m_instance_versioning_counter.fetch_add(1, std::memory_order_relaxed);
+    }
+
+private:
+    bool m_is_read_only = false; // prevent any alloc or free operations
+
+    friend class Table;
+    friend class ClusterTree;
+    friend class Group;
+    friend class WrappedAllocator;
+    friend class Obj;
+    template <class>
+    friend class CollectionBaseImpl;
+    friend class Dictionary;
+};
+
+
+class WrappedAllocator : public Allocator {
+public:
+    WrappedAllocator(Allocator& underlying_allocator)
+        : m_alloc(&underlying_allocator)
+    {
+        m_baseline.store(m_alloc->m_baseline, std::memory_order_relaxed);
+        m_debug_watch = 0;
+        m_ref_translation_ptr.store(m_alloc->m_ref_translation_ptr);
+    }
+
+    ~WrappedAllocator() {}
+
+    void switch_underlying_allocator(Allocator& underlying_allocator)
+    {
+        m_alloc = &underlying_allocator;
+        m_baseline.store(m_alloc->m_baseline, std::memory_order_relaxed);
+        m_debug_watch = 0;
+        refresh_ref_translation();
+    }
+
+    void update_from_underlying_allocator(bool writable)
+    {
+        switch_underlying_allocator(*m_alloc);
+        set_read_only(!writable);
+    }
+
+    void refresh_ref_translation()
+    {
+        m_ref_translation_ptr.store(m_alloc->m_ref_translation_ptr);
+    }
+
+protected:
+    void get_or_add_xover_mapping(RefTranslation& txl, size_t index, size_t offset, size_t size) override
+    {
+        m_alloc->get_or_add_xover_mapping(txl, index, offset, size);
+    }
+
+private:
+    Allocator* m_alloc;
+    MemRef do_alloc(const size_t size) override
+    {
+        auto result = m_alloc->do_alloc(size);
+        bump_storage_version();
+        m_baseline.store(m_alloc->m_baseline, std::memory_order_relaxed);
+        m_ref_translation_ptr.store(m_alloc->m_ref_translation_ptr);
+        return result;
+    }
+    virtual MemRef do_realloc(ref_type ref, char* addr, size_t old_size, size_t new_size) override
+    {
+        auto result = m_alloc->do_realloc(ref, addr, old_size, new_size);
+        bump_storage_version();
+        m_baseline.store(m_alloc->m_baseline, std::memory_order_relaxed);
+        m_ref_translation_ptr.store(m_alloc->m_ref_translation_ptr);
+        return result;
+    }
+
+    virtual void do_free(ref_type ref, char* addr) noexcept override
+    {
+        return m_alloc->do_free(ref, addr);
+    }
+
+    virtual char* do_translate(ref_type ref) const noexcept override
+    {
+        return m_alloc->translate(ref);
+    }
+
+    virtual void verify() const override
+    {
+        m_alloc->verify();
+    }
+};
+
+
+// Implementation:
+
+inline int_fast64_t from_ref(ref_type v) noexcept
+{
+    // Check that v is divisible by 8 (64-bit aligned).
+    REALM_ASSERT_DEBUG(v % 8 == 0);
+
+    static_assert(std::is_same<ref_type, size_t>::value,
+                  "If ref_type changes, from_ref and to_ref should probably be updated");
+
+    // Make sure that we preserve the bit pattern of the ref_type (without sign extension).
+    return int_fast64_t(uint_fast64_t(v));
+}
+
+inline ref_type to_ref(int_fast64_t v) noexcept
+{
+    // Check that v is divisible by 8 (64-bit aligned).
+    REALM_ASSERT_DEBUG(v % 8 == 0);
+
+    // C++11 standard, paragraph 4.7.2 [conv.integral]:
+    // If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source
+    // integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two's
+    // complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is
+    // no truncation). - end note ]
+    static_assert(std::is_unsigned<ref_type>::value,
+                  "If ref_type changes, from_ref and to_ref should probably be updated");
+    return ref_type(v);
+}
+
+inline int64_t to_int64(size_t value) noexcept
+{
+    int64_t res = static_cast<int64_t>(value);
+    REALM_ASSERT_DEBUG(res >= 0);
+    return static_cast<int64_t>(value);
+}
+
+
+inline MemRef::MemRef() noexcept
+    : m_addr(nullptr)
+    , m_ref(0)
+{
+}
+
+inline MemRef::~MemRef() noexcept {}
+
+inline MemRef::MemRef(char* addr, ref_type ref, Allocator& alloc) noexcept
+    : m_addr(addr)
+    , m_ref(ref)
+{
+    static_cast<void>(alloc);
+#if REALM_ENABLE_MEMDEBUG
+    m_alloc = &alloc;
+#endif
+}
+
+inline MemRef::MemRef(ref_type ref, Allocator& alloc) noexcept
+    : m_addr(alloc.translate(ref))
+    , m_ref(ref)
+{
+    static_cast<void>(alloc);
+#if REALM_ENABLE_MEMDEBUG
+    m_alloc = &alloc;
+#endif
+}
+
+inline char* MemRef::get_addr() const
+{
+#if REALM_ENABLE_MEMDEBUG
+    // Asserts if the ref has been freed
+    m_alloc->translate(m_ref);
+#endif
+    return m_addr;
+}
+
+inline ref_type MemRef::get_ref() const
+{
+#if REALM_ENABLE_MEMDEBUG
+    // Asserts if the ref has been freed
+    m_alloc->translate(m_ref);
+#endif
+    return m_ref;
+}
+
+inline void MemRef::set_ref(ref_type ref)
+{
+#if REALM_ENABLE_MEMDEBUG
+    // Asserts if the ref has been freed
+    m_alloc->translate(ref);
+#endif
+    m_ref = ref;
+}
+
+inline void MemRef::set_addr(char* addr)
+{
+    m_addr = addr;
+}
+
+inline MemRef Allocator::alloc(size_t size)
+{
+    if (m_is_read_only)
+        throw realm::LogicError(realm::LogicError::wrong_transact_state);
+    return do_alloc(size);
+}
+
+inline MemRef Allocator::realloc_(ref_type ref, const char* addr, size_t old_size, size_t new_size)
+{
+#ifdef REALM_DEBUG
+    if (ref == m_debug_watch)
+        REALM_TERMINATE("Allocator watch: Ref was reallocated");
+#endif
+    if (m_is_read_only)
+        throw realm::LogicError(realm::LogicError::wrong_transact_state);
+    return do_realloc(ref, const_cast<char*>(addr), old_size, new_size);
+}
+
+inline void Allocator::free_(ref_type ref, const char* addr) noexcept
+{
+#ifdef REALM_DEBUG
+    if (ref == m_debug_watch)
+        REALM_TERMINATE("Allocator watch: Ref was freed");
+#endif
+    REALM_ASSERT(!m_is_read_only);
+
+    return do_free(ref, const_cast<char*>(addr));
+}
+
+inline void Allocator::free_(MemRef mem) noexcept
+{
+    free_(mem.get_ref(), mem.get_addr());
+}
+
+inline size_t Allocator::get_section_base(size_t index) const noexcept
+{
+    return index << section_shift; // 64MB chunks
+}
+
+inline size_t Allocator::get_section_index(size_t pos) const noexcept
+{
+    return pos >> section_shift; // 64Mb chunks
+}
+
+inline bool Allocator::is_read_only(ref_type ref) const noexcept
+{
+    REALM_ASSERT_DEBUG(ref != 0);
+    // REALM_ASSERT_DEBUG(m_baseline != 0); // Attached SlabAlloc
+    return ref < m_baseline.load(std::memory_order_relaxed);
+}
+
+inline Allocator::Allocator() noexcept
+{
+    m_content_versioning_counter = 0;
+    m_storage_versioning_counter = 0;
+    m_instance_versioning_counter = 0;
+    m_ref_translation_ptr = nullptr;
+}
+
+inline Allocator::~Allocator() noexcept {}
+
+// performance critical part of the translation process. Less critical code is in translate_less_critical.
+inline char* Allocator::translate_critical(RefTranslation* ref_translation_ptr, ref_type ref) const noexcept
+{
+    size_t idx = get_section_index(ref);
+    RefTranslation& txl = ref_translation_ptr[idx];
+    if (REALM_LIKELY(txl.cookie == 0x1234567890)) {
+        size_t offset = ref - get_section_base(idx);
+        size_t lowest_possible_xover_offset = txl.lowest_possible_xover_offset.load(std::memory_order_relaxed);
+        if (REALM_LIKELY(offset < lowest_possible_xover_offset)) {
+            // the lowest possible xover offset may grow concurrently, but that will not affect this code path
+            char* addr = txl.mapping_addr + offset;
+#if REALM_ENABLE_ENCRYPTION
+            realm::util::encryption_read_barrier(addr, NodeHeader::header_size, txl.encrypted_mapping,
+                                                 NodeHeader::get_byte_size_from_header);
+#endif
+            return addr;
+        }
+        else {
+            // the lowest possible xover offset may grow concurrently, but that will be handled inside the call
+            return translate_less_critical(ref_translation_ptr, ref);
+        }
+    }
+    realm::util::terminate("Invalid ref translation entry", __FILE__, __LINE__, txl.cookie, 0x1234567890);
+    return nullptr;
+}
+
+inline char* Allocator::translate(ref_type ref) const noexcept
+{
+    auto ref_translation_ptr = m_ref_translation_ptr.load(std::memory_order_acquire);
+    if (REALM_LIKELY(ref_translation_ptr)) {
+        return translate_critical(ref_translation_ptr, ref);
+    }
+    else {
+        return do_translate(ref);
+    }
+}
+
+
+} // namespace realm
+
+#endif // REALM_ALLOC_HPP

+ 781 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/alloc_slab.hpp

@@ -0,0 +1,781 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ALLOC_SLAB_HPP
+#define REALM_ALLOC_SLAB_HPP
+
+#include <cstdint> // unint8_t etc
+#include <vector>
+#include <map>
+#include <string>
+#include <atomic>
+#include <mutex>
+
+#include <realm/util/features.h>
+#include <realm/util/file.hpp>
+#include <realm/util/thread.hpp>
+#include <realm/alloc.hpp>
+#include <realm/disable_sync_to_disk.hpp>
+
+namespace realm {
+
+// Pre-declarations
+class Group;
+class GroupWriter;
+
+namespace util {
+struct SharedFileInfo;
+}
+
+/// Thrown by Group and DB constructors if the specified file
+/// (or memory buffer) does not appear to contain a valid Realm
+/// database.
+struct InvalidDatabase;
+
+
+/// The allocator that is used to manage the memory of a Realm
+/// group, i.e., a Realm database.
+///
+/// Optionally, it can be attached to an pre-existing database (file
+/// or memory buffer) which then becomes an immuatble part of the
+/// managed memory.
+///
+/// To attach a slab allocator to a pre-existing database, call
+/// attach_file() or attach_buffer(). To create a new database
+/// in-memory, call attach_empty().
+///
+/// For efficiency, this allocator manages its mutable memory as a set
+/// of slabs.
+class SlabAlloc : public Allocator {
+public:
+    ~SlabAlloc() noexcept override;
+    SlabAlloc();
+
+    // Disable copying. Copying an allocator can produce double frees.
+    SlabAlloc(const SlabAlloc&) = delete;
+    SlabAlloc& operator=(const SlabAlloc&) = delete;
+
+    /// \struct Config
+    /// \brief Storage for combining setup flags for initialization to
+    /// the SlabAlloc.
+    ///
+    /// \var Config::is_shared
+    /// Must be true if, and only if we are called on behalf of DB.
+    ///
+    /// \var Config::read_only
+    /// Open the file in read-only mode. This implies \a Config::no_create.
+    ///
+    /// \var Config::no_create
+    /// Fail if the file does not already exist.
+    ///
+    /// \var Config::skip_validate
+    /// Skip validation of file header. In a
+    /// set of overlapping DBs, only the first one (the one
+    /// that creates/initlializes the coordination file) may validate
+    /// the header, otherwise it will result in a race condition.
+    ///
+    /// \var Config::encryption_key
+    /// 32-byte key to use to encrypt and decrypt the backing storage,
+    /// or nullptr to disable encryption.
+    ///
+    /// \var Config::session_initiator
+    /// If set, the caller is the session initiator and
+    /// guarantees exclusive access to the file. If attaching in
+    /// read/write mode, the file is modified: files on streaming form
+    /// is changed to non-streaming form, and if needed the file size
+    /// is adjusted to match mmap boundaries.
+    /// Must be set to false if is_shared is false.
+    ///
+    /// \var Config::clear_file
+    /// Always initialize the file as if it was a newly
+    /// created file and ignore any pre-existing contents. Requires that
+    /// Config::session_initiator be true as well.
+    struct Config {
+        bool is_shared = false;
+        bool read_only = false;
+        bool no_create = false;
+        bool skip_validate = false;
+        bool session_initiator = false;
+        bool clear_file = false;
+        bool disable_sync = false;
+        const char* encryption_key = nullptr;
+    };
+
+    struct Retry {
+    };
+
+    /// \brief Attach this allocator to the specified file.
+    ///
+    /// It is an error if this function is called at a time where the specified
+    /// Realm file (file system inode) is modified asynchronously.
+    ///
+    /// In non-shared mode (when this function is called on behalf of a
+    /// free-standing Group instance), it is the responsibility of the
+    /// application to ensure that the Realm file is not modified concurrently
+    /// from any other thread or process.
+    ///
+    /// In shared mode (when this function is called on behalf of a DB
+    /// instance), the caller (DB::do_open()) must take steps to ensure
+    /// cross-process mutual exclusion.
+    ///
+    /// Except for \a file_path, the parameters are passed in through a
+    /// configuration object.
+    ///
+    /// \return The `ref` of the root node, or zero if there is none.
+    ///
+    /// Please note that attach_file can fail to attach to a file due to a
+    /// collision with a writer extending the file. This can only happen if the
+    /// caller is *not* the session initiator. When this happens, attach_file()
+    /// throws SlabAlloc::Retry, and the caller must retry the call. The caller
+    /// should check if it has become the session initiator before retrying.
+    /// This can happen if the conflicting thread (or process) terminates or
+    /// crashes before the next retry.
+    ///
+    /// \throw util::File::AccessError
+    /// \throw SlabAlloc::Retry
+    ref_type attach_file(const std::string& file_path, Config& cfg);
+
+    /// Get the attached file. Only valid when called on an allocator with
+    /// an attached file.
+    util::File& get_file();
+
+    /// Attach this allocator to the specified memory buffer.
+    ///
+    /// It is an error to call this function on an attached
+    /// allocator. Doing so will result in undefined behavor.
+    ///
+    /// \return The `ref` of the root node, or zero if there is none.
+    ///
+    /// \sa own_buffer()
+    ///
+    /// \throw InvalidDatabase
+    ref_type attach_buffer(const char* data, size_t size);
+
+    /// Reads file format from file header. Must be called from within a write
+    /// transaction.
+    int get_committed_file_format_version() const noexcept;
+
+    bool is_file_on_streaming_form() const
+    {
+        const Header& header = *reinterpret_cast<const Header*>(m_data);
+        return is_file_on_streaming_form(header);
+    }
+
+    /// Attach this allocator to an empty buffer.
+    ///
+    /// It is an error to call this function on an attached
+    /// allocator. Doing so will result in undefined behavor.
+    void attach_empty();
+
+    /// Detach from a previously attached file or buffer.
+    ///
+    /// This function does not reset free space tracking. To
+    /// completely reset the allocator, you must also call
+    /// reset_free_space_tracking().
+    ///
+    /// This function has no effect if the allocator is already in the
+    /// detached state (idempotency).
+    void detach() noexcept;
+
+    class DetachGuard;
+
+    /// If a memory buffer has been attached using attach_buffer(),
+    /// mark it as owned by this slab allocator. Behaviour is
+    /// undefined if this function is called on a detached allocator,
+    /// one that is not attached using attach_buffer(), or one for
+    /// which this function has already been called during the latest
+    /// attachment.
+    void own_buffer() noexcept;
+
+    /// Returns true if, and only if this allocator is currently
+    /// in the attached state.
+    bool is_attached() const noexcept;
+
+    /// Returns true if, and only if this allocator is currently in
+    /// the attached state and attachment was not established using
+    /// attach_empty().
+    bool nonempty_attachment() const noexcept;
+
+    /// Reserve disk space now to avoid allocation errors at a later
+    /// point in time, and to minimize on-disk fragmentation. In some
+    /// cases, less fragmentation translates into improved
+    /// performance. On flash or SSD-drives this is likely a waste.
+    ///
+    /// Note: File::prealloc() may misbehave under race conditions (see
+    /// documentation of File::prealloc()). For that reason, to avoid race
+    /// conditions, when this allocator is used in a transactional mode, this
+    /// function may be called only when the caller has exclusive write
+    /// access. In non-transactional mode it is the responsibility of the user
+    /// to ensure non-concurrent file mutation.
+    ///
+    /// This function will call File::sync().
+    ///
+    /// It is an error to call this function on an allocator that is not
+    /// attached to a file. Doing so will result in undefined behavior.
+    void resize_file(size_t new_file_size);
+
+#ifdef REALM_DEBUG
+    /// Deprecated method, only called from a unit test
+    ///
+    /// WARNING: This method is NOT thread safe on multiple platforms; see
+    /// File::prealloc().
+    ///
+    /// Reserve disk space now to avoid allocation errors at a later point in
+    /// time, and to minimize on-disk fragmentation. In some cases, less
+    /// fragmentation translates into improved performance. On SSD-drives
+    /// preallocation is likely a waste.
+    ///
+    /// When supported by the system, a call to this function will make the
+    /// database file at least as big as the specified size, and cause space on
+    /// the target device to be allocated (note that on many systems on-disk
+    /// allocation is done lazily by default). If the file is already bigger
+    /// than the specified size, the size will be unchanged, and on-disk
+    /// allocation will occur only for the initial section that corresponds to
+    /// the specified size.
+    ///
+    /// This function will call File::sync() if it changes the size of the file.
+    ///
+    /// It is an error to call this function on an allocator that is not
+    /// attached to a file. Doing so will result in undefined behavior.
+    void reserve_disk_space(size_t size_in_bytes);
+#endif
+
+    /// Get the size of the attached database file or buffer in number
+    /// of bytes. This size is not affected by new allocations. After
+    /// attachment, it can only be modified by a call to update_reader_view().
+    ///
+    /// It is an error to call this function on a detached allocator,
+    /// or one that was attached using attach_empty(). Doing so will
+    /// result in undefined behavior.
+    size_t get_baseline() const noexcept;
+
+    /// Get the total amount of managed memory. This is the baseline plus the
+    /// sum of the sizes of the allocated slabs. It includes any free space.
+    ///
+    /// It is an error to call this function on a detached
+    /// allocator. Doing so will result in undefined behavior.
+    size_t get_total_size() const noexcept;
+
+    /// Mark all mutable memory (ref-space outside the attached file) as free
+    /// space.
+    void reset_free_space_tracking();
+
+    /// Update the readers view of the file:
+    ///
+    /// Remap the attached file such that a prefix of the specified
+    /// size becomes available in memory. If sucessfull,
+    /// get_baseline() will return the specified new file size.
+    ///
+    /// It is an error to call this function on a detached allocator,
+    /// or one that was not attached using attach_file(). Doing so
+    /// will result in undefined behavior.
+    ///
+    /// Updates the memory mappings to reflect a new size for the file.
+    /// Stale mappings are retained so that they remain valid for other threads,
+    /// which haven't yet seen the file size change. The stale mappings are
+    /// associated with a version count if one is provided.
+    /// They are later purged by calls to purge_old_mappings().
+    /// The version parameter is subtly different from the mapping_version obtained
+    /// by get_mapping_version() below. The mapping version changes whenever a
+    /// ref->ptr translation changes, and is used by Group to enforce re-translation.
+    void update_reader_view(size_t file_size);
+    void purge_old_mappings(uint64_t oldest_live_version, uint64_t youngest_live_version);
+    void init_mapping_management(uint64_t currently_live_version);
+
+    /// Get an ID for the current mapping version. This ID changes whenever any part
+    /// of an existing mapping is changed. Such a change requires all refs to be
+    /// retranslated to new pointers. This will happen whenever the reader view
+    /// is extended unless the old size was aligned to a section boundary.
+    uint64_t get_mapping_version()
+    {
+        return m_mapping_version;
+    }
+
+    /// Returns true initially, and after a call to reset_free_space_tracking()
+    /// up until the point of the first call to SlabAlloc::alloc(). Note that a
+    /// call to SlabAlloc::alloc() corresponds to a mutation event.
+    bool is_free_space_clean() const noexcept;
+
+    /// Returns the amount of memory requested by calls to SlabAlloc::alloc().
+    size_t get_commit_size() const
+    {
+        return m_commit_size;
+    }
+
+    /// Returns the total amount of memory currently allocated in slab area
+    size_t get_allocated_size() const noexcept;
+
+    /// Returns total amount of slab for all slab allocators
+    static size_t get_total_slab_size() noexcept;
+
+    /// Hooks used to keep the encryption layer informed of the start and stop
+    /// of transactions.
+    void note_reader_start(const void* reader_id);
+    void note_reader_end(const void* reader_id) noexcept;
+
+    void verify() const override;
+#ifdef REALM_DEBUG
+    void enable_debug(bool enable)
+    {
+        m_debug_out = enable;
+    }
+    bool is_all_free() const;
+    void print() const;
+#endif
+
+protected:
+    MemRef do_alloc(const size_t size) override;
+    MemRef do_realloc(ref_type, char*, size_t old_size, size_t new_size) override;
+    void do_free(ref_type, char*) override;
+    char* do_translate(ref_type) const noexcept override;
+
+    /// Returns the first section boundary *above* the given position.
+    size_t get_upper_section_boundary(size_t start_pos) const noexcept;
+
+    /// Returns the section boundary at or above the given size
+    size_t align_size_to_section_boundary(size_t size) const noexcept;
+
+    /// Returns the first section boundary *at or below* the given position.
+    size_t get_lower_section_boundary(size_t start_pos) const noexcept;
+
+    /// Returns true if the given position is at a section boundary
+    bool matches_section_boundary(size_t pos) const noexcept;
+
+    /// Actually compute the starting offset of a section. Only used to initialize
+    /// a table of predefined results, which are then used by get_section_base().
+    size_t compute_section_base(size_t index) const noexcept;
+
+    /// Find a possible allocation of 'request_size' that will fit into a section
+    /// which is inside the range from 'start_pos' to 'start_pos'+'free_chunk_size'
+    /// If found return the position, if not return 0.
+    size_t find_section_in_range(size_t start_pos, size_t free_chunk_size, size_t request_size) const noexcept;
+
+private:
+    enum AttachMode {
+        attach_None,        // Nothing is attached
+        attach_OwnedBuffer, // We own the buffer (m_data = nullptr for empty buffer)
+        attach_UsersBuffer, // We do not own the buffer
+        attach_SharedFile,  // On behalf of DB
+        attach_UnsharedFile // Not on behalf of DB
+    };
+
+    // A slab is a dynamically allocated contiguous chunk of memory used to
+    // extend the amount of space available for database node
+    // storage. Inter-node references are represented as file offsets
+    // (a.k.a. "refs"), and each slab creates an apparently seamless extension
+    // of this file offset addressable space. Slabs are stored as rows in the
+    // Slabs table in order of ascending file offsets.
+    struct Slab {
+        ref_type ref_end;
+        char* addr;
+        size_t size;
+
+        Slab(ref_type r, size_t s);
+        ~Slab();
+
+        Slab(const Slab&) = delete;
+        Slab(Slab&& other) noexcept
+            : ref_end(other.ref_end)
+            , addr(other.addr)
+            , size(other.size)
+        {
+            other.addr = nullptr;
+            other.size = 0;
+            other.ref_end = 0;
+        }
+
+        Slab& operator=(const Slab&) = delete;
+        Slab& operator=(Slab&&) = delete;
+    };
+
+    // free blocks that are in the slab area are managed using the following structures:
+    // - FreeBlock: Placed at the start of any free space. Holds the 'ref' corresponding to
+    //              the start of the space, and prev/next links used to place it in a size-specific
+    //              freelist.
+    // - BetweenBlocks: Structure sitting between any two free OR allocated spaces.
+    //                  describes the size of the space before and after.
+    // Each slab (area obtained from the underlying system) has a terminating BetweenBlocks
+    // at the beginning and at the end of the Slab.
+    struct FreeBlock {
+        ref_type ref;    // ref for this entry. Saves a reverse translate / representing links as refs
+        FreeBlock* prev; // circular doubly linked list
+        FreeBlock* next;
+        void clear_links()
+        {
+            prev = next = nullptr;
+        }
+        void unlink();
+    };
+    struct BetweenBlocks {         // stores sizes and used/free status of blocks before and after.
+        int32_t block_before_size; // negated if block is in use,
+        int32_t block_after_size;  // positive if block is free - and zero at end
+    };
+
+    Config m_cfg;
+    using FreeListMap = std::map<int, FreeBlock*>; // log(N) addressing for larger blocks
+    FreeListMap m_block_map;
+
+    // abstract notion of a freelist - used to hide whether a freelist
+    // is residing in the small blocks or the large blocks structures.
+    struct FreeList {
+        int size = 0; // size of every element in the list, 0 if not found
+        FreeListMap::iterator it;
+        bool found_something()
+        {
+            return size != 0;
+        }
+        bool found_exact(int sz)
+        {
+            return size == sz;
+        }
+    };
+
+    // simple helper functions for accessing/navigating blocks and betweenblocks (TM)
+    BetweenBlocks* bb_before(FreeBlock* entry) const
+    {
+        return reinterpret_cast<BetweenBlocks*>(entry) - 1;
+    }
+    BetweenBlocks* bb_after(FreeBlock* entry) const
+    {
+        auto bb = bb_before(entry);
+        size_t sz = bb->block_after_size;
+        char* addr = reinterpret_cast<char*>(entry) + sz;
+        return reinterpret_cast<BetweenBlocks*>(addr);
+    }
+    FreeBlock* block_before(BetweenBlocks* bb) const
+    {
+        size_t sz = bb->block_before_size;
+        if (sz <= 0)
+            return nullptr; // only blocks that are not in use
+        char* addr = reinterpret_cast<char*>(bb) - sz;
+        return reinterpret_cast<FreeBlock*>(addr);
+    }
+    FreeBlock* block_after(BetweenBlocks* bb) const
+    {
+        if (bb->block_after_size <= 0)
+            return nullptr;
+        return reinterpret_cast<FreeBlock*>(bb + 1);
+    }
+    int size_from_block(FreeBlock* entry) const
+    {
+        return bb_before(entry)->block_after_size;
+    }
+    void mark_allocated(FreeBlock* entry);
+    // mark the entry freed in bordering BetweenBlocks. Also validate size.
+    void mark_freed(FreeBlock* entry, int size);
+
+    // hook for the memory verifier in Group.
+    template <typename Func>
+    void for_all_free_entries(Func f) const;
+
+    // Main entry points for alloc/free:
+    FreeBlock* allocate_block(int size);
+    void free_block(ref_type ref, FreeBlock* addr);
+
+    // Searching/manipulating freelists
+    FreeList find(int size);
+    FreeList find_larger(FreeList hint, int size);
+    FreeBlock* pop_freelist_entry(FreeList list);
+    void push_freelist_entry(FreeBlock* entry);
+    void remove_freelist_entry(FreeBlock* element);
+    void rebuild_freelists_from_slab();
+    void clear_freelists();
+
+    // grow the slab area.
+    // returns a free block large enough to handle the request.
+    FreeBlock* grow_slab(int size);
+    // create a single free chunk with "BetweenBlocks" at both ends and a
+    // single free chunk between them. This free chunk will be of size:
+    //   slab_size - 2 * sizeof(BetweenBlocks)
+    FreeBlock* slab_to_entry(const Slab& slab, ref_type ref_start);
+
+    // breaking/merging of blocks
+    FreeBlock* get_prev_block_if_mergeable(FreeBlock* block);
+    FreeBlock* get_next_block_if_mergeable(FreeBlock* block);
+    // break 'block' to give it 'new_size'. Return remaining block.
+    // If the block is too small to split, return nullptr.
+    FreeBlock* break_block(FreeBlock* block, int new_size);
+    FreeBlock* merge_blocks(FreeBlock* first, FreeBlock* second);
+
+    // Values of each used bit in m_flags
+    enum {
+        flags_SelectBit = 1,
+    };
+
+    // 24 bytes
+    struct Header {
+        uint64_t m_top_ref[2]; // 2 * 8 bytes
+        // Info-block 8-bytes
+        uint8_t m_mnemonic[4];    // "T-DB"
+        uint8_t m_file_format[2]; // See `library_file_format`
+        uint8_t m_reserved;
+        // bit 0 of m_flags is used to select between the two top refs.
+        uint8_t m_flags;
+    };
+
+    // 16 bytes
+    struct StreamingFooter {
+        uint64_t m_top_ref;
+        uint64_t m_magic_cookie;
+    };
+
+    // Description of to-be-deleted memory mapping
+    struct OldMapping {
+        uint64_t replaced_at_version;
+        util::File::Map<char> mapping;
+    };
+    struct OldRefTranslation {
+        OldRefTranslation(uint64_t v, size_t c, RefTranslation* m) noexcept
+            : replaced_at_version(v)
+            , translation_count(c)
+            , translations(m)
+        {
+        }
+        uint64_t replaced_at_version;
+        size_t translation_count;
+        std::unique_ptr<RefTranslation[]> translations;
+    };
+    static_assert(sizeof(Header) == 24, "Bad header size");
+    static_assert(sizeof(StreamingFooter) == 16, "Bad footer size");
+
+    static const Header empty_file_header;
+    static void init_streaming_header(Header*, int file_format_version);
+
+    static const uint_fast64_t footer_magic_cookie = 0x3034125237E526C8ULL;
+
+    util::RaceDetector changes;
+
+    void verify_old_translations(uint64_t verify_old_translations);
+
+    // mappings used by newest transactions - additional mappings may be open
+    // and in use by older transactions. These translations are in m_old_mappings.
+    struct MapEntry {
+        util::File::Map<char> primary_mapping;
+        size_t lowest_possible_xover_offset = 0;
+        util::File::Map<char> xover_mapping;
+    };
+    std::vector<MapEntry> m_mappings;
+    size_t m_translation_table_size = 0;
+    uint64_t m_mapping_version = 1;
+    uint64_t m_youngest_live_version = 1;
+    std::mutex m_mapping_mutex;
+    util::File m_file;
+    util::SharedFileInfo* m_realm_file_info = nullptr;
+    // vectors where old mappings, are held from deletion to ensure translations are
+    // kept open and ref->ptr translations work for other threads..
+    std::vector<OldMapping> m_old_mappings;
+    std::vector<OldRefTranslation> m_old_translations;
+    // Rebuild the ref translations in a thread-safe manner. Save the old one along with it's
+    // versioning information for later deletion - 'requires_new_fast_mapping' must be
+    // true if there are changes to entries among the existing translations. Must be called
+    // with m_mapping_mutex locked.
+    void rebuild_translations(bool requires_new_fast_mapping, size_t old_num_sections);
+    // Add a translation covering a new section in the slab area. The translation is always
+    // added at the end.
+    void extend_fast_mapping_with_slab(char* address);
+    void get_or_add_xover_mapping(RefTranslation& txl, size_t index, size_t offset, size_t size) override;
+
+    const char* m_data = nullptr;
+    size_t m_initial_section_size = 0;
+    int m_section_shifts = 0;
+    AttachMode m_attach_mode = attach_None;
+    enum FeeeSpaceState {
+        free_space_Clean,
+        free_space_Dirty,
+        free_space_Invalid,
+    };
+    constexpr static int minimal_alloc = 128 * 1024;
+    constexpr static int maximal_alloc = 1 << section_shift;
+
+    /// When set to free_space_Invalid, the free lists are no longer
+    /// up-to-date. This happens if do_free() or
+    /// reset_free_space_tracking() fails, presumably due to
+    /// std::bad_alloc being thrown during updating of the free space
+    /// list. In this this case, alloc(), realloc_(), and
+    /// get_free_read_only() must throw. This member is deliberately
+    /// placed here (after m_attach_mode) in the hope that it leads to
+    /// less padding between members due to alignment requirements.
+    FeeeSpaceState m_free_space_state = free_space_Clean;
+
+    typedef std::vector<Slab> Slabs;
+    using Chunks = std::map<ref_type, size_t>;
+    Slabs m_slabs;
+    Chunks m_free_read_only;
+    size_t m_commit_size = 0;
+
+    bool m_debug_out = false;
+
+    /// Throws if free-lists are no longer valid.
+    size_t consolidate_free_read_only();
+    /// Throws if free-lists are no longer valid.
+    const Chunks& get_free_read_only() const;
+
+    /// Throws InvalidDatabase if the file is not a Realm file, if the file is
+    /// corrupted, or if the specified encryption key is incorrect. This
+    /// function will not detect all forms of corruption, though.
+    /// Returns the top_ref for the latest commit.
+    ref_type validate_header(const char* data, size_t len, const std::string& path);
+    ref_type validate_header(const Header* header, const StreamingFooter* footer, size_t size,
+                             const std::string& path);
+    void throw_header_exception(std::string msg, const Header& header, const std::string& path);
+
+    static bool is_file_on_streaming_form(const Header& header);
+    /// Read the top_ref from the given buffer and set m_file_on_streaming_form
+    /// if the buffer contains a file in streaming form
+    static ref_type get_top_ref(const char* data, size_t len);
+
+    // Gets the path of the attached file, or other relevant debugging info.
+    std::string get_file_path_for_assertions() const;
+
+    static bool ref_less_than_slab_ref_end(ref_type, const Slab&) noexcept;
+
+    friend class Group;
+    friend class DB;
+    friend class GroupWriter;
+};
+
+
+class SlabAlloc::DetachGuard {
+public:
+    DetachGuard(SlabAlloc& alloc) noexcept
+        : m_alloc(&alloc)
+    {
+    }
+    ~DetachGuard() noexcept;
+    SlabAlloc* release() noexcept;
+
+private:
+    SlabAlloc* m_alloc;
+};
+
+
+// Implementation:
+
+struct InvalidDatabase : util::File::AccessError {
+    InvalidDatabase(const std::string& msg, const std::string& path)
+        : util::File::AccessError(msg, path)
+    {
+    }
+};
+
+inline void SlabAlloc::own_buffer() noexcept
+{
+    REALM_ASSERT_3(m_attach_mode, ==, attach_UsersBuffer);
+    REALM_ASSERT(m_data);
+    m_attach_mode = attach_OwnedBuffer;
+}
+
+inline bool SlabAlloc::is_attached() const noexcept
+{
+    return m_attach_mode != attach_None;
+}
+
+inline bool SlabAlloc::nonempty_attachment() const noexcept
+{
+    return is_attached() && m_data;
+}
+
+inline size_t SlabAlloc::get_baseline() const noexcept
+{
+    REALM_ASSERT_DEBUG(is_attached());
+    return m_baseline.load(std::memory_order_relaxed);
+}
+
+inline bool SlabAlloc::is_free_space_clean() const noexcept
+{
+    return m_free_space_state == free_space_Clean;
+}
+
+inline SlabAlloc::DetachGuard::~DetachGuard() noexcept
+{
+    if (m_alloc)
+        m_alloc->detach();
+}
+
+inline SlabAlloc* SlabAlloc::DetachGuard::release() noexcept
+{
+    SlabAlloc* alloc = m_alloc;
+    m_alloc = nullptr;
+    return alloc;
+}
+
+inline bool SlabAlloc::ref_less_than_slab_ref_end(ref_type ref, const Slab& slab) noexcept
+{
+    return ref < slab.ref_end;
+}
+
+inline size_t SlabAlloc::get_upper_section_boundary(size_t start_pos) const noexcept
+{
+    return get_section_base(1 + get_section_index(start_pos));
+}
+
+inline size_t SlabAlloc::align_size_to_section_boundary(size_t size) const noexcept
+{
+    if (matches_section_boundary(size))
+        return size;
+    else
+        return get_upper_section_boundary(size);
+}
+
+inline size_t SlabAlloc::get_lower_section_boundary(size_t start_pos) const noexcept
+{
+    return get_section_base(get_section_index(start_pos));
+}
+
+inline bool SlabAlloc::matches_section_boundary(size_t pos) const noexcept
+{
+    auto boundary = get_lower_section_boundary(pos);
+    return pos == boundary;
+}
+
+template <typename Func>
+void SlabAlloc::for_all_free_entries(Func f) const
+{
+    ref_type ref = align_size_to_section_boundary(m_baseline.load(std::memory_order_relaxed));
+    for (const auto& e : m_slabs) {
+        BetweenBlocks* bb = reinterpret_cast<BetweenBlocks*>(e.addr);
+        REALM_ASSERT(bb->block_before_size == 0);
+        while (1) {
+            int size = bb->block_after_size;
+            f(ref, sizeof(BetweenBlocks));
+            ref += sizeof(BetweenBlocks);
+            if (size == 0) {
+                break;
+            }
+            if (size > 0) { // freeblock.
+                f(ref, size);
+                bb = reinterpret_cast<BetweenBlocks*>(reinterpret_cast<char*>(bb) + sizeof(BetweenBlocks) + size);
+                ref += size;
+            }
+            else {
+                bb = reinterpret_cast<BetweenBlocks*>(reinterpret_cast<char*>(bb) + sizeof(BetweenBlocks) - size);
+                ref -= size;
+            }
+        }
+        // any gaps in ref-space is reported as a free block to the validator:
+        auto next_ref = align_size_to_section_boundary(ref);
+        if (next_ref > ref) {
+            f(ref, next_ref - ref);
+            ref = next_ref;
+        }
+    }
+}
+
+} // namespace realm
+
+#endif // REALM_ALLOC_SLAB_HPP

+ 2091 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array.hpp

@@ -0,0 +1,2091 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+/*
+Searching: The main finding function is:
+    template <class cond, Action action, size_t bitwidth, class Callback>
+    void find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState *state, Callback callback) const
+
+    cond:       One of Equal, NotEqual, Greater, etc. classes
+    Action:     One of act_ReturnFirst, act_FindAll, act_Max, act_CallbackIdx, etc, constants
+    Callback:   Optional function to call for each search result. Will be called if action == act_CallbackIdx
+
+    find() will call find_action_pattern() or find_action() that again calls match() for each search result which
+    optionally calls callback():
+
+        find() -> find_action() -------> bool match() -> bool callback()
+             |                            ^
+             +-> find_action_pattern()----+
+
+    If callback() returns false, find() will exit, otherwise it will keep searching remaining items in array.
+*/
+
+#ifndef REALM_ARRAY_HPP
+#define REALM_ARRAY_HPP
+
+#include <realm/node.hpp>
+
+#include <cmath>
+#include <cstdlib> // size_t
+#include <algorithm>
+#include <utility>
+#include <vector>
+#include <ostream>
+
+#include <cstdint> // unint8_t etc
+
+#include <realm/util/assert.hpp>
+#include <realm/util/file_mapper.hpp>
+#include <realm/utilities.hpp>
+#include <realm/alloc.hpp>
+#include <realm/string_data.hpp>
+#include <realm/query_conditions.hpp>
+#include <realm/column_fwd.hpp>
+#include <realm/array_direct.hpp>
+#include <realm/array_unsigned.hpp>
+
+/*
+    MMX: mmintrin.h
+    SSE: xmmintrin.h
+    SSE2: emmintrin.h
+    SSE3: pmmintrin.h
+    SSSE3: tmmintrin.h
+    SSE4A: ammintrin.h
+    SSE4.1: smmintrin.h
+    SSE4.2: nmmintrin.h
+*/
+#ifdef REALM_COMPILER_SSE
+#include <emmintrin.h>             // SSE2
+#include <realm/realm_nmmintrin.h> // SSE42
+#endif
+
+namespace realm {
+
+template <class T>
+inline T no0(T v)
+{
+    return v == 0 ? 1 : v;
+}
+
+// Pre-definitions
+struct ObjKey;
+class Array;
+class GroupWriter;
+namespace _impl {
+class ArrayWriterBase;
+}
+
+template <class T>
+class BPlusTree;
+
+using KeyColumn = BPlusTree<ObjKey>;
+
+
+struct MemStats {
+    size_t allocated = 0;
+    size_t used = 0;
+    size_t array_count = 0;
+};
+
+#ifdef REALM_DEBUG
+template <class C, class T>
+std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, MemStats stats);
+#endif
+
+
+// Stores a value obtained from Array::get(). It is a ref if the least
+// significant bit is clear, otherwise it is a tagged integer. A tagged interger
+// is obtained from a logical integer value by left shifting by one bit position
+// (multiplying by two), and then setting the least significant bit to
+// one. Clearly, this means that the maximum value that can be stored as a
+// tagged integer is 2**63 - 1.
+class RefOrTagged {
+public:
+    bool is_ref() const noexcept;
+    bool is_tagged() const noexcept;
+    ref_type get_as_ref() const noexcept;
+    uint_fast64_t get_as_int() const noexcept;
+
+    static RefOrTagged make_ref(ref_type) noexcept;
+    static RefOrTagged make_tagged(uint_fast64_t) noexcept;
+
+private:
+    int_fast64_t m_value;
+    RefOrTagged(int_fast64_t) noexcept;
+    friend class Array;
+};
+
+
+struct TreeInsertBase {
+    size_t m_split_offset;
+    size_t m_split_size;
+};
+template <class T>
+class QueryStateFindAll : public QueryStateBase {
+public:
+    explicit QueryStateFindAll(T& keys, size_t limit = -1)
+        : QueryStateBase(limit)
+        , m_keys(keys)
+    {
+    }
+    bool match(size_t index, Mixed) noexcept final;
+
+private:
+    T& m_keys;
+};
+
+class QueryStateFindFirst : public QueryStateBase {
+public:
+    size_t m_state = realm::not_found;
+    QueryStateFindFirst()
+        : QueryStateBase(1)
+    {
+    }
+    bool match(size_t index, Mixed) noexcept final
+    {
+        m_match_count++;
+        m_state = index;
+        return false;
+    }
+};
+
+class Array : public Node, public ArrayParent {
+public:
+    //    void state_init(int action, QueryState *state);
+    //    bool match(int action, size_t index, int64_t value, QueryState *state);
+
+    /// Create an array accessor in the unattached state.
+    explicit Array(Allocator& allocator) noexcept
+        : Node(allocator)
+    {
+    }
+
+    ~Array() noexcept override {}
+
+    /// Create a new integer array of the specified type and size, and filled
+    /// with the specified value, and attach this accessor to it. This does not
+    /// modify the parent reference information of this accessor.
+    ///
+    /// Note that the caller assumes ownership of the allocated underlying
+    /// node. It is not owned by the accessor.
+    void create(Type, bool context_flag = false, size_t size = 0, int_fast64_t value = 0);
+
+    /// Reinitialize this array accessor to point to the specified new
+    /// underlying memory. This does not modify the parent reference information
+    /// of this accessor.
+    void init_from_ref(ref_type ref) noexcept
+    {
+        REALM_ASSERT_DEBUG(ref);
+        char* header = m_alloc.translate(ref);
+        init_from_mem(MemRef(header, ref, m_alloc));
+    }
+
+    /// Same as init_from_ref(ref_type) but avoid the mapping of 'ref' to memory
+    /// pointer.
+    void init_from_mem(MemRef) noexcept;
+
+    /// Same as `init_from_ref(get_ref_from_parent())`.
+    void init_from_parent() noexcept
+    {
+        ref_type ref = get_ref_from_parent();
+        init_from_ref(ref);
+    }
+
+    /// Called in the context of Group::commit() to ensure that attached
+    /// accessors stay valid across a commit. Please note that this works only
+    /// for non-transactional commits. Accessors obtained during a transaction
+    /// are always detached when the transaction ends.
+    void update_from_parent() noexcept;
+
+    /// Change the type of an already attached array node.
+    ///
+    /// The effect of calling this function on an unattached accessor is
+    /// undefined.
+    void set_type(Type);
+
+    /// Construct a complete copy of this array (including its subarrays) using
+    /// the specified target allocator and return just the reference to the
+    /// underlying memory.
+    MemRef clone_deep(Allocator& target_alloc) const;
+
+    /// Construct an empty integer array of the specified type, and return just
+    /// the reference to the underlying memory.
+    static MemRef create_empty_array(Type, bool context_flag, Allocator&);
+
+    /// Construct an integer array of the specified type and size, and return
+    /// just the reference to the underlying memory. All elements will be
+    /// initialized to the specified value.
+    static MemRef create_array(Type, bool context_flag, size_t size, int_fast64_t value, Allocator&);
+
+    Type get_type() const noexcept;
+
+    /// The meaning of 'width' depends on the context in which this
+    /// array is used.
+    size_t get_width() const noexcept
+    {
+        REALM_ASSERT_3(m_width, ==, get_width_from_header(get_header()));
+        return m_width;
+    }
+
+    static void add_to_column(IntegerColumn* column, int64_t value);
+    static void add_to_column(KeyColumn* column, int64_t value);
+
+    void insert(size_t ndx, int_fast64_t value);
+    void add(int_fast64_t value);
+
+    // Used from ArrayBlob
+    size_t blob_size() const noexcept;
+    ref_type blob_replace(size_t begin, size_t end, const char* data, size_t data_size, bool add_zero_term);
+
+    /// This function is guaranteed to not throw if the current width is
+    /// sufficient for the specified value (e.g. if you have called
+    /// ensure_minimum_width(value)) and get_alloc().is_read_only(get_ref())
+    /// returns false (noexcept:array-set). Note that for a value of zero, the
+    /// first criterion is trivially satisfied.
+    void set(size_t ndx, int64_t value);
+
+    void set_as_ref(size_t ndx, ref_type ref);
+
+    template <size_t w>
+    void set(size_t ndx, int64_t value);
+
+    int64_t get(size_t ndx) const noexcept;
+
+    template <size_t w>
+    int64_t get(size_t ndx) const noexcept;
+
+    void get_chunk(size_t ndx, int64_t res[8]) const noexcept;
+
+    template <size_t w>
+    void get_chunk(size_t ndx, int64_t res[8]) const noexcept;
+
+    ref_type get_as_ref(size_t ndx) const noexcept;
+
+    RefOrTagged get_as_ref_or_tagged(size_t ndx) const noexcept;
+    void set(size_t ndx, RefOrTagged);
+    void add(RefOrTagged);
+    void ensure_minimum_width(RefOrTagged);
+
+    int64_t front() const noexcept;
+    int64_t back() const noexcept;
+
+    void alloc(size_t init_size, size_t new_width)
+    {
+        REALM_ASSERT_3(m_width, ==, get_width_from_header(get_header()));
+        REALM_ASSERT_3(m_size, ==, get_size_from_header(get_header()));
+        Node::alloc(init_size, new_width);
+        update_width_cache_from_header();
+    }
+
+    /// Remove the element at the specified index, and move elements at higher
+    /// indexes to the next lower index.
+    ///
+    /// This function does **not** destroy removed subarrays. That is, if the
+    /// erased element is a 'ref' pointing to a subarray, then that subarray
+    /// will not be destroyed automatically.
+    ///
+    /// This function guarantees that no exceptions will be thrown if
+    /// get_alloc().is_read_only(get_ref()) would return false before the
+    /// call. This is automatically guaranteed if the array is used in a
+    /// non-transactional context, or if the array has already been successfully
+    /// modified within the current write transaction.
+    void erase(size_t ndx);
+
+    /// Same as erase(size_t), but remove all elements in the specified
+    /// range.
+    ///
+    /// Please note that this function does **not** destroy removed subarrays.
+    ///
+    /// This function guarantees that no exceptions will be thrown if
+    /// get_alloc().is_read_only(get_ref()) would return false before the call.
+    void erase(size_t begin, size_t end);
+
+    /// Reduce the size of this array to the specified number of elements. It is
+    /// an error to specify a size that is greater than the current size of this
+    /// array. The effect of doing so is undefined. This is just a shorthand for
+    /// calling the ranged erase() function with appropriate arguments.
+    ///
+    /// Please note that this function does **not** destroy removed
+    /// subarrays. See clear_and_destroy_children() for an alternative.
+    ///
+    /// This function guarantees that no exceptions will be thrown if
+    /// get_alloc().is_read_only(get_ref()) would return false before the call.
+    void truncate(size_t new_size);
+
+    /// Reduce the size of this array to the specified number of elements. It is
+    /// an error to specify a size that is greater than the current size of this
+    /// array. The effect of doing so is undefined. Subarrays will be destroyed
+    /// recursively, as if by a call to `destroy_deep(subarray_ref, alloc)`.
+    ///
+    /// This function is guaranteed not to throw if
+    /// get_alloc().is_read_only(get_ref()) returns false.
+    void truncate_and_destroy_children(size_t new_size);
+
+    /// Remove every element from this array. This is just a shorthand for
+    /// calling truncate(0).
+    ///
+    /// Please note that this function does **not** destroy removed
+    /// subarrays. See clear_and_destroy_children() for an alternative.
+    ///
+    /// This function guarantees that no exceptions will be thrown if
+    /// get_alloc().is_read_only(get_ref()) would return false before the call.
+    void clear();
+
+    /// Remove every element in this array. Subarrays will be destroyed
+    /// recursively, as if by a call to `destroy_deep(subarray_ref,
+    /// alloc)`. This is just a shorthand for calling
+    /// truncate_and_destroy_children(0).
+    ///
+    /// This function guarantees that no exceptions will be thrown if
+    /// get_alloc().is_read_only(get_ref()) would return false before the call.
+    void clear_and_destroy_children();
+
+    /// If neccessary, expand the representation so that it can store the
+    /// specified value.
+    void ensure_minimum_width(int_fast64_t value);
+
+    /// This one may change the represenation of the array, so be carefull if
+    /// you call it after ensure_minimum_width().
+    void set_all_to_zero();
+
+    /// Add \a diff to the element at the specified index.
+    void adjust(size_t ndx, int_fast64_t diff);
+
+    /// Add \a diff to all the elements in the specified index range.
+    void adjust(size_t begin, size_t end, int_fast64_t diff);
+
+    //@{
+    /// This is similar in spirit to std::move() from `<algorithm>`.
+    /// \a dest_begin must not be in the range [`begin`,`end`)
+    ///
+    /// This function is guaranteed to not throw if
+    /// `get_alloc().is_read_only(get_ref())` returns false.
+    void move(size_t begin, size_t end, size_t dest_begin);
+    //@}
+
+    // Move elements from ndx and above to another array
+    void move(Array& dst, size_t ndx);
+
+    //@{
+    /// Find the lower/upper bound of the specified value in a sequence of
+    /// integers which must already be sorted ascendingly.
+    ///
+    /// For an integer value '`v`', lower_bound_int(v) returns the index '`l`'
+    /// of the first element such that `get(l) &ge; v`, and upper_bound_int(v)
+    /// returns the index '`u`' of the first element such that `get(u) &gt;
+    /// v`. In both cases, if no such element is found, the returned value is
+    /// the number of elements in the array.
+    ///
+    ///     3 3 3 4 4 4 5 6 7 9 9 9
+    ///     ^     ^     ^     ^     ^
+    ///     |     |     |     |     |
+    ///     |     |     |     |      -- Lower and upper bound of 15
+    ///     |     |     |     |
+    ///     |     |     |      -- Lower and upper bound of 8
+    ///     |     |     |
+    ///     |     |      -- Upper bound of 4
+    ///     |     |
+    ///     |      -- Lower bound of 4
+    ///     |
+    ///      -- Lower and upper bound of 1
+    ///
+    /// These functions are similar to std::lower_bound() and
+    /// std::upper_bound().
+    ///
+    /// We currently use binary search. See for example
+    /// http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary.
+    ///
+    /// FIXME: It may be worth considering if overall efficiency can be improved
+    /// by doing a linear search for short sequences.
+    size_t lower_bound_int(int64_t value) const noexcept;
+    size_t upper_bound_int(int64_t value) const noexcept;
+    //@}
+
+    int64_t get_sum(size_t start = 0, size_t end = size_t(-1)) const
+    {
+        return sum(start, end);
+    }
+
+    /// This information is guaranteed to be cached in the array accessor.
+    bool is_inner_bptree_node() const noexcept;
+
+    /// Returns true if type is either type_HasRefs or type_InnerColumnNode.
+    ///
+    /// This information is guaranteed to be cached in the array accessor.
+    bool has_refs() const noexcept;
+    void set_has_refs(bool) noexcept;
+
+    /// This information is guaranteed to be cached in the array accessor.
+    ///
+    /// Columns and indexes can use the context bit to differentiate leaf types.
+    bool get_context_flag() const noexcept;
+    void set_context_flag(bool) noexcept;
+
+    /// Recursively destroy children (as if calling
+    /// clear_and_destroy_children()), then put this accessor into the detached
+    /// state (as if calling detach()), then free the allocated memory. If this
+    /// accessor is already in the detached state, this function has no effect
+    /// (idempotency).
+    void destroy_deep() noexcept;
+
+    /// Shorthand for `destroy_deep(MemRef(ref, alloc), alloc)`.
+    static void destroy_deep(ref_type ref, Allocator& alloc) noexcept;
+
+    /// Destroy the specified array node and all of its children, recursively.
+    ///
+    /// This is done by freeing the specified array node after calling
+    /// destroy_deep() for every contained 'ref' element.
+    static void destroy_deep(MemRef, Allocator&) noexcept;
+
+    // Clone deep
+    static MemRef clone(MemRef, Allocator& from_alloc, Allocator& target_alloc);
+
+    // Serialization
+
+    /// Returns the ref (position in the target stream) of the written copy of
+    /// this array, or the ref of the original array if \a only_if_modified is
+    /// true, and this array is unmodified (Alloc::is_read_only()).
+    ///
+    /// The number of bytes that will be written by a non-recursive invocation
+    /// of this function is exactly the number returned by get_byte_size().
+    ///
+    /// \param out The destination stream (writer).
+    ///
+    /// \param deep If true, recursively write out subarrays, but still subject
+    /// to \a only_if_modified.
+    ///
+    /// \param only_if_modified Set to `false` to always write, or to `true` to
+    /// only write the array if it has been modified.
+    ref_type write(_impl::ArrayWriterBase& out, bool deep, bool only_if_modified) const;
+
+    /// Same as non-static write() with `deep` set to true. This is for the
+    /// cases where you do not already have an array accessor available.
+    static ref_type write(ref_type, Allocator&, _impl::ArrayWriterBase&, bool only_if_modified);
+
+    // Main finding function - used for find_first, find_all, sum, max, min, etc.
+    bool find(int cond, int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state) const;
+
+    template <class cond, class Callback>
+    bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+              Callback callback) const;
+
+    // Wrappers for backwards compatibility and for simple use without
+    // setting up state initialization etc
+    template <class cond>
+    size_t find_first(int64_t value, size_t start = 0, size_t end = size_t(-1)) const;
+
+    void find_all(IntegerColumn* result, int64_t value, size_t col_offset = 0, size_t begin = 0,
+                  size_t end = size_t(-1)) const;
+
+    size_t find_first(int64_t value, size_t begin = 0, size_t end = size_t(-1)) const;
+
+    // Non-SSE find for the four functions Equal/NotEqual/Less/Greater
+    template <class cond, size_t bitwidth, class Callback>
+    bool compare(int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                 Callback callback) const;
+
+    // Non-SSE find for Equal/NotEqual
+    template <bool eq, size_t width, class Callback>
+    inline bool compare_equality(int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                                 Callback callback) const;
+
+    // Non-SSE find for Less/Greater
+    template <bool gt, size_t bitwidth, class Callback>
+    bool compare_relation(int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                          Callback callback) const;
+
+    template <class cond, size_t foreign_width, class Callback, size_t width>
+    bool compare_leafs_4(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                         Callback callback) const;
+
+    template <class cond, class Callback>
+    bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                       Callback callback) const;
+
+    template <class cond, size_t width, class Callback>
+    bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                       Callback callback) const;
+
+// SSE find for the four functions Equal/NotEqual/Less/Greater
+#ifdef REALM_COMPILER_SSE
+    template <class cond, size_t width, class Callback>
+    bool find_sse(int64_t value, __m128i* data, size_t items, QueryStateBase* state, size_t baseindex,
+                  Callback callback) const;
+
+    template <class cond, size_t width, class Callback>
+    REALM_FORCEINLINE bool find_sse_intern(__m128i* action_data, __m128i* data, size_t items, QueryStateBase* state,
+                                           size_t baseindex, Callback callback) const;
+
+#endif
+
+    template <size_t width>
+    inline bool test_zero(uint64_t value) const; // Tests value for 0-elements
+
+    template <bool eq, size_t width>
+    size_t find_zero(uint64_t v) const; // Finds position of 0/non-zero element
+
+    template <size_t width, bool zero>
+    uint64_t cascade(uint64_t a) const; // Sets lowermost bits of zero or non-zero elements
+
+    template <bool gt, size_t width>
+    int64_t
+    find_gtlt_magic(int64_t v) const; // Compute magic constant needed for searching for value 'v' using bit hacks
+
+    template <size_t width>
+    inline int64_t lower_bits() const; // Return chunk with lower bit set in each element
+
+    size_t first_set_bit(unsigned int v) const;
+    size_t first_set_bit64(int64_t v) const;
+
+    template <size_t w>
+    int64_t get_universal(const char* const data, const size_t ndx) const;
+
+    // Find value greater/less in 64-bit chunk - only works for positive values
+    template <bool gt, size_t width, class Callback>
+    bool find_gtlt_fast(uint64_t chunk, uint64_t magic, QueryStateBase* state, size_t baseindex,
+                        Callback callback) const;
+
+    // Find value greater/less in 64-bit chunk - no constraints
+    template <bool gt, size_t width, class Callback>
+    bool find_gtlt(int64_t v, uint64_t chunk, QueryStateBase* state, size_t baseindex, Callback callback) const;
+
+    /// Get the specified element without the cost of constructing an
+    /// array instance. If an array instance is already available, or
+    /// you need to get multiple values, then this method will be
+    /// slower.
+    static int_fast64_t get(const char* header, size_t ndx) noexcept;
+
+    /// Like get(const char*, size_t) but gets two consecutive
+    /// elements.
+    static std::pair<int64_t, int64_t> get_two(const char* header, size_t ndx) noexcept;
+
+    static void get_three(const char* data, size_t ndx, ref_type& v0, ref_type& v1, ref_type& v2) noexcept;
+
+    static RefOrTagged get_as_ref_or_tagged(const char* header, size_t ndx) noexcept
+    {
+        return get(header, ndx);
+    }
+
+    /// Get the number of bytes currently in use by this array. This
+    /// includes the array header, but it does not include allocated
+    /// bytes corresponding to excess capacity. The result is
+    /// guaranteed to be a multiple of 8 (i.e., 64-bit aligned).
+    ///
+    /// This number is exactly the number of bytes that will be
+    /// written by a non-recursive invocation of write().
+    size_t get_byte_size() const noexcept;
+
+    /// Get the maximum number of bytes that can be written by a
+    /// non-recursive invocation of write() on an array with the
+    /// specified number of elements, that is, the maximum value that
+    /// can be returned by get_byte_size().
+    static size_t get_max_byte_size(size_t num_elems) noexcept;
+
+    /// FIXME: Belongs in IntegerArray
+    static size_t calc_aligned_byte_size(size_t size, int width);
+
+    class MemUsageHandler {
+    public:
+        virtual void handle(ref_type ref, size_t allocated, size_t used) = 0;
+    };
+
+    void report_memory_usage(MemUsageHandler&) const;
+
+    void stats(MemStats& stats_dest) const noexcept;
+
+    void verify() const;
+
+    Array& operator=(const Array&) = delete; // not allowed
+    Array(const Array&) = delete;            // not allowed
+
+protected:
+    // This returns the minimum value ("lower bound") of the representable values
+    // for the given bit width. Valid widths are 0, 1, 2, 4, 8, 16, 32, and 64.
+    static constexpr int_fast64_t lbound_for_width(size_t width) noexcept;
+
+    // This returns the maximum value ("inclusive upper bound") of the representable values
+    // for the given bit width. Valid widths are 0, 1, 2, 4, 8, 16, 32, and 64.
+    static constexpr int_fast64_t ubound_for_width(size_t width) noexcept;
+
+private:
+    void update_width_cache_from_header() noexcept;
+
+    void do_ensure_minimum_width(int_fast64_t);
+
+    int64_t sum(size_t start, size_t end) const;
+    size_t count(int64_t value) const noexcept;
+
+    bool maximum(int64_t& result, size_t start = 0, size_t end = size_t(-1), size_t* return_ndx = nullptr) const;
+
+    bool minimum(int64_t& result, size_t start = 0, size_t end = size_t(-1), size_t* return_ndx = nullptr) const;
+
+    template <size_t w>
+    int64_t sum(size_t start, size_t end) const;
+
+    template <bool max, size_t w>
+    bool minmax(int64_t& result, size_t start, size_t end, size_t* return_ndx) const;
+
+protected:
+    /// It is an error to specify a non-zero value unless the width
+    /// type is wtype_Bits. It is also an error to specify a non-zero
+    /// size if the width type is wtype_Ignore.
+    static MemRef create(Type, bool context_flag, WidthType, size_t size, int_fast64_t value, Allocator&);
+
+    // Overriding method in ArrayParent
+    void update_child_ref(size_t, ref_type) override;
+
+    // Overriding method in ArrayParent
+    ref_type get_child_ref(size_t) const noexcept override;
+
+    void destroy_children(size_t offset = 0) noexcept;
+
+protected:
+    // Getters and Setters for adaptive-packed arrays
+    typedef int64_t (Array::*Getter)(size_t) const; // Note: getters must not throw
+    typedef void (Array::*Setter)(size_t, int64_t);
+    typedef bool (Array::*Finder)(int64_t, size_t, size_t, size_t, QueryStateBase*) const;
+    typedef void (Array::*ChunkGetter)(size_t, int64_t res[8]) const; // Note: getters must not throw
+
+    struct VTable {
+        Getter getter;
+        ChunkGetter chunk_getter;
+        Setter setter;
+        Finder finder[cond_VTABLE_FINDER_COUNT]; // one for each active function pointer
+    };
+    template <size_t w>
+    struct VTableForWidth;
+
+    // This is the one installed into the m_vtable->finder slots.
+    template <class cond, size_t bitwidth>
+    bool find_vtable(int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state) const;
+
+
+protected:
+    /// Takes a 64-bit value and returns the minimum number of bits needed
+    /// to fit the value. For alignment this is rounded up to nearest
+    /// log2. Posssible results {0, 1, 2, 4, 8, 16, 32, 64}
+    static size_t bit_width(int64_t value);
+
+    void report_memory_usage_2(MemUsageHandler&) const;
+
+private:
+    Getter m_getter = nullptr; // cached to avoid indirection
+    const VTable* m_vtable = nullptr;
+
+protected:
+    uint_least8_t m_width = 0; // Size of an element (meaning depend on type of array).
+    int64_t m_lbound;          // min number that can be stored with current m_width
+    int64_t m_ubound;          // max number that can be stored with current m_width
+
+    bool m_is_inner_bptree_node; // This array is an inner node of B+-tree.
+    bool m_has_refs;             // Elements whose first bit is zero are refs to subarrays.
+    bool m_context_flag;         // Meaning depends on context.
+
+private:
+    ref_type do_write_shallow(_impl::ArrayWriterBase&) const;
+    ref_type do_write_deep(_impl::ArrayWriterBase&, bool only_if_modified) const;
+
+    friend class Allocator;
+    friend class SlabAlloc;
+    friend class GroupWriter;
+
+    // Optimized implementation for release mode
+    template <class cond, size_t bitwidth, class Callback>
+    bool find_optimized(int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                        Callback callback) const;
+
+protected:
+    // Called for each search result
+    template <class Callback>
+    bool find_action(size_t index, util::Optional<int64_t> value, QueryStateBase* state, Callback callback) const;
+
+    bool find_action_pattern(size_t index, uint64_t pattern, QueryStateBase* state) const;
+    template <size_t bitwidth, class Callback>
+    bool find_all_will_match(size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                             Callback callback) const;
+};
+
+class ClusterKeyArray : public ArrayUnsigned {
+public:
+    using ArrayUnsigned::ArrayUnsigned;
+
+    uint64_t get(size_t ndx) const
+    {
+        return (m_data != nullptr) ? ArrayUnsigned::get(ndx) : uint64_t(ndx);
+    }
+};
+
+// Implementation:
+
+
+constexpr inline int_fast64_t Array::lbound_for_width(size_t width) noexcept
+{
+    if (width == 32) {
+        return -0x80000000LL;
+    }
+    else if (width == 16) {
+        return -0x8000LL;
+    }
+    else if (width < 8) {
+        return 0;
+    }
+    else if (width == 8) {
+        return -0x80LL;
+    }
+    else if (width == 64) {
+        return -0x8000000000000000LL;
+    }
+    else {
+        REALM_UNREACHABLE();
+    }
+}
+
+constexpr inline int_fast64_t Array::ubound_for_width(size_t width) noexcept
+{
+    if (width == 32) {
+        return 0x7FFFFFFFLL;
+    }
+    else if (width == 16) {
+        return 0x7FFFLL;
+    }
+    else if (width == 0) {
+        return 0;
+    }
+    else if (width == 1) {
+        return 1;
+    }
+    else if (width == 2) {
+        return 3;
+    }
+    else if (width == 4) {
+        return 15;
+    }
+    else if (width == 8) {
+        return 0x7FLL;
+    }
+    else if (width == 64) {
+        return 0x7FFFFFFFFFFFFFFFLL;
+    }
+    else {
+        REALM_UNREACHABLE();
+    }
+}
+
+inline bool RefOrTagged::is_ref() const noexcept
+{
+    return (m_value & 1) == 0;
+}
+
+inline bool RefOrTagged::is_tagged() const noexcept
+{
+    return !is_ref();
+}
+
+inline ref_type RefOrTagged::get_as_ref() const noexcept
+{
+    // to_ref() is defined in <alloc.hpp>
+    return to_ref(m_value);
+}
+
+inline uint_fast64_t RefOrTagged::get_as_int() const noexcept
+{
+    // The bitwise AND is there in case uint_fast64_t is wider than 64 bits.
+    return (uint_fast64_t(m_value) & 0xFFFFFFFFFFFFFFFFULL) >> 1;
+}
+
+inline RefOrTagged RefOrTagged::make_ref(ref_type ref) noexcept
+{
+    // from_ref() is defined in <alloc.hpp>
+    int_fast64_t value = from_ref(ref);
+    return RefOrTagged(value);
+}
+
+inline RefOrTagged RefOrTagged::make_tagged(uint_fast64_t i) noexcept
+{
+    REALM_ASSERT(i < (1ULL << 63));
+    return RefOrTagged((i << 1) | 1);
+}
+
+inline RefOrTagged::RefOrTagged(int_fast64_t value) noexcept
+    : m_value(value)
+{
+}
+
+inline void Array::create(Type type, bool context_flag, size_t length, int_fast64_t value)
+{
+    MemRef mem = create_array(type, context_flag, length, value, m_alloc); // Throws
+    init_from_mem(mem);
+}
+
+
+inline Array::Type Array::get_type() const noexcept
+{
+    if (m_is_inner_bptree_node) {
+        REALM_ASSERT_DEBUG(m_has_refs);
+        return type_InnerBptreeNode;
+    }
+    if (m_has_refs)
+        return type_HasRefs;
+    return type_Normal;
+}
+
+
+inline void Array::get_chunk(size_t ndx, int64_t res[8]) const noexcept
+{
+    REALM_ASSERT_DEBUG(ndx < m_size);
+    (this->*(m_vtable->chunk_getter))(ndx, res);
+}
+
+
+inline int64_t Array::get(size_t ndx) const noexcept
+{
+    REALM_ASSERT_DEBUG(is_attached());
+    REALM_ASSERT_DEBUG(ndx < m_size);
+    return (this->*m_getter)(ndx);
+
+    // Two ideas that are not efficient but may be worth looking into again:
+    /*
+        // Assume correct width is found early in REALM_TEMPEX, which is the case for B tree offsets that
+        // are probably either 2^16 long. Turns out to be 25% faster if found immediately, but 50-300% slower
+        // if found later
+        REALM_TEMPEX(return get, (ndx));
+    */
+    /*
+        // Slightly slower in both of the if-cases. Also needs an matchcount m_size check too, to avoid
+        // reading beyond array.
+        if (m_width >= 8 && m_size > ndx + 7)
+            return get<64>(ndx >> m_shift) & m_widthmask;
+        else
+            return (this->*(m_vtable->getter))(ndx);
+    */
+}
+
+inline int64_t Array::front() const noexcept
+{
+    return get(0);
+}
+
+inline int64_t Array::back() const noexcept
+{
+    return get(m_size - 1);
+}
+
+inline ref_type Array::get_as_ref(size_t ndx) const noexcept
+{
+    REALM_ASSERT_DEBUG(is_attached());
+    REALM_ASSERT_DEBUG(m_has_refs);
+    int64_t v = get(ndx);
+    return to_ref(v);
+}
+
+inline RefOrTagged Array::get_as_ref_or_tagged(size_t ndx) const noexcept
+{
+    REALM_ASSERT(has_refs());
+    return RefOrTagged(get(ndx));
+}
+
+inline void Array::set(size_t ndx, RefOrTagged ref_or_tagged)
+{
+    REALM_ASSERT(has_refs());
+    set(ndx, ref_or_tagged.m_value); // Throws
+}
+
+inline void Array::add(RefOrTagged ref_or_tagged)
+{
+    REALM_ASSERT(has_refs());
+    add(ref_or_tagged.m_value); // Throws
+}
+
+inline void Array::ensure_minimum_width(RefOrTagged ref_or_tagged)
+{
+    REALM_ASSERT(has_refs());
+    ensure_minimum_width(ref_or_tagged.m_value); // Throws
+}
+
+inline bool Array::is_inner_bptree_node() const noexcept
+{
+    return m_is_inner_bptree_node;
+}
+
+inline bool Array::has_refs() const noexcept
+{
+    return m_has_refs;
+}
+
+inline void Array::set_has_refs(bool value) noexcept
+{
+    if (m_has_refs != value) {
+        REALM_ASSERT(!is_read_only());
+        m_has_refs = value;
+        set_hasrefs_in_header(value, get_header());
+    }
+}
+
+inline bool Array::get_context_flag() const noexcept
+{
+    return m_context_flag;
+}
+
+inline void Array::set_context_flag(bool value) noexcept
+{
+    if (m_context_flag != value) {
+        copy_on_write();
+        m_context_flag = value;
+        set_context_flag_in_header(value, get_header());
+    }
+}
+
+inline void Array::destroy_deep() noexcept
+{
+    if (!is_attached())
+        return;
+
+    if (m_has_refs)
+        destroy_children();
+
+    char* header = get_header_from_data(m_data);
+    m_alloc.free_(m_ref, header);
+    m_data = nullptr;
+}
+
+inline ref_type Array::write(_impl::ArrayWriterBase& out, bool deep, bool only_if_modified) const
+{
+    REALM_ASSERT(is_attached());
+
+    if (only_if_modified && m_alloc.is_read_only(m_ref))
+        return m_ref;
+
+    if (!deep || !m_has_refs)
+        return do_write_shallow(out); // Throws
+
+    return do_write_deep(out, only_if_modified); // Throws
+}
+
+inline ref_type Array::write(ref_type ref, Allocator& alloc, _impl::ArrayWriterBase& out, bool only_if_modified)
+{
+    if (only_if_modified && alloc.is_read_only(ref))
+        return ref;
+
+    Array array(alloc);
+    array.init_from_ref(ref);
+
+    if (!array.m_has_refs)
+        return array.do_write_shallow(out); // Throws
+
+    return array.do_write_deep(out, only_if_modified); // Throws
+}
+
+inline void Array::add(int_fast64_t value)
+{
+    insert(m_size, value);
+}
+
+inline void Array::erase(size_t ndx)
+{
+    // This can throw, but only if array is currently in read-only
+    // memory.
+    move(ndx + 1, size(), ndx);
+
+    // Update size (also in header)
+    --m_size;
+    set_header_size(m_size);
+}
+
+
+inline void Array::erase(size_t begin, size_t end)
+{
+    if (begin != end) {
+        // This can throw, but only if array is currently in read-only memory.
+        move(end, size(), begin); // Throws
+
+        // Update size (also in header)
+        m_size -= end - begin;
+        set_header_size(m_size);
+    }
+}
+
+inline void Array::clear()
+{
+    truncate(0); // Throws
+}
+
+inline void Array::clear_and_destroy_children()
+{
+    truncate_and_destroy_children(0);
+}
+
+inline void Array::destroy_deep(ref_type ref, Allocator& alloc) noexcept
+{
+    destroy_deep(MemRef(ref, alloc), alloc);
+}
+
+inline void Array::destroy_deep(MemRef mem, Allocator& alloc) noexcept
+{
+    if (!get_hasrefs_from_header(mem.get_addr())) {
+        alloc.free_(mem);
+        return;
+    }
+    Array array(alloc);
+    array.init_from_mem(mem);
+    array.destroy_deep();
+}
+
+
+inline void Array::adjust(size_t ndx, int_fast64_t diff)
+{
+    REALM_ASSERT_3(ndx, <=, m_size);
+    if (diff != 0) {
+        // FIXME: Should be optimized
+        int_fast64_t v = get(ndx);
+        set(ndx, int64_t(v + diff)); // Throws
+    }
+}
+
+inline void Array::adjust(size_t begin, size_t end, int_fast64_t diff)
+{
+    if (diff != 0) {
+        // FIXME: Should be optimized
+        for (size_t i = begin; i != end; ++i)
+            adjust(i, diff); // Throws
+    }
+}
+
+
+//-------------------------------------------------
+
+
+inline size_t Array::get_byte_size() const noexcept
+{
+    const char* header = get_header_from_data(m_data);
+    WidthType wtype = Node::get_wtype_from_header(header);
+    size_t num_bytes = NodeHeader::calc_byte_size(wtype, m_size, m_width);
+
+    REALM_ASSERT_7(m_alloc.is_read_only(m_ref), ==, true, ||, num_bytes, <=, get_capacity_from_header(header));
+
+    return num_bytes;
+}
+
+
+//-------------------------------------------------
+
+inline MemRef Array::clone_deep(Allocator& target_alloc) const
+{
+    char* header = get_header_from_data(m_data);
+    return clone(MemRef(header, m_ref, m_alloc), m_alloc, target_alloc); // Throws
+}
+
+inline MemRef Array::create_empty_array(Type type, bool context_flag, Allocator& alloc)
+{
+    size_t size = 0;
+    int_fast64_t value = 0;
+    return create_array(type, context_flag, size, value, alloc); // Throws
+}
+
+inline MemRef Array::create_array(Type type, bool context_flag, size_t size, int_fast64_t value, Allocator& alloc)
+{
+    return create(type, context_flag, wtype_Bits, size, value, alloc); // Throws
+}
+
+inline size_t Array::get_max_byte_size(size_t num_elems) noexcept
+{
+    int max_bytes_per_elem = 8;
+    return header_size + num_elems * max_bytes_per_elem;
+}
+
+
+inline void Array::update_child_ref(size_t child_ndx, ref_type new_ref)
+{
+    set(child_ndx, new_ref);
+}
+
+inline ref_type Array::get_child_ref(size_t child_ndx) const noexcept
+{
+    return get_as_ref(child_ndx);
+}
+
+inline void Array::ensure_minimum_width(int_fast64_t value)
+{
+    if (value >= m_lbound && value <= m_ubound)
+        return;
+    do_ensure_minimum_width(value);
+}
+
+
+//*************************************************************************************
+// Finding code                                                                       *
+//*************************************************************************************
+
+template <size_t w>
+int64_t Array::get(size_t ndx) const noexcept
+{
+    return get_universal<w>(m_data, ndx);
+}
+
+template <size_t w>
+int64_t Array::get_universal(const char* data, size_t ndx) const
+{
+    if (w == 0) {
+        return 0;
+    }
+    else if (w == 1) {
+        size_t offset = ndx >> 3;
+        return (data[offset] >> (ndx & 7)) & 0x01;
+    }
+    else if (w == 2) {
+        size_t offset = ndx >> 2;
+        return (data[offset] >> ((ndx & 3) << 1)) & 0x03;
+    }
+    else if (w == 4) {
+        size_t offset = ndx >> 1;
+        return (data[offset] >> ((ndx & 1) << 2)) & 0x0F;
+    }
+    else if (w == 8) {
+        return *reinterpret_cast<const signed char*>(data + ndx);
+    }
+    else if (w == 16) {
+        size_t offset = ndx * 2;
+        return *reinterpret_cast<const int16_t*>(data + offset);
+    }
+    else if (w == 32) {
+        size_t offset = ndx * 4;
+        return *reinterpret_cast<const int32_t*>(data + offset);
+    }
+    else if (w == 64) {
+        size_t offset = ndx * 8;
+        return *reinterpret_cast<const int64_t*>(data + offset);
+    }
+    else {
+        REALM_ASSERT_DEBUG(false);
+        return int64_t(-1);
+    }
+}
+
+/*
+find() (calls find_optimized()) may call find_action for each search result.
+
+'index' tells the row index of a single match and 'value' tells its value. Return false to make Array-finder break
+its search or return true to let it continue until 'end' or 'limit'.
+*/
+template <class Callback>
+bool Array::find_action(size_t index, util::Optional<int64_t>, QueryStateBase*, Callback callback) const
+{
+    return callback(index);
+}
+
+// This function is used when there is no callback. Here we will just perform the action implemented in 'state'.
+template <>
+inline bool Array::find_action<std::nullptr_t>(size_t index, util::Optional<int64_t> value, QueryStateBase* state,
+                                               std::nullptr_t) const
+{
+    return state->match(index, value);
+}
+
+/*
+find() (calls find_optimized()) may call find_action_pattern before calling find_action.
+
+'indexpattern' contains a 64-bit chunk of elements, each of 'width' bits in size where each element indicates a
+match if its lower bit is set, otherwise it indicates a non-match. 'index' tells the database row index of the
+first element. You must return true if you chose to 'consume' the chunk or false if not. If not, then Array-finder
+will afterwards call match() successive times with pattern == false.
+
+Array-finder decides itself if - and when - it wants to pass you an indexpattern. It depends on array bit width, match
+frequency, and whether the arithemetic and computations for the given search criteria makes it feasible to construct
+such a pattern.
+*/
+inline bool Array::find_action_pattern(size_t /*index*/, uint64_t /*pattern*/, QueryStateBase* /*st*/) const
+{
+    // return st->match_pattern(index, pattern); FIXME: Use for act_Count
+    return false;
+}
+
+
+template <size_t width, bool zero>
+uint64_t Array::cascade(uint64_t a) const
+{
+    // Takes a chunk of values as argument and sets the least significant bit for each
+    // element which is zero or non-zero, depending on the template parameter.
+    // Example for zero=true:
+    // width == 4 and a = 0x5fd07a107610f610
+    // will return:       0x0001000100010001
+
+    // static values needed for fast population count
+    const uint64_t m1 = 0x5555555555555555ULL;
+
+    if (width == 1) {
+        return zero ? ~a : a;
+    }
+    else if (width == 2) {
+        // Masks to avoid spillover between segments in cascades
+        const uint64_t c1 = ~0ULL / 0x3 * 0x1;
+
+        a |= (a >> 1) & c1; // cascade ones in non-zeroed segments
+        a &= m1;            // isolate single bit in each segment
+        if (zero)
+            a ^= m1; // reverse isolated bits if checking for zeroed segments
+
+        return a;
+    }
+    else if (width == 4) {
+        const uint64_t m = ~0ULL / 0xF * 0x1;
+
+        // Masks to avoid spillover between segments in cascades
+        const uint64_t c1 = ~0ULL / 0xF * 0x7;
+        const uint64_t c2 = ~0ULL / 0xF * 0x3;
+
+        a |= (a >> 1) & c1; // cascade ones in non-zeroed segments
+        a |= (a >> 2) & c2;
+        a &= m; // isolate single bit in each segment
+        if (zero)
+            a ^= m; // reverse isolated bits if checking for zeroed segments
+
+        return a;
+    }
+    else if (width == 8) {
+        const uint64_t m = ~0ULL / 0xFF * 0x1;
+
+        // Masks to avoid spillover between segments in cascades
+        const uint64_t c1 = ~0ULL / 0xFF * 0x7F;
+        const uint64_t c2 = ~0ULL / 0xFF * 0x3F;
+        const uint64_t c3 = ~0ULL / 0xFF * 0x0F;
+
+        a |= (a >> 1) & c1; // cascade ones in non-zeroed segments
+        a |= (a >> 2) & c2;
+        a |= (a >> 4) & c3;
+        a &= m; // isolate single bit in each segment
+        if (zero)
+            a ^= m; // reverse isolated bits if checking for zeroed segments
+
+        return a;
+    }
+    else if (width == 16) {
+        const uint64_t m = ~0ULL / 0xFFFF * 0x1;
+
+        // Masks to avoid spillover between segments in cascades
+        const uint64_t c1 = ~0ULL / 0xFFFF * 0x7FFF;
+        const uint64_t c2 = ~0ULL / 0xFFFF * 0x3FFF;
+        const uint64_t c3 = ~0ULL / 0xFFFF * 0x0FFF;
+        const uint64_t c4 = ~0ULL / 0xFFFF * 0x00FF;
+
+        a |= (a >> 1) & c1; // cascade ones in non-zeroed segments
+        a |= (a >> 2) & c2;
+        a |= (a >> 4) & c3;
+        a |= (a >> 8) & c4;
+        a &= m; // isolate single bit in each segment
+        if (zero)
+            a ^= m; // reverse isolated bits if checking for zeroed segments
+
+        return a;
+    }
+
+    else if (width == 32) {
+        const uint64_t m = ~0ULL / 0xFFFFFFFF * 0x1;
+
+        // Masks to avoid spillover between segments in cascades
+        const uint64_t c1 = ~0ULL / 0xFFFFFFFF * 0x7FFFFFFF;
+        const uint64_t c2 = ~0ULL / 0xFFFFFFFF * 0x3FFFFFFF;
+        const uint64_t c3 = ~0ULL / 0xFFFFFFFF * 0x0FFFFFFF;
+        const uint64_t c4 = ~0ULL / 0xFFFFFFFF * 0x00FFFFFF;
+        const uint64_t c5 = ~0ULL / 0xFFFFFFFF * 0x0000FFFF;
+
+        a |= (a >> 1) & c1; // cascade ones in non-zeroed segments
+        a |= (a >> 2) & c2;
+        a |= (a >> 4) & c3;
+        a |= (a >> 8) & c4;
+        a |= (a >> 16) & c5;
+        a &= m; // isolate single bit in each segment
+        if (zero)
+            a ^= m; // reverse isolated bits if checking for zeroed segments
+
+        return a;
+    }
+    else if (width == 64) {
+        return (a == 0) == zero;
+    }
+    else {
+        REALM_ASSERT_DEBUG(false);
+        return uint64_t(-1);
+    }
+}
+
+template <size_t bitwidth, class Callback>
+REALM_NOINLINE bool Array::find_all_will_match(size_t start2, size_t end, size_t baseindex, QueryStateBase* state,
+                                               Callback callback) const
+{
+    size_t end2;
+
+    if constexpr (!std::is_same_v<Callback, std::nullptr_t>)
+        end2 = end;
+    else {
+        REALM_ASSERT_DEBUG(state->m_match_count < state->m_limit);
+        size_t process = state->m_limit - state->m_match_count;
+        end2 = end - start2 > process ? start2 + process : end;
+    }
+    for (; start2 < end2; start2++)
+        if (!find_action(start2 + baseindex, get<bitwidth>(start2), state, callback))
+            return false;
+    return true;
+}
+
+// This is the main finding function for Array. Other finding functions are just wrappers around this one.
+// Search for 'value' using condition cond (Equal, NotEqual, Less, etc) and call find_action() or
+// find_action_pattern() for each match. Break and return if find_action() returns false or 'end' is reached.
+template <class cond, size_t bitwidth, class Callback>
+bool Array::find_optimized(int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                           Callback callback) const
+{
+    REALM_ASSERT_DEBUG(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end);
+
+    size_t start2 = start;
+    cond c;
+
+    if (end == npos)
+        end = m_size;
+
+    if (!(m_size > start2 && start2 < end))
+        return true;
+
+    constexpr int64_t lbound = lbound_for_width(bitwidth);
+    constexpr int64_t ubound = ubound_for_width(bitwidth);
+
+    // Return immediately if no items in array can match (such as if cond == Greater && value == 100 &&
+    // m_ubound == 15)
+    if (!c.can_match(value, lbound, ubound))
+        return true;
+
+    // optimization if all items are guaranteed to match (such as cond == NotEqual && value == 100 && m_ubound == 15)
+    if (c.will_match(value, lbound, ubound)) {
+        return find_all_will_match<bitwidth, Callback>(start2, end, baseindex, state, callback);
+    }
+
+    // finder cannot handle this bitwidth
+    REALM_ASSERT_3(m_width, !=, 0);
+
+#if defined(REALM_COMPILER_SSE)
+    // Only use SSE if payload is at least one SSE chunk (128 bits) in size. Also note taht SSE doesn't support
+    // Less-than comparison for 64-bit values.
+    if ((!(std::is_same<cond, Less>::value && m_width == 64)) && end - start2 >= sizeof(__m128i) && m_width >= 8 &&
+        (sseavx<42>() || (sseavx<30>() && std::is_same<cond, Equal>::value && m_width < 64))) {
+
+        // find_sse() must start2 at 16-byte boundary, so search area before that using compare_equality()
+        __m128i* const a = reinterpret_cast<__m128i*>(round_up(m_data + start2 * bitwidth / 8, sizeof(__m128i)));
+        __m128i* const b = reinterpret_cast<__m128i*>(round_down(m_data + end * bitwidth / 8, sizeof(__m128i)));
+
+        if (!compare<cond, bitwidth, Callback>(
+                value, start2, (reinterpret_cast<char*>(a) - m_data) * 8 / no0(bitwidth), baseindex, state, callback))
+            return false;
+
+        // Search aligned area with SSE
+        if (b > a) {
+            if (sseavx<42>()) {
+                if (!find_sse<cond, bitwidth, Callback>(
+                        value, a, b - a, state,
+                        baseindex + ((reinterpret_cast<char*>(a) - m_data) * 8 / no0(bitwidth)), callback))
+                    return false;
+            }
+            else if (sseavx<30>()) {
+
+                if (!find_sse<Equal, bitwidth, Callback>(
+                        value, a, b - a, state,
+                        baseindex + ((reinterpret_cast<char*>(a) - m_data) * 8 / no0(bitwidth)), callback))
+                    return false;
+            }
+        }
+
+        // Search remainder with compare_equality()
+        if (!compare<cond, bitwidth, Callback>(value, (reinterpret_cast<char*>(b) - m_data) * 8 / no0(bitwidth), end,
+                                               baseindex, state, callback))
+            return false;
+
+        return true;
+    }
+    else {
+        return compare<cond, bitwidth, Callback>(value, start2, end, baseindex, state, callback);
+    }
+#else
+    return compare<cond, bitwidth, Callback>(value, start2, end, baseindex, state, callback);
+#endif
+}
+
+template <size_t width>
+inline int64_t Array::lower_bits() const
+{
+    if (width == 1)
+        return 0xFFFFFFFFFFFFFFFFULL;
+    else if (width == 2)
+        return 0x5555555555555555ULL;
+    else if (width == 4)
+        return 0x1111111111111111ULL;
+    else if (width == 8)
+        return 0x0101010101010101ULL;
+    else if (width == 16)
+        return 0x0001000100010001ULL;
+    else if (width == 32)
+        return 0x0000000100000001ULL;
+    else if (width == 64)
+        return 0x0000000000000001ULL;
+    else {
+        REALM_ASSERT_DEBUG(false);
+        return int64_t(-1);
+    }
+}
+
+// Tests if any chunk in 'value' is 0
+template <size_t width>
+inline bool Array::test_zero(uint64_t value) const
+{
+    uint64_t hasZeroByte;
+    uint64_t lower = lower_bits<width>();
+    uint64_t upper = lower_bits<width>() * 1ULL << (width == 0 ? 0 : (width - 1ULL));
+    hasZeroByte = (value - lower) & ~value & upper;
+    return hasZeroByte != 0;
+}
+
+// Finds first zero (if eq == true) or non-zero (if eq == false) element in v and returns its position.
+// IMPORTANT: This function assumes that at least 1 item matches (test this with test_zero() or other means first)!
+template <bool eq, size_t width>
+size_t Array::find_zero(uint64_t v) const
+{
+    size_t start = 0;
+    uint64_t hasZeroByte;
+    // Warning free way of computing (1ULL << width) - 1
+    uint64_t mask = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - 1ULL));
+
+    if (eq == (((v >> (width * start)) & mask) == 0)) {
+        return 0;
+    }
+
+    // Bisection optimization, speeds up small bitwidths with high match frequency. More partions than 2 do NOT pay
+    // off because the work done by test_zero() is wasted for the cases where the value exists in first half, but
+    // useful if it exists in last half. Sweet spot turns out to be the widths and partitions below.
+    if (width <= 8) {
+        hasZeroByte = test_zero<width>(v | 0xffffffff00000000ULL);
+        if (eq ? !hasZeroByte : (v & 0x00000000ffffffffULL) == 0) {
+            // 00?? -> increasing
+            start += 64 / no0(width) / 2;
+            if (width <= 4) {
+                hasZeroByte = test_zero<width>(v | 0xffff000000000000ULL);
+                if (eq ? !hasZeroByte : (v & 0x0000ffffffffffffULL) == 0) {
+                    // 000?
+                    start += 64 / no0(width) / 4;
+                }
+            }
+        }
+        else {
+            if (width <= 4) {
+                // ??00
+                hasZeroByte = test_zero<width>(v | 0xffffffffffff0000ULL);
+                if (eq ? !hasZeroByte : (v & 0x000000000000ffffULL) == 0) {
+                    // 0?00
+                    start += 64 / no0(width) / 4;
+                }
+            }
+        }
+    }
+
+    while (eq == (((v >> (width * start)) & mask) != 0)) {
+        // You must only call find_zero() if you are sure that at least 1 item matches
+        REALM_ASSERT_3(start, <=, 8 * sizeof(v));
+        start++;
+    }
+
+    return start;
+}
+
+// Generate a magic constant used for later bithacks
+template <bool gt, size_t width>
+int64_t Array::find_gtlt_magic(int64_t v) const
+{
+    uint64_t mask1 =
+        (width == 64
+             ? ~0ULL
+             : ((1ULL << (width == 64 ? 0 : width)) - 1ULL)); // Warning free way of computing (1ULL << width) - 1
+    uint64_t mask2 = mask1 >> 1;
+    uint64_t magic = gt ? (~0ULL / no0(mask1) * (mask2 - v)) : (~0ULL / no0(mask1) * v);
+    return magic;
+}
+
+template <bool gt, size_t width, class Callback>
+bool Array::find_gtlt_fast(uint64_t chunk, uint64_t magic, QueryStateBase* state, size_t baseindex,
+                           Callback callback) const
+{
+    // Tests if a a chunk of values contains values that are greater (if gt == true) or less (if gt == false) than v.
+    // Fast, but limited to work when all values in the chunk are positive.
+
+    uint64_t mask1 =
+        (width == 64
+             ? ~0ULL
+             : ((1ULL << (width == 64 ? 0 : width)) - 1ULL)); // Warning free way of computing (1ULL << width) - 1
+    uint64_t mask2 = mask1 >> 1;
+    uint64_t m = gt ? (((chunk + magic) | chunk) & ~0ULL / no0(mask1) * (mask2 + 1))
+                    : ((chunk - magic) & ~chunk & ~0ULL / no0(mask1) * (mask2 + 1));
+    size_t p = 0;
+    while (m) {
+        if (find_action_pattern(baseindex, m >> (no0(width) - 1), state))
+            break; // consumed, so do not call find_action()
+
+        size_t t = first_set_bit64(m) / no0(width);
+        p += t;
+        if (!find_action(p + baseindex, (chunk >> (p * width)) & mask1, state, callback))
+            return false;
+
+        if ((t + 1) * width == 64)
+            m = 0;
+        else
+            m >>= (t + 1) * width;
+        p++;
+    }
+
+    return true;
+}
+
+// clang-format off
+template <bool gt, size_t width, class Callback>
+bool Array::find_gtlt(int64_t v, uint64_t chunk, QueryStateBase* state, size_t baseindex, Callback callback) const
+{
+    // Find items in 'chunk' that are greater (if gt == true) or smaller (if gt == false) than 'v'. Fixme, __forceinline can make it crash in vS2010 - find out why
+    if constexpr (width == 1) {
+        for (size_t i = 0; i < 64; ++i) {
+            int64_t v2 = static_cast<int64_t>(chunk & 0x1);
+            if (gt ? v2 > v : v2 < v) {
+                if (!find_action(i + baseindex, v2, state, callback)) {
+                    return false;
+                }
+            }
+            chunk >>= 1;
+        }
+    }
+    else if constexpr (width == 2) {
+        for (size_t i = 0; i < 32; ++i) {
+            int64_t v2 = static_cast<int64_t>(chunk & 0x3);
+            if (gt ? v2 > v : v2 < v) {
+                if (!find_action(i + baseindex, v2, state, callback)) {
+                    return false;
+                }
+            }
+            chunk >>= 2;
+        }
+    }
+    else if constexpr (width == 4) {
+        for (size_t i = 0; i < 16; ++i) {
+            int64_t v2 = static_cast<int64_t>(chunk & 0xf);
+            if (gt ? v2 > v : v2 < v) {
+                if (!find_action(i + baseindex, v2, state, callback)) {
+                    return false;
+                }
+            }
+            chunk >>= 4;
+        }
+    }
+    else if constexpr (width == 8) {
+        for (size_t i = 0; i < 8; ++i) {
+            int64_t v2 = static_cast<int64_t>(static_cast<int8_t>(chunk & 0xff));
+            if (gt ? v2 > v : v2 < v) {
+                if (!find_action(i + baseindex, v2, state, callback)) {
+                    return false;
+                }
+            }
+            chunk >>= 8;
+        }
+    }
+    else if constexpr (width == 16) {
+        for (size_t i = 0; i < 4; ++i) {
+            int64_t v2 = static_cast<int64_t>(static_cast<int16_t>(chunk & 0xffff));
+            if (gt ? v2 > v : v2 < v) {
+                if (!find_action(i + baseindex, v2, state, callback)) {
+                    return false;
+                }
+            }
+            chunk >>= 16;
+        }
+    }
+    else if constexpr (width == 32) {
+        for (size_t i = 0; i < 2; ++i) {
+            int64_t v2 = static_cast<int64_t>(static_cast<int32_t>(chunk & 0xffffffff));
+            if (gt ? v2 > v : v2 < v) {
+                if (!find_action(i + baseindex, v2, state, callback)) {
+                    return false;
+                }
+            }
+            chunk >>= 32;
+        }
+    }
+    else if constexpr (width == 64) {
+        int64_t v2 = static_cast<int64_t>(chunk);
+        if (gt ? v2 > v : v2 < v) {
+            return find_action(baseindex, v2, state, callback);
+        }
+    }
+
+    static_cast<void>(state);
+    static_cast<void>(callback);
+    return true;
+}
+// clang-format on
+
+/// Find items in this Array that are equal (eq == true) or different (eq = false) from 'value'
+template <bool eq, size_t width, class Callback>
+inline bool Array::compare_equality(int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                                    Callback callback) const
+{
+    REALM_ASSERT_DEBUG(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end);
+
+    size_t ee = round_up(start, 64 / no0(width));
+    ee = ee > end ? end : ee;
+    for (; start < ee; ++start)
+        if (eq ? (get<width>(start) == value) : (get<width>(start) != value)) {
+            if (!find_action(start + baseindex, get<width>(start), state, callback))
+                return false;
+        }
+
+    if (start >= end)
+        return true;
+
+    if (width != 32 && width != 64) {
+        const int64_t* p = reinterpret_cast<const int64_t*>(m_data + (start * width / 8));
+        const int64_t* const e = reinterpret_cast<int64_t*>(m_data + (end * width / 8)) - 1;
+        const uint64_t mask =
+            (width == 64
+                 ? ~0ULL
+                 : ((1ULL << (width == 64 ? 0 : width)) - 1ULL)); // Warning free way of computing (1ULL << width) - 1
+        const uint64_t valuemask =
+            ~0ULL / no0(mask) * (value & mask); // the "== ? :" is to avoid division by 0 compiler error
+
+        while (p < e) {
+            uint64_t chunk = *p;
+            uint64_t v2 = chunk ^ valuemask;
+            start = (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(width);
+            size_t a = 0;
+
+            while (eq ? test_zero<width>(v2) : v2) {
+
+                if (find_action_pattern(start + baseindex, cascade<width, eq>(v2), state))
+                    break; // consumed
+
+                size_t t = find_zero<eq, width>(v2);
+                a += t;
+
+                if (a >= 64 / no0(width))
+                    break;
+
+                if (!find_action(a + start + baseindex, get<width>(start + a), state, callback))
+                    return false;
+                v2 >>= (t + 1) * width;
+                a += 1;
+            }
+
+            ++p;
+        }
+
+        // Loop ended because we are near end or end of array. No need to optimize search in remainder in this case
+        // because end of array means that
+        // lots of search work has taken place prior to ending here. So time spent searching remainder is relatively
+        // tiny
+        start = (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(width);
+    }
+
+    while (start < end) {
+        if (eq ? get<width>(start) == value : get<width>(start) != value) {
+            if (!find_action(start + baseindex, get<width>(start), state, callback))
+                return false;
+        }
+        ++start;
+    }
+
+    return true;
+}
+
+// There exists a couple of find() functions that take more or less template arguments. Always call the one that
+// takes as most as possible to get best performance.
+
+// This is the one installed into the m_vtable->finder slots.
+template <class cond, size_t bitwidth>
+bool Array::find_vtable(int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state) const
+{
+    return find_optimized<cond, bitwidth>(value, start, end, baseindex, state, nullptr);
+}
+
+template <class cond, class Callback>
+bool Array::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                 Callback callback) const
+{
+    REALM_TEMPEX3(return find_optimized, cond, m_width, Callback, (value, start, end, baseindex, state, callback));
+}
+
+#ifdef REALM_COMPILER_SSE
+// 'items' is the number of 16-byte SSE chunks. Returns index of packed element relative to first integer of first
+// chunk
+template <class cond, size_t width, class Callback>
+bool Array::find_sse(int64_t value, __m128i* data, size_t items, QueryStateBase* state, size_t baseindex,
+                     Callback callback) const
+{
+    __m128i search = {0};
+
+    if (width == 8)
+        search = _mm_set1_epi8(static_cast<char>(value));
+    else if (width == 16)
+        search = _mm_set1_epi16(static_cast<short int>(value));
+    else if (width == 32)
+        search = _mm_set1_epi32(static_cast<int>(value));
+    else if (width == 64) {
+        if (std::is_same<cond, Less>::value)
+            REALM_ASSERT(false);
+        else
+            search = _mm_set_epi64x(value, value);
+    }
+
+    return find_sse_intern<cond, width, Callback>(data, &search, items, state, baseindex, callback);
+}
+
+// Compares packed action_data with packed data (equal, less, etc) and performs aggregate action (max, min, sum,
+// find_all, etc) on value inside action_data for first match, if any
+template <class cond, size_t width, class Callback>
+REALM_FORCEINLINE bool Array::find_sse_intern(__m128i* action_data, __m128i* data, size_t items,
+                                              QueryStateBase* state, size_t baseindex, Callback callback) const
+{
+    size_t i = 0;
+    __m128i compare_result = {0};
+    unsigned int resmask;
+
+    // Search loop. Unrolling it has been tested to NOT increase performance (apparently mem bound)
+    for (i = 0; i < items; ++i) {
+        // equal / not-equal
+        if (std::is_same<cond, Equal>::value || std::is_same<cond, NotEqual>::value) {
+            if (width == 8)
+                compare_result = _mm_cmpeq_epi8(action_data[i], *data);
+            if (width == 16)
+                compare_result = _mm_cmpeq_epi16(action_data[i], *data);
+            if (width == 32)
+                compare_result = _mm_cmpeq_epi32(action_data[i], *data);
+            if (width == 64) {
+                compare_result = _mm_cmpeq_epi64(action_data[i], *data); // SSE 4.2 only
+            }
+        }
+
+        // greater
+        else if (std::is_same<cond, Greater>::value) {
+            if (width == 8)
+                compare_result = _mm_cmpgt_epi8(action_data[i], *data);
+            if (width == 16)
+                compare_result = _mm_cmpgt_epi16(action_data[i], *data);
+            if (width == 32)
+                compare_result = _mm_cmpgt_epi32(action_data[i], *data);
+            if (width == 64)
+                compare_result = _mm_cmpgt_epi64(action_data[i], *data);
+        }
+        // less
+        else if (std::is_same<cond, Less>::value) {
+            if (width == 8)
+                compare_result = _mm_cmplt_epi8(action_data[i], *data);
+            else if (width == 16)
+                compare_result = _mm_cmplt_epi16(action_data[i], *data);
+            else if (width == 32)
+                compare_result = _mm_cmplt_epi32(action_data[i], *data);
+            else
+                REALM_ASSERT(false);
+        }
+
+        resmask = _mm_movemask_epi8(compare_result);
+
+        if (std::is_same<cond, NotEqual>::value)
+            resmask = ~resmask & 0x0000ffff;
+
+        size_t s = i * sizeof(__m128i) * 8 / no0(width);
+
+        while (resmask != 0) {
+
+            uint64_t upper = lower_bits<width / 8>() << (no0(width / 8) - 1);
+            uint64_t pattern =
+                resmask &
+                upper; // fixme, bits at wrong offsets. Only OK because we only use them in 'count' aggregate
+            if (find_action_pattern(s + baseindex, pattern, state))
+                break;
+
+            size_t idx = first_set_bit(resmask) * 8 / no0(width);
+            s += idx;
+            if (!find_action(s + baseindex, get_universal<width>(reinterpret_cast<char*>(action_data), s), state,
+                             callback))
+                return false;
+            resmask >>= (idx + 1) * no0(width) / 8;
+            ++s;
+        }
+    }
+
+    return true;
+}
+#endif // REALM_COMPILER_SSE
+
+template <class cond, class Callback>
+bool Array::compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                          Callback callback) const
+{
+    cond c;
+    REALM_ASSERT_3(start, <=, end);
+    if (start == end)
+        return true;
+
+
+    int64_t v;
+
+    // We can compare first element without checking for out-of-range
+    v = get(start);
+    if (c(v, foreign->get(start))) {
+        if (!find_action(start + baseindex, v, state, callback))
+            return false;
+    }
+
+    start++;
+
+    if (start + 3 < end) {
+        v = get(start);
+        if (c(v, foreign->get(start)))
+            if (!find_action(start + baseindex, v, state, callback))
+                return false;
+
+        v = get(start + 1);
+        if (c(v, foreign->get(start + 1)))
+            if (!find_action(start + 1 + baseindex, v, state, callback))
+                return false;
+
+        v = get(start + 2);
+        if (c(v, foreign->get(start + 2)))
+            if (!find_action(start + 2 + baseindex, v, state, callback))
+                return false;
+
+        start += 3;
+    }
+    else if (start == end) {
+        return true;
+    }
+
+    bool r;
+    REALM_TEMPEX3(r = compare_leafs, cond, m_width, Callback, (foreign, start, end, baseindex, state, callback))
+    return r;
+}
+
+
+template <class cond, size_t width, class Callback>
+bool Array::compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                          Callback callback) const
+{
+    size_t fw = foreign->m_width;
+    bool r;
+    REALM_TEMPEX4(r = compare_leafs_4, cond, width, Callback, fw, (foreign, start, end, baseindex, state, callback))
+    return r;
+}
+
+
+template <class cond, size_t width, class Callback, size_t foreign_width>
+bool Array::compare_leafs_4(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                            Callback callback) const
+{
+    cond c;
+    char* foreign_m_data = foreign->m_data;
+
+    if (width == 0 && foreign_width == 0) {
+        if (c(0, 0)) {
+            while (start < end) {
+                if (!find_action(start + baseindex, 0, state, callback))
+                    return false;
+                start++;
+            }
+        }
+        else {
+            return true;
+        }
+    }
+
+
+#if defined(REALM_COMPILER_SSE)
+    if (sseavx<42>() && width == foreign_width && (width == 8 || width == 16 || width == 32)) {
+        // We can only use SSE if both bitwidths are equal and above 8 bits and all values are signed
+        // and the two arrays are aligned the same way
+        if ((reinterpret_cast<size_t>(m_data) & 0xf) == (reinterpret_cast<size_t>(foreign_m_data) & 0xf)) {
+            while (start < end && (((reinterpret_cast<size_t>(m_data) & 0xf) * 8 + start * width) % (128) != 0)) {
+                int64_t v = get_universal<width>(m_data, start);
+                int64_t fv = get_universal<foreign_width>(foreign_m_data, start);
+                if (c(v, fv)) {
+                    if (!find_action(start + baseindex, v, state, callback))
+                        return false;
+                }
+                start++;
+            }
+            if (start == end)
+                return true;
+
+
+            size_t sse_items = (end - start) * width / 128;
+            size_t sse_end = start + sse_items * 128 / no0(width);
+
+            while (start < sse_end) {
+                __m128i* a = reinterpret_cast<__m128i*>(m_data + start * width / 8);
+                __m128i* b = reinterpret_cast<__m128i*>(foreign_m_data + start * width / 8);
+
+                bool continue_search =
+                    find_sse_intern<cond, width, Callback>(a, b, 1, state, baseindex + start, callback);
+
+                if (!continue_search)
+                    return false;
+
+                start += 128 / no0(width);
+            }
+        }
+    }
+#endif
+
+    while (start < end) {
+        int64_t v = get_universal<width>(m_data, start);
+        int64_t fv = get_universal<foreign_width>(foreign_m_data, start);
+
+        if (c(v, fv)) {
+            if (!find_action(start + baseindex, v, state, callback))
+                return false;
+        }
+
+        start++;
+    }
+
+    return true;
+}
+
+
+template <class cond, size_t bitwidth, class Callback>
+bool Array::compare(int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                    Callback callback) const
+{
+    bool ret = false;
+
+    if (std::is_same<cond, Equal>::value)
+        ret = compare_equality<true, bitwidth, Callback>(value, start, end, baseindex, state, callback);
+    else if (std::is_same<cond, NotEqual>::value)
+        ret = compare_equality<false, bitwidth, Callback>(value, start, end, baseindex, state, callback);
+    else if (std::is_same<cond, Greater>::value)
+        ret = compare_relation<true, bitwidth, Callback>(value, start, end, baseindex, state, callback);
+    else if (std::is_same<cond, Less>::value)
+        ret = compare_relation<false, bitwidth, Callback>(value, start, end, baseindex, state, callback);
+    else
+        REALM_ASSERT_DEBUG(false);
+
+    return ret;
+}
+
+template <bool gt, size_t bitwidth, class Callback>
+bool Array::compare_relation(int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                             Callback callback) const
+{
+    REALM_ASSERT(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end);
+    uint64_t mask = (bitwidth == 64 ? ~0ULL
+                                    : ((1ULL << (bitwidth == 64 ? 0 : bitwidth)) -
+                                       1ULL)); // Warning free way of computing (1ULL << width) - 1
+
+    size_t ee = round_up(start, 64 / no0(bitwidth));
+    ee = ee > end ? end : ee;
+    for (; start < ee; start++) {
+        if (gt ? (get<bitwidth>(start) > value) : (get<bitwidth>(start) < value)) {
+            if (!find_action(start + baseindex, get<bitwidth>(start), state, callback))
+                return false;
+        }
+    }
+
+    if (start >= end)
+        return true; // none found, continue (return true) regardless what find_action() would have returned on match
+
+    const int64_t* p = reinterpret_cast<const int64_t*>(m_data + (start * bitwidth / 8));
+    const int64_t* const e = reinterpret_cast<int64_t*>(m_data + (end * bitwidth / 8)) - 1;
+
+    // Matches are rare enough to setup fast linear search for remaining items. We use
+    // bit hacks from http://graphics.stanford.edu/~seander/bithacks.html#HasLessInWord
+
+    if (bitwidth == 1 || bitwidth == 2 || bitwidth == 4 || bitwidth == 8 || bitwidth == 16) {
+        uint64_t magic = find_gtlt_magic<gt, bitwidth>(value);
+
+        // Bit hacks only work if searched item has its most significant bit clear for 'greater than' or
+        // 'item <= 1 << bitwidth' for 'less than'
+        if (value != int64_t((magic & mask)) && value >= 0 && bitwidth >= 2 &&
+            value <= static_cast<int64_t>((mask >> 1) - (gt ? 1 : 0))) {
+            // 15 ms
+            while (p < e) {
+                uint64_t upper = lower_bits<bitwidth>() << (no0(bitwidth) - 1);
+
+                const int64_t v = *p;
+                size_t idx;
+
+                // Bit hacks only works if all items in chunk have their most significant bit clear. Test this:
+                upper = upper & v;
+
+                if (!upper) {
+                    idx = find_gtlt_fast<gt, bitwidth, Callback>(
+                        v, magic, state, (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(bitwidth) + baseindex,
+                        callback);
+                }
+                else
+                    idx = find_gtlt<gt, bitwidth, Callback>(
+                        value, v, state, (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(bitwidth) + baseindex,
+                        callback);
+
+                if (!idx)
+                    return false;
+                ++p;
+            }
+        }
+        else {
+            // 24 ms
+            while (p < e) {
+                int64_t v = *p;
+                if (!find_gtlt<gt, bitwidth, Callback>(
+                        value, v, state, (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(bitwidth) + baseindex,
+                        callback))
+                    return false;
+                ++p;
+            }
+        }
+        start = (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(bitwidth);
+    }
+
+    // matchcount logic in SIMD no longer pays off for 32/64 bit ints because we have just 4/2 elements
+
+    // Test unaligned end and/or values of width > 16 manually
+    while (start < end) {
+        if (gt ? get<bitwidth>(start) > value : get<bitwidth>(start) < value) {
+            if (!find_action(start + baseindex, get<bitwidth>(start), state, callback))
+                return false;
+        }
+        ++start;
+    }
+    return true;
+}
+
+template <class cond>
+size_t Array::find_first(int64_t value, size_t start, size_t end) const
+{
+    REALM_ASSERT(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end);
+    // todo, would be nice to avoid this in order to speed up find_first loops
+    QueryStateFindFirst state;
+    Finder finder = m_vtable->finder[cond::condition];
+    (this->*finder)(value, start, end, 0, &state);
+
+    return static_cast<size_t>(state.m_state);
+}
+
+//*************************************************************************************
+// Finding code ends                                                                  *
+//*************************************************************************************
+
+
+} // namespace realm
+
+#endif // REALM_ARRAY_HPP

+ 90 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_backlink.hpp

@@ -0,0 +1,90 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_BACKLINK_HPP
+#define REALM_ARRAY_BACKLINK_HPP
+
+#include <realm/cluster.hpp>
+
+namespace realm {
+class ArrayBacklink : public ArrayPayload, private Array {
+public:
+    using Array::Array;
+    using Array::init_from_parent;
+    using Array::copy_on_write;
+    using Array::update_parent;
+    using Array::get_ref;
+    using Array::size;
+
+    static int64_t default_value(bool)
+    {
+        return 0;
+    }
+
+    void init_from_ref(ref_type ref) noexcept override
+    {
+        Array::init_from_ref(ref);
+    }
+    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override
+    {
+        Array::set_parent(parent, ndx_in_parent);
+    }
+    void create()
+    {
+        Array::create(type_HasRefs);
+    }
+
+    void insert(size_t ndx, int64_t val)
+    {
+        Array::insert(ndx, val);
+    }
+
+    int64_t get(size_t ndx) const
+    {
+        return Array::get(ndx);
+    }
+    Mixed get_any(size_t ndx) const override
+    {
+        REALM_ASSERT(false);
+        return Mixed(get(ndx));
+    }
+    void add(int64_t val)
+    {
+        Array::add(val);
+    }
+
+    // nullify forward links corresponding to any backward links at index 'ndx'
+    void nullify_fwd_links(size_t ndx, CascadeState& state);
+    void add(size_t ndx, ObjKey key);
+    bool remove(size_t ndx, ObjKey key);
+    void erase(size_t ndx);
+    size_t get_backlink_count(size_t ndx) const;
+    ObjKey get_backlink(size_t ndx, size_t index) const;
+    void move(ArrayBacklink& dst, size_t ndx)
+    {
+        Array::move(dst, ndx);
+    }
+    void clear()
+    {
+        Array::truncate_and_destroy_children(0);
+    }
+    void verify() const;
+};
+}
+
+#endif /* SRC_REALM_ARRAY_KEY_HPP_ */

+ 218 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_basic.hpp

@@ -0,0 +1,218 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_BASIC_HPP
+#define REALM_ARRAY_BASIC_HPP
+
+#include <realm/array.hpp>
+
+namespace realm {
+
+/// A BasicArray can currently only be used for simple unstructured
+/// types like float, double.
+template <class T>
+class BasicArray : public Array, public ArrayPayload {
+public:
+    using value_type = T;
+
+    explicit BasicArray(Allocator&) noexcept;
+    ~BasicArray() noexcept override
+    {
+    }
+
+    static T default_value(bool)
+    {
+        return T(0.0);
+    }
+
+    void init_from_ref(ref_type ref) noexcept override
+    {
+        Array::init_from_ref(ref);
+    }
+
+    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override
+    {
+        Array::set_parent(parent, ndx_in_parent);
+    }
+
+    // Disable copying, this is not allowed.
+    BasicArray& operator=(const BasicArray&) = delete;
+    BasicArray(const BasicArray&) = delete;
+
+    T get(size_t ndx) const noexcept;
+    bool is_null(size_t ndx) const noexcept
+    {
+        // FIXME: This assumes BasicArray will only ever be instantiated for float-like T.
+        static_assert(realm::is_any<T, float, double>::value, "T can only be float or double");
+        auto x = BasicArray<T>::get(ndx);
+        return null::is_null_float(x);
+    }
+    void add(T value);
+    void set(size_t ndx, T value);
+    void insert(size_t ndx, T value);
+    void erase(size_t ndx);
+    void truncate(size_t size);
+    void move(BasicArray& dst, size_t ndx)
+    {
+        for (size_t i = ndx; i < m_size; i++) {
+            dst.add(get(i));
+        }
+        truncate(ndx);
+    }
+    void clear();
+
+    size_t find_first(T value, size_t begin = 0, size_t end = npos) const;
+    void find_all(IntegerColumn* result, T value, size_t add_offset = 0, size_t begin = 0, size_t end = npos) const;
+
+    size_t count(T value, size_t begin = 0, size_t end = npos) const;
+    bool maximum(T& result, size_t begin = 0, size_t end = npos) const;
+    bool minimum(T& result, size_t begin = 0, size_t end = npos) const;
+
+    /// Compare two arrays for equality.
+    bool compare(const BasicArray<T>&) const;
+
+    /// Get the specified element without the cost of constructing an
+    /// array instance. If an array instance is already available, or
+    /// you need to get multiple values, then this method will be
+    /// slower.
+    static T get(const char* header, size_t ndx) noexcept;
+    Mixed get_any(size_t ndx) const override
+    {
+        return Mixed(get(ndx));
+    }
+
+    size_t lower_bound(T value) const noexcept;
+    size_t upper_bound(T value) const noexcept;
+
+    /// Construct a basic array of the specified size and return just
+    /// the reference to the underlying memory. All elements will be
+    /// initialized to `T()`.
+    static MemRef create_array(size_t size, Allocator&);
+
+    static MemRef create_array(Array::Type leaf_type, bool context_flag, size_t size, T value, Allocator&);
+
+    /// Create a new empty array and attach this accessor to it. This
+    /// does not modify the parent reference information of this
+    /// accessor.
+    ///
+    /// Note that the caller assumes ownership of the allocated
+    /// underlying node. It is not owned by the accessor.
+    void create(Array::Type = type_Normal, bool context_flag = false);
+
+private:
+    size_t find(T target, size_t begin, size_t end) const;
+
+    size_t calc_byte_len(size_t count, size_t width) const override;
+    virtual size_t calc_item_count(size_t bytes, size_t width) const noexcept override;
+
+    template <bool find_max>
+    bool minmax(T& result, size_t begin, size_t end) const;
+
+    /// Calculate the total number of bytes needed for a basic array
+    /// with the specified number of elements. This includes the size
+    /// of the header. The result will be upwards aligned to the
+    /// closest 8-byte boundary.
+    static size_t calc_aligned_byte_size(size_t size);
+};
+
+template <class T>
+class BasicArrayNull : public BasicArray<T> {
+public:
+    using BasicArray<T>::BasicArray;
+
+    static util::Optional<T> default_value(bool nullable)
+    {
+        return nullable ? util::Optional<T>() : util::Optional<T>(0.0);
+    }
+    void set(size_t ndx, util::Optional<T> value)
+    {
+        if (value) {
+            BasicArray<T>::set(ndx, *value);
+        }
+        else {
+            BasicArray<T>::set(ndx, null::get_null_float<T>());
+        }
+    }
+    void add(util::Optional<T> value)
+    {
+        if (value) {
+            BasicArray<T>::add(*value);
+        }
+        else {
+            BasicArray<T>::add(null::get_null_float<T>());
+        }
+    }
+    void insert(size_t ndx, util::Optional<T> value)
+    {
+        if (value) {
+            BasicArray<T>::insert(ndx, *value);
+        }
+        else {
+            BasicArray<T>::insert(ndx, null::get_null_float<T>());
+        }
+    }
+
+    void set_null(size_t ndx)
+    {
+        // FIXME: This assumes BasicArray will only ever be instantiated for float-like T.
+        set(ndx, null::get_null_float<T>());
+    }
+
+    util::Optional<T> get(size_t ndx) const noexcept
+    {
+        T val = BasicArray<T>::get(ndx);
+        return null::is_null_float(val) ? util::none : util::make_optional(val);
+    }
+    Mixed get_any(size_t ndx) const override
+    {
+        return Mixed(get(ndx));
+    }
+    size_t find_first(util::Optional<T> value, size_t begin = 0, size_t end = npos) const
+    {
+        if (value) {
+            return BasicArray<T>::find_first(*value, begin, end);
+        }
+        else {
+            return find_first_null(begin, end);
+        }
+    }
+    void find_all(IntegerColumn* result, util::Optional<T> value, size_t add_offset = 0, size_t begin = 0,
+                  size_t end = npos) const
+    {
+        if (value) {
+            return BasicArray<T>::find_all(result, *value, add_offset, begin, end);
+        }
+        else {
+            return find_all_null(result, add_offset, begin, end);
+        }
+    }
+    size_t find_first_null(size_t begin = 0, size_t end = npos) const;
+    void find_all_null(IntegerColumn* result, size_t add_offset = 0, size_t begin = 0, size_t end = npos) const;
+};
+
+// Class typedefs for BasicArray's: ArrayFloat and ArrayDouble
+typedef BasicArray<float> ArrayFloat;
+typedef BasicArray<double> ArrayDouble;
+typedef BasicArrayNull<float> ArrayFloatNull;
+typedef BasicArrayNull<double> ArrayDoubleNull;
+
+} // namespace realm
+
+#include <realm/array_basic_tpl.hpp>
+
+#endif // REALM_ARRAY_BASIC_HPP

+ 377 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_basic_tpl.hpp

@@ -0,0 +1,377 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_BASIC_TPL_HPP
+#define REALM_ARRAY_BASIC_TPL_HPP
+
+#include <algorithm>
+#include <limits>
+#include <stdexcept>
+#include <iomanip>
+
+#include <realm/impl/destroy_guard.hpp>
+
+namespace realm {
+
+template <class T>
+inline BasicArray<T>::BasicArray(Allocator& allocator) noexcept
+    : Array(allocator)
+{
+}
+
+template <class T>
+inline MemRef BasicArray<T>::create_array(size_t init_size, Allocator& allocator)
+{
+    size_t byte_size_0 = calc_aligned_byte_size(init_size); // Throws
+    // Adding zero to Array::initial_capacity to avoid taking the
+    // address of that member
+    size_t byte_size = std::max(byte_size_0, Array::initial_capacity + 0); // Throws
+
+    MemRef mem = allocator.alloc(byte_size); // Throws
+
+    bool is_inner_bptree_node = false;
+    bool has_refs = false;
+    bool context_flag = false;
+    int width = sizeof(T);
+    init_header(mem.get_addr(), is_inner_bptree_node, has_refs, context_flag, wtype_Multiply, width, init_size,
+                byte_size);
+
+    return mem;
+}
+
+
+template <class T>
+inline MemRef BasicArray<T>::create_array(Array::Type type, bool context_flag, size_t init_size, T value,
+                                          Allocator& allocator)
+{
+    REALM_ASSERT(type == Array::type_Normal);
+    REALM_ASSERT(!context_flag);
+    MemRef mem = create_array(init_size, allocator);
+    if (init_size) {
+        // GCC 7.x emits a false-positive strict aliasing warning for this code. Suppress it, since it
+        // clutters up the build output.  See <https://github.com/realm/realm-core/issues/2665> for details.
+        REALM_DIAG_PUSH();
+        REALM_DIAG(ignored "-Wstrict-aliasing");
+
+        BasicArray<T> tmp(allocator);
+        tmp.init_from_mem(mem);
+        T* p = reinterpret_cast<T*>(tmp.m_data);
+        T* end = p + init_size;
+        while (p < end) {
+            *p++ = value;
+        }
+
+        REALM_DIAG_POP();
+    }
+    return mem;
+}
+
+
+template <class T>
+inline void BasicArray<T>::create(Array::Type type, bool context_flag)
+{
+    REALM_ASSERT(type == Array::type_Normal);
+    REALM_ASSERT(!context_flag);
+    size_t length = 0;
+    MemRef mem = create_array(length, get_alloc()); // Throws
+    init_from_mem(mem);
+}
+
+
+template <class T>
+inline void BasicArray<T>::add(T value)
+{
+    insert(m_size, value);
+}
+
+
+template <class T>
+inline T BasicArray<T>::get(size_t ndx) const noexcept
+{
+    return *(reinterpret_cast<const T*>(m_data) + ndx);
+}
+
+
+template <class T>
+inline T BasicArray<T>::get(const char* header, size_t ndx) noexcept
+{
+    const char* data = get_data_from_header(header);
+    // This casting assumes that T can be aliged on an 8-bype
+    // boundary (since data is aligned on an 8-byte boundary.)
+    return *(reinterpret_cast<const T*>(data) + ndx);
+}
+
+
+template <class T>
+inline void BasicArray<T>::set(size_t ndx, T value)
+{
+    REALM_ASSERT_3(ndx, <, m_size);
+    if (get(ndx) == value)
+        return;
+
+    // Check if we need to copy before modifying
+    copy_on_write(); // Throws
+
+    // Set the value
+    T* data = reinterpret_cast<T*>(m_data) + ndx;
+    *data = value;
+}
+
+template <class T>
+void BasicArray<T>::insert(size_t ndx, T value)
+{
+    REALM_ASSERT_3(ndx, <=, m_size);
+
+    // Check if we need to copy before modifying
+    copy_on_write(); // Throws
+
+    // Make room for the new value
+    const auto old_size = m_size;
+    alloc(m_size + 1, m_width); // Throws
+
+    // Move values below insertion
+    if (ndx != old_size) {
+        char* src_begin = m_data + ndx * m_width;
+        char* src_end = m_data + old_size * m_width;
+        char* dst_end = src_end + m_width;
+        std::copy_backward(src_begin, src_end, dst_end);
+    }
+
+    // Set the value
+    T* data = reinterpret_cast<T*>(m_data) + ndx;
+    *data = value;
+}
+
+template <class T>
+void BasicArray<T>::erase(size_t ndx)
+{
+    REALM_ASSERT_3(ndx, <, m_size);
+
+    // Check if we need to copy before modifying
+    copy_on_write(); // Throws
+
+    // move data under deletion up
+    if (ndx < m_size - 1) {
+        char* dst_begin = m_data + ndx * m_width;
+        const char* src_begin = dst_begin + m_width;
+        const char* src_end = m_data + m_size * m_width;
+        realm::safe_copy_n(src_begin, src_end - src_begin, dst_begin);
+    }
+
+    // Update size (also in header)
+    --m_size;
+    set_header_size(m_size);
+}
+
+template <class T>
+void BasicArray<T>::truncate(size_t to_size)
+{
+    REALM_ASSERT(is_attached());
+    REALM_ASSERT_3(to_size, <=, m_size);
+
+    copy_on_write(); // Throws
+
+    // Update size in accessor and in header. This leaves the capacity
+    // unchanged.
+    m_size = to_size;
+    set_header_size(to_size);
+}
+
+template <class T>
+inline void BasicArray<T>::clear()
+{
+    truncate(0); // Throws
+}
+
+template <class T>
+bool BasicArray<T>::compare(const BasicArray<T>& a) const
+{
+    size_t n = size();
+    if (a.size() != n)
+        return false;
+    const T* data_1 = reinterpret_cast<const T*>(m_data);
+    const T* data_2 = reinterpret_cast<const T*>(a.m_data);
+    return realm::safe_equal(data_1, data_1 + n, data_2);
+}
+
+
+template <class T>
+size_t BasicArray<T>::calc_byte_len(size_t for_size, size_t) const
+{
+    // FIXME: Consider calling `calc_aligned_byte_size(size)`
+    // instead. Note however, that calc_byte_len() is supposed to return
+    // the unaligned byte size. It is probably the case that no harm
+    // is done by returning the aligned version, and most callers of
+    // calc_byte_len() will actually benefit if calc_byte_len() was
+    // changed to always return the aligned byte size.
+    return header_size + for_size * sizeof(T);
+}
+
+template <class T>
+size_t BasicArray<T>::calc_item_count(size_t bytes, size_t) const noexcept
+{
+    size_t bytes_without_header = bytes - header_size;
+    return bytes_without_header / sizeof(T);
+}
+
+template <class T>
+size_t BasicArray<T>::find(T value, size_t begin, size_t end) const
+{
+    if (end == npos)
+        end = m_size;
+    REALM_ASSERT(begin <= m_size && end <= m_size && begin <= end);
+    const T* data = reinterpret_cast<const T*>(m_data);
+    const T* i = std::find(data + begin, data + end, value);
+    return i == data + end ? not_found : size_t(i - data);
+}
+
+template <class T>
+inline size_t BasicArray<T>::find_first(T value, size_t begin, size_t end) const
+{
+    return this->find(value, begin, end);
+}
+
+template <class T>
+void BasicArray<T>::find_all(IntegerColumn* result, T value, size_t add_offset, size_t begin, size_t end) const
+{
+    size_t first = begin - 1;
+    for (;;) {
+        first = this->find(value, first + 1, end);
+        if (first == not_found)
+            break;
+
+        Array::add_to_column(result, first + add_offset);
+    }
+}
+template <class T>
+size_t BasicArrayNull<T>::find_first_null(size_t begin, size_t end) const
+{
+    size_t sz = Array::size();
+    if (end == npos)
+        end = sz;
+    REALM_ASSERT(begin <= sz && end <= sz && begin <= end);
+    while (begin != end) {
+        if (this->is_null(begin))
+            return begin;
+        begin++;
+    }
+    return not_found;
+}
+
+template <class T>
+void BasicArrayNull<T>::find_all_null(IntegerColumn* result, size_t add_offset, size_t begin, size_t end) const
+{
+    size_t first = begin - 1;
+    for (;;) {
+        first = this->find_first_null(first + 1, end);
+        if (first == not_found)
+            break;
+
+        Array::add_to_column(result, first + add_offset);
+    }
+}
+
+template <class T>
+size_t BasicArray<T>::count(T value, size_t begin, size_t end) const
+{
+    if (end == npos)
+        end = m_size;
+    REALM_ASSERT(begin <= m_size && end <= m_size && begin <= end);
+    const T* data = reinterpret_cast<const T*>(m_data);
+    return std::count(data + begin, data + end, value);
+}
+
+#if 0
+// currently unused
+template <class T>
+double BasicArray<T>::sum(size_t begin, size_t end) const
+{
+    if (end == npos)
+        end = m_size;
+    REALM_ASSERT(begin <= m_size && end <= m_size && begin <= end);
+    const T* data = reinterpret_cast<const T*>(m_data);
+    return std::accumulate(data + begin, data + end, double(0));
+}
+#endif
+
+template <class T>
+template <bool find_max>
+bool BasicArray<T>::minmax(T& result, size_t begin, size_t end) const
+{
+    if (end == npos)
+        end = m_size;
+    if (m_size == 0)
+        return false;
+    REALM_ASSERT(begin < m_size && end <= m_size && begin < end);
+
+    T m = get(begin);
+    ++begin;
+    for (; begin < end; ++begin) {
+        T val = get(begin);
+        if (find_max ? val > m : val < m)
+            m = val;
+    }
+    result = m;
+    return true;
+}
+
+template <class T>
+bool BasicArray<T>::maximum(T& result, size_t begin, size_t end) const
+{
+    return minmax<true>(result, begin, end);
+}
+
+template <class T>
+bool BasicArray<T>::minimum(T& result, size_t begin, size_t end) const
+{
+    return minmax<false>(result, begin, end);
+}
+
+
+template <class T>
+inline size_t BasicArray<T>::lower_bound(T value) const noexcept
+{
+    const T* begin = reinterpret_cast<const T*>(m_data);
+    const T* end = begin + size();
+    return std::lower_bound(begin, end, value) - begin;
+}
+
+template <class T>
+inline size_t BasicArray<T>::upper_bound(T value) const noexcept
+{
+    const T* begin = reinterpret_cast<const T*>(m_data);
+    const T* end = begin + size();
+    return std::upper_bound(begin, end, value) - begin;
+}
+
+template <class T>
+inline size_t BasicArray<T>::calc_aligned_byte_size(size_t size)
+{
+    size_t max = std::numeric_limits<size_t>::max();
+    size_t max_2 = max & ~size_t(7); // Allow for upwards 8-byte alignment
+    if (size > (max_2 - header_size) / sizeof(T))
+        throw util::overflow_error("Byte size overflow");
+    size_t byte_size = header_size + size * sizeof(T);
+    REALM_ASSERT_3(byte_size, >, 0);
+    size_t aligned_byte_size = ((byte_size - 1) | 7) + 1; // 8-byte alignment
+    return aligned_byte_size;
+}
+
+} // namespace realm
+
+#endif // REALM_ARRAY_BASIC_TPL_HPP

+ 118 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_binary.hpp

@@ -0,0 +1,118 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_BINARY_HPP
+#define REALM_ARRAY_BINARY_HPP
+
+#include <realm/array_blobs_small.hpp>
+#include <realm/array_blobs_big.hpp>
+
+namespace realm {
+
+class ArrayBinary : public ArrayPayload {
+public:
+    using value_type = BinaryData;
+
+    explicit ArrayBinary(Allocator&);
+
+    static BinaryData default_value(bool nullable)
+    {
+        return nullable ? BinaryData{} : BinaryData{"", 0};
+    }
+
+    void create();
+
+    ref_type get_ref() const
+    {
+        return m_arr->get_ref();
+    }
+
+    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override
+    {
+        m_arr->set_parent(parent, ndx_in_parent);
+    }
+
+    void update_parent()
+    {
+        m_arr->update_parent();
+    }
+
+    void init_from_mem(MemRef mem) noexcept;
+    void init_from_ref(ref_type ref) noexcept override
+    {
+        init_from_mem(MemRef(m_alloc.translate(ref), ref, m_alloc));
+    }
+    void init_from_parent();
+
+    size_t size() const;
+
+    void add(BinaryData value);
+    void set(size_t ndx, BinaryData value);
+    void set_null(size_t ndx)
+    {
+        set(ndx, BinaryData{});
+    }
+    void insert(size_t ndx, BinaryData value);
+    BinaryData get(size_t ndx) const;
+    BinaryData get_at(size_t ndx, size_t& pos) const;
+    Mixed get_any(size_t ndx) const override;
+    bool is_null(size_t ndx) const;
+    void erase(size_t ndx);
+    void move(ArrayBinary& dst, size_t ndx);
+    void clear();
+
+    size_t find_first(BinaryData value, size_t begin, size_t end) const noexcept;
+
+    /// Get the specified element without the cost of constructing an
+    /// array instance. If an array instance is already available, or
+    /// you need to get multiple values, then this method will be
+    /// slower.
+    static BinaryData get(const char* header, size_t ndx, Allocator& alloc) noexcept;
+
+    void verify() const;
+
+private:
+    static constexpr size_t small_blob_max_size = 64;
+
+    union Storage {
+        std::aligned_storage<sizeof(ArraySmallBlobs), alignof(ArraySmallBlobs)>::type m_small_blobs;
+        std::aligned_storage<sizeof(ArrayBigBlobs), alignof(ArrayBigBlobs)>::type m_big_blobs;
+    };
+
+    bool m_is_big = false;
+
+    Allocator& m_alloc;
+    Storage m_storage;
+    Array* m_arr;
+
+    bool upgrade_leaf(size_t value_size);
+};
+
+inline BinaryData ArrayBinary::get(const char* header, size_t ndx, Allocator& alloc) noexcept
+{
+    bool is_big = Array::get_context_flag_from_header(header);
+    if (!is_big) {
+        return ArraySmallBlobs::get(header, ndx, alloc);
+    }
+    else {
+        return ArrayBigBlobs::get(header, ndx, alloc);
+    }
+}
+}
+
+#endif /* SRC_REALM_ARRAY_BINARY_HPP_ */

+ 142 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_blob.hpp

@@ -0,0 +1,142 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_BLOB_HPP
+#define REALM_ARRAY_BLOB_HPP
+
+#include <realm/array.hpp>
+
+namespace realm {
+
+
+class ArrayBlob : public Array {
+public:
+    static constexpr size_t max_binary_size = 0xFFFFF8 - Array::header_size;
+
+    explicit ArrayBlob(Allocator&) noexcept;
+    ~ArrayBlob() noexcept override
+    {
+    }
+
+    // Disable copying, this is not allowed.
+    ArrayBlob& operator=(const ArrayBlob&) = delete;
+    ArrayBlob(const ArrayBlob&) = delete;
+
+    const char* get(size_t index) const noexcept;
+    BinaryData get_at(size_t& pos) const noexcept;
+    bool is_null(size_t index) const noexcept;
+    ref_type add(const char* data, size_t data_size, bool add_zero_term = false);
+    void insert(size_t pos, const char* data, size_t data_size, bool add_zero_term = false);
+    ref_type replace(size_t begin, size_t end, const char* data, size_t data_size, bool add_zero_term = false);
+    void erase(size_t begin, size_t end);
+
+    /// Get the specified element without the cost of constructing an
+    /// array instance. If an array instance is already available, or
+    /// you need to get multiple values, then this method will be
+    /// slower.
+    static const char* get(const char* header, size_t index) noexcept;
+
+    /// Create a new empty blob (binary) array and attach this
+    /// accessor to it. This does not modify the parent reference
+    /// information of this accessor.
+    ///
+    /// Note that the caller assumes ownership of the allocated
+    /// underlying node. It is not owned by the accessor.
+    void create();
+
+    /// Construct a blob of the specified size and return just the
+    /// reference to the underlying memory. All bytes will be
+    /// initialized to zero.
+    static MemRef create_array(size_t init_size, Allocator&);
+
+    void verify() const;
+private:
+    size_t calc_byte_len(size_t for_size, size_t width) const override;
+    size_t calc_item_count(size_t bytes, size_t width) const noexcept override;
+};
+
+
+// Implementation:
+
+// Creates new array (but invalid, call init_from_ref() to init)
+inline ArrayBlob::ArrayBlob(Allocator& allocator) noexcept
+    : Array(allocator)
+{
+}
+
+inline bool ArrayBlob::is_null(size_t index) const noexcept
+{
+    return (get(index) == nullptr);
+}
+
+inline const char* ArrayBlob::get(size_t index) const noexcept
+{
+    return m_data + index;
+}
+
+inline ref_type ArrayBlob::add(const char* data, size_t data_size, bool add_zero_term)
+{
+    return replace(m_size, m_size, data, data_size, add_zero_term);
+}
+
+inline void ArrayBlob::insert(size_t pos, const char* data, size_t data_size, bool add_zero_term)
+{
+    replace(pos, pos, data, data_size, add_zero_term);
+}
+
+inline void ArrayBlob::erase(size_t begin, size_t end)
+{
+    const char* data = nullptr;
+    size_t data_size = 0;
+    replace(begin, end, data, data_size);
+}
+
+inline const char* ArrayBlob::get(const char* header, size_t pos) noexcept
+{
+    const char* data = get_data_from_header(header);
+    return data + pos;
+}
+
+inline void ArrayBlob::create()
+{
+    size_t init_size = 0;
+    MemRef mem = create_array(init_size, get_alloc()); // Throws
+    init_from_mem(mem);
+}
+
+inline MemRef ArrayBlob::create_array(size_t init_size, Allocator& allocator)
+{
+    bool context_flag = false;
+    int_fast64_t value = 0;
+    return Array::create(type_Normal, context_flag, wtype_Ignore, init_size, value, allocator); // Throws
+}
+
+inline size_t ArrayBlob::calc_byte_len(size_t for_size, size_t) const
+{
+    return header_size + for_size;
+}
+
+inline size_t ArrayBlob::calc_item_count(size_t bytes, size_t) const noexcept
+{
+    return bytes - header_size;
+}
+
+
+} // namespace realm
+
+#endif // REALM_ARRAY_BLOB_HPP

+ 206 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_blobs_big.hpp

@@ -0,0 +1,206 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_BIG_BLOBS_HPP
+#define REALM_ARRAY_BIG_BLOBS_HPP
+
+#include <realm/array_blob.hpp>
+
+namespace realm {
+
+
+class ArrayBigBlobs : public Array {
+public:
+    typedef BinaryData value_type;
+
+    explicit ArrayBigBlobs(Allocator&, bool nullable) noexcept;
+
+    // Disable copying, this is not allowed.
+    ArrayBigBlobs& operator=(const ArrayBigBlobs&) = delete;
+    ArrayBigBlobs(const ArrayBigBlobs&) = delete;
+
+    BinaryData get(size_t ndx) const noexcept;
+    bool is_null(size_t ndx) const;
+    BinaryData get_at(size_t ndx, size_t& pos) const noexcept;
+    void set(size_t ndx, BinaryData value, bool add_zero_term = false);
+    void add(BinaryData value, bool add_zero_term = false);
+    void insert(size_t ndx, BinaryData value, bool add_zero_term = false);
+    void erase(size_t ndx);
+    void truncate(size_t new_size);
+    void clear();
+    void destroy();
+
+    size_t count(BinaryData value, bool is_string = false, size_t begin = 0, size_t end = npos) const noexcept;
+    size_t find_first(BinaryData value, bool is_string = false, size_t begin = 0, size_t end = npos) const noexcept;
+    void find_all(IntegerColumn& result, BinaryData value, bool is_string = false, size_t add_offset = 0,
+                  size_t begin = 0, size_t end = npos);
+
+    /// Get the specified element without the cost of constructing an
+    /// array instance. If an array instance is already available, or
+    /// you need to get multiple values, then this method will be
+    /// slower.
+    static BinaryData get(const char* header, size_t ndx, Allocator&) noexcept;
+
+    //@{
+    /// Those that return a string, discard the terminating zero from
+    /// the stored value. Those that accept a string argument, add a
+    /// terminating zero before storing the value.
+    StringData get_string(size_t ndx) const noexcept;
+    void add_string(StringData value);
+    void set_string(size_t ndx, StringData value);
+    void insert_string(size_t ndx, StringData value);
+    static StringData get_string(const char* header, size_t ndx, Allocator&, bool nullable) noexcept;
+    //@}
+
+    /// Create a new empty big blobs array and attach this accessor to
+    /// it. This does not modify the parent reference information of
+    /// this accessor.
+    ///
+    /// Note that the caller assumes ownership of the allocated
+    /// underlying node. It is not owned by the accessor.
+    void create();
+
+    void verify() const;
+
+private:
+    bool m_nullable;
+};
+
+
+// Implementation:
+
+inline ArrayBigBlobs::ArrayBigBlobs(Allocator& allocator, bool nullable) noexcept
+    : Array(allocator)
+    , m_nullable(nullable)
+{
+}
+
+inline BinaryData ArrayBigBlobs::get(size_t ndx) const noexcept
+{
+    ref_type ref = get_as_ref(ndx);
+    if (ref == 0)
+        return {}; // realm::null();
+
+    const char* blob_header = get_alloc().translate(ref);
+    if (!get_context_flag_from_header(blob_header)) {
+        const char* value = ArrayBlob::get(blob_header, 0);
+        size_t sz = get_size_from_header(blob_header);
+        return BinaryData(value, sz);
+    }
+    return {};
+}
+
+inline bool ArrayBigBlobs::is_null(size_t ndx) const
+{
+    ref_type ref = get_as_ref(ndx);
+    return ref == 0;
+}
+
+inline BinaryData ArrayBigBlobs::get(const char* header, size_t ndx, Allocator& alloc) noexcept
+{
+    ref_type blob_ref = to_ref(Array::get(header, ndx));
+    if (blob_ref == 0)
+        return {};
+
+    const char* blob_header = alloc.translate(blob_ref);
+    if (!get_context_flag_from_header(blob_header)) {
+        const char* blob_data = Array::get_data_from_header(blob_header);
+        size_t sz = Array::get_size_from_header(blob_header);
+        return BinaryData(blob_data, sz);
+    }
+    return {};
+}
+
+inline void ArrayBigBlobs::erase(size_t ndx)
+{
+    ref_type blob_ref = Array::get_as_ref(ndx);
+    if (blob_ref != 0) {                       // nothing to destroy if null
+        Array::destroy_deep(blob_ref, get_alloc()); // Deep
+    }
+    Array::erase(ndx);
+}
+
+inline void ArrayBigBlobs::truncate(size_t new_size)
+{
+    Array::truncate_and_destroy_children(new_size);
+}
+
+inline void ArrayBigBlobs::clear()
+{
+    Array::clear_and_destroy_children();
+}
+
+inline void ArrayBigBlobs::destroy()
+{
+    Array::destroy_deep();
+}
+
+inline StringData ArrayBigBlobs::get_string(size_t ndx) const noexcept
+{
+    BinaryData bin = get(ndx);
+    if (bin.is_null())
+        return realm::null();
+    else
+        return StringData(bin.data(), bin.size() - 1); // Do not include terminating zero
+}
+
+inline void ArrayBigBlobs::set_string(size_t ndx, StringData value)
+{
+    REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null()));
+    BinaryData bin(value.data(), value.size());
+    bool add_zero_term = true;
+    set(ndx, bin, add_zero_term);
+}
+
+inline void ArrayBigBlobs::add_string(StringData value)
+{
+    REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null()));
+    BinaryData bin(value.data(), value.size());
+    bool add_zero_term = true;
+    add(bin, add_zero_term);
+}
+
+inline void ArrayBigBlobs::insert_string(size_t ndx, StringData value)
+{
+    REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null()));
+    BinaryData bin(value.data(), value.size());
+    bool add_zero_term = true;
+    insert(ndx, bin, add_zero_term);
+}
+
+inline StringData ArrayBigBlobs::get_string(const char* header, size_t ndx, Allocator& alloc,
+                                            bool nullable = true) noexcept
+{
+    static_cast<void>(nullable);
+    BinaryData bin = get(header, ndx, alloc);
+    REALM_ASSERT_DEBUG(!(!nullable && bin.is_null()));
+    if (bin.is_null())
+        return realm::null();
+    else
+        return StringData(bin.data(), bin.size() - 1); // Do not include terminating zero
+}
+
+inline void ArrayBigBlobs::create()
+{
+    bool context_flag = true;
+    Array::create(type_HasRefs, context_flag); // Throws
+}
+
+} // namespace realm
+
+#endif // REALM_ARRAY_BIG_BLOBS_HPP

+ 274 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_blobs_small.hpp

@@ -0,0 +1,274 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_BLOBS_SMALL_HPP
+#define REALM_ARRAY_BLOBS_SMALL_HPP
+
+#include <realm/binary_data.hpp>
+#include <realm/array_blob.hpp>
+#include <realm/exceptions.hpp>
+
+namespace realm {
+
+/*
+STORAGE FORMAT
+---------------------------------------------------------------------------------------
+ArraySmallBlobs stores binary elements using two ArrayInteger and one ArrayBlob. The ArrayBlob can only store one
+single concecutive array of bytes (contrary to its 'Array' name that misleadingly indicates it could store multiple
+elements).
+
+Assume we have the strings "a", "", "abc", null, "ab". Then the three arrays will contain:
+
+ArrayInteger    m_offsets   1, 1, 5, 5, 6
+ArrayBlob       m_blob      aabcab
+ArrayInteger    m_nulls     0, 0, 0, 1, 0 // 1 indicates null, 0 indicates non-null
+
+So for each element the ArrayInteger, the ArrayInteger points into the ArrayBlob at the position of the first
+byte of the next element.
+
+m_nulls is always present (except for old database files; see below), so any ArraySmallBlobs is always nullable!
+The nullable property (such as throwing exception upon set(null) on non-nullable column, etc) is handled on
+column level only.
+
+DATABASE FILE VERSION CHANGES
+---------------------------------------------------------------------------------------
+Old database files do not have any m_nulls array. To be backwardscompatible, many methods will have tests like
+`if(Array::size() == 3)` and have a backwards compatible code paths for these (e.g. avoid writing to m_nulls
+in set(), etc). This way no file format upgrade is needed to support nulls for BinaryData.
+*/
+
+class ArraySmallBlobs : public Array {
+public:
+    explicit ArraySmallBlobs(Allocator&) noexcept;
+    ~ArraySmallBlobs() noexcept override
+    {
+    }
+
+    // Disable copying, this is not allowed.
+    ArraySmallBlobs& operator=(const ArraySmallBlobs&) = delete;
+    ArraySmallBlobs(const ArraySmallBlobs&) = delete;
+
+    /// Create a new empty binary array and attach this accessor to
+    /// it. This does not modify the parent reference information of
+    /// this accessor.
+    ///
+    /// Note that the caller assumes ownership of the allocated
+    /// underlying node. It is not owned by the accessor.
+    void create();
+
+    //@{
+    /// Overriding functions of Array
+    void init_from_ref(ref_type) noexcept;
+    void init_from_mem(MemRef) noexcept;
+    void init_from_parent() noexcept;
+    //@}
+
+    bool is_empty() const noexcept;
+    size_t size() const noexcept;
+
+    BinaryData get(size_t ndx) const noexcept;
+    StringData get_string(size_t ndx) const;
+    bool is_null(size_t ndx) const;
+
+    void add(BinaryData value, bool add_zero_term = false);
+    void set(size_t ndx, BinaryData value, bool add_zero_term = false);
+    void insert(size_t ndx, BinaryData value, bool add_zero_term = false);
+    void add_string(StringData value);
+    void set_string(size_t ndx, StringData value);
+    void insert_string(size_t ndx, StringData value);
+    void erase(size_t ndx);
+    void truncate(size_t new_size);
+    void clear();
+    void destroy();
+
+    size_t find_first(BinaryData value, bool is_string, size_t begin, size_t end) const noexcept;
+
+    /// Get the specified element without the cost of constructing an
+    /// array instance. If an array instance is already available, or
+    /// you need to get multiple values, then this method will be
+    /// slower.
+    static BinaryData get(const char* header, size_t ndx, Allocator&) noexcept;
+    static StringData get_string(const char* header, size_t ndx, Allocator& alloc) noexcept;
+
+    static size_t get_size_from_header(const char*, Allocator&) noexcept;
+
+    /// Construct a binary array of the specified size and return just
+    /// the reference to the underlying memory. All elements will be
+    /// initialized to the binary value `defaults`, which can be either
+    /// null or zero-length non-null (value with size > 0 is not allowed as
+    /// initialization value).
+    static MemRef create_array(size_t size, Allocator&, BinaryData defaults);
+
+    void update_from_parent() noexcept;
+
+private:
+    friend class ArrayString;
+    Array m_offsets;
+    ArrayBlob m_blob;
+    Array m_nulls;
+
+    StringData get_string_legacy(size_t ndx) const;
+};
+
+
+// Implementation:
+
+inline ArraySmallBlobs::ArraySmallBlobs(Allocator& allocator) noexcept
+    : Array(allocator)
+    , m_offsets(allocator)
+    , m_blob(allocator)
+    , m_nulls(allocator)
+{
+    m_offsets.set_parent(this, 0);
+    m_blob.set_parent(this, 1);
+    m_nulls.set_parent(this, 2);
+}
+
+inline void ArraySmallBlobs::create()
+{
+    size_t init_size = 0;
+    BinaryData defaults = BinaryData{};                          // This init value is ignored because size = 0
+    MemRef mem = create_array(init_size, get_alloc(), defaults); // Throws
+    init_from_mem(mem);
+}
+
+inline void ArraySmallBlobs::init_from_ref(ref_type ref) noexcept
+{
+    REALM_ASSERT(ref);
+    char* header = get_alloc().translate(ref);
+    init_from_mem(MemRef(header, ref, m_alloc));
+}
+
+inline void ArraySmallBlobs::init_from_parent() noexcept
+{
+    ref_type ref = get_ref_from_parent();
+    init_from_ref(ref);
+}
+
+inline bool ArraySmallBlobs::is_empty() const noexcept
+{
+    return m_offsets.is_empty();
+}
+
+inline size_t ArraySmallBlobs::size() const noexcept
+{
+    return m_offsets.size();
+}
+
+inline BinaryData ArraySmallBlobs::get(size_t ndx) const noexcept
+{
+    REALM_ASSERT_3(ndx, <, m_offsets.size());
+
+    if (m_nulls.get(ndx)) {
+        return BinaryData();
+    }
+    else {
+        size_t begin = ndx ? to_size_t(m_offsets.get(ndx - 1)) : 0;
+        size_t end = to_size_t(m_offsets.get(ndx));
+
+        BinaryData bd = BinaryData(m_blob.get(begin), end - begin);
+        // Old database file (non-nullable column should never return null)
+        REALM_ASSERT(!bd.is_null());
+        return bd;
+    }
+}
+
+inline bool ArraySmallBlobs::is_null(size_t ndx) const
+{
+    REALM_ASSERT_3(ndx, <, m_nulls.size());
+
+    return m_nulls.get(ndx) != 0;
+}
+
+inline StringData ArraySmallBlobs::get_string(size_t ndx) const
+{
+    BinaryData bin = get(ndx);
+    if (bin.is_null())
+        return realm::null();
+    else
+        return StringData(bin.data(), bin.size() - 1); // Do not include terminating zero
+}
+
+inline StringData ArraySmallBlobs::get_string(const char* header, size_t ndx, Allocator& alloc) noexcept
+{
+    BinaryData bin = get(header, ndx, alloc);
+    if (bin.is_null())
+        return realm::null();
+    else
+        return StringData(bin.data(), bin.size() - 1); // Do not include terminating zero
+}
+
+inline void ArraySmallBlobs::add_string(StringData value)
+{
+    add(BinaryData(value.data(), value.size()), true);
+}
+
+inline void ArraySmallBlobs::set_string(size_t ndx, StringData value)
+{
+    set(ndx, BinaryData(value.data(), value.size()), true);
+}
+
+inline void ArraySmallBlobs::insert_string(size_t ndx, StringData value)
+{
+    insert(ndx, BinaryData(value.data(), value.size()), true);
+}
+
+inline void ArraySmallBlobs::truncate(size_t new_size)
+{
+    REALM_ASSERT(new_size == 0 || new_size < m_offsets.size());
+
+    size_t sz = new_size ? to_size_t(m_offsets.get(new_size - 1)) : 0;
+
+    m_offsets.truncate(new_size);
+    m_blob.truncate(sz);
+    m_nulls.truncate(new_size);
+}
+
+inline void ArraySmallBlobs::clear()
+{
+    m_blob.clear();
+    m_offsets.clear();
+    m_nulls.clear();
+}
+
+inline void ArraySmallBlobs::destroy()
+{
+    m_blob.destroy();
+    m_offsets.destroy();
+    m_nulls.destroy();
+    Array::destroy();
+}
+
+inline size_t ArraySmallBlobs::get_size_from_header(const char* header, Allocator& alloc) noexcept
+{
+    ref_type offsets_ref = to_ref(Array::get(header, 0));
+    const char* offsets_header = alloc.translate(offsets_ref);
+    return Array::get_size_from_header(offsets_header);
+}
+
+inline void ArraySmallBlobs::update_from_parent() noexcept
+{
+    Array::update_from_parent();
+    m_blob.update_from_parent();
+    m_offsets.update_from_parent();
+    m_nulls.update_from_parent();
+}
+
+} // namespace realm
+
+#endif // REALM_ARRAY_BINARY_HPP

+ 156 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_bool.hpp

@@ -0,0 +1,156 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_BOOL_HPP
+#define REALM_ARRAY_BOOL_HPP
+
+#include <realm/array.hpp>
+
+namespace realm {
+
+/// ArrayBool supports both nullable and non-nullable arrays with respect to
+/// adding and inserting values. In this way we don't need to distinguish
+/// between the two type when adding a row and when adding a column.
+/// add, insert and getting of non-nullable values are taken care of by the
+/// respective functions in Array.
+class ArrayBool : public Array, public ArrayPayload {
+public:
+    using value_type = bool;
+
+    using Array::Array;
+    using Array::init_from_ref;
+    using Array::init_from_parent;
+    using Array::update_parent;
+    using Array::get_ref;
+    using Array::size;
+    using Array::erase;
+    using Array::truncate_and_destroy_children;
+
+    static bool default_value(bool)
+    {
+        return false;
+    }
+    void create()
+    {
+        Array::create(type_Normal);
+    }
+    void init_from_ref(ref_type ref) noexcept override
+    {
+        Array::init_from_ref(ref);
+    }
+    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override
+    {
+        Array::set_parent(parent, ndx_in_parent);
+    }
+    bool is_null(size_t) const
+    {
+        return false;
+    }
+    void set(size_t ndx, bool value)
+    {
+        Array::set(ndx, value ? 1 : 0);
+    }
+    bool get(size_t ndx) const
+    {
+        return Array::get(ndx) != 0;
+    }
+    Mixed get_any(size_t ndx) const override
+    {
+        return Mixed(get(ndx));
+    }
+    void add(bool value)
+    {
+        Array::add(value);
+    }
+    void insert(size_t ndx, bool value)
+    {
+        Array::insert(ndx, value);
+    }
+
+    size_t find_first(util::Optional<bool> value, size_t begin = 0, size_t end = npos) const noexcept
+    {
+        if (value) {
+            return Array::find_first(*value, begin, end);
+        }
+        else {
+            return Array::find_first(null_value, begin, end);
+        }
+    }
+
+protected:
+    // We can still be in two bits as small values are considered unsigned
+    static constexpr int null_value = 3;
+};
+
+class ArrayBoolNull : public ArrayBool {
+public:
+    using value_type = util::Optional<bool>;
+    using ArrayBool::ArrayBool;
+
+    static util::Optional<bool> default_value(bool nullable)
+    {
+        return nullable ? util::none : util::some<bool>(false);
+    }
+    void set(size_t ndx, util::Optional<bool> value)
+    {
+        if (value) {
+            Array::set(ndx, *value);
+        }
+        else {
+            Array::set(ndx, null_value);
+        }
+    }
+    void add(util::Optional<bool> value)
+    {
+        if (value) {
+            Array::add(*value);
+        }
+        else {
+            Array::add(null_value);
+        }
+    }
+    void insert(size_t ndx, util::Optional<bool> value)
+    {
+        if (value) {
+            Array::insert(ndx, *value);
+        }
+        else {
+            Array::insert(ndx, null_value);
+        }
+    }
+    Mixed get_any(size_t ndx) const override
+    {
+        return Mixed(get(ndx));
+    }
+    void set_null(size_t ndx)
+    {
+        Array::set(ndx, null_value);
+    }
+    bool is_null(size_t ndx) const
+    {
+        return Array::get(ndx) == null_value;
+    }
+    util::Optional<bool> get(size_t ndx) const
+    {
+        int64_t val = Array::get(ndx);
+        return (val == null_value) ? util::none : util::make_optional(val != 0);
+    }
+};
+}
+
+#endif /* REALM_ARRAY_BOOL_HPP */

+ 109 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_decimal128.hpp

@@ -0,0 +1,109 @@
+/*************************************************************************
+ *
+ * Copyright 2019 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_DECIMAL128_HPP
+#define REALM_ARRAY_DECIMAL128_HPP
+
+#include <realm/array.hpp>
+#include <realm/decimal128.hpp>
+
+namespace realm {
+
+class ArrayDecimal128 : public ArrayPayload, private Array {
+public:
+    using value_type = Decimal128;
+
+    using Array::Array;
+    using Array::destroy;
+    using Array::get_ref;
+    using Array::init_from_mem;
+    using Array::init_from_parent;
+    using Array::size;
+    using Array::truncate;
+    using Array::update_parent;
+    using Array::verify;
+
+    static Decimal128 default_value(bool nullable)
+    {
+        return nullable ? Decimal128(realm::null()) : Decimal128(0);
+    }
+
+    void create()
+    {
+        auto mem = Array::create(type_Normal, false, wtype_Multiply, 0, 0, m_alloc); // Throws
+        Array::init_from_mem(mem);
+    }
+
+    void init_from_ref(ref_type ref) noexcept override
+    {
+        Array::init_from_ref(ref);
+    }
+
+    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override
+    {
+        Array::set_parent(parent, ndx_in_parent);
+    }
+
+    bool is_null(size_t ndx) const
+    {
+        return this->get_width() == 0 || get(ndx).is_null();
+    }
+
+    Decimal128 get(size_t ndx) const
+    {
+        REALM_ASSERT(ndx < m_size);
+        auto values = reinterpret_cast<Decimal128*>(this->m_data);
+        return values[ndx];
+    }
+
+    Mixed get_any(size_t ndx) const override
+    {
+        return Mixed(get(ndx));
+    }
+
+    void add(Decimal128 value)
+    {
+        insert(size(), value);
+    }
+
+    void set(size_t ndx, Decimal128 value);
+    void set_null(size_t ndx)
+    {
+        set(ndx, Decimal128(realm::null()));
+    }
+
+    void insert(size_t ndx, Decimal128 value);
+    void erase(size_t ndx);
+    void move(ArrayDecimal128& dst, size_t ndx);
+    void clear()
+    {
+        truncate(0);
+    }
+
+    size_t find_first(Decimal128 value, size_t begin = 0, size_t end = npos) const noexcept;
+
+protected:
+    size_t calc_byte_len(size_t num_items, size_t) const override
+    {
+        return num_items * sizeof(Decimal128) + header_size;
+    }
+};
+
+} // namespace realm
+
+#endif /* REALM_ARRAY_DECIMAL128_HPP */

+ 369 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_direct.hpp

@@ -0,0 +1,369 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_DIRECT_HPP
+#define REALM_ARRAY_DIRECT_HPP
+
+#include <realm/utilities.hpp>
+#include <realm/alloc.hpp>
+
+// clang-format off
+/* wid == 16/32 likely when accessing offsets in B tree */
+#define REALM_TEMPEX(fun, wid, arg) \
+    if (wid == 16) {fun<16> arg;} \
+    else if (wid == 32) {fun<32> arg;} \
+    else if (wid == 0) {fun<0> arg;} \
+    else if (wid == 1) {fun<1> arg;} \
+    else if (wid == 2) {fun<2> arg;} \
+    else if (wid == 4) {fun<4> arg;} \
+    else if (wid == 8) {fun<8> arg;} \
+    else if (wid == 64) {fun<64> arg;} \
+    else {REALM_ASSERT_DEBUG(false); fun<0> arg;}
+
+#define REALM_TEMPEX2(fun, targ, wid, arg) \
+    if (wid == 16) {fun<targ, 16> arg;} \
+    else if (wid == 32) {fun<targ, 32> arg;} \
+    else if (wid == 0) {fun<targ, 0> arg;} \
+    else if (wid == 1) {fun<targ, 1> arg;} \
+    else if (wid == 2) {fun<targ, 2> arg;} \
+    else if (wid == 4) {fun<targ, 4> arg;} \
+    else if (wid == 8) {fun<targ, 8> arg;} \
+    else if (wid == 64) {fun<targ, 64> arg;} \
+    else {REALM_ASSERT_DEBUG(false); fun<targ, 0> arg;}
+
+#define REALM_TEMPEX3(fun, targ1, wid, targ3, arg) \
+    if (wid == 16) {fun<targ1, 16, targ3> arg;} \
+    else if (wid == 32) {fun<targ1, 32, targ3> arg;} \
+    else if (wid == 0) {fun<targ1, 0, targ3> arg;} \
+    else if (wid == 1) {fun<targ1, 1, targ3> arg;} \
+    else if (wid == 2) {fun<targ1, 2, targ3> arg;} \
+    else if (wid == 4) {fun<targ1, 4, targ3> arg;} \
+    else if (wid == 8) {fun<targ1, 8, targ3> arg;} \
+    else if (wid == 64) {fun<targ1, 64, targ3> arg;} \
+    else {REALM_ASSERT_DEBUG(false); fun<targ1, 0, targ3> arg;}
+
+#define REALM_TEMPEX4(fun, targ1, targ3, targ4, wid, arg) \
+    if (wid == 16) {fun<targ1, targ3, targ4, 16> arg;} \
+    else if (wid == 32) {fun<targ1, targ3, targ4, 32> arg;} \
+    else if (wid == 0) {fun<targ1, targ3, targ4, 0> arg;} \
+    else if (wid == 1) {fun<targ1, targ3, targ4, 1> arg;} \
+    else if (wid == 2) {fun<targ1, targ3, targ4, 2> arg;} \
+    else if (wid == 4) {fun<targ1, targ3, targ4, 4> arg;} \
+    else if (wid == 8) {fun<targ1, targ3, targ4, 8> arg;} \
+    else if (wid == 64) {fun<targ1, targ3, targ4, 64> arg;} \
+    else {REALM_ASSERT_DEBUG(false); fun<targ1, targ3, targ4, 0> arg;}
+// clang-format on
+
+namespace realm {
+
+/// Takes a 64-bit value and returns the minimum number of bits needed
+/// to fit the value. For alignment this is rounded up to nearest
+/// log2. Posssible results {0, 1, 2, 4, 8, 16, 32, 64}
+size_t bit_width(int64_t value);
+
+// Direct access methods
+
+template <size_t width>
+void set_direct(char* data, size_t ndx, int_fast64_t value) noexcept
+{
+    if (width == 0) {
+        REALM_ASSERT_DEBUG(value == 0);
+        return;
+    }
+    else if (width == 1) {
+        REALM_ASSERT_DEBUG(0 <= value && value <= 0x01);
+        size_t byte_ndx = ndx / 8;
+        size_t bit_ndx = ndx % 8;
+        typedef unsigned char uchar;
+        uchar* p = reinterpret_cast<uchar*>(data) + byte_ndx;
+        *p = uchar((*p & ~(0x01 << bit_ndx)) | (int(value) & 0x01) << bit_ndx);
+    }
+    else if (width == 2) {
+        REALM_ASSERT_DEBUG(0 <= value && value <= 0x03);
+        size_t byte_ndx = ndx / 4;
+        size_t bit_ndx = ndx % 4 * 2;
+        typedef unsigned char uchar;
+        uchar* p = reinterpret_cast<uchar*>(data) + byte_ndx;
+        *p = uchar((*p & ~(0x03 << bit_ndx)) | (int(value) & 0x03) << bit_ndx);
+    }
+    else if (width == 4) {
+        REALM_ASSERT_DEBUG(0 <= value && value <= 0x0F);
+        size_t byte_ndx = ndx / 2;
+        size_t bit_ndx = ndx % 2 * 4;
+        typedef unsigned char uchar;
+        uchar* p = reinterpret_cast<uchar*>(data) + byte_ndx;
+        *p = uchar((*p & ~(0x0F << bit_ndx)) | (int(value) & 0x0F) << bit_ndx);
+    }
+    else if (width == 8) {
+        REALM_ASSERT_DEBUG(std::numeric_limits<int8_t>::min() <= value &&
+                           value <= std::numeric_limits<int8_t>::max());
+        *(reinterpret_cast<int8_t*>(data) + ndx) = int8_t(value);
+    }
+    else if (width == 16) {
+        REALM_ASSERT_DEBUG(std::numeric_limits<int16_t>::min() <= value &&
+                           value <= std::numeric_limits<int16_t>::max());
+        *(reinterpret_cast<int16_t*>(data) + ndx) = int16_t(value);
+    }
+    else if (width == 32) {
+        REALM_ASSERT_DEBUG(std::numeric_limits<int32_t>::min() <= value &&
+                           value <= std::numeric_limits<int32_t>::max());
+        *(reinterpret_cast<int32_t*>(data) + ndx) = int32_t(value);
+    }
+    else if (width == 64) {
+        REALM_ASSERT_DEBUG(std::numeric_limits<int64_t>::min() <= value &&
+                           value <= std::numeric_limits<int64_t>::max());
+        *(reinterpret_cast<int64_t*>(data) + ndx) = int64_t(value);
+    }
+    else {
+        REALM_ASSERT_DEBUG(false);
+    }
+}
+
+inline void set_direct(char* data, size_t width, size_t ndx, int_fast64_t value) noexcept
+{
+    REALM_TEMPEX(set_direct, width, (data, ndx, value));
+}
+
+template <size_t width>
+void fill_direct(char* data, size_t begin, size_t end, int_fast64_t value) noexcept
+{
+    for (size_t i = begin; i != end; ++i)
+        set_direct<width>(data, i, value);
+}
+
+template <int w>
+int64_t get_direct(const char* data, size_t ndx) noexcept
+{
+    if (w == 0) {
+        return 0;
+    }
+    if (w == 1) {
+        size_t offset = ndx >> 3;
+        return (data[offset] >> (ndx & 7)) & 0x01;
+    }
+    if (w == 2) {
+        size_t offset = ndx >> 2;
+        return (data[offset] >> ((ndx & 3) << 1)) & 0x03;
+    }
+    if (w == 4) {
+        size_t offset = ndx >> 1;
+        return (data[offset] >> ((ndx & 1) << 2)) & 0x0F;
+    }
+    if (w == 8) {
+        return *reinterpret_cast<const signed char*>(data + ndx);
+    }
+    if (w == 16) {
+        size_t offset = ndx * 2;
+        return *reinterpret_cast<const int16_t*>(data + offset);
+    }
+    if (w == 32) {
+        size_t offset = ndx * 4;
+        return *reinterpret_cast<const int32_t*>(data + offset);
+    }
+    if (w == 64) {
+        size_t offset = ndx * 8;
+        return *reinterpret_cast<const int64_t*>(data + offset);
+    }
+    REALM_ASSERT_DEBUG(false);
+    return int64_t(-1);
+}
+
+inline int64_t get_direct(const char* data, size_t width, size_t ndx) noexcept
+{
+    REALM_TEMPEX(return get_direct, width, (data, ndx));
+}
+
+
+template <int width>
+inline std::pair<int64_t, int64_t> get_two(const char* data, size_t ndx) noexcept
+{
+    return std::make_pair(to_size_t(get_direct<width>(data, ndx + 0)), to_size_t(get_direct<width>(data, ndx + 1)));
+}
+
+inline std::pair<int64_t, int64_t> get_two(const char* data, size_t width, size_t ndx) noexcept
+{
+    REALM_TEMPEX(return get_two, width, (data, ndx));
+}
+
+
+template <int width>
+inline void get_three(const char* data, size_t ndx, ref_type& v0, ref_type& v1, ref_type& v2) noexcept
+{
+    v0 = to_ref(get_direct<width>(data, ndx + 0));
+    v1 = to_ref(get_direct<width>(data, ndx + 1));
+    v2 = to_ref(get_direct<width>(data, ndx + 2));
+}
+
+inline void get_three(const char* data, size_t width, size_t ndx, ref_type& v0, ref_type& v1, ref_type& v2) noexcept
+{
+    REALM_TEMPEX(get_three, width, (data, ndx, v0, v1, v2));
+}
+
+
+// Lower/upper bound in sorted sequence
+// ------------------------------------
+//
+//   3 3 3 4 4 4 5 6 7 9 9 9
+//   ^     ^     ^     ^     ^
+//   |     |     |     |     |
+//   |     |     |     |      -- Lower and upper bound of 15
+//   |     |     |     |
+//   |     |     |      -- Lower and upper bound of 8
+//   |     |     |
+//   |     |      -- Upper bound of 4
+//   |     |
+//   |      -- Lower bound of 4
+//   |
+//    -- Lower and upper bound of 1
+//
+// These functions are semantically identical to std::lower_bound() and
+// std::upper_bound().
+//
+// We currently use binary search. See for example
+// http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary.
+template <int width>
+inline size_t lower_bound(const char* data, size_t size, int64_t value) noexcept
+{
+    // The binary search used here is carefully optimized. Key trick is to use a single
+    // loop controlling variable (size) instead of high/low pair, and to keep updates
+    // to size done inside the loop independent of comparisons. Further key to speed
+    // is to avoid branching inside the loop, using conditional moves instead. This
+    // provides robust performance for random searches, though predictable searches
+    // might be slightly faster if we used branches instead. The loop unrolling yields
+    // a final 5-20% speedup depending on circumstances.
+
+    size_t low = 0;
+
+    while (size >= 8) {
+        // The following code (at X, Y and Z) is 3 times manually unrolled instances of (A) below.
+        // These code blocks must be kept in sync. Meassurements indicate 3 times unrolling to give
+        // the best performance. See (A) for comments on the loop body.
+        // (X)
+        size_t half = size / 2;
+        size_t other_half = size - half;
+        size_t probe = low + half;
+        size_t other_low = low + other_half;
+        int64_t v = get_direct<width>(data, probe);
+        size = half;
+        low = (v < value) ? other_low : low;
+
+        // (Y)
+        half = size / 2;
+        other_half = size - half;
+        probe = low + half;
+        other_low = low + other_half;
+        v = get_direct<width>(data, probe);
+        size = half;
+        low = (v < value) ? other_low : low;
+
+        // (Z)
+        half = size / 2;
+        other_half = size - half;
+        probe = low + half;
+        other_low = low + other_half;
+        v = get_direct<width>(data, probe);
+        size = half;
+        low = (v < value) ? other_low : low;
+    }
+    while (size > 0) {
+        // (A)
+        // To understand the idea in this code, please note that
+        // for performance, computation of size for the next iteration
+        // MUST be INDEPENDENT of the conditional. This allows the
+        // processor to unroll the loop as fast as possible, and it
+        // minimizes the length of dependence chains leading up to branches.
+        // Making the unfolding of the loop independent of the data being
+        // searched, also minimizes the delays incurred by branch
+        // mispredictions, because they can be determined earlier
+        // and the speculation corrected earlier.
+
+        // Counterintuitive:
+        // To make size independent of data, we cannot always split the
+        // range at the theoretical optimal point. When we determine that
+        // the key is larger than the probe at some index K, and prepare
+        // to search the upper part of the range, you would normally start
+        // the search at the next index, K+1, to get the shortest range.
+        // We can only do this when splitting a range with odd number of entries.
+        // If there is an even number of entries we search from K instead of K+1.
+        // This potentially leads to redundant comparisons, but in practice we
+        // gain more performance by making the changes to size predictable.
+
+        // if size is even, half and other_half are the same.
+        // if size is odd, half is one less than other_half.
+        size_t half = size / 2;
+        size_t other_half = size - half;
+        size_t probe = low + half;
+        size_t other_low = low + other_half;
+        int64_t v = get_direct<width>(data, probe);
+        size = half;
+        // for max performance, the line below should compile into a conditional
+        // move instruction. Not all compilers do this. To maximize chance
+        // of succes, no computation should be done in the branches of the
+        // conditional.
+        low = (v < value) ? other_low : low;
+    };
+
+    return low;
+}
+
+// See lower_bound()
+template <int width>
+inline size_t upper_bound(const char* data, size_t size, int64_t value) noexcept
+{
+    size_t low = 0;
+    while (size >= 8) {
+        size_t half = size / 2;
+        size_t other_half = size - half;
+        size_t probe = low + half;
+        size_t other_low = low + other_half;
+        int64_t v = get_direct<width>(data, probe);
+        size = half;
+        low = (value >= v) ? other_low : low;
+
+        half = size / 2;
+        other_half = size - half;
+        probe = low + half;
+        other_low = low + other_half;
+        v = get_direct<width>(data, probe);
+        size = half;
+        low = (value >= v) ? other_low : low;
+
+        half = size / 2;
+        other_half = size - half;
+        probe = low + half;
+        other_low = low + other_half;
+        v = get_direct<width>(data, probe);
+        size = half;
+        low = (value >= v) ? other_low : low;
+    }
+
+    while (size > 0) {
+        size_t half = size / 2;
+        size_t other_half = size - half;
+        size_t probe = low + half;
+        size_t other_low = low + other_half;
+        int64_t v = get_direct<width>(data, probe);
+        size = half;
+        low = (value >= v) ? other_low : low;
+    };
+
+    return low;
+}
+}
+
+#endif /* ARRAY_TPL_HPP_ */

+ 240 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_fixed_bytes.hpp

@@ -0,0 +1,240 @@
+/*************************************************************************
+ *
+ * Copyright 2019 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_FIXED_BYTES_HPP
+#define REALM_ARRAY_FIXED_BYTES_HPP
+
+#include <realm/array.hpp>
+#include <realm/object_id.hpp>
+#include <realm/uuid.hpp>
+
+namespace realm {
+
+template <class ObjectType, int ElementSize>
+class ArrayFixedBytes : public ArrayPayload, protected Array {
+public:
+    using value_type = ObjectType;
+    using self_type = ArrayFixedBytes<ObjectType, ElementSize>;
+
+    using Array::Array;
+    using Array::destroy;
+    using Array::get_ref;
+    using Array::init_from_mem;
+    using Array::init_from_parent;
+    using Array::update_parent;
+    using Array::verify;
+
+    static ObjectType default_value(bool nullable)
+    {
+        REALM_ASSERT(!nullable);
+        return ObjectType();
+    }
+
+    void create()
+    {
+        auto mem = Array::create(type_Normal, false, wtype_Multiply, 0, 0, m_alloc); // Throws
+        Array::init_from_mem(mem);
+    }
+
+    void init_from_ref(ref_type ref) noexcept override
+    {
+        Array::init_from_ref(ref);
+    }
+
+    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override
+    {
+        Array::set_parent(parent, ndx_in_parent);
+    }
+
+    size_t size() const
+    {
+        auto data_bytes = m_size - div_round_up<s_block_size>(m_size); // remove one byte per block.
+        return data_bytes / s_width;
+    }
+
+    bool is_null(size_t ndx) const
+    {
+        return this->get_width() == 0 || get_pos(ndx).is_null(this);
+    }
+
+    ObjectType get(size_t ndx) const
+    {
+        REALM_ASSERT(is_valid_ndx(ndx));
+        REALM_ASSERT(!is_null(ndx));
+        return get_pos(ndx).get_value(this);
+    }
+
+    Mixed get_any(size_t ndx) const override
+    {
+        return Mixed(get(ndx));
+    }
+
+    void add(const ObjectType& value)
+    {
+        insert(size(), value);
+    }
+
+    void set(size_t ndx, const ObjectType& value);
+    void insert(size_t ndx, const ObjectType& value);
+    void erase(size_t ndx);
+    void move(ArrayFixedBytes<ObjectType, ElementSize>& dst, size_t ndx);
+    void clear()
+    {
+        truncate(0);
+    }
+    void truncate(size_t ndx)
+    {
+        Array::truncate(calc_required_bytes(ndx));
+    }
+
+    size_t find_first(const ObjectType& value, size_t begin = 0, size_t end = npos) const noexcept;
+
+protected:
+    static constexpr size_t s_width = ElementSize; // Size of each element
+
+    // A block is a byte bitvector indicating null entries and 8 ObjectIds.
+    static constexpr size_t s_block_size = s_width * 8 + 1; // 97
+
+    template <size_t div>
+    static size_t div_round_up(size_t num)
+    {
+        return (num + div - 1) / div;
+    }
+
+    // An accessor for the data at a given index. All casting and offset calculation should be kept here.
+    struct Pos {
+        size_t base_byte;
+        size_t offset;
+
+        void set_value(self_type* arr, const ObjectType& val) const
+        {
+            reinterpret_cast<ObjectType*>(arr->m_data + base_byte + 1 /*null bit byte*/)[offset] = val;
+        }
+        const ObjectType& get_value(const self_type* arr) const
+        {
+            return reinterpret_cast<const ObjectType*>(arr->m_data + base_byte + 1 /*null bit byte*/)[offset];
+        }
+
+        void set_null(self_type* arr, bool new_is_null) const
+        {
+            auto& bitvec = arr->m_data[base_byte];
+            if (new_is_null) {
+                bitvec |= 1 << offset;
+            }
+            else {
+                bitvec &= ~(1 << offset);
+            }
+        }
+        bool is_null(const self_type* arr) const
+        {
+            return arr->m_data[base_byte] & (1 << offset);
+        }
+    };
+
+    static Pos get_pos(size_t ndx)
+    {
+
+        return Pos{(ndx / 8) * s_block_size, ndx % 8};
+    }
+
+    static size_t calc_required_bytes(size_t num_items)
+    {
+        return (num_items * s_width) +       // ObjectId data
+               (div_round_up<8>(num_items)); // null bitvectors (1 byte per 8 oids, rounded up)
+    }
+
+    size_t calc_byte_len(size_t num_items, size_t /*unused width*/ = 0) const override
+    {
+        return num_items + Node::header_size;
+    }
+
+    bool is_valid_ndx(size_t ndx) const
+    {
+        return calc_byte_len(ndx) <= m_size;
+    }
+};
+
+// The nullable ObjectType array uses the same layout and is compatible with the non-nullable one. It adds support for
+// operations on null. Because the base class maintains null markers, we are able to defer to it for many operations.
+template <class ObjectType, int ElementSize>
+class ArrayFixedBytesNull : public ArrayFixedBytes<ObjectType, ElementSize> {
+public:
+    using Base = ArrayFixedBytes<ObjectType, ElementSize>;
+    ArrayFixedBytesNull(Allocator& alloc) noexcept
+        : ArrayFixedBytes<ObjectType, ElementSize>(alloc)
+    {
+    }
+    static constexpr util::Optional<ObjectType> default_value(bool nullable)
+    {
+        if (nullable)
+            return util::none;
+        return ObjectType();
+    }
+
+    void set(size_t ndx, const util::Optional<ObjectType>& value)
+    {
+        if (value) {
+            Base::set(ndx, *value);
+        }
+        else {
+            set_null(ndx);
+        }
+    }
+    void add(const util::Optional<ObjectType>& value)
+    {
+        insert(this->size(), value);
+    }
+    void insert(size_t ndx, const util::Optional<ObjectType>& value);
+    void set_null(size_t ndx);
+    util::Optional<ObjectType> get(size_t ndx) const noexcept
+    {
+        auto pos = this->get_pos(ndx);
+        if (pos.is_null(this)) {
+            return util::none;
+        }
+        return pos.get_value(this);
+    }
+    Mixed get_any(size_t ndx) const override
+    {
+        return Mixed(get(ndx));
+    }
+    size_t find_first(const util::Optional<ObjectType>& value, size_t begin = 0, size_t end = npos) const
+    {
+        if (value) {
+            return Base::find_first(*value, begin, end);
+        }
+        else {
+            return find_first_null(begin, end);
+        }
+    }
+    size_t find_first_null(size_t begin = 0, size_t end = npos) const;
+};
+
+typedef ArrayFixedBytes<ObjectId, ObjectId::num_bytes> ArrayObjectId;
+typedef ArrayFixedBytesNull<ObjectId, ObjectId::num_bytes> ArrayObjectIdNull;
+typedef ArrayFixedBytes<UUID, UUID::num_bytes> ArrayUUID;
+typedef ArrayFixedBytesNull<UUID, UUID::num_bytes> ArrayUUIDNull;
+
+extern template class ArrayFixedBytes<ObjectId, ObjectId::num_bytes>;
+extern template class ArrayFixedBytesNull<ObjectId, ObjectId::num_bytes>;
+extern template class ArrayFixedBytes<UUID, UUID::num_bytes>;
+extern template class ArrayFixedBytesNull<UUID, UUID::num_bytes>;
+
+} // namespace realm
+
+#endif /* REALM_ARRAY_FIXED_BYTES_HPP */

+ 383 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_integer.hpp

@@ -0,0 +1,383 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_INTEGER_HPP
+#define REALM_ARRAY_INTEGER_HPP
+
+#include <realm/array.hpp>
+#include <realm/util/safe_int_ops.hpp>
+#include <realm/util/optional.hpp>
+#include <realm/array_key.hpp>
+
+namespace realm {
+
+class ArrayInteger : public Array, public ArrayPayload {
+public:
+    using value_type = int64_t;
+
+    using Array::add;
+    using Array::get;
+    using Array::insert;
+    using Array::move;
+    using Array::set;
+
+    explicit ArrayInteger(Allocator&) noexcept;
+    ~ArrayInteger() noexcept override {}
+
+    static value_type default_value(bool)
+    {
+        return 0;
+    }
+
+    void init_from_ref(ref_type ref) noexcept override
+    {
+        Array::init_from_ref(ref);
+    }
+    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override
+    {
+        Array::set_parent(parent, ndx_in_parent);
+    }
+
+    // Disable copying, this is not allowed.
+    ArrayInteger& operator=(const ArrayInteger&) = delete;
+    ArrayInteger(const ArrayInteger&) = delete;
+
+    void create()
+    {
+        Array::create(type_Normal, false, 0, 0);
+    }
+    Mixed get_any(size_t ndx) const override;
+
+    bool is_null(size_t) const
+    {
+        return false;
+    }
+};
+
+
+class ArrayIntNull : public Array, public ArrayPayload {
+public:
+    using value_type = util::Optional<int64_t>;
+
+    explicit ArrayIntNull(Allocator&) noexcept;
+    ~ArrayIntNull() noexcept override;
+
+    static value_type default_value(bool nullable)
+    {
+        return nullable ? util::none : util::Optional<int64_t>(0);
+    }
+
+    /// Construct an array of the specified type and size, and return just the
+    /// reference to the underlying memory. All elements will be initialized to
+    /// the specified value.
+    static MemRef create_array(Type, bool context_flag, size_t size, Allocator&);
+    void create()
+    {
+        MemRef r = create_array(type_Normal, false, 0, m_alloc);
+        init_from_mem(r);
+    }
+
+    void init_from_ref(ref_type) noexcept override;
+    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override
+    {
+        Array::set_parent(parent, ndx_in_parent);
+    }
+    void init_from_mem(MemRef) noexcept;
+    void init_from_parent() noexcept;
+
+    size_t size() const noexcept;
+    bool is_empty() const noexcept;
+
+    void insert(size_t ndx, value_type value);
+    void add(value_type value);
+    void set(size_t ndx, value_type value);
+    value_type get(size_t ndx) const noexcept;
+    Mixed get_any(size_t ndx) const override;
+    static value_type get(const char* header, size_t ndx) noexcept;
+    void get_chunk(size_t ndx, value_type res[8]) const noexcept;
+    void set_null(size_t ndx);
+    bool is_null(size_t ndx) const noexcept;
+    int64_t null_value() const noexcept;
+
+    void erase(size_t ndx);
+    void erase(size_t begin, size_t end);
+    void move(ArrayIntNull& dst, size_t ndx);
+    void clear();
+
+    void move(size_t begin, size_t end, size_t dest_begin);
+
+    bool find(int cond, value_type value, size_t start, size_t end, size_t baseindex, QueryStateBase* state) const;
+
+    // This is the one installed into the m_finder slots.
+    template <class cond, size_t bitwidth>
+    bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryStateBase* state) const;
+
+    template <class cond, class Callback>
+    bool find(value_type value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+              Callback callback) const;
+
+    // Wrappers for backwards compatibility and for simple use without
+    // setting up state initialization etc
+    template <class cond>
+    size_t find_first(value_type value, size_t start = 0, size_t end = npos) const;
+
+    void find_all(IntegerColumn* result, value_type value, size_t col_offset = 0, size_t begin = 0,
+                  size_t end = npos) const;
+
+
+    size_t find_first(value_type value, size_t begin = 0, size_t end = npos) const;
+
+protected:
+    void avoid_null_collision(int64_t value);
+
+private:
+    int_fast64_t choose_random_null(int64_t incoming) const;
+    void replace_nulls_with(int64_t new_null);
+    bool can_use_as_null(int64_t value) const;
+
+    template <class Callback>
+    bool find_impl(int cond, value_type value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                   Callback callback) const;
+    template <class cond, class Callback>
+    bool find_impl(value_type value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                   Callback callback) const;
+};
+
+
+// Implementation:
+
+inline ArrayInteger::ArrayInteger(Allocator& allocator) noexcept
+    : Array(allocator)
+{
+    m_is_inner_bptree_node = false;
+}
+
+inline ArrayIntNull::ArrayIntNull(Allocator& allocator) noexcept
+    : Array(allocator)
+{
+}
+
+inline ArrayIntNull::~ArrayIntNull() noexcept {}
+
+inline size_t ArrayIntNull::size() const noexcept
+{
+    return Array::size() - 1;
+}
+
+inline bool ArrayIntNull::is_empty() const noexcept
+{
+    return size() == 0;
+}
+
+inline void ArrayIntNull::insert(size_t ndx, value_type value)
+{
+    if (value) {
+        avoid_null_collision(*value);
+        Array::insert(ndx + 1, *value);
+    }
+    else {
+        Array::insert(ndx + 1, null_value());
+    }
+}
+
+inline void ArrayIntNull::add(value_type value)
+{
+    if (value) {
+        avoid_null_collision(*value);
+        Array::add(*value);
+    }
+    else {
+        Array::add(null_value());
+    }
+}
+
+inline void ArrayIntNull::set(size_t ndx, value_type value)
+{
+    if (value) {
+        avoid_null_collision(*value);
+        Array::set(ndx + 1, *value);
+    }
+    else {
+        Array::set(ndx + 1, null_value());
+    }
+}
+
+inline void ArrayIntNull::set_null(size_t ndx)
+{
+    Array::set(ndx + 1, null_value());
+}
+
+inline ArrayIntNull::value_type ArrayIntNull::get(size_t ndx) const noexcept
+{
+    int64_t value = Array::get(ndx + 1);
+    if (value == null_value()) {
+        return util::none;
+    }
+    return util::some<int64_t>(value);
+}
+
+inline ArrayIntNull::value_type ArrayIntNull::get(const char* header, size_t ndx) noexcept
+{
+    int64_t null_value = Array::get(header, 0);
+    int64_t value = Array::get(header, ndx + 1);
+    if (value == null_value) {
+        return util::none;
+    }
+    else {
+        return util::some<int64_t>(value);
+    }
+}
+
+inline bool ArrayIntNull::is_null(size_t ndx) const noexcept
+{
+    return !get(ndx);
+}
+
+inline int64_t ArrayIntNull::null_value() const noexcept
+{
+    return Array::get(0);
+}
+
+inline void ArrayIntNull::erase(size_t ndx)
+{
+    Array::erase(ndx + 1);
+}
+
+inline void ArrayIntNull::erase(size_t begin, size_t end)
+{
+    Array::erase(begin + 1, end + 1);
+}
+
+inline void ArrayIntNull::clear()
+{
+    Array::truncate(0);
+    Array::add(0);
+}
+
+inline void ArrayIntNull::move(size_t begin, size_t end, size_t dest_begin)
+{
+    Array::move(begin + 1, end + 1, dest_begin + 1);
+}
+
+inline bool ArrayIntNull::find(int cond, value_type value, size_t start, size_t end, size_t baseindex,
+                               QueryStateBase* state) const
+{
+    return find_impl(cond, value, start, end, baseindex, state, nullptr);
+}
+
+template <class cond, class Callback>
+inline bool ArrayIntNull::find(value_type value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                               Callback callback) const
+{
+    return find_impl<cond, Callback>(value, start, end, baseindex, state, callback);
+}
+
+template <class Callback>
+inline bool ArrayIntNull::find_impl(int cond, value_type value, size_t start, size_t end, size_t baseindex,
+                                    QueryStateBase* state, Callback callback) const
+{
+    switch (cond) {
+        case cond_Equal:
+            return find_impl<Equal>(value, start, end, baseindex, state, callback);
+        case cond_NotEqual:
+            return find_impl<NotEqual>(value, start, end, baseindex, state, callback);
+        case cond_Greater:
+            return find_impl<Greater>(value, start, end, baseindex, state, callback);
+        case cond_Less:
+            return find_impl<Less>(value, start, end, baseindex, state, callback);
+        case cond_None:
+            return find_impl<None>(value, start, end, baseindex, state, callback);
+        case cond_LeftNotNull:
+            return find_impl<NotNull>(value, start, end, baseindex, state, callback);
+    }
+    REALM_ASSERT_DEBUG(false);
+    return false;
+}
+
+template <class cond, class Callback>
+bool ArrayIntNull::find_impl(value_type opt_value, size_t start, size_t end, size_t baseindex, QueryStateBase* state,
+                             Callback callback) const
+{
+    int64_t null_value = Array::get(0);
+    bool find_null = !bool(opt_value);
+    int64_t value;
+
+    size_t end2 = (end == npos ? size() : end) + 1;
+    size_t start2 = start + 1;
+    size_t baseindex2 = baseindex - 1;
+
+    if constexpr (std::is_same_v<cond, Equal>) {
+        if (find_null) {
+            value = null_value;
+        }
+        else {
+            if (*opt_value == null_value) {
+                // If the value to search for is equal to the null value, the value cannot be in the array
+                return true;
+            }
+            else {
+                value = *opt_value;
+            }
+        }
+
+        // Fall back to plain Array find.
+        return Array::find<cond>(value, start2, end2, baseindex2, state, callback);
+    }
+    else {
+        cond c;
+
+        if (opt_value) {
+            value = *opt_value;
+        }
+        else {
+            value = null_value;
+        }
+
+        for (size_t i = start2; i < end2; ++i) {
+            int64_t v = Array::get(i);
+            bool value_is_null = (v == null_value);
+            if (c(v, value, value_is_null, find_null)) {
+                util::Optional<int64_t> v2 = value_is_null ? util::none : util::make_optional(v);
+                if (!Array::find_action(i + baseindex2, v2, state, callback)) {
+                    return false; // tell caller to stop aggregating/search
+                }
+            }
+        }
+        return true; // tell caller to continue aggregating/search (on next array leafs)
+    }
+}
+
+template <class cond>
+size_t ArrayIntNull::find_first(value_type value, size_t start, size_t end) const
+{
+    QueryStateFindFirst state;
+    find_impl<cond>(value, start, end, 0, &state, nullptr);
+
+    if (state.m_match_count > 0)
+        return to_size_t(state.m_state);
+    else
+        return not_found;
+}
+
+inline size_t ArrayIntNull::find_first(value_type value, size_t begin, size_t end) const
+{
+    return find_first<Equal>(value, begin, end);
+}
+} // namespace realm
+
+#endif // REALM_ARRAY_INTEGER_HPP

+ 132 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_key.hpp

@@ -0,0 +1,132 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_KEY_HPP
+#define REALM_ARRAY_KEY_HPP
+
+#include <realm/array.hpp>
+#include <realm/cluster.hpp>
+#include <realm/impl/destroy_guard.hpp>
+
+namespace realm {
+
+// If this class is used directly in a cluster leaf, the links are stored as the
+// link value +1 in order to represent the null_key (-1) as 0. If the class is used
+// in BPlusTree<ObjKey> class, the values should not be adjusted.
+template <int adj>
+class ArrayKeyBase : public ArrayPayload, private Array {
+public:
+    using value_type = ObjKey;
+
+    using Array::is_attached;
+    using Array::init_from_mem;
+    using Array::init_from_parent;
+    using Array::update_parent;
+    using Array::get_ref;
+    using Array::size;
+    using Array::erase;
+    using Array::clear;
+    using Array::destroy;
+
+    ArrayKeyBase(Allocator& allocator)
+        : Array(allocator)
+    {
+    }
+
+    static ObjKey default_value(bool)
+    {
+        return {};
+    }
+
+    void init_from_ref(ref_type ref) noexcept override
+    {
+        Array::init_from_ref(ref);
+    }
+
+    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override
+    {
+        Array::set_parent(parent, ndx_in_parent);
+    }
+
+    void create()
+    {
+        Array::create(type_Normal);
+    }
+
+    void add(ObjKey value)
+    {
+        Array::add(value.value + adj);
+    }
+    void set(size_t ndx, ObjKey value)
+    {
+        Array::set(ndx, value.value + adj);
+    }
+
+    void set_null(size_t ndx)
+    {
+        Array::set(ndx, 0);
+    }
+    void insert(size_t ndx, ObjKey value)
+    {
+        Array::insert(ndx, value.value + adj);
+    }
+    ObjKey get(size_t ndx) const
+    {
+        return ObjKey{Array::get(ndx) - adj};
+    }
+    Mixed get_any(size_t ndx) const override
+    {
+        return Mixed(get(ndx));
+    }
+    bool is_null(size_t ndx) const
+    {
+        ObjKey key = get(ndx);
+        return !key || key.is_unresolved();
+    }
+    void move(ArrayKeyBase& dst, size_t ndx)
+    {
+        Array::move(dst, ndx);
+    }
+
+    size_t find_first(ObjKey value, size_t begin, size_t end) const noexcept
+    {
+        return Array::find_first(value.value + adj, begin, end);
+    }
+
+    void nullify(ObjKey key)
+    {
+        size_t begin = find_first(key, 0, Array::size());
+        // There must be one
+        REALM_ASSERT(begin != realm::npos);
+        Array::erase(begin);
+    }
+    void verify() const;
+};
+
+class ArrayKey : public ArrayKeyBase<1> {
+public:
+    using ArrayKeyBase::ArrayKeyBase;
+};
+
+class ArrayKeyNonNullable : public ArrayKeyBase<0> {
+public:
+    using ArrayKeyBase::ArrayKeyBase;
+};
+}
+
+#endif /* SRC_REALM_ARRAY_KEY_HPP_ */

+ 99 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_list.hpp

@@ -0,0 +1,99 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_LIST_HPP
+#define REALM_ARRAY_LIST_HPP
+
+#include <realm/array.hpp>
+
+namespace realm {
+
+class ArrayList : public ArrayPayload, private Array {
+public:
+    using value_type = ref_type;
+
+    using Array::Array;
+    using Array::init_from_parent;
+    using Array::update_parent;
+    using Array::get_ref;
+    using Array::size;
+    using Array::erase;
+
+    static ref_type default_value(bool)
+    {
+        return 0;
+    }
+
+    void init_from_ref(ref_type ref) noexcept override
+    {
+        Array::init_from_ref(ref);
+    }
+
+    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override
+    {
+        Array::set_parent(parent, ndx_in_parent);
+    }
+
+    void create()
+    {
+        Array::create(type_HasRefs);
+    }
+
+    void add(ref_type value)
+    {
+        Array::add(from_ref(value));
+    }
+    void set(size_t ndx, ref_type value)
+    {
+        Array::set_as_ref(ndx, value);
+    }
+
+    void set_null(size_t ndx)
+    {
+        Array::set(ndx, 0);
+    }
+    void insert(size_t ndx, ref_type value)
+    {
+        Array::insert(ndx, from_ref(value));
+    }
+    ref_type get(size_t ndx) const
+    {
+        return Array::get_as_ref(ndx);
+    }
+    Mixed get_any(size_t) const override
+    {
+        REALM_ASSERT_DEBUG(false);
+        return {};
+    }
+    bool is_null(size_t ndx) const
+    {
+        return Array::get(ndx) == 0;
+    }
+    void truncate_and_destroy_children(size_t ndx)
+    {
+        Array::truncate(ndx);
+    }
+
+    size_t find_first(ref_type value, size_t begin, size_t end) const noexcept
+    {
+        return Array::find_first(from_ref(value), begin, end);
+    }
+};
+}
+
+#endif /* REALM_ARRAY_LIST_HPP */

+ 138 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_mixed.hpp

@@ -0,0 +1,138 @@
+/*************************************************************************
+ *
+ * Copyright 2018 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_MIXED_HPP
+#define REALM_ARRAY_MIXED_HPP
+
+#include <realm/data_type.hpp>
+#include <realm/mixed.hpp>
+#include <realm/obj.hpp>
+#include <realm/array_binary.hpp>
+#include <realm/array_string.hpp>
+#include <realm/array_timestamp.hpp>
+#include <realm/array_key.hpp>
+
+namespace realm {
+
+class ArrayMixed : public ArrayPayload, private Array {
+public:
+    using value_type = Mixed;
+
+    using Array::detach;
+    using Array::is_attached;
+    using Array::get_ref;
+    using Array::set_parent;
+    using Array::update_parent;
+    using Array::get_parent;
+
+    explicit ArrayMixed(Allocator&);
+
+    static Mixed default_value(bool)
+    {
+        return Mixed{};
+    }
+
+    void create();
+    void destroy()
+    {
+        Array::destroy_deep();
+    }
+
+    void init_from_mem(MemRef mem) noexcept;
+
+    void init_from_ref(ref_type ref) noexcept override
+    {
+        init_from_mem(MemRef(m_alloc.translate(ref), ref, m_alloc));
+    }
+    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override
+    {
+        Array::set_parent(parent, ndx_in_parent);
+    }
+    void init_from_parent()
+    {
+        ref_type ref = get_ref_from_parent();
+        ArrayMixed::init_from_ref(ref);
+    }
+
+    size_t size() const
+    {
+        return m_composite.size();
+    }
+
+    void add(Mixed value);
+    void set(size_t ndx, Mixed value);
+    void set_null(size_t ndx);
+    void insert(size_t ndx, Mixed value);
+    Mixed get(size_t ndx) const;
+    Mixed get_any(size_t ndx) const override
+    {
+        return get(ndx);
+    }
+    bool is_null(size_t ndx) const
+    {
+        return m_composite.get(ndx) == 0;
+    }
+
+    void clear();
+    void erase(size_t ndx);
+    void truncate_and_destroy_children(size_t ndx);
+    void move(ArrayMixed& dst, size_t ndx);
+
+    size_t find_first(Mixed value, size_t begin = 0, size_t end = realm::npos) const noexcept;
+
+    void verify() const;
+
+private:
+    enum { payload_idx_type, payload_idx_int, payload_idx_pair, payload_idx_str, payload_idx_size };
+
+    static constexpr int64_t s_data_type_mask = 0b0001'1111;
+    static constexpr int64_t s_payload_idx_mask = 0b1110'0000;
+    static constexpr int64_t s_payload_idx_shift = 5;
+    static constexpr int64_t s_data_shift = 8;
+
+    // This primary array contains an aggregation of the actual value - which can be
+    // either the value itself or an index into one of the payload arrays - the index
+    // of the payload array and the data_type.
+    //
+    // value << s_data_shift | payload_idx << s_payload_idx_shift | data_type
+    //
+    // payload_idx one of PayloadIdx
+    Array m_composite;
+
+    // Used to store big ints, floats and doubles
+    mutable Array m_ints;
+    // Used to store timestamps
+    mutable Array m_int_pairs;
+    // Used to store String and Binary
+    mutable ArrayString m_strings;
+
+    DataType get_type(size_t ndx) const
+    {
+        return DataType((m_composite.get(ndx) & s_data_type_mask) - 1);
+    }
+    int64_t store(const Mixed&);
+    void ensure_array_accessor(Array& arr, size_t ndx_in_parent) const;
+    void ensure_int_array() const;
+    void ensure_int_pair_array() const;
+    void ensure_string_array() const;
+    void replace_index(size_t old_ndx, size_t new_ndx, size_t payload_index);
+    void erase_linked_payload(size_t ndx);
+};
+} // namespace realm
+
+#endif /* REALM_ARRAY_MIXED_HPP */

+ 70 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_ref.hpp

@@ -0,0 +1,70 @@
+/*************************************************************************
+ *
+ * Copyright 2020 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_REF_HPP_
+#define REALM_ARRAY_REF_HPP_
+
+#include <realm/array.hpp>
+
+namespace realm {
+
+class ArrayRef : public Array {
+public:
+    using value_type = ref_type;
+
+    explicit ArrayRef(Allocator& allocator) noexcept
+        : Array(allocator)
+    {
+    }
+
+    void create(size_t sz = 0)
+    {
+        Array::create(type_HasRefs, false, sz, 0);
+    }
+
+    void add(ref_type value)
+    {
+        Array::add(from_ref(value));
+    }
+
+    void set(size_t ndx, ref_type value)
+    {
+        Array::set(ndx, from_ref(value));
+    }
+
+    void insert(size_t ndx, ref_type value)
+    {
+        Array::insert(ndx, from_ref(value));
+    }
+
+    ref_type get(size_t ndx) const noexcept
+    {
+        return to_ref(Array::get(ndx));
+    }
+    void verify() const
+    {
+#ifdef REALM_DEBUG
+        Array::verify();
+        REALM_ASSERT(has_refs());
+#endif
+    }
+};
+
+} // namespace realm
+
+#endif /* REALM_ARRAY_REF_HPP_ */

+ 170 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_string.hpp

@@ -0,0 +1,170 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_STRING_HPP
+#define REALM_ARRAY_STRING_HPP
+
+#include <realm/array_string_short.hpp>
+#include <realm/array_blobs_small.hpp>
+#include <realm/array_blobs_big.hpp>
+
+namespace realm {
+
+class Spec;
+
+class ArrayString : public ArrayPayload {
+public:
+    using value_type = StringData;
+
+    explicit ArrayString(Allocator&);
+
+    static StringData default_value(bool nullable)
+    {
+        return nullable ? StringData{} : StringData{""};
+    }
+
+    // This is only used in the upgrade process
+    void set_nullability(bool n)
+    {
+        m_nullable = n;
+    }
+    void create();
+
+    bool is_attached() const
+    {
+        return m_arr->is_attached();
+    }
+
+    void detach() const
+    {
+        m_arr->detach();
+    }
+
+    ref_type get_ref() const
+    {
+        return m_arr->get_ref();
+    }
+    ArrayParent* get_parent() const
+    {
+        return m_arr->get_parent();
+    }
+    size_t get_ndx_in_parent() const
+    {
+        return m_arr->get_ndx_in_parent();
+    }
+    void set_parent(ArrayParent* p, size_t n) noexcept override
+    {
+        m_arr->set_parent(p, n);
+    }
+    bool need_spec() const override
+    {
+        return true;
+    }
+    void set_spec(Spec* spec, size_t col_ndx) const override
+    {
+        m_spec = spec;
+        m_col_ndx = col_ndx;
+    }
+
+    void update_parent()
+    {
+        m_arr->update_parent();
+    }
+
+    void init_from_mem(MemRef mem) noexcept;
+    void init_from_ref(ref_type ref) noexcept override
+    {
+        init_from_mem(MemRef(m_alloc.translate(ref), ref, m_alloc));
+    }
+    void init_from_parent();
+    void destroy();
+
+    size_t size() const;
+
+    void add(StringData value);
+    void set(size_t ndx, StringData value);
+    void set_null(size_t ndx)
+    {
+        set(ndx, StringData{});
+    }
+    void insert(size_t ndx, StringData value);
+    StringData get(size_t ndx) const;
+    StringData get_legacy(size_t ndx) const;
+    Mixed get_any(size_t ndx) const override;
+    bool is_null(size_t ndx) const;
+    void erase(size_t ndx);
+    void move(ArrayString& dst, size_t ndx);
+    void clear();
+
+    size_t find_first(StringData value, size_t begin, size_t end) const noexcept;
+
+    size_t lower_bound(StringData value);
+
+    /// Get the specified element without the cost of constructing an
+    /// array instance. If an array instance is already available, or
+    /// you need to get multiple values, then this method will be
+    /// slower.
+    static StringData get(const char* header, size_t ndx, Allocator& alloc) noexcept;
+
+    void verify() const;
+
+private:
+    static constexpr size_t small_string_max_size = 15;  // ArrayStringShort
+    static constexpr size_t medium_string_max_size = 63; // ArrayStringLong
+    union Storage {
+        std::aligned_storage<sizeof(ArrayStringShort), alignof(ArrayStringShort)>::type m_string_short;
+        std::aligned_storage<sizeof(ArraySmallBlobs), alignof(ArraySmallBlobs)>::type m_string_long;
+        std::aligned_storage<sizeof(ArrayBigBlobs), alignof(ArrayBigBlobs)>::type m_big_blobs;
+        std::aligned_storage<sizeof(Array), alignof(Array)>::type m_enum;
+    };
+    enum class Type { small_strings, medium_strings, big_strings, enum_strings };
+
+    Type m_type = Type::small_strings;
+
+    Allocator& m_alloc;
+    Storage m_storage;
+    Array* m_arr;
+    mutable Spec* m_spec = nullptr;
+    mutable size_t m_col_ndx = realm::npos;
+    bool m_nullable = true;
+
+    std::unique_ptr<ArrayString> m_string_enum_values;
+
+    Type upgrade_leaf(size_t value_size);
+};
+
+inline StringData ArrayString::get(const char* header, size_t ndx, Allocator& alloc) noexcept
+{
+    bool long_strings = Array::get_hasrefs_from_header(header);
+    if (!long_strings) {
+        return ArrayStringShort::get(header, ndx, true);
+    }
+    else {
+        bool is_big = Array::get_context_flag_from_header(header);
+        if (!is_big) {
+            return ArraySmallBlobs::get_string(header, ndx, alloc);
+        }
+        else {
+            return ArrayBigBlobs::get_string(header, ndx, alloc);
+        }
+    }
+}
+
+}
+
+#endif /* REALM_ARRAY_STRING_HPP */

+ 173 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_string_short.hpp

@@ -0,0 +1,173 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_STRING_SHORT_HPP
+#define REALM_ARRAY_STRING_SHORT_HPP
+
+#include <realm/array.hpp>
+
+namespace realm {
+
+/*
+ArrayStringShort stores strings as a concecutive list of fixed-length blocks of m_width bytes. The
+longest string it can store is (m_width - 1) bytes before it needs to expand.
+
+An example of the format for m_width = 4 is following sequence of bytes, where x is payload:
+
+xxx0 xx01 x002 0003 0004 (strings "xxx",. "xx", "x", "", realm::null())
+
+So each string is 0 terminated, and the last byte in a block tells how many 0s are present, except
+for a realm::null() which has the byte set to m_width (4). The byte is used to compute the length of a string
+in various functions.
+
+New: If m_witdh = 0, then all elements are realm::null(). So to add an empty string we must expand m_width
+New: StringData is null() if-and-only-if StringData::data() == 0.
+*/
+
+class ArrayStringShort : public Array {
+public:
+    static const size_t max_width = 64;
+
+    typedef StringData value_type;
+    // Constructor defaults to non-nullable because we use non-nullable ArrayStringShort so many places internally
+    // in core (data which isn't user payload) where null isn't needed.
+    explicit ArrayStringShort(Allocator&, bool nullable = false) noexcept;
+    ~ArrayStringShort() noexcept override
+    {
+    }
+
+    bool is_null(size_t ndx) const;
+    void set_null(size_t ndx);
+    StringData get(size_t ndx) const noexcept;
+    void add();
+    void add(StringData value);
+    void set(size_t ndx, StringData value);
+    void insert(size_t ndx, StringData value);
+    void erase(size_t ndx);
+
+    size_t count(StringData value, size_t begin = 0, size_t end = npos) const noexcept;
+    size_t find_first(StringData value, size_t begin = 0, size_t end = npos) const noexcept;
+    void find_all(IntegerColumn& result, StringData value, size_t add_offset = 0, size_t begin = 0,
+                  size_t end = npos);
+
+    /// Compare two string arrays for equality.
+    bool compare_string(const ArrayStringShort&) const noexcept;
+
+    /// Get the specified element without the cost of constructing an
+    /// array instance. If an array instance is already available, or
+    /// you need to get multiple values, then this method will be
+    /// slower.
+    static StringData get(const char* header, size_t ndx, bool nullable) noexcept;
+
+    /// Construct a string array of the specified size and return just
+    /// the reference to the underlying memory. All elements will be
+    /// initialized to the empty string.
+    static MemRef create_array(size_t size, Allocator&);
+
+    /// Create a new empty string array and attach this accessor to
+    /// it. This does not modify the parent reference information of
+    /// this accessor.
+    ///
+    /// Note that the caller assumes ownership of the allocated
+    /// underlying node. It is not owned by the accessor.
+    void create();
+
+#ifdef REALM_DEBUG
+    void string_stats() const;
+#endif
+
+private:
+    size_t calc_byte_len(size_t num_items, size_t width) const override;
+    size_t calc_item_count(size_t bytes, size_t width) const noexcept override;
+
+    bool m_nullable;
+};
+
+
+// Implementation:
+
+// Creates new array (but invalid, call init_from_ref() to init)
+inline ArrayStringShort::ArrayStringShort(Allocator& allocator, bool nullable) noexcept
+    : Array(allocator)
+    , m_nullable(nullable)
+{
+}
+
+inline void ArrayStringShort::create()
+{
+    size_t init_size = 0;
+    MemRef mem = create_array(init_size, get_alloc()); // Throws
+    init_from_mem(mem);
+}
+
+inline MemRef ArrayStringShort::create_array(size_t init_size, Allocator& allocator)
+{
+    bool context_flag = false;
+    int_fast64_t value = 0;
+    return Array::create(type_Normal, context_flag, wtype_Multiply, init_size, value, allocator); // Throws
+}
+
+inline StringData ArrayStringShort::get(size_t ndx) const noexcept
+{
+    REALM_ASSERT_3(ndx, <, m_size);
+    if (m_width == 0)
+        return m_nullable ? realm::null() : StringData("");
+
+    const char* data = m_data + (ndx * m_width);
+    size_t array_size = (m_width - 1) - data[m_width - 1];
+
+    if (array_size == static_cast<size_t>(-1))
+        return m_nullable ? realm::null() : StringData("");
+
+    REALM_ASSERT_EX(data[array_size] == 0, data[array_size],
+                    array_size); // Realm guarantees 0 terminated return strings
+    return StringData(data, array_size);
+}
+
+inline void ArrayStringShort::add(StringData value)
+{
+    REALM_ASSERT(!(!m_nullable && value.is_null()));
+    insert(m_size, value); // Throws
+}
+
+inline void ArrayStringShort::add()
+{
+    add(m_nullable ? realm::null() : StringData("")); // Throws
+}
+
+inline StringData ArrayStringShort::get(const char* header, size_t ndx, bool nullable) noexcept
+{
+    REALM_ASSERT(ndx < get_size_from_header(header));
+    uint_least8_t width = get_width_from_header(header);
+    const char* data = get_data_from_header(header) + (ndx * width);
+
+    if (width == 0)
+        return nullable ? realm::null() : StringData("");
+
+    size_t size = (width - 1) - data[width - 1];
+
+    if (size == static_cast<size_t>(-1))
+        return nullable ? realm::null() : StringData("");
+
+    return StringData(data, size);
+}
+
+
+} // namespace realm
+
+#endif // REALM_ARRAY_STRING_HPP

+ 136 - 0
Example/Pods/Realm/core/realm-monorepo.xcframework/ios-arm64_i386_x86_64-simulator/Headers/realm/array_timestamp.hpp

@@ -0,0 +1,136 @@
+/*************************************************************************
+ *
+ * Copyright 2016 Realm Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ **************************************************************************/
+
+#ifndef REALM_ARRAY_TIMESTAMP_HPP
+#define REALM_ARRAY_TIMESTAMP_HPP
+
+#include <realm/array_integer.hpp>
+#include <realm/timestamp.hpp>
+
+namespace realm {
+
+class ArrayTimestamp : public ArrayPayload, private Array {
+public:
+    using value_type = Timestamp;
+
+    explicit ArrayTimestamp(Allocator&);
+
+    using Array::update_parent;
+    using Array::get_parent;
+    using Array::get_ndx_in_parent;
+    using Array::get_ref;
+
+    static Timestamp default_value(bool nullable)
+    {
+        return nullable ? Timestamp{} : Timestamp{0, 0};
+    }
+
+    void create();
+
+    void init_from_mem(MemRef mem) noexcept;
+    void init_from_ref(ref_type ref) noexcept override
+    {
+        init_from_mem(MemRef(m_alloc.translate(ref), ref, m_alloc));
+    }
+    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override
+    {
+        Array::set_parent(parent, ndx_in_parent);
+    }
+    void init_from_parent()
+    {
+        init_from_ref(Array::get_ref_from_parent());
+    }
+
+    size_t size() const
+    {
+        return m_seconds.size();
+    }
+
+    void add(Timestamp value)
+    {
+        insert(m_seconds.size(), value);
+    }
+    void set(size_t ndx, Timestamp value);
+    void set_null(size_t ndx)
+    {
+        // Value in m_nanoseconds is irrelevant if m_seconds is null
+        m_seconds.set_null(ndx); // Throws
+    }
+    void insert(size_t ndx, Timestamp value);
+    Timestamp get(size_t ndx) const
+    {
+        util::Optional<int64_t> seconds = m_seconds.get(ndx);
+        return seconds ? Timestamp(*seconds, int32_t(m_nanoseconds.get(ndx))) : Timestamp{};
+    }
+    Mixed get_any(size_t ndx) const final
+    {
+        return Mixed(get(ndx));
+    }
+    bool is_null(size_t ndx) const
+    {
+        return m_seconds.is_null(ndx);
+    }
+    void erase(size_t ndx)
+    {
+        m_seconds.erase(ndx);
+        m_nanoseconds.erase(ndx);
+    }
+    void move(ArrayTimestamp& dst, size_t ndx)
+    {
+        m_seconds.move(dst.m_seconds, ndx);
+        m_nanoseconds.move(dst.m_nanoseconds, ndx);
+    }
+    void clear()
+    {
+        m_seconds.clear();
+        m_nanoseconds.clear();
+    }
+
+    template <class Condition>
+    size_t find_first(Timestamp value, size_t begin, size_t end) const noexcept;
+
+    size_t find_first(Timestamp value, size_t begin, size_t end) const noexcept;
+
+    void verify() const;
+
+private:
+    ArrayIntNull m_seconds;
+    ArrayInteger m_nanoseconds;
+};
+
+template <>
+size_t ArrayTimestamp::find_first<Equal>(Timestamp value, size_t begin, size_t end) const noexcept;
+template <>
+size_t ArrayTimestamp::find_first<NotEqual>(Timestamp value, size_t begin, size_t end) const noexcept;
+template <>
+size_t ArrayTimestamp::find_first<Less>(Timestamp value, size_t begin, size_t end) const noexcept;
+template <>
+size_t ArrayTimestamp::find_first<LessEqual>(Timestamp value, size_t begin, size_t end) const noexcept;
+template <>
+size_t ArrayTimestamp::find_first<GreaterEqual>(Timestamp value, size_t begin, size_t end) const noexcept;
+template <>
+size_t ArrayTimestamp::find_first<Greater>(Timestamp value, size_t begin, size_t end) const noexcept;
+
+inline size_t ArrayTimestamp::find_first(Timestamp value, size_t begin, size_t end) const noexcept
+{
+    return find_first<Equal>(value, begin, end);
+}
+
+}
+
+#endif /* SRC_REALM_ARRAY_BINARY_HPP_ */

部分文件因文件數量過多而無法顯示