1 /////////////////////////////////////////////////////////////////////////////// 2 // 3 // Copyright (c) 2015-2016 The Khronos Group Inc. 4 // Copyright (c) 2015-2016 Valve Corporation 5 // Copyright (c) 2015-2016 LunarG, Inc. 6 // Copyright (c) 2015-2016 Google, Inc. 7 // 8 // Permission is hereby granted, free of charge, to any person obtaining a copy 9 // of this software and/or associated documentation files (the "Materials"), to 10 // deal in the Materials without restriction, including without limitation the 11 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 12 // sell copies of the Materials, and to permit persons to whom the Materials are 13 // furnished to do so, subject to the following conditions: 14 // 15 // The above copyright notice(s) and this permission notice shall be included in 16 // all copies or substantial portions of the Materials. 17 // 18 // THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 21 // 22 // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 23 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 24 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE 25 // USE OR OTHER DEALINGS IN THE MATERIALS. 26 /////////////////////////////////////////////////////////////////////////////// 27 28 #include "vkjson.h" 29 30 #include <assert.h> 31 #include <string.h> 32 33 #include <cmath> 34 #include <cinttypes> 35 #include <cstdio> 36 #include <limits> 37 #include <memory> 38 #include <sstream> 39 #include <type_traits> 40 #include <utility> 41 42 #include <cJSON.h> 43 #include <vulkan/vk_sdk_platform.h> 44 45 namespace { 46 47 inline bool IsIntegral(double value) { 48 return std::trunc(value) == value; 49 } 50 51 template <typename T> struct EnumTraits; 52 template <> struct EnumTraits<VkPhysicalDeviceType> { 53 static uint32_t min() { return VK_PHYSICAL_DEVICE_TYPE_BEGIN_RANGE; } 54 static uint32_t max() { return VK_PHYSICAL_DEVICE_TYPE_END_RANGE; } 55 }; 56 57 template <> struct EnumTraits<VkFormat> { 58 static uint32_t min() { return VK_FORMAT_BEGIN_RANGE; } 59 static uint32_t max() { return VK_FORMAT_END_RANGE; } 60 }; 61 62 63 // VkSparseImageFormatProperties 64 65 template <typename Visitor> 66 inline bool Iterate(Visitor* visitor, VkExtent3D* extents) { 67 return 68 visitor->Visit("width", &extents->width) && 69 visitor->Visit("height", &extents->height) && 70 visitor->Visit("depth", &extents->depth); 71 } 72 73 template <typename Visitor> 74 inline bool Iterate(Visitor* visitor, VkImageFormatProperties* properties) { 75 return 76 visitor->Visit("maxExtent", &properties->maxExtent) && 77 visitor->Visit("maxMipLevels", &properties->maxMipLevels) && 78 visitor->Visit("maxArrayLayers", &properties->maxArrayLayers) && 79 visitor->Visit("sampleCounts", &properties->sampleCounts) && 80 visitor->Visit("maxResourceSize", &properties->maxResourceSize); 81 } 82 83 template <typename Visitor> 84 inline bool Iterate(Visitor* visitor, VkPhysicalDeviceLimits* limits) { 85 return 86 visitor->Visit("maxImageDimension1D", &limits->maxImageDimension1D) && 87 visitor->Visit("maxImageDimension2D", &limits->maxImageDimension2D) && 88 visitor->Visit("maxImageDimension3D", &limits->maxImageDimension3D) && 89 visitor->Visit("maxImageDimensionCube", &limits->maxImageDimensionCube) && 90 visitor->Visit("maxImageArrayLayers", &limits->maxImageArrayLayers) && 91 visitor->Visit("maxTexelBufferElements", &limits->maxTexelBufferElements) && 92 visitor->Visit("maxUniformBufferRange", &limits->maxUniformBufferRange) && 93 visitor->Visit("maxStorageBufferRange", &limits->maxStorageBufferRange) && 94 visitor->Visit("maxPushConstantsSize", &limits->maxPushConstantsSize) && 95 visitor->Visit("maxMemoryAllocationCount", &limits->maxMemoryAllocationCount) && 96 visitor->Visit("maxSamplerAllocationCount", &limits->maxSamplerAllocationCount) && 97 visitor->Visit("bufferImageGranularity", &limits->bufferImageGranularity) && 98 visitor->Visit("sparseAddressSpaceSize", &limits->sparseAddressSpaceSize) && 99 visitor->Visit("maxBoundDescriptorSets", &limits->maxBoundDescriptorSets) && 100 visitor->Visit("maxPerStageDescriptorSamplers", &limits->maxPerStageDescriptorSamplers) && 101 visitor->Visit("maxPerStageDescriptorUniformBuffers", &limits->maxPerStageDescriptorUniformBuffers) && 102 visitor->Visit("maxPerStageDescriptorStorageBuffers", &limits->maxPerStageDescriptorStorageBuffers) && 103 visitor->Visit("maxPerStageDescriptorSampledImages", &limits->maxPerStageDescriptorSampledImages) && 104 visitor->Visit("maxPerStageDescriptorStorageImages", &limits->maxPerStageDescriptorStorageImages) && 105 visitor->Visit("maxPerStageDescriptorInputAttachments", &limits->maxPerStageDescriptorInputAttachments) && 106 visitor->Visit("maxPerStageResources", &limits->maxPerStageResources) && 107 visitor->Visit("maxDescriptorSetSamplers", &limits->maxDescriptorSetSamplers) && 108 visitor->Visit("maxDescriptorSetUniformBuffers", &limits->maxDescriptorSetUniformBuffers) && 109 visitor->Visit("maxDescriptorSetUniformBuffersDynamic", &limits->maxDescriptorSetUniformBuffersDynamic) && 110 visitor->Visit("maxDescriptorSetStorageBuffers", &limits->maxDescriptorSetStorageBuffers) && 111 visitor->Visit("maxDescriptorSetStorageBuffersDynamic", &limits->maxDescriptorSetStorageBuffersDynamic) && 112 visitor->Visit("maxDescriptorSetSampledImages", &limits->maxDescriptorSetSampledImages) && 113 visitor->Visit("maxDescriptorSetStorageImages", &limits->maxDescriptorSetStorageImages) && 114 visitor->Visit("maxDescriptorSetInputAttachments", &limits->maxDescriptorSetInputAttachments) && 115 visitor->Visit("maxVertexInputAttributes", &limits->maxVertexInputAttributes) && 116 visitor->Visit("maxVertexInputBindings", &limits->maxVertexInputBindings) && 117 visitor->Visit("maxVertexInputAttributeOffset", &limits->maxVertexInputAttributeOffset) && 118 visitor->Visit("maxVertexInputBindingStride", &limits->maxVertexInputBindingStride) && 119 visitor->Visit("maxVertexOutputComponents", &limits->maxVertexOutputComponents) && 120 visitor->Visit("maxTessellationGenerationLevel", &limits->maxTessellationGenerationLevel) && 121 visitor->Visit("maxTessellationPatchSize", &limits->maxTessellationPatchSize) && 122 visitor->Visit("maxTessellationControlPerVertexInputComponents", &limits->maxTessellationControlPerVertexInputComponents) && 123 visitor->Visit("maxTessellationControlPerVertexOutputComponents", &limits->maxTessellationControlPerVertexOutputComponents) && 124 visitor->Visit("maxTessellationControlPerPatchOutputComponents", &limits->maxTessellationControlPerPatchOutputComponents) && 125 visitor->Visit("maxTessellationControlTotalOutputComponents", &limits->maxTessellationControlTotalOutputComponents) && 126 visitor->Visit("maxTessellationEvaluationInputComponents", &limits->maxTessellationEvaluationInputComponents) && 127 visitor->Visit("maxTessellationEvaluationOutputComponents", &limits->maxTessellationEvaluationOutputComponents) && 128 visitor->Visit("maxGeometryShaderInvocations", &limits->maxGeometryShaderInvocations) && 129 visitor->Visit("maxGeometryInputComponents", &limits->maxGeometryInputComponents) && 130 visitor->Visit("maxGeometryOutputComponents", &limits->maxGeometryOutputComponents) && 131 visitor->Visit("maxGeometryOutputVertices", &limits->maxGeometryOutputVertices) && 132 visitor->Visit("maxGeometryTotalOutputComponents", &limits->maxGeometryTotalOutputComponents) && 133 visitor->Visit("maxFragmentInputComponents", &limits->maxFragmentInputComponents) && 134 visitor->Visit("maxFragmentOutputAttachments", &limits->maxFragmentOutputAttachments) && 135 visitor->Visit("maxFragmentDualSrcAttachments", &limits->maxFragmentDualSrcAttachments) && 136 visitor->Visit("maxFragmentCombinedOutputResources", &limits->maxFragmentCombinedOutputResources) && 137 visitor->Visit("maxComputeSharedMemorySize", &limits->maxComputeSharedMemorySize) && 138 visitor->Visit("maxComputeWorkGroupCount", &limits->maxComputeWorkGroupCount) && 139 visitor->Visit("maxComputeWorkGroupInvocations", &limits->maxComputeWorkGroupInvocations) && 140 visitor->Visit("maxComputeWorkGroupSize", &limits->maxComputeWorkGroupSize) && 141 visitor->Visit("subPixelPrecisionBits", &limits->subPixelPrecisionBits) && 142 visitor->Visit("subTexelPrecisionBits", &limits->subTexelPrecisionBits) && 143 visitor->Visit("mipmapPrecisionBits", &limits->mipmapPrecisionBits) && 144 visitor->Visit("maxDrawIndexedIndexValue", &limits->maxDrawIndexedIndexValue) && 145 visitor->Visit("maxDrawIndirectCount", &limits->maxDrawIndirectCount) && 146 visitor->Visit("maxSamplerLodBias", &limits->maxSamplerLodBias) && 147 visitor->Visit("maxSamplerAnisotropy", &limits->maxSamplerAnisotropy) && 148 visitor->Visit("maxViewports", &limits->maxViewports) && 149 visitor->Visit("maxViewportDimensions", &limits->maxViewportDimensions) && 150 visitor->Visit("viewportBoundsRange", &limits->viewportBoundsRange) && 151 visitor->Visit("viewportSubPixelBits", &limits->viewportSubPixelBits) && 152 visitor->Visit("minMemoryMapAlignment", &limits->minMemoryMapAlignment) && 153 visitor->Visit("minTexelBufferOffsetAlignment", &limits->minTexelBufferOffsetAlignment) && 154 visitor->Visit("minUniformBufferOffsetAlignment", &limits->minUniformBufferOffsetAlignment) && 155 visitor->Visit("minStorageBufferOffsetAlignment", &limits->minStorageBufferOffsetAlignment) && 156 visitor->Visit("minTexelOffset", &limits->minTexelOffset) && 157 visitor->Visit("maxTexelOffset", &limits->maxTexelOffset) && 158 visitor->Visit("minTexelGatherOffset", &limits->minTexelGatherOffset) && 159 visitor->Visit("maxTexelGatherOffset", &limits->maxTexelGatherOffset) && 160 visitor->Visit("minInterpolationOffset", &limits->minInterpolationOffset) && 161 visitor->Visit("maxInterpolationOffset", &limits->maxInterpolationOffset) && 162 visitor->Visit("subPixelInterpolationOffsetBits", &limits->subPixelInterpolationOffsetBits) && 163 visitor->Visit("maxFramebufferWidth", &limits->maxFramebufferWidth) && 164 visitor->Visit("maxFramebufferHeight", &limits->maxFramebufferHeight) && 165 visitor->Visit("maxFramebufferLayers", &limits->maxFramebufferLayers) && 166 visitor->Visit("framebufferColorSampleCounts", &limits->framebufferColorSampleCounts) && 167 visitor->Visit("framebufferDepthSampleCounts", &limits->framebufferDepthSampleCounts) && 168 visitor->Visit("framebufferStencilSampleCounts", &limits->framebufferStencilSampleCounts) && 169 visitor->Visit("framebufferNoAttachmentsSampleCounts", &limits->framebufferNoAttachmentsSampleCounts) && 170 visitor->Visit("maxColorAttachments", &limits->maxColorAttachments) && 171 visitor->Visit("sampledImageColorSampleCounts", &limits->sampledImageColorSampleCounts) && 172 visitor->Visit("sampledImageIntegerSampleCounts", &limits->sampledImageIntegerSampleCounts) && 173 visitor->Visit("sampledImageDepthSampleCounts", &limits->sampledImageDepthSampleCounts) && 174 visitor->Visit("sampledImageStencilSampleCounts", &limits->sampledImageStencilSampleCounts) && 175 visitor->Visit("storageImageSampleCounts", &limits->storageImageSampleCounts) && 176 visitor->Visit("maxSampleMaskWords", &limits->maxSampleMaskWords) && 177 visitor->Visit("timestampComputeAndGraphics", &limits->timestampComputeAndGraphics) && 178 visitor->Visit("timestampPeriod", &limits->timestampPeriod) && 179 visitor->Visit("maxClipDistances", &limits->maxClipDistances) && 180 visitor->Visit("maxCullDistances", &limits->maxCullDistances) && 181 visitor->Visit("maxCombinedClipAndCullDistances", &limits->maxCombinedClipAndCullDistances) && 182 visitor->Visit("discreteQueuePriorities", &limits->discreteQueuePriorities) && 183 visitor->Visit("pointSizeRange", &limits->pointSizeRange) && 184 visitor->Visit("lineWidthRange", &limits->lineWidthRange) && 185 visitor->Visit("pointSizeGranularity", &limits->pointSizeGranularity) && 186 visitor->Visit("lineWidthGranularity", &limits->lineWidthGranularity) && 187 visitor->Visit("strictLines", &limits->strictLines) && 188 visitor->Visit("standardSampleLocations", &limits->standardSampleLocations) && 189 visitor->Visit("optimalBufferCopyOffsetAlignment", &limits->optimalBufferCopyOffsetAlignment) && 190 visitor->Visit("optimalBufferCopyRowPitchAlignment", &limits->optimalBufferCopyRowPitchAlignment) && 191 visitor->Visit("nonCoherentAtomSize", &limits->nonCoherentAtomSize); 192 } 193 194 template <typename Visitor> 195 inline bool Iterate(Visitor* visitor, 196 VkPhysicalDeviceSparseProperties* properties) { 197 return 198 visitor->Visit("residencyStandard2DBlockShape", &properties->residencyStandard2DBlockShape) && 199 visitor->Visit("residencyStandard2DMultisampleBlockShape", &properties->residencyStandard2DMultisampleBlockShape) && 200 visitor->Visit("residencyStandard3DBlockShape", &properties->residencyStandard3DBlockShape) && 201 visitor->Visit("residencyAlignedMipSize", &properties->residencyAlignedMipSize) && 202 visitor->Visit("residencyNonResidentStrict", &properties->residencyNonResidentStrict); 203 } 204 205 template <typename Visitor> 206 inline bool Iterate(Visitor* visitor, 207 VkPhysicalDeviceProperties* properties) { 208 return 209 visitor->Visit("apiVersion", &properties->apiVersion) && 210 visitor->Visit("driverVersion", &properties->driverVersion) && 211 visitor->Visit("vendorID", &properties->vendorID) && 212 visitor->Visit("deviceID", &properties->deviceID) && 213 visitor->Visit("deviceType", &properties->deviceType) && 214 visitor->Visit("deviceName", &properties->deviceName) && 215 visitor->Visit("pipelineCacheUUID", &properties->pipelineCacheUUID) && 216 visitor->Visit("limits", &properties->limits) && 217 visitor->Visit("sparseProperties", &properties->sparseProperties); 218 } 219 220 template <typename Visitor> 221 inline bool Iterate(Visitor* visitor, VkPhysicalDeviceFeatures* features) { 222 return 223 visitor->Visit("robustBufferAccess", &features->robustBufferAccess) && 224 visitor->Visit("fullDrawIndexUint32", &features->fullDrawIndexUint32) && 225 visitor->Visit("imageCubeArray", &features->imageCubeArray) && 226 visitor->Visit("independentBlend", &features->independentBlend) && 227 visitor->Visit("geometryShader", &features->geometryShader) && 228 visitor->Visit("tessellationShader", &features->tessellationShader) && 229 visitor->Visit("sampleRateShading", &features->sampleRateShading) && 230 visitor->Visit("dualSrcBlend", &features->dualSrcBlend) && 231 visitor->Visit("logicOp", &features->logicOp) && 232 visitor->Visit("multiDrawIndirect", &features->multiDrawIndirect) && 233 visitor->Visit("drawIndirectFirstInstance", &features->drawIndirectFirstInstance) && 234 visitor->Visit("depthClamp", &features->depthClamp) && 235 visitor->Visit("depthBiasClamp", &features->depthBiasClamp) && 236 visitor->Visit("fillModeNonSolid", &features->fillModeNonSolid) && 237 visitor->Visit("depthBounds", &features->depthBounds) && 238 visitor->Visit("wideLines", &features->wideLines) && 239 visitor->Visit("largePoints", &features->largePoints) && 240 visitor->Visit("alphaToOne", &features->alphaToOne) && 241 visitor->Visit("multiViewport", &features->multiViewport) && 242 visitor->Visit("samplerAnisotropy", &features->samplerAnisotropy) && 243 visitor->Visit("textureCompressionETC2", &features->textureCompressionETC2) && 244 visitor->Visit("textureCompressionASTC_LDR", &features->textureCompressionASTC_LDR) && 245 visitor->Visit("textureCompressionBC", &features->textureCompressionBC) && 246 visitor->Visit("occlusionQueryPrecise", &features->occlusionQueryPrecise) && 247 visitor->Visit("pipelineStatisticsQuery", &features->pipelineStatisticsQuery) && 248 visitor->Visit("vertexPipelineStoresAndAtomics", &features->vertexPipelineStoresAndAtomics) && 249 visitor->Visit("fragmentStoresAndAtomics", &features->fragmentStoresAndAtomics) && 250 visitor->Visit("shaderTessellationAndGeometryPointSize", &features->shaderTessellationAndGeometryPointSize) && 251 visitor->Visit("shaderImageGatherExtended", &features->shaderImageGatherExtended) && 252 visitor->Visit("shaderStorageImageExtendedFormats", &features->shaderStorageImageExtendedFormats) && 253 visitor->Visit("shaderStorageImageMultisample", &features->shaderStorageImageMultisample) && 254 visitor->Visit("shaderStorageImageReadWithoutFormat", &features->shaderStorageImageReadWithoutFormat) && 255 visitor->Visit("shaderStorageImageWriteWithoutFormat", &features->shaderStorageImageWriteWithoutFormat) && 256 visitor->Visit("shaderUniformBufferArrayDynamicIndexing", &features->shaderUniformBufferArrayDynamicIndexing) && 257 visitor->Visit("shaderSampledImageArrayDynamicIndexing", &features->shaderSampledImageArrayDynamicIndexing) && 258 visitor->Visit("shaderStorageBufferArrayDynamicIndexing", &features->shaderStorageBufferArrayDynamicIndexing) && 259 visitor->Visit("shaderStorageImageArrayDynamicIndexing", &features->shaderStorageImageArrayDynamicIndexing) && 260 visitor->Visit("shaderClipDistance", &features->shaderClipDistance) && 261 visitor->Visit("shaderCullDistance", &features->shaderCullDistance) && 262 visitor->Visit("shaderFloat64", &features->shaderFloat64) && 263 visitor->Visit("shaderInt64", &features->shaderInt64) && 264 visitor->Visit("shaderInt16", &features->shaderInt16) && 265 visitor->Visit("shaderResourceResidency", &features->shaderResourceResidency) && 266 visitor->Visit("shaderResourceMinLod", &features->shaderResourceMinLod) && 267 visitor->Visit("sparseBinding", &features->sparseBinding) && 268 visitor->Visit("sparseResidencyBuffer", &features->sparseResidencyBuffer) && 269 visitor->Visit("sparseResidencyImage2D", &features->sparseResidencyImage2D) && 270 visitor->Visit("sparseResidencyImage3D", &features->sparseResidencyImage3D) && 271 visitor->Visit("sparseResidency2Samples", &features->sparseResidency2Samples) && 272 visitor->Visit("sparseResidency4Samples", &features->sparseResidency4Samples) && 273 visitor->Visit("sparseResidency8Samples", &features->sparseResidency8Samples) && 274 visitor->Visit("sparseResidency16Samples", &features->sparseResidency16Samples) && 275 visitor->Visit("sparseResidencyAliased", &features->sparseResidencyAliased) && 276 visitor->Visit("variableMultisampleRate", &features->variableMultisampleRate) && 277 visitor->Visit("inheritedQueries", &features->inheritedQueries); 278 } 279 280 template <typename Visitor> 281 inline bool Iterate(Visitor* visitor, VkMemoryType* type) { 282 return 283 visitor->Visit("propertyFlags", &type->propertyFlags) && 284 visitor->Visit("heapIndex", &type->heapIndex); 285 } 286 287 template <typename Visitor> 288 inline bool Iterate(Visitor* visitor, VkMemoryHeap* heap) { 289 return 290 visitor->Visit("size", &heap->size) && 291 visitor->Visit("flags", &heap->flags); 292 } 293 294 template <typename Visitor> 295 inline bool Iterate(Visitor* visitor, VkPhysicalDeviceMemoryProperties* properties) { 296 return 297 visitor->Visit("memoryTypeCount", &properties->memoryTypeCount) && 298 visitor->VisitArray("memoryTypes", properties->memoryTypeCount, &properties->memoryTypes) && 299 visitor->Visit("memoryHeapCount", &properties->memoryHeapCount) && 300 visitor->VisitArray("memoryHeaps", properties->memoryHeapCount, &properties->memoryHeaps); 301 } 302 303 template <typename Visitor> 304 inline bool Iterate(Visitor* visitor, VkQueueFamilyProperties* properties) { 305 return 306 visitor->Visit("queueFlags", &properties->queueFlags) && 307 visitor->Visit("queueCount", &properties->queueCount) && 308 visitor->Visit("timestampValidBits", &properties->timestampValidBits) && 309 visitor->Visit("minImageTransferGranularity", &properties->minImageTransferGranularity); 310 } 311 312 template <typename Visitor> 313 inline bool Iterate(Visitor* visitor, VkExtensionProperties* properties) { 314 return 315 visitor->Visit("extensionName", &properties->extensionName) && 316 visitor->Visit("specVersion", &properties->specVersion); 317 } 318 319 template <typename Visitor> 320 inline bool Iterate(Visitor* visitor, VkLayerProperties* properties) { 321 return 322 visitor->Visit("layerName", &properties->layerName) && 323 visitor->Visit("specVersion", &properties->specVersion) && 324 visitor->Visit("implementationVersion", &properties->implementationVersion) && 325 visitor->Visit("description", &properties->description); 326 } 327 328 template <typename Visitor> 329 inline bool Iterate(Visitor* visitor, VkFormatProperties* properties) { 330 return 331 visitor->Visit("linearTilingFeatures", &properties->linearTilingFeatures) && 332 visitor->Visit("optimalTilingFeatures", &properties->optimalTilingFeatures) && 333 visitor->Visit("bufferFeatures", &properties->bufferFeatures); 334 } 335 336 template <typename Visitor> 337 inline bool Iterate(Visitor* visitor, VkJsonLayer* layer) { 338 return visitor->Visit("properties", &layer->properties) && 339 visitor->Visit("extensions", &layer->extensions); 340 } 341 342 template <typename Visitor> 343 inline bool Iterate(Visitor* visitor, VkJsonDevice* device) { 344 return visitor->Visit("properties", &device->properties) && 345 visitor->Visit("features", &device->features) && 346 visitor->Visit("memory", &device->memory) && 347 visitor->Visit("queues", &device->queues) && 348 visitor->Visit("extensions", &device->extensions) && 349 visitor->Visit("layers", &device->layers) && 350 visitor->Visit("formats", &device->formats); 351 } 352 353 template <typename Visitor> 354 inline bool Iterate(Visitor* visitor, VkJsonInstance* instance) { 355 return visitor->Visit("layers", &instance->layers) && 356 visitor->Visit("extensions", &instance->extensions) && 357 visitor->Visit("devices", &instance->devices); 358 } 359 360 template <typename T> 361 using EnableForArithmetic = 362 typename std::enable_if<std::is_arithmetic<T>::value, void>::type; 363 364 template <typename T> 365 using EnableForStruct = 366 typename std::enable_if<std::is_class<T>::value, void>::type; 367 368 template <typename T> 369 using EnableForEnum = 370 typename std::enable_if<std::is_enum<T>::value, void>::type; 371 372 template <typename T, typename = EnableForStruct<T>, typename = void> 373 cJSON* ToJsonValue(const T& value); 374 375 template <typename T, typename = EnableForArithmetic<T>> 376 inline cJSON* ToJsonValue(const T& value) { 377 return cJSON_CreateNumber(static_cast<double>(value)); 378 } 379 380 inline cJSON* ToJsonValue(const uint64_t& value) { 381 char string[19] = {0}; // "0x" + 16 digits + terminal \0 382 snprintf(string, sizeof(string), "0x%016" PRIx64, value); 383 return cJSON_CreateString(string); 384 } 385 386 template <typename T, typename = EnableForEnum<T>, typename = void, 387 typename = void> 388 inline cJSON* ToJsonValue(const T& value) { 389 return cJSON_CreateNumber(static_cast<double>(value)); 390 } 391 392 template <typename T> 393 inline cJSON* ArrayToJsonValue(uint32_t count, const T* values) { 394 cJSON* array = cJSON_CreateArray(); 395 for (unsigned int i = 0; i < count; ++i) 396 cJSON_AddItemToArray(array, ToJsonValue(values[i])); 397 return array; 398 } 399 400 template <typename T, unsigned int N> 401 inline cJSON* ToJsonValue(const T (&value)[N]) { 402 return ArrayToJsonValue(N, value); 403 } 404 405 template <size_t N> 406 inline cJSON* ToJsonValue(const char (&value)[N]) { 407 assert(strlen(value) < N); 408 return cJSON_CreateString(value); 409 } 410 411 template <typename T> 412 inline cJSON* ToJsonValue(const std::vector<T>& value) { 413 assert(value.size() <= std::numeric_limits<uint32_t>::max()); 414 return ArrayToJsonValue(static_cast<uint32_t>(value.size()), value.data()); 415 } 416 417 template <typename F, typename S> 418 inline cJSON* ToJsonValue(const std::pair<F, S>& value) { 419 cJSON* array = cJSON_CreateArray(); 420 cJSON_AddItemToArray(array, ToJsonValue(value.first)); 421 cJSON_AddItemToArray(array, ToJsonValue(value.second)); 422 return array; 423 } 424 425 template <typename F, typename S> 426 inline cJSON* ToJsonValue(const std::map<F, S>& value) { 427 cJSON* array = cJSON_CreateArray(); 428 for (auto& kv : value) 429 cJSON_AddItemToArray(array, ToJsonValue(kv)); 430 return array; 431 } 432 433 class JsonWriterVisitor { 434 public: 435 JsonWriterVisitor() : object_(cJSON_CreateObject()) {} 436 437 ~JsonWriterVisitor() { 438 if (object_) 439 cJSON_Delete(object_); 440 } 441 442 template <typename T> bool Visit(const char* key, const T* value) { 443 cJSON_AddItemToObjectCS(object_, key, ToJsonValue(*value)); 444 return true; 445 } 446 447 template <typename T, uint32_t N> 448 bool VisitArray(const char* key, uint32_t count, const T (*value)[N]) { 449 assert(count <= N); 450 cJSON_AddItemToObjectCS(object_, key, ArrayToJsonValue(count, *value)); 451 return true; 452 } 453 454 cJSON* get_object() const { return object_; } 455 cJSON* take_object() { 456 cJSON* object = object_; 457 object_ = nullptr; 458 return object; 459 } 460 461 private: 462 cJSON* object_; 463 }; 464 465 template <typename Visitor, typename T> 466 inline void VisitForWrite(Visitor* visitor, const T& t) { 467 Iterate(visitor, const_cast<T*>(&t)); 468 } 469 470 template <typename T, typename /*= EnableForStruct<T>*/, typename /*= void*/> 471 cJSON* ToJsonValue(const T& value) { 472 JsonWriterVisitor visitor; 473 VisitForWrite(&visitor, value); 474 return visitor.take_object(); 475 } 476 477 template <typename T, typename = EnableForStruct<T>> 478 bool AsValue(cJSON* json_value, T* t); 479 480 inline bool AsValue(cJSON* json_value, int32_t* value) { 481 double d = json_value->valuedouble; 482 if (json_value->type != cJSON_Number || !IsIntegral(d) || 483 d < static_cast<double>(std::numeric_limits<int32_t>::min()) || 484 d > static_cast<double>(std::numeric_limits<int32_t>::max())) 485 return false; 486 *value = static_cast<int32_t>(d); 487 return true; 488 } 489 490 inline bool AsValue(cJSON* json_value, uint64_t* value) { 491 if (json_value->type != cJSON_String) 492 return false; 493 int result = std::sscanf(json_value->valuestring, "0x%016" PRIx64, value); 494 return result == 1; 495 } 496 497 inline bool AsValue(cJSON* json_value, uint32_t* value) { 498 double d = json_value->valuedouble; 499 if (json_value->type != cJSON_Number || !IsIntegral(d) || 500 d < 0.0 || d > static_cast<double>(std::numeric_limits<uint32_t>::max())) 501 return false; 502 *value = static_cast<uint32_t>(d); 503 return true; 504 } 505 506 inline bool AsValue(cJSON* json_value, uint8_t* value) { 507 uint32_t value32 = 0; 508 AsValue(json_value, &value32); 509 if (value32 > std::numeric_limits<uint8_t>::max()) 510 return false; 511 *value = static_cast<uint8_t>(value32); 512 return true; 513 } 514 515 inline bool AsValue(cJSON* json_value, float* value) { 516 if (json_value->type != cJSON_Number) 517 return false; 518 *value = static_cast<float>(json_value->valuedouble); 519 return true; 520 } 521 522 template <typename T> 523 inline bool AsArray(cJSON* json_value, uint32_t count, T* values) { 524 if (json_value->type != cJSON_Array || 525 cJSON_GetArraySize(json_value) != count) 526 return false; 527 for (uint32_t i = 0; i < count; ++i) { 528 if (!AsValue(cJSON_GetArrayItem(json_value, i), values + i)) 529 return false; 530 } 531 return true; 532 } 533 534 template <typename T, unsigned int N> 535 inline bool AsValue(cJSON* json_value, T (*value)[N]) { 536 return AsArray(json_value, N, *value); 537 } 538 539 template <size_t N> 540 inline bool AsValue(cJSON* json_value, char (*value)[N]) { 541 if (json_value->type != cJSON_String) 542 return false; 543 size_t len = strlen(json_value->valuestring); 544 if (len >= N) 545 return false; 546 memcpy(*value, json_value->valuestring, len); 547 memset(*value + len, 0, N-len); 548 return true; 549 } 550 551 template <typename T, typename = EnableForEnum<T>, typename = void> 552 inline bool AsValue(cJSON* json_value, T* t) { 553 // TODO(piman): to/from strings instead? 554 uint32_t value = 0; 555 if (!AsValue(json_value, &value)) 556 return false; 557 if (value < EnumTraits<T>::min() || value > EnumTraits<T>::max()) 558 return false; 559 *t = static_cast<T>(value); 560 return true; 561 } 562 563 template <typename T> 564 inline bool AsValue(cJSON* json_value, std::vector<T>* value) { 565 if (json_value->type != cJSON_Array) 566 return false; 567 int size = cJSON_GetArraySize(json_value); 568 value->resize(size); 569 return AsArray(json_value, size, value->data()); 570 } 571 572 template <typename F, typename S> 573 inline bool AsValue(cJSON* json_value, std::pair<F, S>* value) { 574 if (json_value->type != cJSON_Array || cJSON_GetArraySize(json_value) != 2) 575 return false; 576 return AsValue(cJSON_GetArrayItem(json_value, 0), &value->first) && 577 AsValue(cJSON_GetArrayItem(json_value, 1), &value->second); 578 } 579 580 template <typename F, typename S> 581 inline bool AsValue(cJSON* json_value, std::map<F, S>* value) { 582 if (json_value->type != cJSON_Array) 583 return false; 584 int size = cJSON_GetArraySize(json_value); 585 for (int i = 0; i < size; ++i) { 586 std::pair<F, S> elem; 587 if (!AsValue(cJSON_GetArrayItem(json_value, i), &elem)) 588 return false; 589 if (!value->insert(elem).second) 590 return false; 591 } 592 return true; 593 } 594 595 template <typename T> 596 bool ReadValue(cJSON* object, const char* key, T* value, 597 std::string* errors) { 598 cJSON* json_value = cJSON_GetObjectItem(object, key); 599 if (!json_value) { 600 if (errors) 601 *errors = std::string(key) + " missing."; 602 return false; 603 } 604 if (AsValue(json_value, value)) 605 return true; 606 if (errors) 607 *errors = std::string("Wrong type for ") + std::string(key) + "."; 608 return false; 609 } 610 611 template <typename Visitor, typename T> 612 inline bool VisitForRead(Visitor* visitor, T* t) { 613 return Iterate(visitor, t); 614 } 615 616 class JsonReaderVisitor { 617 public: 618 JsonReaderVisitor(cJSON* object, std::string* errors) 619 : object_(object), errors_(errors) {} 620 621 template <typename T> bool Visit(const char* key, T* value) const { 622 return ReadValue(object_, key, value, errors_); 623 } 624 625 template <typename T, uint32_t N> 626 bool VisitArray(const char* key, uint32_t count, T (*value)[N]) { 627 if (count > N) 628 return false; 629 cJSON* json_value = cJSON_GetObjectItem(object_, key); 630 if (!json_value) { 631 if (errors_) 632 *errors_ = std::string(key) + " missing."; 633 return false; 634 } 635 if (AsArray(json_value, count, *value)) 636 return true; 637 if (errors_) 638 *errors_ = std::string("Wrong type for ") + std::string(key) + "."; 639 return false; 640 } 641 642 643 private: 644 cJSON* object_; 645 std::string* errors_; 646 }; 647 648 template <typename T, typename /*= EnableForStruct<T>*/> 649 bool AsValue(cJSON* json_value, T* t) { 650 if (json_value->type != cJSON_Object) 651 return false; 652 JsonReaderVisitor visitor(json_value, nullptr); 653 return VisitForRead(&visitor, t); 654 } 655 656 657 template <typename T> std::string VkTypeToJson(const T& t) { 658 JsonWriterVisitor visitor; 659 VisitForWrite(&visitor, t); 660 661 char* output = cJSON_Print(visitor.get_object()); 662 std::string result(output); 663 free(output); 664 return result; 665 } 666 667 template <typename T> bool VkTypeFromJson(const std::string& json, 668 T* t, 669 std::string* errors) { 670 *t = T(); 671 cJSON* object = cJSON_Parse(json.c_str()); 672 if (!object) { 673 if (errors) 674 errors->assign(cJSON_GetErrorPtr()); 675 return false; 676 } 677 bool result = AsValue(object, t); 678 cJSON_Delete(object); 679 return result; 680 } 681 682 } // anonymous namespace 683 684 std::string VkJsonInstanceToJson(const VkJsonInstance& instance) { 685 return VkTypeToJson(instance); 686 } 687 688 bool VkJsonInstanceFromJson(const std::string& json, 689 VkJsonInstance* instance, 690 std::string* errors) { 691 return VkTypeFromJson(json, instance, errors); 692 } 693 694 std::string VkJsonDeviceToJson(const VkJsonDevice& device) { 695 return VkTypeToJson(device); 696 } 697 698 bool VkJsonDeviceFromJson(const std::string& json, 699 VkJsonDevice* device, 700 std::string* errors) { 701 return VkTypeFromJson(json, device, errors); 702 }; 703 704 std::string VkJsonImageFormatPropertiesToJson( 705 const VkImageFormatProperties& properties) { 706 return VkTypeToJson(properties); 707 } 708 709 bool VkJsonImageFormatPropertiesFromJson(const std::string& json, 710 VkImageFormatProperties* properties, 711 std::string* errors) { 712 return VkTypeFromJson(json, properties, errors); 713 }; 714