# Definitions used for Jinja template replacement.

# This file is part of Cantera. See License.txt in the top-level directory or
# at https://cantera.org/license.txt for license and copyright information.

csharp-interop-func: |-
  [LibraryImport(LibFile{{ ', StringMarshalling = StringMarshalling.Utf8' if has_string_param }})]
  {%- if check_return %}
  [return: MarshalUsing(typeof(ReturnCodeChecker))]
  {%- endif %}
  {% if public %}public {% else %}private {% endif %}static partial {{ declaration }};

csharp-getstring-func: |-
  [SkipLocalsInit]
  public static {{ declaration }}
  {
      // try with stack-allocated buffer
      Span<byte> {{ span_param_name }} = stackalloc byte[BufferSize];
      var {{ length_param_name }} = BufferSize;

      var neededSize = {{ invocation }};
      if (neededSize <= {{ length_param_name }})
      {
          // remove null terminator byte
          {{ span_param_name }} = {{ span_param_name }}[..(neededSize - 1)];
          return Encoding.UTF8.GetString({{ span_param_name }});
      }

      // try with rented array buffer
      // array will be at least neededSize but could be larger
      var array = ArrayPool<byte>.Shared.Rent(neededSize);
      {{ span_param_name }} = array;
      {{ length_param_name }} = array.Length;
      try
      {
          neededSize = {{ invocation }};
          if (neededSize <= {{ length_param_name }})
          {
              // remove null terminator byte
              {{ span_param_name }} = {{ span_param_name }}[..(neededSize - 1)];
              // use span overload, which skips bounds checks
              return Encoding.UTF8.GetString({{ span_param_name }});
          }
      }
      finally
      {
        ArrayPool<byte>.Shared.Return(array);
      }

      ThrowOnBadString();
      return null; // not reached
  }

csharp-span-func: |-
  [SkipLocalsInit]
  public static {{ declaration }}
  {
    var {{ length_param_name }} = {{ span_param_name }}.Length;
    {{ invocation }};
  }

csharp-getarray-func: |-
  [SkipLocalsInit]
  public static {{ declaration }}
  {
    var {{ length_param_name }} = {{ get_size_invocation }};
    var {{ span_param_name }} = new double[{{ length_param_name }}];
    {{ invocation }};
    return {{ span_param_name }};
  }

csharp-base-handle: |-
  [NativeMarshalling(typeof(Marshaller<{{ class_name }}>))]
  class {{ class_name }} : CanteraHandle
  {
      protected override void Close() =>
          LibCantera.{{ release_func_name }}(this);
  }

csharp-derived-handle: |-
  [NativeMarshalling(typeof(Marshaller<{{ derived_class_name }}>))]
  class {{ derived_class_name }} : {{ base_class_name }} { }

csharp-property: |-
  public {{ prop_type }} {{ cs_name }}
  {
      get => LibCantera.{{ getter }}(_handle);
      {%- if setter %}
      set => LibCantera.{{ setter }}(_handle, value);
      {%- endif %}
  }
