AZ_NODISCARD az_result _az_span_url_encode()

in sdk/src/azure/core/az_span.c [935:982]


AZ_NODISCARD az_result _az_span_url_encode(az_span destination, az_span source, int32_t* out_length)
{
  _az_PRECONDITION_NOT_NULL(out_length);
  _az_PRECONDITION_VALID_SPAN(source, 0, true);

  int32_t const source_size = az_span_size(source);
  _az_PRECONDITION_VALID_SPAN(destination, source_size, false);

  _az_PRECONDITION_NO_OVERLAP_SPANS(destination, source);

  uint8_t* const dest_begin = az_span_ptr(destination);
  uint8_t* const dest_end = dest_begin + az_span_size(destination);

  uint8_t* const src_ptr = az_span_ptr(source);
  uint8_t* dest_ptr = dest_begin;

  for (int32_t i = 0; i < source_size; i++)
  {
    uint8_t c = src_ptr[i];
    if (!_az_span_url_should_encode(c))
    {
      if (dest_ptr >= dest_end)
      {
        *out_length = 0;
        return AZ_ERROR_NOT_ENOUGH_SPACE;
      }

      *dest_ptr = c;
      ++dest_ptr;
    }
    else
    {
      if (dest_ptr >= dest_end - 2)
      {
        *out_length = 0;
        return AZ_ERROR_NOT_ENOUGH_SPACE;
      }

      dest_ptr[0] = '%';
      dest_ptr[1] = _az_number_to_upper_hex(c >> 4U);
      dest_ptr[2] = _az_number_to_upper_hex(c & (uint32_t)_az_LARGEST_HEX_VALUE);
      dest_ptr += 3;
    }
  }

  *out_length = (int32_t)(dest_ptr - dest_begin);
  return AZ_OK;
}