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