vkjson.cc revision 594091db7f508f6073975efddb5fab8d0fb273e7
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 "vk_sdk_platform.h"
44
45namespace {
46
47inline bool IsIntegral(double value) {
48  return std::trunc(value) == value;
49}
50
51template <typename T> struct EnumTraits;
52template <> 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
57template <> 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
65template <typename Visitor>
66inline 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
73template <typename Visitor>
74inline 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
83template <typename Visitor>
84inline 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
194template <typename Visitor>
195inline 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
205template <typename Visitor>
206inline 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
220template <typename Visitor>
221inline 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
280template <typename Visitor>
281inline bool Iterate(Visitor* visitor, VkMemoryType* type) {
282  return
283    visitor->Visit("propertyFlags", &type->propertyFlags) &&
284    visitor->Visit("heapIndex", &type->heapIndex);
285}
286
287template <typename Visitor>
288inline bool Iterate(Visitor* visitor, VkMemoryHeap* heap) {
289  return
290    visitor->Visit("size", &heap->size) &&
291    visitor->Visit("flags", &heap->flags);
292}
293
294template <typename Visitor>
295inline 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
303template <typename Visitor>
304inline 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
312template <typename Visitor>
313inline bool Iterate(Visitor* visitor, VkExtensionProperties* properties) {
314  return
315    visitor->Visit("extensionName", &properties->extensionName) &&
316    visitor->Visit("specVersion", &properties->specVersion);
317}
318
319template <typename Visitor>
320inline 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
328template <typename Visitor>
329inline 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
336template <typename Visitor>
337inline bool Iterate(Visitor* visitor, VkJsonDevice* device) {
338  return visitor->Visit("properties", &device->properties) &&
339         visitor->Visit("features", &device->features) &&
340         visitor->Visit("memory", &device->memory) &&
341         visitor->Visit("queues", &device->queues) &&
342         visitor->Visit("extensions", &device->extensions) &&
343         visitor->Visit("layers", &device->layers) &&
344         visitor->Visit("formats", &device->formats);
345}
346
347
348template <typename T>
349using EnableForArithmetic =
350    typename std::enable_if<std::is_arithmetic<T>::value, void>::type;
351
352template <typename T>
353using EnableForStruct =
354    typename std::enable_if<std::is_class<T>::value, void>::type;
355
356template <typename T>
357using EnableForEnum =
358    typename std::enable_if<std::is_enum<T>::value, void>::type;
359
360template <typename T, typename = EnableForStruct<T>, typename = void>
361cJSON* ToJsonValue(const T& value);
362
363template <typename T, typename = EnableForArithmetic<T>>
364inline cJSON* ToJsonValue(const T& value) {
365  return cJSON_CreateNumber(static_cast<double>(value));
366}
367
368inline cJSON* ToJsonValue(const uint64_t& value) {
369  char string[19] = {0};  // "0x" + 16 digits + terminal \0
370  snprintf(string, sizeof(string), "0x%016" PRIx64, value);
371  return cJSON_CreateString(string);
372}
373
374template <typename T, typename = EnableForEnum<T>, typename = void,
375          typename = void>
376inline cJSON* ToJsonValue(const T& value) {
377  return cJSON_CreateNumber(static_cast<double>(value));
378}
379
380template <typename T>
381inline cJSON* ArrayToJsonValue(uint32_t count, const T* values) {
382  cJSON* array = cJSON_CreateArray();
383  for (unsigned int i = 0; i < count; ++i)
384    cJSON_AddItemToArray(array, ToJsonValue(values[i]));
385  return array;
386}
387
388template <typename T, unsigned int N>
389inline cJSON* ToJsonValue(const T (&value)[N]) {
390  return ArrayToJsonValue(N, value);
391}
392
393template <size_t N>
394inline cJSON* ToJsonValue(const char (&value)[N]) {
395  assert(strlen(value) < N);
396  return cJSON_CreateString(value);
397}
398
399template <typename T>
400inline cJSON* ToJsonValue(const std::vector<T>& value) {
401  assert(value.size() <= std::numeric_limits<uint32_t>::max());
402  return ArrayToJsonValue(static_cast<uint32_t>(value.size()), value.data());
403}
404
405template <typename F, typename S>
406inline cJSON* ToJsonValue(const std::pair<F, S>& value) {
407  cJSON* array = cJSON_CreateArray();
408  cJSON_AddItemToArray(array, ToJsonValue(value.first));
409  cJSON_AddItemToArray(array, ToJsonValue(value.second));
410  return array;
411}
412
413template <typename F, typename S>
414inline cJSON* ToJsonValue(const std::map<F, S>& value) {
415  cJSON* array = cJSON_CreateArray();
416  for (auto& kv : value)
417    cJSON_AddItemToArray(array, ToJsonValue(kv));
418  return array;
419}
420
421class JsonWriterVisitor {
422 public:
423  JsonWriterVisitor() : object_(cJSON_CreateObject()) {}
424
425  ~JsonWriterVisitor() {
426    if (object_)
427      cJSON_Delete(object_);
428  }
429
430  template <typename T> bool Visit(const char* key, const T* value) {
431    cJSON_AddItemToObjectCS(object_, key, ToJsonValue(*value));
432    return true;
433  }
434
435  template <typename T, uint32_t N>
436  bool VisitArray(const char* key, uint32_t count, const T (*value)[N]) {
437    assert(count <= N);
438    cJSON_AddItemToObjectCS(object_, key, ArrayToJsonValue(count, *value));
439    return true;
440  }
441
442  cJSON* get_object() const { return object_; }
443  cJSON* take_object() {
444    cJSON* object = object_;
445    object_ = nullptr;
446    return object;
447  }
448
449 private:
450  cJSON* object_;
451};
452
453template <typename Visitor, typename T>
454inline void VisitForWrite(Visitor* visitor, const T& t) {
455  Iterate(visitor, const_cast<T*>(&t));
456}
457
458template <typename T, typename = EnableForStruct<T>, typename = void>
459cJSON* ToJsonValue(const T& value) {
460  JsonWriterVisitor visitor;
461  VisitForWrite(&visitor, value);
462  return visitor.take_object();
463}
464
465template <typename T, typename = EnableForStruct<T>>
466bool AsValue(cJSON* json_value, T* t);
467
468inline bool AsValue(cJSON* json_value, int32_t* value) {
469  double d = json_value->valuedouble;
470  if (json_value->type != cJSON_Number || !IsIntegral(d) ||
471      d < static_cast<double>(std::numeric_limits<int32_t>::min()) ||
472      d > static_cast<double>(std::numeric_limits<int32_t>::max()))
473    return false;
474  *value = static_cast<int32_t>(d);
475  return true;
476}
477
478inline bool AsValue(cJSON* json_value, uint64_t* value) {
479  if (json_value->type != cJSON_String)
480    return false;
481  int result = std::sscanf(json_value->valuestring, "0x%016" PRIx64, value);
482  return result == 1;
483}
484
485inline bool AsValue(cJSON* json_value, uint32_t* value) {
486  double d = json_value->valuedouble;
487  if (json_value->type != cJSON_Number || !IsIntegral(d) ||
488      d < 0.0 || d > static_cast<double>(std::numeric_limits<uint32_t>::max()))
489    return false;
490  *value = static_cast<uint32_t>(d);
491  return true;
492}
493
494inline bool AsValue(cJSON* json_value, uint8_t* value) {
495  uint32_t value32 = 0;
496  AsValue(json_value, &value32);
497  if (value32 > std::numeric_limits<uint8_t>::max())
498    return false;
499  *value = static_cast<uint8_t>(value32);
500  return true;
501}
502
503inline bool AsValue(cJSON* json_value, float* value) {
504  if (json_value->type != cJSON_Number)
505    return false;
506  *value = static_cast<float>(json_value->valuedouble);
507  return true;
508}
509
510template <typename T>
511inline bool AsArray(cJSON* json_value, uint32_t count, T* values) {
512  if (json_value->type != cJSON_Array ||
513      cJSON_GetArraySize(json_value) != count)
514    return false;
515  for (uint32_t i = 0; i < count; ++i) {
516    if (!AsValue(cJSON_GetArrayItem(json_value, i), values + i))
517      return false;
518  }
519  return true;
520}
521
522template <typename T, unsigned int N>
523inline bool AsValue(cJSON* json_value, T (*value)[N]) {
524  return AsArray(json_value, N, *value);
525}
526
527template <size_t N>
528inline bool AsValue(cJSON* json_value, char (*value)[N]) {
529  if (json_value->type != cJSON_String)
530    return false;
531  size_t len = strlen(json_value->valuestring);
532  if (len >= N)
533    return false;
534  memcpy(*value, json_value->valuestring, len);
535  memset(*value + len, 0, N-len);
536  return true;
537}
538
539template <typename T, typename = EnableForEnum<T>, typename = void>
540inline bool AsValue(cJSON* json_value, T* t) {
541  // TODO(piman): to/from strings instead?
542  uint32_t value = 0;
543  if (!AsValue(json_value, &value))
544      return false;
545  if (value < EnumTraits<T>::min() || value > EnumTraits<T>::max())
546    return false;
547  *t = static_cast<T>(value);
548  return true;
549}
550
551template <typename T>
552inline bool AsValue(cJSON* json_value, std::vector<T>* value) {
553  if (json_value->type != cJSON_Array)
554    return false;
555  int size = cJSON_GetArraySize(json_value);
556  value->resize(size);
557  return AsArray(json_value, size, value->data());
558}
559
560template <typename F, typename S>
561inline bool AsValue(cJSON* json_value, std::pair<F, S>* value) {
562  if (json_value->type != cJSON_Array || cJSON_GetArraySize(json_value) != 2)
563    return false;
564  return AsValue(cJSON_GetArrayItem(json_value, 0), &value->first) &&
565         AsValue(cJSON_GetArrayItem(json_value, 1), &value->second);
566}
567
568template <typename F, typename S>
569inline bool AsValue(cJSON* json_value, std::map<F, S>* value) {
570  if (json_value->type != cJSON_Array)
571    return false;
572  int size = cJSON_GetArraySize(json_value);
573  for (int i = 0; i < size; ++i) {
574    std::pair<F, S> elem;
575    if (!AsValue(cJSON_GetArrayItem(json_value, i), &elem))
576      return false;
577    if (!value->insert(elem).second)
578      return false;
579  }
580  return true;
581}
582
583template <typename T>
584bool ReadValue(cJSON* object, const char* key, T* value,
585               std::string* errors) {
586  cJSON* json_value = cJSON_GetObjectItem(object, key);
587  if (!json_value) {
588    if (errors)
589      *errors = std::string(key) + " missing.";
590    return false;
591  }
592  if (AsValue(json_value, value))
593    return true;
594  if (errors)
595    *errors = std::string("Wrong type for ") + std::string(key) + ".";
596  return false;
597}
598
599template <typename Visitor, typename T>
600inline bool VisitForRead(Visitor* visitor, T* t) {
601  return Iterate(visitor, t);
602}
603
604class JsonReaderVisitor {
605 public:
606  JsonReaderVisitor(cJSON* object, std::string* errors)
607      : object_(object), errors_(errors) {}
608
609  template <typename T> bool Visit(const char* key, T* value) const {
610    return ReadValue(object_, key, value, errors_);
611  }
612
613  template <typename T, uint32_t N>
614  bool VisitArray(const char* key, uint32_t count, T (*value)[N]) {
615    if (count > N)
616      return false;
617    cJSON* json_value = cJSON_GetObjectItem(object_, key);
618    if (!json_value) {
619      if (errors_)
620        *errors_ = std::string(key) + " missing.";
621      return false;
622    }
623    if (AsArray(json_value, count, *value))
624      return true;
625    if (errors_)
626      *errors_ = std::string("Wrong type for ") + std::string(key) + ".";
627    return false;
628  }
629
630
631 private:
632  cJSON* object_;
633  std::string* errors_;
634};
635
636template <typename T, typename = EnableForStruct<T>>
637bool AsValue(cJSON* json_value, T* t) {
638  if (json_value->type != cJSON_Object)
639    return false;
640  JsonReaderVisitor visitor(json_value, nullptr);
641  return VisitForRead(&visitor, t);
642}
643
644
645template <typename T> std::string VkTypeToJson(const T& t) {
646  JsonWriterVisitor visitor;
647  VisitForWrite(&visitor, t);
648
649  char* output = cJSON_Print(visitor.get_object());
650  std::string result(output);
651  free(output);
652  return result;
653}
654
655template <typename T> bool VkTypeFromJson(const std::string& json,
656                                          T* t,
657                                          std::string* errors) {
658  *t = T();
659  cJSON* object = cJSON_Parse(json.c_str());
660  if (!object) {
661    if (errors)
662      errors->assign(cJSON_GetErrorPtr());
663    return false;
664  }
665  bool result = AsValue(object, t);
666  cJSON_Delete(object);
667  return result;
668}
669
670}  // anonymous namespace
671
672std::string VkJsonDeviceToJson(const VkJsonDevice& device) {
673  return VkTypeToJson(device);
674}
675
676bool VkJsonDeviceFromJson(const std::string& json,
677                          VkJsonDevice* device,
678                          std::string* errors) {
679  return VkTypeFromJson(json, device, errors);
680};
681
682std::string VkJsonImageFormatPropertiesToJson(
683    const VkImageFormatProperties& properties) {
684  return VkTypeToJson(properties);
685}
686
687bool VkJsonImageFormatPropertiesFromJson(const std::string& json,
688                                         VkImageFormatProperties* properties,
689                                         std::string* errors) {
690  return VkTypeFromJson(json, properties, errors);
691};
692