1 // Copyright 2014 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_MAP_DATA_INTERNAL_H_ 6 #define MOJO_PUBLIC_CPP_BINDINGS_LIB_MAP_DATA_INTERNAL_H_ 7 8 #include "mojo/public/cpp/bindings/lib/array_internal.h" 9 #include "mojo/public/cpp/bindings/lib/validate_params.h" 10 #include "mojo/public/cpp/bindings/lib/validation_errors.h" 11 #include "mojo/public/cpp/bindings/lib/validation_util.h" 12 13 namespace mojo { 14 namespace internal { 15 16 // Map serializes into a struct which has two arrays as struct fields, the keys 17 // and the values. 18 template <typename Key, typename Value> 19 class Map_Data { 20 public: 21 static Map_Data* New(Buffer* buf) { 22 return new (buf->Allocate(sizeof(Map_Data))) Map_Data(); 23 } 24 25 // |validate_params| must have non-null |key_validate_params| and 26 // |element_validate_params| members. 27 static bool Validate(const void* data, 28 ValidationContext* validation_context, 29 const ContainerValidateParams* validate_params) { 30 if (!data) 31 return true; 32 33 if (!ValidateStructHeaderAndClaimMemory(data, validation_context)) 34 return false; 35 36 const Map_Data* object = static_cast<const Map_Data*>(data); 37 if (object->header_.num_bytes != sizeof(Map_Data) || 38 object->header_.version != 0) { 39 ReportValidationError(validation_context, 40 VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); 41 return false; 42 } 43 44 if (!ValidatePointerNonNullable( 45 object->keys, "null key array in map struct", validation_context) || 46 !ValidateContainer(object->keys, validation_context, 47 validate_params->key_validate_params)) { 48 return false; 49 } 50 51 if (!ValidatePointerNonNullable(object->values, 52 "null value array in map struct", 53 validation_context) || 54 !ValidateContainer(object->values, validation_context, 55 validate_params->element_validate_params)) { 56 return false; 57 } 58 59 if (object->keys.Get()->size() != object->values.Get()->size()) { 60 ReportValidationError(validation_context, 61 VALIDATION_ERROR_DIFFERENT_SIZED_ARRAYS_IN_MAP); 62 return false; 63 } 64 65 return true; 66 } 67 68 StructHeader header_; 69 70 Pointer<Array_Data<Key>> keys; 71 Pointer<Array_Data<Value>> values; 72 73 private: 74 Map_Data() { 75 header_.num_bytes = sizeof(*this); 76 header_.version = 0; 77 } 78 ~Map_Data() = delete; 79 }; 80 static_assert(sizeof(Map_Data<char, char>) == 24, "Bad sizeof(Map_Data)"); 81 82 } // namespace internal 83 } // namespace mojo 84 85 #endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_MAP_DATA_INTERNAL_H_ 86