chromium/mojo/public/tools/bindings/generators/cpp_templates/struct_definition.tmpl

{%- import "validation_macros.tmpl" as validation_macros %}
{%- set class_name = struct.name ~ "_Data" %}

// static
bool {{class_name}}::Validate(
    const void* data,
    mojo::internal::ValidationContext* validation_context) {
  if (!data)
    return true;

{%- if struct.versions|length == 1 %}
  if (!ValidateUnversionedStructHeaderAndSizeAndClaimMemory(
          data, {{struct.versions[0].num_bytes}}, validation_context)) {
    return false;
  }
{%- else %}
  static constexpr mojo::internal::StructVersionSize kVersionSizes[] = {
{%- for version in struct.versions %}
    { {{version.version}}, {{version.num_bytes}} },
{%- endfor %}
  };
  if (!ValidateStructHeaderAndVersionSizeAndClaimMemory(
          data, kVersionSizes, validation_context)) {
    return false;
  }
{%- endif %}

  // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if
  // the message comes from an older version.
  [[maybe_unused]] const {{class_name}}* object =
      static_cast<const {{class_name}}*>(data);

{#- Before validating fields introduced at a certain version, we need to add
    a version check, which makes sure we skip further validation if |object|
    is from an earlier version. |last_checked_version| records the last
    version that we have added such version check. #}
{%- set ns = namespace(last_checked_version = 0) %}
{%- for packed_field in struct.packed.packed_fields_in_ordinal_order %}
{%-   set kind = packed_field.field.kind %}
{%-   if kind|is_object_kind or kind|is_any_handle_or_interface_kind or
         kind|is_enum_kind %}
{%-     if packed_field.min_version > ns.last_checked_version %}
{%-       set ns.last_checked_version = packed_field.min_version %}
  if (object->header_.version < {{packed_field.min_version}})
    return true;
{%-     endif %}
{%-     set field_expr = "object->" ~ packed_field.field.name %}
{{validation_macros.validate_field(packed_field.field, loop.index, field_expr, true)}}
{%-   endif %}
{%- endfor %}

  return true;
}

{{class_name}}::{{class_name}}()
    : header_({sizeof(*this), {{struct.versions[-1].version}}}) {}