Skip to content

Return size of json written to buffer that is not resizable #1633

@elliot-spidertracks

Description

@elliot-spidertracks

Maybe I have missed something, but currently it doesn't seem like you can know how much data was serialized into a buffer if it's not resizable.
For example I want to pass in a std::span and on success be able to know where the serialization ended.
Locally I have tried just writing the location value in the error_ctx that is returned and this works nicely however I know that location is documented as being for internal use.

   template <opts Opts, class T, output_buffer Buffer>
      requires write_supported<Opts.format, T>
   [[nodiscard]] error_ctx write(T&& value, Buffer& buffer, is_context auto&& ctx)
   {
      if constexpr (resizable<Buffer>) {
         // A buffer could be size 1, to ensure we have sufficient memory we can't just check `empty()`
         if (buffer.size() < 2 * write_padding_bytes) {
            buffer.resize(2 * write_padding_bytes);
         }
      }
      size_t ix = 0; // overwrite index
      detail::to<Opts.format, std::remove_cvref_t<T>>::template op<Opts>(std::forward<T>(value), ctx, buffer, ix);
      if constexpr (resizable<Buffer>) {
         buffer.resize(ix);
      }

      return {ctx.error, ctx.custom_error_message, ix}; //include location
   }

Any thoughts on making changes like this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions