glaze icon indicating copy to clipboard operation
glaze copied to clipboard

Return size of json written to buffer that is not resizable

Open elliot-spidertracks opened this issue 1 year ago • 1 comments

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?

elliot-spidertracks avatar Feb 26 '25 00:02 elliot-spidertracks

This is also an active issue here: #1285. This is definitely a feature that should be added. There is other internal refactoring that I'm finishing for v5.0.0, but soon after that I would like to tackle this problem. I'll leave this issue open as well, as I think it is quite important.

stephenberry avatar Feb 26 '25 14:02 stephenberry