7¤0ìÔ¶:0A¨2ãŒ0333333333}mÿo)…m‘Ý¦²mewËbø3æ6âÆŒ8ˆ�û�×ÐˆˆöÓr-v[+ÌD%Àã   ˆ†#2©T*Œë€ � ˜‘�Œdâh0Ir †QA2Æ d�B
Í  ä×E=Ì)d                    present, Stephen Berry

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Softwar  }

      template <class K>
         requires detail::transparent_lookup<Hash, KeyEqual>
      const_iterator find(const K& key) const
      {
         uint32_t bi = find_bucket(key);
         if (bi == bucket_count_) return values_.end();
         return values_.begin() + buckets_[bi].index;
      }

      mapped_type& at(const key_type& key)
      {
         auto it = find(key);
         if (it == end()) {
            GLZ_THROW_OR_ABORT(std::out_of_range("ordered_map::at: key not found"));
         }
         return it->second;    requires(std::is_constructible_v<mapped_type, M &&> && std::is_assignable_v<mapped_type&, M &&>)
      std::pair<iterator, bool> insert_or_assign(const key_type& key, M&& obj)
      {
         auto [bucket_idx, stored, found] = insert_to_buckets(key);
         if (found) {
            auto it = values_.begin() + buckets_[bucket_idx].index;
            it->second = std::forward<M>(obj);
            return {it, false};
         }
         values_.emplace_back(key, std::forward<M>(obj));
         return {values_.end() - 1, true};
count_ = new_count;
         bucket_mask_ = bucket_count_ - 1;
         load_threshold_ = static_cast<uint32_t>(static_cast<float>(bucket_count_) * max_load_factor_);
         allocate_buckets();

         for (uint32_t i = 0; i < static_cast<uint32_t>(values_.size()); ++i) {
            const size_t h = hash_(values_[i].first);
            insert_into_buckets({i, to_stored_hash(h)});
         }
      }

      // Insert implementation that handles grow, duplicate check, and robin hood placement.
      // Returns {bucket_idx, storedte <class T>
   concept is_state_view = std::same_as<std::decay_t<T>, state_view>;

   /// Read parameters from state_view (zero-copy from input buffer)
   /// Returns number of bytes read, or 0 on error (error set in state.out)
   template <auto Opts, class Value>
   size_t read_params(Value&& value, state_view& state)
   {
      glz::context ctx{};
      auto body = state.in.body;
      auto b = body.data();
      auto e = b + body.size();

      if (body.empty()) [[unlikely]] {
         ctx.error = error_code::no_read_input;
   
            hdr_.length = sizeof(header) + body.size();

            buffer_->resize(hdr_.length);
            std::memcpy(buffer_->data(), &hdr_, sizeof(header));
            if (!body.empty()) {
               std::memcpy(buffer_->data() + sizeof(header), body.data(), body.size());
            }
         }
      }

      /// Get the finalized response as a span (buffer mode only)
      [[nodiscard]] std::span<const char> finish() const noexcept
      {
         if (buffer_) {
            return {buffer_->data(), buffer_->size()}of(repe::header) + msg.query.size() + msg.body.size();
            return msg;
         }

         template <class Value>
         message operator()(const user_header& h, Value&& value) const
         {
            message msg{};
            msg.header = encode(h);
            msg.query = std::string{h.query};
            msg.header.query_format = repe::query_format::JSON_POINTER;
            // TODO: Handle potential write errors and put in msg
            std::ignore = glz::write<Opts>(std::forward<Value>(value), msg.body);
   Deserialize a repe::message from raw bytes
   /// @param data Pointer to wire-format data
   /// @param size Size of data in bytes
   /// @param msg Output message
   /// @return error_code::none on success, appropriate error on failure
   inline error_code from_buffer(const char* data, size_t size, message& msg)
   {
      if (size < sizeof(header)) {
         return error_code::invalid_header;
      }

      std::memcpy(&msg.header, data, sizeof(header));

      // Validate REPE magic
      if (msg.header.spec != repe_magic) {
  ssert(sizeof(header) == 48);

   // Computes the expected total message length (header + query + body) from an
   // attacker-controllable header without overflowing. query_length and body_length
   // are 64-bit fields supplied on the wire, so a naive sum can wrap and defeat the
   // subsequent buffer-size validation, producing out-of-bounds query/body views.
   // Returns false if the lengths would overflow, in which case the header is malformed.
   [[nodiscard]] inline bool checked_message_length(const header& hdr, uint64_t& exeturn R"({"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid Request","data":"Empty batch"},"id":null})";
            }
            return process_batch(*batch_requests);
         }

         // Single request
         auto response = process_single_request(json_request);
         return response.value_or("");
      }

     private:
      // Process a single JSON RPC request, returns nullopt for notifications
      std::optional<std::string> process_single_request(std::string_view json_request)
         requires(Proto == JSOngth = body.size();
            out.header.body_format = repe::body_format::UTF8; // Error messages are UTF-8
            out.header.length = sizeof(repe::header) + out.query.size() + out.body.size();
         };

         // REPE Header Validation

         // Version validation - REPE spec requires version 1
         if (in.header.version != 1) {
            out.header.ec = error_code::version_mismatch;
            out.header.id = in.header.id; // Echo back the original ID
            write_error(detail::build_version_error(in.henrpc::write_response<Opts>((value.*func)(), state);
            }
         };
      }

      template <class T, class F, class Input, class Ret, class RegistryType>
      static void register_member_function_with_params_endpoint(const sv path, T& value, F func, RegistryType& reg)
      {
         reg.endpoints[path] = [&value, func](jsonrpc::state&& state) mutable {
            static thread_local Input input{};
            input = {}; // reset to avoid stale optional/variant fields across calls
            if (state.has_body()) {
 func) const&
      {
         return (bool(func(B::value)) && ...);
      }
      template <class F, class... B>
      constexpr bool all_impl(tuplet::type_list<B...>, F&& func) &&
      {
         return (bool(func(static_cast<T&&>(B::value))) && ...);
      }
   };
   template <>
   struct tuple<> : tuplet::tuple_base_t<>
   {
      constexpr static size_t N = 0;
      using super = tuplet::tuple_base_t<>;
      using base_list = tuplet::type_list<>;

      template <tuplet::other_than<tuple> U> // Preserves default assignments
&& not std::is_scoped_enum_v<decltype(E)>)
   consteval auto get_name()
   {
#if defined(_MSC_VER) && !defined(__clang__)
      std::string_view str = extract_template_argument(GLZ_PRETTY_FUNCTION);
      if (const auto eq_pos = str.rfind("= "); eq_pos != std::string_view::npos) {
         str.remove_prefix(eq_pos + 2);
      }
      return normalize_extracted_name(strip_leading_decl_keywords(str));
#else
      std::string_view str = GLZ_PRETTY_FUNCTION;
      str = str.substr(str.rfind("= ") + 2);
      return str.substr(0, str.fiexpr auto member_names_impl(std::index_sequence<I...>)
   {
      if constexpr (sizeof...(I) == 0) {
         return std::array<sv, 0>{};
      }
      else {
         return std::array{glz::meta<std::remove_cvref_t<T>>::rename_key(member_nameof<I, T>)...};
      }
   }

   // Concept for indexed rename_key that provides type information
   template <class T>
   concept meta_has_rename_key_indexed = requires {
      { glz::meta<std::remove_cvref_t<T>>::template rename_key<0>() } -> std::convertible_to<std::string_view>;
   } && !mevoid duplicate `to_tie` template instantiations with rest of Glaze
   // Temporary fix: const qualify it despite. Caused issues with reflect begin/end indices
   // See https://github.com/stephenberry/glaze/issues/1568
   template <class T>
   extern const T external;

   // using const char* simplifies the compiler's output and should improve compile times
   template <auto Ptr>
   [[nodiscard]] consteval auto mangled_name()
   {
      // return std::source_location::current().function_name();
      return GLZ_PRETTY_FUNCTION;
   p15, p16, p17, p18, p19, p20,
                         p21, p22, p23, p24, p25, p26, p27, p28, p29, p30, p31, p32, p33, p34, p35, p36, p37, p38, p39,
                         p40, p41, p42, p43, p44, p45, p46, p47, p48, p49, p50, p51, p52, p53, p54, p55, p56, p57, p58,
                         p59, p60, p61, p62, p63, p64, p65, p66, p67, p68, p69, p70, p71, p72, p73, p74, p75, p76, p77,
                         p78, p79, p80, p81, p82, p83, p84, p85, p86, p87, p88, p89, p90, p91, p92);
      }
      else if constexpr (N == 94) {
  3, p74, p75, p76, p77, p78, p79, p80, p81, p82] = t;
         return glz::tie(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20,
                         p21, p22, p23, p24, p25, p26, p27, p28, p29, p30, p31, p32, p33, p34, p35, p36, p37, p38, p39,
                         p40, p41, p42, p43, p44, p45, p46, p47, p48, p49, p50, p51, p52, p53, p54, p55, p56, p57, p58,
                         p59, p60, p61, p62, p63, p64, p65, p66, p67, p68, p69, p70, p71, p72, p73, p74, p75, p76, p77,
                  p59, p60, p61, p62, p63, p64, p65, p66, p67, p68, p69, p70);
      }
      else if constexpr (N == 72) {
         auto& [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22,
                p23, p24, p25, p26, p27, p28, p29, p30, p31, p32, p33, p34, p35, p36, p37, p38, p39, p40, p41, p42, p43,
                p44, p45, p46, p47, p48, p49, p50, p51, p52, p53, p54, p55, p56, p57, p58, p59, p60, p61, p62, p63, p64,
                p65, p66, p67, p68, p69, p70, p71] = t;30, p31, p32, p33, p34, p35, p36, p37, p38, p39,
                         p40, p41, p42, p43, p44, p45, p46, p47, p48, p49, p50, p51, p52, p53, p54, p55, p56);
      }
      else if constexpr (N == 58) {
         auto& [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22,
                p23, p24, p25, p26, p27, p28, p29, p30, p31, p32, p33, p34, p35, p36, p37, p38, p39, p40, p41, p42, p43,
                p44, p45, p46, p47, p48, p49, p50, p51, p52, p53, p54, p55, p56, p57] = t;
 constexpr (N == 40) {
         auto& [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22,
                p23, p24, p25, p26, p27, p28, p29, p30, p31, p32, p33, p34, p35, p36, p37, p38, p39] = t;
         return glz::tie(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20,
                         p21, p22, p23, p24, p25, p26, p27, p28, p29, p30, p31, p32, p33, p34, p35, p36, p37, p38, p39);
      }
      else if constexpr (N == 41) {
  onstexpr (N == 2) {
         auto& [p0, p1] = t;
         return glz::tie(p0, p1);
      }
      else if constexpr (N == 3) {
         auto& [p0, p1, p2] = t;
         return glz::tie(p0, p1, p2);
      }
      else if constexpr (N == 4) {
         auto& [p0, p1, p2, p3] = t;
         return glz::tie(p0, p1, p2, p3);
      }
      else if constexpr (N == 5) {
         auto& [p0, p1, p2, p3, p4] = t;
         return glz::tie(p0, p1, p2, p3, p4);
      }
      else if constexpr (N == 6) {
         auto& [p0, p1, p2, p3, p4, p5] = t;
romise = std::move(promise)](std::expected<response, std::error_code> result) mutable {
                      promise.set_value(std::move(result));
                   });

         return future;
      }

      // Asynchronous POST request
      template <typename CompletionHandler>
      void post_async(std::string_view url, const std::string& body,
                      const std::unordered_map<std::string, std::string>& headers, CompletionHandler&& handler)
      {
         auto url_result = parse_url(url);
         if (!url_ressio::streambuf> buffer; // Use unified streambuf for all reads
      bool is_connected{false};
      std::atomic<bool> should_stop{false};
      stream_read_strategy strategy{stream_read_strategy::bulk_transfer}; // Default strategy
      std::function<bool(int)> status_is_error{}; // Evaluated before treating status as failure
      bool is_https{false}; // Track if this is an HTTPS connection

      // Constructor with optional buffer size limit and strategy
      http_stream_connection(size_t max_buffer_size = 1024 * 1024,
     ertificate verification,
      // making the connection vulnerable to man-in-the-middle attacks.
      // Only use verify_none for testing with self-signed certificates.
      void set_ssl_verify_mode(asio::ssl::verify_mode mode)
      {
         std::unique_lock<std::shared_mutex> lock(ssl_mtx);
         ssl_context->set_verify_mode(mode);
      }

      // Thread-safe access to SSL context for advanced configuration
      // The provided callable is executed while holding an exclusive lock
      // Example: pool.configure_ssl_concard]] acquire_result
      {
         socket_variant socket;
         bool from_pool;
      };

      mutable std::mutex pool_mtx; // Protects available_connections
      std::unordered_map<connection_key, std::vector<pool_entry>, connection_key_hash> available_connections;
      asio::any_io_executor io_executor;
      std::atomic<bool> graceful_ssl_shutdown_{true}; // Whether to perform SSL shutdown when closing connections
      // Default to 4 seconds: just under uvicorn's 5s default keep-alive timeout. Any
      // entry idlerror_code(ssl_error e) noexcept
   {
      return {static_cast<int>(e), get_ssl_error_category()};
   }
   // HTTP client error codes
   enum class http_client_error {
      success = 0,
      response_too_large, // Response body exceeds max_response_body_size
   };

   // HTTP client error category for std::error_code integration
   class http_client_error_category : public std::error_category
   {
     public:
      const char* name() const noexcept override { return "glaze.http_client"; }

      std::string message(int ev) constx to synchronize close handler access between do_close() and force_close()
      std::mutex close_handler_mutex_;

      // Mutex to prevent race between starting async operations and closing the socket.
      // ASIO sockets are NOT thread-safe for concurrent operations (e.g., async_read_some
      // racing with close()). This mutex is held briefly while setting up async ops and
      // while closing the socket.
      std::mutex socket_op_mutex_;

      // Close code and reason for callback
      ws_close_code close_code_{ws_clok_guard<std::mutex> lock(write_mutex_);
            write_queue_.push_back(std::move(frame_buffer));
            if (close_after) {
               close_after_write_ = true; // Set atomically with queuing
            }
            if (write_in_progress_) {
               return; // Another write is in progress, frame will be sent when it completes
            }
            write_in_progress_ = true;
         }

         // Start writing the queued frame
         do_write();
      }

      // Process the write queue - called when a all message handlers if not closed (prevents calling handlers
               // after force_close() when user's captured references may be invalid)
               if (!closed_.load()) {
                  dispatch_message(message_view, opcode);
               }
            }
            else {
               // Fragmented message - must buffer for reassembly
               if (opcode == ws_opcode::text && !text_payload_consumed) {
                  utf8_validator_.reset();
                  if (!utf8_validator_.consume(payload, leng.header_size != header_size ||
             incomplete_text_frame_.expected_payload_size != expected_payload_size ||
             incomplete_text_frame_.mask_key != mask_key) {
            fail_connection(ws_close_code::protocol_error, "Invalid incomplete frame state");
            return false;
         }

         return true;
      }

      // Consume only new payload bytes that arrived since the previous read
      inline bool consume_incomplete_text_payload(ws_opcode opcode, bool fin, bool masked, std::size_t header_size,
    ring_view payload = {}) override { send_frame(ws_opcode::pong, payload); }

      // Close the connection
      // RFC 6455 Section 7.1.2: "To Start the WebSocket Closing Handshake with a status code,
      // an endpoint MUST send a Close control frame"
      // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.2
      void close(ws_close_code code = ws_close_code::normal, std::string_view reason = {}) override
      {
         // Atomically check and set is_closing_ to prevent race conditions
         bool expected = falslaze/ext/glaze_asio.hpp"
#include "glaze/net/http_router.hpp"
#include "glaze/util/parse.hpp"

namespace glz
{
   // WebSocket opcode constants
   enum class ws_opcode : uint8_t { continuation = 0x0, text = 0x1, binary = 0x2, close = 0x8, ping = 0x9, pong = 0xa };

   // WebSocket close codes
   enum class ws_close_code : uint16_t {
      normal = 1000,
      going_away = 1001,
      protocol_error = 1002,
      unsupported_data = 1003,
      invalid_payload = 1007,
      policy_violation = 1008,
      message_too_big = 1009,
     ce >= status_line.size() - 1) {
         return std::unexpected(std::make_error_code(std::errc::protocol_error));
      }

      const size_t second_space = status_line.find(' ', first_space + 1);
      const bool has_status_message = second_space != std::string_view::npos;

      // Extract the components as views instead of creating new strings
      std::string_view version = status_line.substr(http_prefix.length(), first_space - http_prefix.length());

      std::string_view status_code_str = status_line.substr(
         first_ads using hardware_concurrency()
       * @endcode
       *
       * Example with external io_context:
       * @code
       * auto io_ctx = std::make_shared<asio::io_context>();
       * glz::http_server server(io_ctx->get_executor());
       * server.bind(8080);
       * server.start(0);  // Pass 0 to skip creating worker threads
       *
       * // Run io_context in your own thread(s)
       * std::thread io_thread([io_ctx]() {
       *    io_ctx->run();
       * });
       *
       * // ... later ...
       * server.stop();
  connect_handler_ = handler;
         start_disconnect_detection();
      }

      // Check if connection is still alive
      bool is_open() const override { return socket_ && socket_->lowest_layer().is_open() && !is_closed_; }

      // Get remote endpoint info
      std::string remote_address() const override
      {
         if (socket_) {
            try {
               return socket_->lowest_layer().remote_endpoint().address().to_string();
            }
            catch (...) {
            }
         }
         return "";
  -Control: no-cache\r\n");
         }

         response_str.append("\r\n");

         auto buffer = std::make_shared<std::string>(std::move(response_str));
         auto self = this->shared_from_this();

         asio::async_write(*socket_, asio::buffer(*buffer), [self, buffer, handler](std::error_code ec, std::size_t) {
            if (handler) handler(ec);
         });
      }

      // Send a chunk of data
      void send_chunk(std::string_view data, data_sent_handler handler = {}) override
      {
         if (is_closed_) retur/ DIGIT / ALPHA
         return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '!' ||
                ch == '#' || ch == '$' || ch == '%' || ch == '&' || ch == '\'' || ch == '*' || ch == '+' || ch == '-' ||
                ch == '.' || ch == '^' || ch == '_' || ch == '`' || ch == '|' || ch == '~';
      }

      inline bool is_pct_encoded(std::string_view str) noexcept
      {
         // RFC 3986, Appendix A:
         // pct-encoded = "%" HEXDIG HEXDIG

         if (str.size() != 3) {
   losing_bracket_pos + 1);

            // After the IPv6 brackets, only a port is allowed
            if (!tail_after_ipv6.starts_with(':')) {
               return false;
            }

            std::string_view port_str = tail_after_ipv6.substr(1);

            return is_valid_port(port_str);
         }

         // RFC 9110, Section 4.2.3:
         // If the port is equal to the default port for a scheme, the normal
         // form is to omit the port subcomponent.
         size_t port_delimiter_pos = authority.find(':');
               else {
               // Key without value (e.g., "?flag")
               url_decode(pair, key_buffer);
               output[key_buffer] = "";
            }
         }

         pos = amp_pos + 1;
      }
   }

   /**
    * @brief Parse a URL-encoded query string or form body into a provided map
    *
    * Parses key=value pairs separated by '&'.
    * Both keys and values are URL-decoded.
    *
    * @param query_string The query string (without leading '?')
    * @param output The map to write key-value pairs to (cl+ (per application/x-www-form-urlencoded)
    * - All other characters are percent-encoded (%XX)
    *
    * @param input The string to encode
    * @param output The buffer to write the encoded string to (cleared before writing)
    */
   inline void url_encode(std::string_view input, std::string& output)
   {
      output.clear();
      output.reserve(input.size() * 3); // worst case: every char encoded

      constexpr char hex_chars[] = "0123456789ABCDEF";

      for (unsigned char c : input) {
         if ((c >= 'A' && c <= 'Z    res.status(204); // No Content
            },
            put_spec);
      }

      template <class Func, class Result, class RegistryType>
      static void register_function_endpoint(const sv path, Func& func, RegistryType& reg)
      {
         std::string rest_path = convert_to_rest_path(path);

         auto get_spec = create_route_spec_with_types<void, Result>("Get " + get_type_name<Result>(), {"data"});
         // GET handler for functions
         reg.endpoints.route(
            GET, rest_path,
            [&func](conreturn route(
            method, path,
            [handle = std::move(handle)](const request& req, response& res) {
               auto future = handle(req, res);
               future.get();
            },
            spec);
      }

      /**
       * @brief Register an asynchronous GET route
       */
      basic_http_router& get_async(std::string_view path, async_handler handle, const route_spec& spec = {})
         requires is_async_enabled
      {
         return route_async(http_method::GET, path, std::move(handle), spec); routers are intended for standalone use or with custom server implementations.
    */
   template <class Handler = std::function<void(const request&, response&)>>
      requires std::invocable<Handler, const request&, response&>
   struct basic_http_router
   {
      /**
       * @brief Function type for request handlers
       */
      using handler = Handler;

      /**
       * @brief A compile-time boolean indicating whether asynchronous request handlers are enabled.
       */
      static constexpr bool is_async_enabled =
   hod The HTTP method (GET, POST, etc.)
       * @param path The route path, may contain ":param" or trailing "*name" wildcards.
       * @param handle The handler to associate with the route.
       * @param spec Optional spec for the route.
       */
      void add(http_method method, std::string_view path, H handle, const route_spec& spec = {})
      {
         try {
            // Install in the radix tree first. add_route can throw on conflict
            // (duplicate :param or *wildcard names at the same position); if it
     :function<std::future<void>(const request&, response&)>;
   using error_handler = std::function<void(std::error_code, std::source_location)>;

   // Forward declarations for streaming and WebSocket support.
   // Full definitions live in glaze/net/http_server.hpp and glaze/net/websocket_connection.hpp.
   // Forward declarations are sufficient here because streaming_handler holds streaming_response
   // by reference and websocket_handler holds websocket_server through std::shared_ptr.
   struct streaming_response;
   struct websoclude <algorithm>
#include <functional>
#include <future>
#include <iostream>
#include <memory>
#include <optional>
#include <source_location>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>

#include "glaze/json/generic.hpp"
#include "glaze/net/http.hpp"
#include "glaze/net/url.hpp"
#include "glaze/util/key_transformers.hpp"

// To deconflict Windows.h, which defines a DELETE macro that collides with the
// http_method::DELETE used in the route helpers below. http.hpp's own undef is
// include-gu        }

         void on_connected(const url_parts& url)
         {
            if (url.protocol == "wss") {
#ifdef GLZ_ENABLE_SSL
               std::weak_ptr<impl> weak_self = weak_from_this();

               ssl_socket_->async_handshake(asio::ssl::stream_base::client, [weak_self, url](std::error_code ec) {
                  auto self = weak_self.lock();
                  if (!self) return; // Client was destroyed

                  if (ec) {
                     if (self->on_error && *self->on_error) (*self->on_error)(ec);
 if
         mutable std::mutex request_headers_mutex_;
         std::vector<std::pair<std::string, std::string>> request_headers_;
         std::atomic<header_validation_error> last_header_validation_error_{header_validation_error::none};

         size_t max_message_size{1024 * 1024 * 16}; // 16 MB limit
#ifdef GLZ_ENABLE_SSL
         asio::ssl::verify_mode ssl_verify_mode_{asio::ssl::verify_peer}; // Default to verify peer
#endif

         explicit impl(std::shared_ptr<asio::io_context> context) : ctx(std::move(context)) {}

     (*replay_it == '\'') {
                  parse_single_quoted_string(key, ctx, replay_it, replay_end);
               }
               else if (*replay_it == '[' || *replay_it == '{') {
                  // Canonicalize complex alias keys (flow seq/map) to a stable string form.
                  glz::generic key_node{};
                  auto temp_ctx = ctx.make_speculative();
                  from<YAML, glz::generic>::template op<flow_context_on<opts{.error_on_unknown_keys = false}>()>(
                     key_node, temp_ctx, re/ Trim trailing whitespace
         while (!value.empty() && (value.back() == ' ' || value.back() == '\t')) {
            value.pop_back();
         }

         if (in_flow && (value == "---" || value == "..." || value == "-")) {
            ctx.error = error_code::syntax_error;
         }
      }

      // Parse a multiline plain scalar with folding (for block context)
      // This handles plain scalars that span multiple lines, where continuation
      // lines are indented more than the base indent level.
      // Per YAML spec  // Resize to actual length
         value.resize(static_cast<size_t>(dst - dst_start));
         ++it; // skip closing quote
      }

      // Single-quoted string parsing with line folding
      // Only escape is '' -> ' (doubled single quote)
      // Line breaks are folded: single newline -> space, blank line -> newline
      template <class Ctx, class It, class End>
      inline void parse_single_quoted_string(std::string& value, Ctx& ctx, It& it, End end)
      {
         static constexpr size_t string_padding_bytes = 8;

   (std::max)(last_non_trimmable, dst_start);

               // Skip the newline
               if (*src == '\r' && (src + 1) < src_end && *(src + 1) == '\n') {
                  src += 2; // CRLF
               }
               else {
                  ++src;
               }

               // Skip leading indentation on the next line.
               int indent_count = 0;
               if (!yaml::skip_folded_line_indent(src, src_end, ctx, &indent_count)) return;
               if (indent_count == 0 && yaml::starts_with_document_mline bool alias_token_is_mapping_key(It it, End end) noexcept
      {
         if (it == end || *it != '*') return false;
         ++it; // skip '*'
         auto name = parse_anchor_name(it, end);
         if (name.empty()) return false;
         skip_inline_ws(it, end);
         return (it != end && *it == ':') &&
                ((it + 1) == end || whitespace_or_line_end_table[static_cast<uint8_t>(*(it + 1))]);
      }

      struct node_property_state
      {
         bool has_anchor = false;
         std::string anchor_name{};     dump(": ", b, ix);
         write_variant_tag_id<Opts, Variant>(index, ctx, b, ix, indent_level);
         dump('\n', b, ix);

         // The YAML writer threads indentation through explicit parameters, not the context, so a
         // custom serializer (which can only call serialize<YAML>) always emits its body relative to
         // column 0. Render the body, then re-indent every line to the mapping's column so the tag
         // and the body share one block mapping. Relative indentation within the body is preserved.
            dump('{', b, ix);
         bool first = true;
         write_flow_mapping_members<Opts>(value, ctx, b, ix, first);
         dump('}', b, ix);
      }

      // Write a tagged variant's discriminator value (the meta::ids entry for `index`).
      template <auto Opts, class Variant, class B>
      inline void write_variant_tag_id(size_t index, is_context auto&& ctx, B&& b, auto& ix, int32_t indent_level)
      {
         using id_type = std::decay_t<decltype(ids_v<Variant>[0])>;
         if constexpr (std::integral<id_type>)e_block_mapping_nested<Opts>(member, ctx, b, ix, indent_level + 1);
               }
            }
         }
         else if constexpr (writable_map_t<val_t> || writable_array_t<val_t> || glaze_object_t<val_t> ||
                            reflectable<val_t>) {
            // Complex types go on next line with increased indent
            dump('\n', b, ix);

            // Create a modified context with incremented indent level
            if constexpr (requires { ctx.indent_level; }) {
               auto nested_ctx = ctx;
     constexpr (yaml::check_flow_style(Opts) || yaml::check_flow_context(Opts)) {
            yaml::write_flow_sequence<Opts>(value, ctx, b, ix);
         }
         else {
            // Get indent level from context if available, otherwise 0
            int32_t indent_level = 0;
            if constexpr (requires { ctx.indent_level; }) {
               indent_level = ctx.indent_level;
            }
            yaml::write_block_sequence<Opts>(value, ctx, b, ix, indent_level);
         }
      }
   };

   // Tuples (std::tuple, glaze_   if constexpr (str_t<element_t>) {
               dump(' ', b, ix);
               write_yaml_string<Opts>(sv{element}, ctx, b, ix, indent_level);
               dump('\n', b, ix);
            }
            else if constexpr (is_simple_type<element_t>()) {
               dump(' ', b, ix);
               serialize<YAML>::op<Opts>(element, ctx, b, ix);
               dump('\n', b, ix);
            }
            else if constexpr (nullable_like<element_t>) {
               using inner_t = std::remove_cvref_t<decltype(*element)>;
       dump("|\n", b, ix);
         }

         // Write each line with proper indentation
         size_t pos = 0;
         while (pos < str.size()) {
            // Write indentation
            const int32_t spaces = (indent_level + 1) * indent_width;
            if (!ensure_space(ctx, b, ix + spaces + 256)) [[unlikely]] {
               return;
            }
            for (int32_t i = 0; i < spaces; ++i) {
               b[ix++] = ' ';
            }

            // Find end of line
            size_t eol = str.find('\n', pos);
 start = it;
         int32_t line_indent = measure_indent<false>(it, end, ctx);
         if (bool(ctx.error)) [[unlikely]]
            return;

         // Check if this is a blank line
         if (it != end && (*it == '\n' || *it == '\r')) {
            skip_newline(it, end);
            continue;
         }

         // First content line sets the indentation
         if (content_indent < 0) {
            if (line_indent <= base_indent) {
               // Dedented past base - end of block scalar
               it = line_start;
ne;
               skip_newline(it, end);
               continue;
            }
            break;
         }
      }

      // Check for ---
      if (end - it >= 3 && it[0] == '-' && it[1] == '-' && it[2] == '-') {
         auto after = it + 3;
         // Must be followed by whitespace, newline, or end
         if (after == end || *after == ' ' || *after == '\t' || *after == '\n' || *after == '\r' || *after == '#') {
            auto content = after;
            while (content != end && (*content == ' ' || *content == '\t')) {
    return yaml_tag::none;
   }

   template <class It, class End>
   inline yaml_tag parse_yaml_tag(It& it, End end) noexcept
   {
      return parse_yaml_tag(it, end, true);
   }

   template <class It, class End, class Ctx>
   inline yaml_tag parse_yaml_tag(It& it, End end, const Ctx& ctx) noexcept
   {
      return parse_yaml_tag(it, end, !ctx.secondary_tag_handle_overridden);
   }

   // Check if a tag is valid for string types
   inline constexpr bool tag_valid_for_string(yaml_tag tag) noexcept
   {
      return tag == yaml_t
   // Table for characters that terminate block mapping key scanning
   // Characters: newline, carriage return, flow indicators { [ ] } ,
   inline constexpr std::array<bool, 256> block_mapping_end_table = [] {
      std::array<bool, 256> t{};
      t['\n'] = true;
      t['\r'] = true;
      t['{'] = true;
      t['['] = true;
      t[']'] = true;
      t['}'] = true;
      t[','] = true;
      return t;
   }();

   // Scalar style detection
   enum struct scalar_style : uint8_t {
      plain, // unquoted
      single_quoted, //s_internal : uint32_t {
      none = 0,
      flow_context = 1 << 0, // Currently in flow context (no indentation rules)
   };

   struct yaml_opts
   {
      uint32_t format = YAML;
      bool error_on_unknown_keys{true};
      bool error_on_missing_keys{false}; // Require all non-nullable keys to be present
      bool skip_null_members{true}; // Skip writing null members
      uint8_t indent_width{2}; // Spaces per indent level for writing
      bool flow_style{false}; // Use flow style (compact) for output

      uint32_t internsize_t data_end_ = 0; // End of valid data in buffer
      size_t total_consumed_ = 0; // Total bytes consumed (for error reporting)
      bool eof_reached_ = false;

     public:
      using value_type = char;
      using const_reference = const char&;
      using size_type = size_t;
      using const_iterator = const char*;
      using stream_type = Stream;

      // Construct with input stream and optional initial capacity
      explicit basic_istream_buffer(Stream& stream, size_t initial_capacity = DefaultCapacity)
         : s//   - I/O latency (disk/network) dominates CPU overhead
   //   - The function bodies are trivial (return pointer/size)
   //
   //   Streaming parsing is inherently slower than buffer-based parsing due to this
   //   overhead and the need to handle data spanning buffer boundaries. Users choosing
   //   streaming trade some performance for bounded memory usage.
   struct streaming_state
   {
      void* buffer_ptr = nullptr;

      // Function pointers for type-erased operations
      const char* (*get_data)(void*) = nullptr;
     // Other errors
      cannot_be_referenced, //
      invalid_get, //
      invalid_get_fn, //
      invalid_call, //
      invalid_partial_key, //
      name_mismatch, //
      array_element_not_found, //
      elements_not_convertible_to_design, //
      unknown_distribution, //
      invalid_distribution_elements, //
      hostname_failure, //
      includer_error, //
      // Feature support
      feature_not_supported, //
      // JSON Pointer errors (RFC 6901)
      invalid_json_pointer, // Malformed JSON pointer syntax (e.               },
                  index);
               return ret;
            }
            else [[unlikely]] {
               return false;
            }
         }
         else {
            auto it = value.find(key);
            if (it == value.end()) {
               return false;
            }
            return seek(std::forward<F>(func), it->second, json_ptr);
         }
      }
   };

   // Helper to transfer cv-qualifiers from source type to target type
   template <class Source, class Target>
   using copy_cv_t = st|| tuple_t<T> || array_t<T> || is_std_tuple<T>)
   struct seek_op<T>
   {
      template <class F>
      static bool op(F&& func, auto&& value, sv json_ptr)
      {
         if (json_ptr.empty()) {
            func(value);
            return true;
         }
         if (json_ptr[0] != '/' || json_ptr.size() < 2) return false;

         size_t index{};
         auto [p, ec] = std::from_chars(&json_ptr[1], json_ptr.data() + json_ptr.size(), index);
         if (ec != std::errc{}) return false;
         json_ptr = json_ptr.substr(p -  bool b = seek([&](auto&& val) { pe = read<Opts>(val, buffer); }, std::forward<T>(root_value), json_ptr);
      if (b) {
         return pe;
      }
      pe.ec = error_code::seek_failure;
      return pe;
   }

   // Given a JSON pointer path, writes into a buffer the specified value
   template <auto Opts, class T, class B>
   [[nodiscard]] bool write_as(T&& root_value, const sv json_ptr, B&& buffer)
   {
      return seek(
         [&](auto&& val) {
            if constexpr (raw_buffer<B>) {
               std::ignore = write<O    // Convert std::format spec to printf format at compile time
               constexpr auto printf_fmt = detail::to_printf_fmt(opts_type::float_format);

               const auto start = reinterpret_cast<char*>(&b[ix]);
               const auto available = check_write_unchecked(Opts) ? size_t(64) : (b.size() - ix);

               // snprintf returns chars that would be written (excluding null), or negative on error
               const int len = std::snprintf(start, available, printf_fmt.data, static_cast<double>(value));

  e

#include <charconv>
#include <type_traits>

// Detection: is std::to_chars for floating-point available?
// - Non-libc++ implementations (libstdc++, MSVC): always available
// - libc++: only when _LIBCPP_AVAILABILITY_HAS_TO_CHARS_FLOATING_POINT is 1
// This is needed because std::to_chars for floats is unavailable on older Apple platforms
// (iOS < 16.3, macOS < 13.3). The macro is always defined in libc++, but set to 0 or 1.
// Users can define GLZ_USE_STD_FORMAT_FLOAT before including glaze to override detection
#ifndef GLZ_USp"

template <>
struct glz::meta<glz::error_code>
{
   static constexpr sv name = "glz::error_code";
   using enum glz::error_code;
   static constexpr std::array keys{"none",
                                    "version_mismatch",
                                    "invalid_header",
                                    "invalid_query",
                                    "invalid_body",
                                    "parse_error",
                                    "method_not_found",
                                    "ti
         // for each character in the string
         for (size_t c = 0; c < min_length; ++c) {
            cols[c].emplace_back(s[c]);
         }
      }

      // sort columns so that we can determine
      // if the column is unique
      size_t best_index{};
      size_t best_count{};
      for (size_t i = 0; i < min_length; ++i) {
         auto& col = cols[i];
         ranges::sort(col);
         if (auto it = ranges::adjacent_find(col); it == col.end()) {
            // no duplicates found
            best_count = col.size()stexpr uint64_t rich_bitmix(uint64_t h, const uint64_t seed) noexcept
   {
      h ^= h >> 23;
      h *= 0x2127599bf4325c37ULL;
      h ^= seed;
      h *= 0x880355f21e6d1965ULL;
      h ^= h >> 47;
      return h;
   }

   template <size_t N>
   using bucket_value_t = std::conditional_t < N<256, uint8_t, uint16_t>;

   // The larger the underlying bucket the more we avoid collisions with invalid keys.
   // This improves performance of rejecting invalid keys because we don't have to do
   // string comparisons in these cases.
            const auto bit = std::countr_zero(static_cast<UnsignedU>(vals[i]));
               info.table[bit] = static_cast<uint8_t>(i);
            }
            return info;
         }
         else if constexpr (range < sparse_threshold) {
            // Strategy 3: Small range â†’ sparse lookup table
            int_keys_info_t<N, sparse_threshold> info{
               .type = int_hash_type::small_range, .min_value = min_val, .max_value = max_val, .table_size = range + 1};
            info.table.fill(static_cast<uint8_t>(N));

  rom>
   consteval bool custom_type_is_nullable()
   {
      if constexpr (std::is_member_pointer_v<From>) {
         if constexpr (std::is_member_function_pointer_v<From>) {
            using Ret = typename return_type<From>::type;
            if constexpr (std::is_void_v<Ret>) {
               using Tuple = typename inputs_as_tuple<From>::type;
               if constexpr (glz::tuple_size_v<Tuple> == 1) {
                  using Input = std::decay_t<glz::tuple_element_t<0, Tuple>>;
                  return bool(null_t<Input>);
   ostic push
#pragma clang diagnostic ignored "-Wmissing-braces"
#endif
            return tuple{get<value_indices[I]>(meta_v<T>)...}; //
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
         }(std::make_index_sequence<value_indices.size()>{}); //
      }();

      static constexpr auto size = tuple_size_v<decltype(values)>;

      static constexpr auto keys = [] {
         std::array<sv, size> res{};
         [&]<size_t... I>(std::index_sequence<I...>) { //
            ((res[I] = get_key_element<T, value_indices[I]>())me custom_getter_result<custom_t<T, From, To>>::type>::type;
   };

   template <class V>
   using resolve_write_type_t = typename resolve_write_type<std::remove_cvref_t<V>>::type;

   // Invoke `func` with the value a field actually serializes, recursively unwrapping any
   // transparent write wrappers. Continuation-passing keeps a by-value custom getter result
   // alive for the duration of `func` (a getter may return a value rather than a reference).
   template <class V, class Ctx, class Func>
   GLZ_ALWAYS_INLINE void unwrapvalue type associated with the key; used to determine nullability.
   /// @tparam Opts   A policy struct with a boolean member `error_on_missing_keys`.
   ///
   /// @param key          The string identifier whose requirement status is being queried.
   /// @returns `true` if:
   ///            - `meta<T>::requires_key(key, is_nullable)` exists and returns true, or
   ///            - `Opts.error_on_missing_keys` is true *and* Val_T is not nullable;
   ///          otherwise returns `false`.
   template <typename T, typename Val_T,<class From, class To>
   concept non_narrowing_convertable = requires(From from, To to) {
#if __GNUC__
      // TODO: guard gcc against narrowing conversions when fixed
      to = from;
#else
      To{from};
#endif
   };

   /**
    * @brief Extracts the underlying member from a struct.
    *
    * Core Glaze function to extract the underlying member. Typically, the `value` parameter
    * is the struct containing the member field. The `element` parameter denotes a member object
    * pointer or an invocable function, which allows mimic type satisfy bool_t?
   // This allows checking if a custom type mimics boolean behavior.
   template <class T>
   concept mimics_bool_t = has_mimic<T> && bool_t<mimic_type<T>>;

   // Note: custom_num_t, custom_str_t, custom_bool_t concepts are defined in core/custom_meta.hpp
   // (requires custom_t from wrappers.hpp which is not included here)

   template <class T>
   concept readable_map_t = !custom_read<T> && !meta_value_t<T> && !str_t<T> && range<T> && pair_t<range_value_t<T>> &&
                            map_subscre_t n = str.size();
         size_t si = 0;

         // Consume exactly `count` digits at the current position, advancing si on
         // success. Returns -1 on non-digit or if fewer than `count` chars remain.
         const auto take = [&](size_t count) -> int {
            if (si + count > n) return -1;
            const int v = parse_digits(s, si, count);
            if (v >= 0) si += count;
            return v;
         };

         // Parse the seconds field (2 digits). Sub-second fractions are not part of
         // the   case 'd':
            case 'H':
            case 'M':
            case 'S':
            case 'F':
            case 'T':
            case '%':
               ++i;
               break;
            default:
               return false;
            }
         }
         return true;
      }

      // Compile-time check: the format supplies a full calendar date (year, month,
      // day) either explicitly or via %F. A time_point cannot be reconstructed on
      // read without one, so this is enforced where date_format is applied.
 ires { meta<std::decay_t<T>>::version; };

   template <class T>
   inline constexpr version_t version_v = []() -> version_t {
      if constexpr (versioned<T>) {
         return meta<std::decay_t<T>>::version;
      }
      else {
         return {0, 0, 1};
      }
   }();

   // We don't make this constexpr so that we can have heap allocated values like std::string
   // IMPORTANT: GCC has a bug that doesn't default instantiate this object when it isn't constexpr
   // The solution is to use the json_schema_type defined below to me_v<std::decay_t<std::variant_alternative_t<I, T>>>; });
         return ids;
      }
   }();

   // Compile-time string listing the variant type IDs (e.g. "TYPE_A, TYPE_B, TYPE_C")
   // Used for error messages when no matching variant type is found
   namespace detail
   {
      template <is_variant T>
      inline constexpr size_t variant_ids_string_len = [] {
         constexpr auto& ids = ids_v<T>;
         constexpr auto N = ids.size();
         size_t len = 17; // "supported types: "
         for (size_t i = 0; i < N; ++i)  <> struct glz::meta<my_struct> {
   //      static constexpr auto value = glz::reflect_array{};
   //   };
   //
   // meta_wrapper_v replaces this tag with a glz::array(...) equivalent generated
   // from reflection, so the type behaves as glaze_array_t in every format.
   struct reflect_array
   {};

   namespace detail
   {
      template <class T, size_t... I>
      constexpr auto reflect_array_impl(std::index_sequence<I...>) noexcept
      {
#if GLZ_REFLECTION26
         // P2996 reflection splices each member directly
     s { from<Format, std::remove_cvref_t<T>>{}; };

   // Default context type for a format.
   // Formats that need a richer context (e.g. YAML) specialize this.
   template <uint32_t Format>
   struct format_context
   {
      using type = context;
   };

   template <uint32_t Format>
   using format_context_t = typename format_context<Format>::type;

   // Preset options for size-optimized builds (embedded systems)
   struct opts_size : opts
   {
      glz::optimization_level optimization_level = glz::optimization_level::size;
   };ol>(value);
            return ret;
         }
         else {
            struct opts_structs_as_arrays : std::decay_t<decltype(Opts)>
            {
               bool structs_as_arrays{};
            };
            return opts_structs_as_arrays{{Opts}, static_cast<bool>(value)};
         }
      }
      else {
         auto ret = Opts;
         ret.*member_ptr = value;
         return ret;
      }
   }

   template <auto Opts, auto member_ptr>
   constexpr auto opt_on()
   {
      if constexpr (is_append_arrays_tag<member_ptr>) d(auto&& Opts)
   {
      if constexpr (requires { Opts.unquoted; }) {
         return Opts.unquoted;
      }
      else if constexpr (requires { Opts.raw; }) {
         static_assert(deprecated_opts_raw<std::decay_t<decltype(Opts)>>,
                       "\n\n"
                       "  [glaze] Deprecated: 'raw' option has been renamed to 'unquoted'\n"
                       "  \n"
                       "  Please update your custom opts struct:\n"
                       "  \n"
                       "    // OLD (deprecated):\n"
   // bool escape_control_characters = false;
   // Escapes control characters like 0x01 or null characters with proper unicode escape sequences.
   // The default behavior does not escape these characters for performance and safety
   // (embedding nulls can cause issues, especially with C APIs)
   // Glaze will error when parsing non-escaped control character (per the JSON spec)
   // This option allows escaping control characters to avoid such errors.

   // ---
   // float_precision float_max_write_precision{};
   // The maxim
      // Check if underlying stream has failed
      bool fail() const noexcept { return !stream_ || stream_->fail(); }

      // Access underlying stream
      Stream* stream() const noexcept { return stream_; }

      // Bytes flushed so far
      size_t bytes_flushed() const noexcept { return flush_offset_; }

      // Current buffer capacity
      size_t buffer_capacity() const noexcept { return buffer_.size(); }

      // Iterator support (satisfies range concept)
      iterator begin() noexcept { return buffer_.data(); }
     // Concept to check if a buffer type has bounded capacity (like std::array, std::span)
   // Note: Bounded buffers must be at least 512 bytes for reliable serialization.
   // Smaller buffers will return error_code::buffer_overflow.
   template <class B>
   concept has_bounded_capacity = buffer_traits<std::remove_cvref_t<B>>::has_bounded_capacity;

   // Refill helper for streaming input buffers
   // Returns true if buffer has data available after refill, false if EOF
   template <class B>
   GLZ_ALWAYS_INLINE bool refill_buffere glz
{
   // read_constraint allows a user to register a constraint lambda or member function
   // that returns a boolean, which indicates true for success and false for failure
   // this allows arguments to be validated
   template <class T, auto Target, auto Constraint, string_literal Message>
   struct read_constraint_t
   {
      static constexpr bool glaze_wrapper = true;
      static constexpr auto glaze_reflect = false;
      static constexpr std::string_view message = Message;
      using target_t = decltype(Target);
   files should be a map of std::filesystem::path to std::string buffers
   [[nodiscard]] inline error_ctx directory_to_buffers(auto& files, const sv directory_path,
                                                       const sv target_extension = ".json")
   {
      namespace fs = std::filesystem;

      // Use the non-throwing overloads throughout: a concurrent modification of the
      // directory must be reported through error_ctx, not by throwing a
      // std::filesystem_error out of a function whose contract is to return oneing>

#include "glaze/core/context.hpp"

#if defined(_MSC_VER) && !defined(__clang__)
// Turn off MSVC warning for unsafe fopen
#pragma warning(push)
#pragma warning(disable : 4996)
#endif

namespace glz
{
   template <class T>
   [[nodiscard]] error_code file_to_buffer(T& buffer, auto* file, const std::string_view path)
   {
      if (!file) {
         return error_code::file_open_failure;
      }

      std::error_code ec{};
      const auto n = std::filesystem::file_size(path, ec);
      if (ec) {
         std::fclose(file);
   
#pragma once

#if __cpp_exceptions

#include "glaze/core/read.hpp"
#include "glaze/core/write.hpp"

namespace glz::ex
{
   template <auto Opts, class T>
      requires read_supported<T, Opts.format>
   void read(T&& value, auto&& buffer)
   {
      const auto ec = glz::read<Opts>(std::forward<T>(value), buffer);
      if (bool(ec)) [[unlikely]] {
         throw std::runtime_error(format_error(ec, buffer));
      }
   }
}

namespace glz::ex
{
   // For writing to a std::string, std::vector<char>, std::deque<char> and the like
   teo ec = glz::write_file_msgpack<Opts>(std::forward<T>(value), file_name, buffer);
      if (ec == glz::error_code::file_open_failure) {
         throw std::runtime_error("file failed to open: " + std::string(file_name));
      }
      else if (ec) {
         throw std::runtime_error("write_file_msgpack error for: " + std::string(file_name));
      }
   }
}

#endif
// Glaze Library
// For the license information refer to glaze.hpp

#pragma once

#if __cpp_exceptions

#include "glaze/exceptions/core_exceptions.hpp"
#include "glaze/gla

   /// <summary>
   /// recorder for saving state over the course of a run
   /// deques are used to avoid reallocation for large amounts of data as the recording length is typically unknown
   /// </summary>
   template <class... Ts>
   struct recorder
   {
      static constexpr auto glaze_reflect = false;

      using container_type = std::variant<std::deque<Ts>...>;

      std::deque<std::pair<std::string, std::pair<container_type, const void*>>> data;

      auto operator[](const sv name) { return detail::recorder_assigner<dlse_v<Func>, "Your function is not invocable or not concrete");
               }
            }
         });
         std::printf("  %d   Exit Menu\n", uint32_t(N + 1));
         std::printf("--------------------------------\n");

         std::printf("cmd> ");
         std::fflush(stdout);
      restart_input: // needed to support std::cin within user functions
         // https://web.archive.org/web/20201112034702/http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
         long cmd = -1;
         constexpr auto buffer// EOF indicates normal client disconnect, not an error
            if (e.code() == asio::error::eof) {
               co_return;
            }
            emit_error(e.what());
         }
         catch (const std::exception& e) {
            emit_error(e.what());
         }
         // Buffers automatically returned to pool when scoped_buffers are destroyed
      }

      asio::awaitable<void> listener(asio::ip::tcp::acceptor acceptor)
      {
         auto executor = co_await asio::this_coro::executor;

         while (true) {
 ctx->stop(); // Stop the server's io_context
         }
#if defined(_WIN32)
         stop_requested.store(true, std::memory_order_relaxed);
         if (listener_acceptor) {
            asio::error_code ec{};
            listener_acceptor->cancel(ec);
            listener_acceptor->close(ec);
         }

         std::vector<std::shared_ptr<asio::ip::tcp::socket>> sockets_to_close;
         {
            std::lock_guard lock{active_sockets_mutex};
            sockets_to_close = active_sockets;
         }
         for (auto& socket ng&)> error_handler{};

      // Custom call handler - works with raw buffers for zero-copy performance.
      //
      // The handler receives raw request bytes and a response buffer. Leave the buffer
      // empty for no response (e.g., notifications).
      //
      // @param request Raw REPE message bytes
      // @param response_buffer Buffer for building the response (will be resized, empty = no response)
      //
      // Example:
      //   server.call = [&](std::span<const char> request, std::string& response_buffer) {
  (not connected()) {
            throw std::runtime_error("asio_client: NOT CONNECTED");
         }

         repe::message response{};
         auto request = message_pool->borrow();
         request->body.clear();
         repe::request<Opts>(repe::user_header{.query = query}, *request);
         if (bool(request->error())) {
            throw std::runtime_error("bad request");
         }

         unique_socket socket{socket_pool.get()};
         if (not socket) {
            socket.ptr.reset();
            (*is_connected) = fals
      msg.body.resize(msg.header.body_length);
      asio::read(socket, asio::buffer(msg.body), asio::transfer_exactly(msg.header.body_length), e);
      if (e) {
         repe::encode_error(error_code::connection_failure, msg, e.message());
         return;
      }
   }

   inline asio::awaitable<void> co_send_buffer(asio::ip::tcp::socket& socket, const repe::message& msg)
   {
      if (msg.header.length == 0) {
         throw std::runtime_error("No length provided in REPE header");
      }
      if (msg.header.query_length != mquest{glz::read_json<typename meth_t::request_t>(json_request)};
            if (params_request.has_value()) {
               expected<typename meth_t::result_t, rpc::error> result{
                  std::invoke(method.callback, params_request->params)};
               if (result.has_value()) {
                  auto json_result = glz::write_json(result);
                  if (json_result) {
                     return_v = raw_response_t{std::move(req.id), std::move(json_result.value())};
                     if (std::holds_alterna       [](const auto&) { return glz::unexpected{rpc::error{rpc::error_e::internal, "Not implemented"}}; }};
   };

   template <concepts::method_type Method>
   struct client_method_t
   {
      static constexpr std::string_view name_v = Method::name_v;
      using params_t = typename Method::params_t;
      using result_t = typename Method::result_t;
      using request_t = rpc::request_t<params_t>;
      using response_t = rpc::response_t<result_t>;
      using callback_t = std::function<void(const glz::expected<result_t, rpc::ertuvwxyz"
      "0123456789+/";

   inline std::string read_base64(const std::string_view input)
   {
      std::string decoded_data;
      static constexpr std::array<int, 256> decode_table = [] {
         std::array<int, 256> t;
         t.fill(-1);
         for (int i = 0; i < 64; ++i) {
            t[base64_chars[i]] = i;
         }
         return t;
      }();

      int val = 0, valb = -8;
      for (unsigned char c : input) {
         if (decode_table[c] == -1) break; // Stop decoding at padding '=' or invalid characters
   \n' || *it == '\r')) {
                  skip_to_next_line(ctx, it, end);
               }
               else if (it != end && *it != '#') { // If not a comment, it's an error unless it's EOF
                  // Could be an issue if there's no newline before EOF for the last key-value
               }
            }
         }
      }
   }

   template <auto Opts, class T>
   inline bool resolve_nested(T& root, std::span<std::string> path, auto& ctx, auto& it, auto& end)
   {
      if constexpr (!(glz::reflectable<T> || glz::glaze }

         // Parse optional fractional seconds
         int64_t subsec_nanos = 0;
         if (pos < n && s[pos] == '.') {
            ++pos;
            int64_t frac = 0;
            int digits = 0;
            while (pos < n && s[pos] >= '0' && s[pos] <= '9') {
               if (digits < 9) {
                  frac = frac * 10 + (s[pos] - '0');
                  ++digits;
               }
               ++pos;
            }
            // Scale to nanoseconds
            static constexpr int64_t scale[] = {1000000000, 1000000e::parse_error;
            return;
         }

         const char* s = &(*start);

         // YYYY-MM-DDTHH:MM (T can be space)
         const int yr = parse_digits(s, 4);
         const int mo = parse_digits(s + 5, 2);
         const int dy = parse_digits(s + 8, 2);
         const int hr = parse_digits(s + 11, 2);
         const int mi = parse_digits(s + 14, 2);

         // Validate basic structure
         if (yr < 0 || mo < 0 || dy < 0 || hr < 0 || mi < 0 || s[4] != '-' || s[7] != '-' ||
             (s[10] != 'T' && s[10] !l is_toml_number_terminator(const char c) noexcept
      {
         return c == ',' || c == ']' || c == '}' || c == '\n' || c == '\r' || c == '#' || c == ' ' || c == '\t';
      }

      template <std::floating_point T>
      bool parse_toml_special_float(T& value, auto& it, auto end) noexcept
      {
         auto p = it;
         bool negative = false;

         if (p != end && (*p == '+' || *p == '-')) {
            negative = (*p == '-');
            ++p;
         }

         if ((end - p) >= 3 && p[0] == 'i' && p[1] == 'n' && toml(T&& value)
   {
      return write<opts{.format = TOML}>(std::forward<T>(value));
   }

   template <auto Opts = opts{.format = TOML}, write_supported<TOML> T>
   [[nodiscard]] error_ctx write_file_toml(T&& value, const sv file_name, auto&& buffer)
   {
      const auto ec = write<set_toml<Opts>()>(std::forward<T>(value), buffer);
      if (bool(ec)) [[unlikely]] {
         return ec;
      }
      const auto file_ec = buffer_to_file(buffer, file_name);
      if (bool(file_ec)) [[unlikely]] {
         return {0, file_ec};
            // emitting malformed multi-line `key = value` content in value position (issue
            // #2595). Arrays and maps stay classified by the wrapper type so a wrapped sequence
            // or map falls into the scalar path, where write_inline_value unwraps it into a
            // valid inline array / inline table that also round-trips through the reader (the
            // TOML reader cannot feed a [[array]] header into a glz::custom setter).
            // Exception: in inline_mode, arrays of objects are written as inlstexpr (transparent_write_wrapper<val_t>) {
         // A mimic glaze_value_t or glz::custom getter: unwrap to the value it serializes as so
         // a wrapped object/map/array stays inline here, rather than dispatching through its
         // multi-line writer and leaking `key = value` lines or `[table]` headers (issue #2595).
         unwrap_write_value(std::forward<V>(val), ctx,
                            [&](auto&& inner) { write_inline_value<Options>(inner, ctx, b, ix); });
      }
      else {
         // Arrays land herey = value`
   // pairs, no `[table]` / `[[array]]` headers. This routes structs, maps, variants,
   // and nullables to their inline writers; arrays go through the existing array
   // writer, which now invokes write_inline_value for each element so the inline
   // requirement cascades down arbitrary nesting.
   template <auto Opts, class V, class B>
   void write_inline_value(V&& val, is_context auto&& ctx, B&& b, auto& ix);

   // Specialization for inline_table_t wrapper - writes array of objects as inline tables
   // Example _clock::time_point when it's a distinct type (rare)
   template <is_high_res_time_point T>
      requires(not custom_write<T>)
   struct to<TOML, T>
   {
      template <auto Opts, class B>
      static void op(auto&& value, is_context auto&& ctx, B&& b, auto& ix) noexcept
      {
         // Treat like steady_clock - serialize as count since epoch is implementation-defined
         using Duration = typename std::remove_cvref_t<T>::duration;
         using Rep = typename Duration::rep;
         const auto count = value.time_since_etions - inherits from opts to allow TOML-specific configuration
   // without modifying the base opts struct
   struct toml_opts : opts
   {
      bool inline_arrays = false; // Use inline [{...}, {...}] instead of [[array]] syntax

      constexpr toml_opts() : opts{.format = TOML} {}
      constexpr explicit toml_opts(bool inline_arr) : opts{.format = TOML}, inline_arrays(inline_arr) {}
   };

   // Skip member function pointers unless explicitly enabled
   template <class T, auto Options>
   constexpr bool skip_toml_field =
     internal{}; // default to 0
   };

   consteval bool check_is_internal(auto&& o) { return o.internal & uint32_t(opts_internal::internal_struct); }

   template <auto Opts>
   constexpr auto is_internal_on()
   {
      auto ret = Opts;
      ret.internal |= uint32_t(opts_internal::internal_struct);
      return ret;
   }

} // namespace glz::toml
#pragma once

#include <cctype>

#include "glaze/core/common.hpp"

namespace glz
{
   // Skip whitespace and comments
   template <class It, class End>
   inline void skip_ws_and_comments(    // Handle inverted sections and boolean sections
                     if (is_inverted_section) {
                        // For inverted sections, show content if condition is false
                        if (!condition) {
                           std::string inner_buffer;
                           auto inner_ec = stencil<Opts>(inner_template, value, inner_buffer);
                           if (inner_ec) {
                              return inner_ec;
                           }
                           buffer.append(i < end && *it == '}' && *(it + 1) == '}')) {
                        ++it;
                     }
                     if (it + 1 < end) {
                        it += 2; // Skip '}}'
                     }
                     continue;
                  }

                  if (is_section || is_inverted_section) {
                     // Find the closing tag '{{/key}}'
                     std::string closing_tag = "{{/" + std::string(key) + "}}";
                     auto closing_pos = std::search(it, end, closing_tag.begin(),       if constexpr (is_specialization_v<V, std::function>) {
            using Ret = typename function_traits<V>::result_type;

            if constexpr (std::is_void_v<Ret>) {
               using Tuple = typename function_traits<V>::arguments;
               Tuple inputs{};
               using Inputs = std::remove_cvref_t<decltype(inputs)>;
               to<JSON, Inputs>::template op<Opts>(inputs, ctx, args...);
            }
            else {
               static_assert(false_v<T>, "std::function must have void return");
    auto offset = handle_unicode_code_point(start, p, end);
                     if (offset == 0) [[unlikely]] {
                        ctx.error = error_code::unicode_escape_conversion_failure;
                        return;
                     }
                     n += offset;
                     // escape + u + unicode code points
                     n -= 2 + uint32_t(start - mark);
                  }
                  else {
                     p += next;
                     *p = char_unescape_table[uint8_t(*start)];
     value.resize(n);
               ++it;
            }
            else {
               // raw_string
               auto start = it;
               skip_string_view(ctx, it, end);
               if (bool(ctx.error)) [[unlikely]]
                  return;

               value.assign(start, size_t(it - start));
               ++it;
            }
         }
      }

      template <auto Opts, class It, class End>
         requires(not check_is_padded(Opts))
      static void op(auto& value, is_context auto&& ctx, It&& it, End end)
 uint64_t backslash = (lo7 ^ repeat_byte8('\\')) + lo7_mask;
                  const uint64_t less_32 = (swar & repeat_byte8(0b01100000)) + lo7_mask;
                  uint64_t next = ~((backslash & less_32) | swar);

                  next &= repeat_byte8(0b10000000);
                  if (next == 0) {
                     start += 8;
                     p += 8;
                     continue;
                  }

                  next = countr_zero(next) >> 3;
                  start += next;
                  if (start >= it) {
xpr auto N = reflect<T>::size;

      if constexpr (N == 1) {
         decode_index<Opts, T, 0>(value, ctx, it, end, selected_index...);
      }
      else if constexpr (check_linear_search(Opts)) {
         // Linear search path
         auto key_start = it;
         const auto index = decode_linear<T>(ctx, it, end);
         if (bool(ctx.error)) [[unlikely]]
            return;

         if (index >= N) [[unlikely]] {
            if constexpr (Opts.error_on_unknown_keys) {
               ctx.error = error_code::unknown_key;
       from<JSON, std::remove_cvref_t<V>>::template op<ws_handled<Opts>()>(
                  get_member(value, get<I>(to_tie(value))), ctx, it, end);
            }
         }

         if constexpr (Opts.error_on_missing_keys || Opts.partial_read) {
            ((selected_index = I), ...);
         }
      }
      else [[unlikely]] {
         decode_index_unknown_key<Opts, T>(value, ctx, it, end);
      }
   }

   template <auto Opts, class T, size_t I, class Value>
      requires(glaze_enum_t<T> || (meta_keys<T> && std::is_enum_v<T>))or());
   }

   // Write raw text to a JSON value denoted by a JSON Pointer
   template <string_literal Path, auto Opts = opts{}>
   [[nodiscard]] inline error_ctx write_at(const std::string_view value, contiguous auto&& buffer)
   {
      auto view = glz::get_view_json<Path, Opts>(buffer);
      if (view) {
         // erase the current value
         const size_t location = size_t(view->data() - buffer.data());
         buffer.erase(location, view->size());
         // insert the new value
         buffer.insert(location, value);.size()) [[unlikely]] {
                  state.resize(state.size() * 2);
                  if (state.size() >= max_recursive_depth_limit) [[unlikely]] {
                     ctx.error = error_code::exceeded_max_recursive_depth;
                     return;
                  }
               }
               state[indent] = Object_Start;
               if constexpr (not Opts.null_terminated) {
                  if (it != end && *it != '}') [[unlikely]] {
                     append_new_line<use_tabs, indent_width>(b, ix, indent);
    std::visit(
            [&](auto&& val) {
               using V = std::decay_t<decltype(val)>;

               if constexpr (check_write_type_info(Opts) && not tag_v<T>.empty() && custom_write<V>) {
                  // Custom alternative: the user's serializer emits the object body, into which we
                  // merge the variant tag. For this to produce valid JSON the custom to<> must (1)
                  // write an object body and (2) honor opening_and_closing_handled (suppress its own
                  // braces) so        auto&& [key, entry_val] = *it;
                     if (skip_member<Opts>(entry_val)) {
                        continue;
                     }

                     // When Opts.skip_null_members, *any* entry may be skipped, meaning separator dumping must be
                     // conditional for every entry.
                     // Alternatively, write separator after each entry except last but then branch is permanent
                     if (not first) {
                        write_object_entry_separator<Opts>(ctx, bexpr (not check_unquoted(Opts)) {
               dump('"', args...);
            }
         }
         else [[unlikely]] {
            // Value doesn't have a mapped string, serialize as underlying number
            serialize<JSON>::op<Opts>(static_cast<std::underlying_type_t<T>>(value), ctx, std::forward<Args>(args)...);
         }
      }
   };

   // Fallback handler for enums without explicit glz::meta
   // Serializes as underlying integer unless reflect_enums option is enabled (P2996)
   template <class T>
      requires(!me      if constexpr (check_string_as_number(Opts)) {
            const sv str = [&]() -> const sv {
               if constexpr (!char_array_t<T> && std::is_pointer_v<std::decay_t<T>>) {
                  return value ? value : "";
               }
               else if constexpr (array_char_t<T>) {
                  const auto* start = value.data();
                  const auto* end = static_cast<const char*>(std::memchr(start, '\0', value.size()));
                  return sv{start, end ? size_t(end - start) : value.size()};
    T>
      requires(glaze_value_t<T> && !custom_write<T>)
   struct to<JSON, T>
   {
      template <auto Opts, class Value, is_context Ctx, class B, class IX>
      GLZ_ALWAYS_INLINE static void op(Value&& value, Ctx&& ctx, B&& b, IX&& ix)
      {
         using V = std::remove_cvref_t<decltype(get_member(std::declval<Value>(), meta_wrapper_v<T>))>;
         to<JSON, V>::template op<Opts>(get_member(std::forward<Value>(value), meta_wrapper_v<T>),
                                        std::forward<Ctx>(ctx), std::forward<B>(b), std, 2);
         ix += 2;
         std::memset(&b[ix], check_indentation_char(Opts), ctx.depth);
         ix += ctx.depth;
      }
      else {
         if constexpr (minified_check) {
            if (!ensure_space(ctx, b, ix + 1)) [[unlikely]] {
               return;
            }
         }
         std::memcpy(&b[ix], ",", 1);
         ++ix;
      }
      if constexpr (is_output_streaming<B>) {
         flush_buffer(b, ix);
      }
   }

   // Only object types are supported for partial
   template <class T>
      requires(glaze_m_reader<Event>(file)) {
   //      process(event);
   //   }
   //   if (reader.last_error()) { /* handle error */ }
   //
   // Template parameters:
   //   T - The type to deserialize each value into
   //   Stream - Byte-oriented input stream (default: std::istream)

   template <class T, byte_input_stream Stream = std::istream, size_t BufferCapacity = 65536>
   class json_stream_reader
   {
      basic_istream_buffer<Stream, BufferCapacity> buffer_;
      streaming_context ctx_{};
      error_ctx last_error_{};
      bool eof_ escaped unicode you can register your fields with
// the escaped unicode value.
// glz::escape_unicode<"ðŸ˜€"> will generate a compile time escaped unicode version
// of your key.

// These features require constexpr std::string support (not available with _GLIBCXX_USE_CXX11_ABI=0)
#if GLZ_HAS_CONSTEXPR_STRING

namespace glz::detail
{
   // Helper function to append a Unicode escape sequence to the output string.
   inline constexpr void append_unicode_escape(std::string& output, uint16_t code_unit)
   {
      output += '\\';
    r bool glaze_reflect = false;
      using value_type = T;
      T& val;
      std::string_view fmt;
   };

   template <class T>
   struct to<JSON, date_format_t<T>>
   {
      template <auto Opts, class B>
      static void op(auto&& wrapper, is_context auto&& ctx, B&& b, auto& ix) noexcept
      {
         using namespace std::chrono;
         using V = std::remove_cvref_t<T>;
         static_assert(is_system_time_point<V> || is_year_month_day<V>,
                       "glz::date_format requires a std::chrono::system_clock time_ auto&&... args)
      {
         using Value = core_t<decltype(value.val)>;
         to<JSON, Value>::template op<opt_true<Opts, T::opts_member>>(value.val, ctx, args...);
      }
   };

   template <auto MemPtr>
   inline constexpr decltype(auto) quoted_impl() noexcept
   {
      return [](auto&& val) { return quoted_t<std::remove_reference_t<decltype(val.*MemPtr)>>{val.*MemPtr}; };
   }

   // Read a value as a string and unescape, to avoid the user having to parse twice
   template <auto MemPtr>
   constexpr auto quoted = quotepType>
      requires(std::integral<T> && !std::same_as<T, bool> && !std::same_as<T, int64_t> && !std::same_as<T, uint64_t>)
   error_ctx convert_from_generic(T& result, const generic_json<Mode, MapType>& source)
   {
      if (!source.is_number()) {
         return error_ctx{0, error_code::syntax_error};
      }
      if constexpr (Mode == num_mode::u64) {
         if (source.template holds<uint64_t>()) {
            result = static_cast<T>(source.template get<uint64_t>());
         }
         else if (source.template holds<int64_ || std::integral<T> || (readable_array_t<T> && !std::same_as<T, std::string>) ||
      readable_map_t<T>;

   // These functions allow a generic value to be read/written to a C++ struct

   // Optimized overload for types that support direct conversion
   template <auto Opts, class T, num_mode Mode, template <class> class MapType>
      requires read_supported<T, Opts.format> && directly_convertible_from_generic<T>
   [[nodiscard]] error_ctx read(T& value, const generic_json<Mode, MapType>& source)
   {
      return convert_from_gamespace study
   {
      void overwrite(auto& state, const std::unordered_map<std::string, raw_json>& overwrites)
      {
         for (auto&& [json_ptr, raw_json_str] : overwrites) {
            read_as_json(state, json_ptr, raw_json_str.str);
         }
      }

      struct param_set
      {
         basic_ptr param_ptr{}; // to only seek once
         std::vector<basic> elements{};
      };

      template <class State>
      struct full_factorial
      {
         State state{};
         std::vector<param_set> param_sets;
        // Then inline refs in the main schema tree
      detail::inline_single_use_refs(s, *s.defs, ref_counts);
      detail::prune_inlined_defs(s, ref_counts);

      // Making this static constexpr options to fix MSVC bug
      static constexpr opts options = opts_write_type_info_off<decltype(Opts)>{{Opts}};
      return write<options>(std::move(s), std::forward<Buffer>(buffer));
   }

   template <class T, auto Opts = opts{}>
   [[nodiscard]] glz::expected<std::string, error_ctx> write_json_schema()
   {
      std::string buffer{}xpr (nullable_t<val_t>) {
                  // Canonicalize std::optional<T> (and other nullables) so the wrapper itself
                  // is never placed in $defs. Inner type T is referenced via anyOf + null.
                  validate_ref<name_v<inner_val_t>>();
                  auto& def = defs[name_v<inner_val_t>];
                  if (!def.type) {
                     to_json_schema<inner_val_t>::template op<Opts>(def, defs);
                  }
                  if (!prop.ref) {
                     prop.anyOf = make_nul unwrap_nullable<T>
      {
         using type = typename unwrap_nullable<std::decay_t<decltype(*std::declval<T>())>>::type;
      };

      template <class T>
      using unwrap_nullable_t = typename unwrap_nullable<T>::type;

      // Build an inline schema for a primitive type (for items/additionalProperties)
      template <class V>
      std::shared_ptr<schema> make_primitive_schema()
      {
         auto s = std::make_shared<schema>();
         if constexpr (std::same_as<V, bool>) {
            s->type = sv{"boolean"};
    std::is_member_object_pointer_v<meta_wrapper_t<T>>) {
               using val_t = std::remove_cvref_t<member_t<T, meta_wrapper_t<T>>>;
               to_json_schema<val_t>::template op<Opts>(s, defs);
               if constexpr (json_schema_t<T>) {
                  static constexpr auto schema_size = reflect<json_schema_type<T>>::size;
                  if constexpr (schema_size > 0) {
                     static constexpr sv member_name = get_name<meta_wrapper_v<T>>();
                     constexpr auto schema_index = [] {
    boxed<std::variant<bool, std::shared_ptr<schema>>> additionalProperties{};
      boxed<std::map<std::string_view, schema, std::less<>>> defs{};
      boxed<std::vector<schema>> oneOf{};
      boxed<std::vector<schema>> anyOf{};
      boxed<std::vector<std::string_view>> required{};

      static constexpr auto schema_attributes{true}; // allowance flag to indicate metadata within glz::object(...)
   };

   namespace detail
   {

      enum struct defined_formats : uint32_t {
         datetime, //
         date, //
         time, / && *it == '\n') {
                  ++it;
               }
            }
         };

         for_each<N>([&]<auto I>() {
            if (it == end) {
               return;
            }
            if constexpr (I != 0) {
               read_new_lines();
            }
            if constexpr (is_std_tuple<T>) {
               parse<JSON>::op<Opts>(std::get<I>(value), ctx, it, end);
            }
            else if constexpr (glaze_array_t<T>) {
               parse<JSON>::op<Opts>(get_member(value, glz::get<I>(meta_v<T>)), ct !std::is_array_v<std::remove_cvref_t<T>>;

   // Apply a merge patch to a C++ struct/type (in-place modification)
   // Glaze's read_json already has merge-patch semantics: it only updates fields
   // present in the source and leaves other fields unchanged.
   // Note: Uses template parameter G constrained to generic_json to prevent implicit conversion
   // from string literals (which would cause ambiguity with the string_view overload)
   template <class T, class G>
      requires(merge_patch_struct<T> && is_generic_json<std::recursive_depth};
         }

         if (patch.is_object()) {
            // If target is not an object, replace with empty object
            if (!target.is_object()) {
               target.data = typename GenericType::object_t{};
            }

            auto& target_obj = target.get_object();
            const auto& patch_obj = patch.get_object();

            for (const auto& [key, value] : patch_obj) {
               if (value.is_null()) {
                  // Null means remove
                  target_obj.erase(key);
    _code::nonexistent_json_ptr};
         }

         // Add to destination
         return insert_at(doc, path, std::move(*removed), opts.create_intermediate);
      }

      // Copy operation
      template <class GenericType>
         requires is_generic_json<GenericType>
      [[nodiscard]] error_ctx apply_copy(GenericType& doc, std::string_view from, std::string_view path,
                                         const patch_opts& opts)
      {
         const GenericType* source = navigate_to(&doc, from);
         if (!source) {
apType>> : std::true_type
   {};

   template <class T>
   concept is_generic_json = is_generic_json_t<std::decay_t<T>>::value;

   // RFC 6902 operation types
   enum struct patch_op_type : uint8_t { add, remove, replace, move, copy, test };

   // Single patch operation
   // Uses std::optional for fields that are only present for certain operations:
   // - value: required for add, replace, test
   // - from: required for move, copy
   template <class GenericType = generic>
   struct patch_op_t
   {
      patch_op_type op{};
   <T, uint64_t>) {
         if (!is_number()) {
            return unexpected(error_ctx{0, error_code::get_wrong_type});
         }
         uint64_t value{};
         auto it = data_;
         if (!glz::atoi(value, it, end)) {
            return unexpected(error_ctx{0, error_code::parse_number_failure});
         }
         return value;
      }
      else if constexpr (std::is_same_v<T, int32_t>) {
         auto result = get<int64_t>();
         if (!result) return unexpected(result.error());
         return static_cast<int32_t>(*r <opts Opts>
   inline lazy_json_view<Opts> lazy_json_view<Opts>::operator[](size_t index) const
   {
      if (has_error()) return *this;
      if (!is_array()) return make_error(error_code::get_wrong_type);

      const char* end = json_end();
      const char* p = data_ + 1; // skip '['
      skip_ws(p, end);

      // Check for empty array. json_end_ bounds the message in both modes: null_terminated does
      // not guarantee the '\0' sits at json_end_, so fall back to the bound here too.
      if (p >= end || *p == ']') returocument<Opts>* doc, const char* container_start, const char* end, bool is_object);

      // Return reference to stored view - allows parse_pos_ optimization when user uses auto&
      reference operator*() { return current_view_; }
      const lazy_json_view<Opts>& operator*() const { return current_view_; }

      lazy_iterator& operator++();

      lazy_iterator operator++(int)
      {
         auto tmp = *this;
         ++*this;
         return tmp;
      }

      bool operator==(const lazy_iterator& other) const { return at_englz
{
   // Forward declarations (needed for circular references)
   template <opts Opts>
   struct lazy_document;
   template <opts Opts>
   class lazy_iterator;
   template <opts Opts>
   struct indexed_lazy_view;
   template <opts Opts>
   class indexed_lazy_iterator;

   // ============================================================================
   // Truly Lazy JSON Parser - No upfront processing
   // ============================================================================

   namespace detail
   {
      // Skip strin     return {size_t(it - start), ctx.error, ctx.custom_error_message};
   }

   // A "compiled" jmespath expression, which can be pre-computed for efficient traversal
   struct jmespath_expression
   {
      std::string_view path{};
      jmespath::tokenization_error error{};
      std::vector<std::string_view> tokens{}; // evaluated tokens

      jmespath_expression(const std::string_view input_path) noexcept : path(input_path)
      {
         error = jmespath::tokenize_full_jmespath(path, tokens);
      }

      template <size_t use_padded = resizable<Buffer> && non_const_buffer<Buffer> && !check_disable_padding(Options);

      static constexpr auto Opts = use_padded ? is_padded_on<Options>() : is_padded_off<Options>();

      if constexpr (use_padded) {
         // Pad the buffer for SWAR
         buffer.resize(buffer.size() + padding_bytes);
      }
      auto p = read_iterators<Opts>(buffer);
      auto it = p.first;
      auto end = p.second;
      auto start = it;

      context ctx{};

      if constexpr (N == 0) {
         parse<Opts.format>::temp const int32_t end_idx = decomposed_key.end.value_or((std::numeric_limits<int32_t>::max)());

         if (at_end()) return;
         if (*it == ']') {
            ++it;
            return;
         }

         int32_t current_index = 0;

         // Iterate tuple elements
         using TupleType = std::decay_t<T>;
         constexpr size_t N = glz::tuple_size_v<TupleType>;

         for_each<N>([&]<size_t I>() {
            if (bool(ctx.error)) return;

            int32_t target_idx = start_idx + I;

            // If target is       if (result.ec == std::errc()) {
            return value;
         }
         return std::nullopt;
      }

      // Parse a token that may have array indexing or slicing.
      inline constexpr ArrayParseResult parse_jmespath_token(std::string_view token)
      {
         ArrayParseResult result;

         // Find the first '['
         auto open_pos = token.find('[');
         if (open_pos == std::string_view::npos) {
            // No array access, just a key.
            result.key = token;
            return result;
    ::string_view trim_left(std::string_view s)
      {
         size_t start = 0;
         while (start < s.size() && (s[start] == ' ' || s[start] == '\t' || s[start] == '\n' || s[start] == '\r')) {
            start++;
         }
         return s.substr(start);
      }

      /**
       * @brief Splits a JMESPath expression into the first token and the remaining path with error handling.
       *
       * @param s The JMESPath expression to tokenize.
       * @return tokenization_result containing:
       *         - first: The firsmp_newline_indent(check_indentation_char(Opts), ctx.depth, b, ix);
      }

      if constexpr (!check_closing_handled(Opts)) {
         dump(']', b, ix);
      }
   }

   template <auto Opts, class T>
   void read_flatten_map_elements(T& value, is_context auto&& ctx, auto&& it, auto end, bool& first)
   {
      using V = std::remove_cvref_t<T>;

      auto parse_value = [&](auto& item) {
         if (!first) {
            if (skip_ws<Opts>(ctx, it, end)) {
               return;
            }
            if (match_invalid_end<',', {
      auto start = it;
      ++it; // skip quote
      while (it < end) [[likely]] {
         uint64_t chunk;
         std::memcpy(&chunk, it, 8);
         if constexpr (std::endian::native == std::endian::big) {
            chunk = std::byteswap(chunk);
         }
         const uint64_t quote = has_quote(chunk);
         if (quote) {
            it += (countr_zero(quote) >> 3);

            auto* prev = it - 1;
            while (*prev == '\\') {
               --prev;
            }
            if (size_t(it - prev) % 2) {
   g representation.
       * @return An `expected` containing a JSON string if successful, or an error context.
       */
      expected<std::string, error_ctx> dump() const;

      /**
       * @brief Gets the value as the specified type.
       * @tparam T The type to get the value as.
       * @return Reference to the value of the specified type.
       */
      template <class T>
      [[nodiscard]] T& get()
      {
         return std::get<T>(data);
      }

      template <class T>
      [[nodiscard]] const T& get() const
     end) && whitespace_table[uint8_t(*it)]) {
                  ++it;
               }
            }
         };

         skip_whitespace();

         while ([&]() -> bool {
            if constexpr (Opts.null_terminated) {
               return true;
            }
            else {
               return it < end;
            }
         }()) {
            switch (json_types[uint8_t(*it)]) {
            case String: {
               const auto value = read_json_string<Opts>(it, end);
               dump_maybe_empty<false>(value, b, ix
      static constexpr std::string_view name = join_v<chars<"std::deque<">, name_v<T>, chars<">">>;
   };
}
// Glaze Library
// For the license information refer to glaze.hpp

#pragma once

#include <functional>

#include "glaze/core/common.hpp"
#include "glaze/core/meta.hpp"

namespace glz
{
   namespace detail
   {
      template <const std::string_view& Str, class Tuple, size_t I = 0>
      struct expander
      {
         static constexpr auto impl() noexcept
         {
            const auto N = glz::tuple_size_v<Tuple>;
    operator=(const lib_loader&) = delete;
      lib_loader& operator=(lib_loader&&) = delete;

      lib_loader(const std::string_view directory) { load(directory); }

      ~lib_loader()
      {
         api_map.clear();
         for (const auto& lib : loaded_libs) {
#ifdef GLAZE_API_ON_WINDOWS
            FreeLibrary(lib);
#else
            dlclose(lib);
#endif
         }
      }

     private:
      bool load_lib(const std::string& path) noexcept
      {
#ifdef GLAZE_API_ON_WINDOWS
         std::filesystem::path file_path(path);
  to N = sizeof...(Args);
         for_each<N>([&]<auto I>() {
            using V = glz::tuple_element_t<I, T>;
            ptr->emplace(name_v<V>, make_api<V>);
         });

         return ptr;
      };
   }
}
// Glaze Library
// For the license information refer to glaze.hpp

#pragma once

#include <filesystem>
#include <map>
#include <string_view>

#include "glaze/api/api.hpp"

#if defined(_WIN32) || defined(__CYGWIN__)
#ifndef GLAZE_API_ON_WINDOWS
#define GLAZE_API_ON_WINDOWS
#endif
#endif

#ifdef GLAZE_API_ON_WINDOWS
#ifdef N         virtual bool write(const uint32_t /*format*/, const sv /*path*/, std::string& /*data*/) noexcept = 0;

         [[nodiscard]] virtual const sv last_error() const noexcept { return error; }

         /// unchecked `void*` access for low level programming (prefer templated get)
         [[nodiscard]] virtual std::pair<void*, glz::hash_t> get(const sv path) noexcept = 0;

        protected:
         virtual bool caller(const sv path, const glz::hash_t type_hash, void*& ret,
                             std::span<void*> args) && (sizeof(range_value_t<Buffer>) == sizeof(char)) &&
                           non_const_buffer<Buffer> && safe_resizable_buffer<Buffer>;

   template <class Range>
   concept contiguous_byte_range = contiguous<Range> && byte_like<range_value_t<Range>>;

   template <class T>
   constexpr bool const_value_v = std::is_const_v<std::remove_pointer_t<std::remove_reference_t<T>>>;
}

namespace glz::detail
{
   template <class Container>
   using iterator_pair_type =
      typename std::iterator_traits<decltype(std::begin(std::declval<ame_as<T>;
      { t.has_value() } -> std::convertible_to<bool>;
      { t.value() };
      { t = v };
      { t.reset() };
      { t.emplace() };
   };

   template <class T>
   concept pair_t = requires(T pair) {
      typename std::decay_t<T>::first_type;
      typename std::decay_t<T>::second_type;
      { pair.first };
      { pair.second };
   };

   // glz::pair - a simple pair type for use in glaze
   template <class T1, class T2>
   struct pair
   {
      using first_type = T1;
      using second_type = T2;
      T1 first{
   // ===== High-level read APIs =====
   //
   // Per the SQLite JSONB spec: "A valid JSONB BLOB consists of a single JSON element.
   // The element must exactly fill the BLOB." Glaze's core parse only advances across
   // one element; trailing bytes after a valid top-level element would otherwise be
   // silently ignored. Enforce the spec at the public boundary by comparing bytes
   // consumed (ec.count) against the input size.
   namespace jsonb_detail
   {
      template <class Buffer>
      error_ctx enforce_exact_fill(coxpected(std::move(error));
            return;
         }

         // Not an unexpected wrapper. Rewind and parse as the value.
         it = start;
         parse_val();
      }
   };

   namespace jsonb_detail
   {
      // JSONB variant alternative category traits. Distinct from the JSON-side traits
      // because JSONB carries enough type information on the wire to tell INT from FLOAT,
      // so we can auto-deduce variant<int, double> here even though JSON cannot.
      template <class T>
      struct is_jsonb_variant_int  meta_construct_v<T>();
            }
            else if constexpr (requires { value.emplace(); }) {
               value.emplace();
            }
            else {
               ctx.error = error_code::invalid_nullable_read;
               return;
            }
         }
         parse<JSONB>::op<Opts>(*value, ctx, it, end);
      }
   };

   // nullable_value_t (e.g. std::optional without full nullable_like)
   template <class T>
      requires(nullable_value_t<T> && !nullable_like<T> && !is_expected<T> && !custom_read<T>)
  itable_map_t T>
   struct from<JSONB, T> final
   {
      template <auto Opts>
      static void op(auto& value, is_context auto& ctx, auto& it, auto end)
      {
         depth_guard g{ctx};
         if (!g) return;
         using Key = typename std::remove_cvref_t<T>::key_type;
         static_assert(str_t<Key> || std::same_as<Key, std::string>,
                       "JSONB objects only support string keys (types 7-10).");

         uint8_t tc{};
         uint64_t sz{};
         if (!jsonb::read_header(ctx, it, end, tc, sz)) ret    // Parse a JSONB integer payload (INT or INT5) and store into target.
      template <class T>
      inline void parse_int_payload(is_context auto& ctx, uint8_t type_code, const char* p, size_t n, T& out) noexcept
      {
         if (n == 0) [[unlikely]] {
            ctx.error = error_code::parse_number_failure;
            return;
         }

         const char* start = p;
         const char* stop = p + n;

         if (type_code == jsonb::type::int5) {
            // JSON5: allow optional leading sign, followed by decimaltring>
#include <string_view>

#include "glaze/core/opts.hpp"
#include "glaze/json/write.hpp"
#include "glaze/jsonb/header.hpp"
#include "glaze/jsonb/text_decode.hpp"

namespace glz
{
   namespace jsonb_detail
   {
      // Emit a JSON string literal from a raw UTF-8 byte payload. Uses the JSON writer so all
      // control characters and structural JSON chars are correctly escaped.
      template <auto Opts, class B>
      inline void emit_raw_string_as_json(is_context auto& ctx, const char* data, size_t size, B& out, size_t& ix)pointer T>
   struct to<JSONB, T>
   {
      template <auto Opts>
      static void op(auto&&, is_context auto&&, auto&&, auto&&) noexcept
      {}
   };

   // Generic JSON value â€” dispatch each variant alternative to the matching JSONB element.
   // Without this specialization, glz::generic would fall through to the variant handler and
   // serialize as an [index, value] array rather than as the native element type.
   template <num_mode Mode, template <class> class MapType>
   struct to<JSONB, generic_json<Mode, MapType>> fiif (!jsonb_detail::reserve_container_header(ctx, b, ix, header_pos)) [[unlikely]] {
            return;
         }
         const size_t payload_start = ix;

         using map_t = std::remove_cvref_t<decltype(value)>;
         using val_t = std::remove_cvref_t<detail::iterator_second_type<map_t>>;
         constexpr bool may_skip = null_t<val_t> && Opts.skip_null_members;

         for (auto&& [k, v] : value) {
            if constexpr (may_skip) {
               if (skip_member<Opts>(v)) continue;
            }
            serial1;
      inline constexpr uint8_t object = 12;
      // 13, 14, 15 reserved
   }

   namespace size_code
   {
      inline constexpr uint8_t u8_follows = 12;
      inline constexpr uint8_t u16_follows = 13;
      inline constexpr uint8_t u32_follows = 14;
      inline constexpr uint8_t u64_follows = 15;
   }

   // Maximum header length in bytes (9 = 1 header byte + 8 for uint64 size)
   inline constexpr size_t max_header_bytes = 9;

   [[nodiscard]] GLZ_ALWAYS_INLINE constexpr uint8_t get_type(uint8_t initial) noexcept { return inexcept
   {
      return read<eetf::eetf_opts{.format = EETF, .layout = layout}>(value, std::forward<Buffer>(buffer));
   }

   template <uint8_t layout = glz::eetf::map_layout, read_supported<EETF> T, is_buffer Buffer>
   [[nodiscard]] expected<T, error_ctx> read_term(Buffer&& buffer) noexcept
   {
      T value{};
      context ctx{};
      const error_ctx ec =
         read<eetf::eetf_opts{.format = EETF, .layout = layout}>(value, std::forward<Buffer>(buffer), ctx);
      if (ec) {
         return unexpected<error_ctx>(ec);
    inline constexpr int eetf_magic_version = 131;

   template <class T>
   concept atom_t = string_t<T> && std::same_as<typename T::tag, eetf::tag_atom>;
} // namespace glz
#pragma once

#include <ei.h>

#include <array>
#include <cstdint>
#include <string>

#include "cmp.hpp"

namespace glz::eetf
{
   struct tag_atom
   {};

   struct tag_string
   {};

   template <typename Tag>
   struct tagged_string : std::string
   {
      using tag = Tag;

      auto operator<=>(const tagged_string& rhs) const = default;
   };

   using atom =ails to compile when the
      // scratch type (long / long long) is a distinct type of the same width as V -- e.g. on
      // platforms where int64_t is long long while long is also 64-bit (macOS/LLP64-style).
      if constexpr (std::floating_point<std::remove_cvref_t<T>>) {
         double v;
         detail::decode_impl([&](const char* buf, int* index) { return ei_decode_double(buf, index, &v); },
                             std::forward<Args>(args)...);
         value = static_cast<std::remove_cvref_t<T>>(v);
      }
      e  [&]<size_t... I>(std::index_sequence<I...>) {
               (serialize<EETF>::op<Opts>(glz::get<I>(value), ctx, args...), ...);
            }(std::make_index_sequence<N>{});
         }
      }
   };

   template <writable_array_t T>
   struct to<EETF, T> final
   {
      template <auto Opts, class V, class... Args>
         requires(not check_no_header(Opts))
      GLZ_ALWAYS_INLINE static void op(V&& v, Args&&... args) noexcept
      {
         encode_version(std::forward<Args>(args)...);
         op<no_header_on<Opts>()>(std::      case ERL_MAP_EXT: {
            // decode_map_header reads the tag plus a 4-byte arity off the raw pointer; bound it.
            if (check_invalid_offset(ctx, it, end, 5u)) return;
            [[maybe_unused]] auto [arity, idx] = decode_map_header(ctx, it);
            if (bool(ctx.error)) {
               return;
            }

            std::advance(it, idx);
            dump('{', out, ix);
            if constexpr (Opts.prettify) {
               ctx.depth += check_indentation_width(Opts);
               dump('\n', out,ported<CSV> T, class Buffer>
   [[nodiscard]] inline auto read_csv(Buffer&& buffer)
   {
      T value{};
      read<opts_csv{.layout = layout}>(value, std::forward<Buffer>(buffer));
      return value;
   }

   template <uint32_t layout = rowwise, read_supported<CSV> T, is_buffer Buffer>
   [[nodiscard]] inline error_ctx read_file_csv(T& value, const sv file_name, Buffer&& buffer)
   {
      context ctx{};
      ctx.current_file = file_name;

      const auto ec = file_to_buffer(buffer, ctx.current_file);

      if (bool(ec)) {
  nst auto index = decode_hash_with_size<CSV, T, HashInfo, HashInfo.type>::op(
                  key.data(), key.data() + key.size(), key.size());

               // Verify that the decoded index actually matches the key string to avoid
               // accidental matches from non-member inputs (e.g., fuzzed data).
               if (index < N && reflect<T>::keys[index] == key) [[likely]] {
                  visit<N>(
                     [&]<size_t I>() {
                        decltype(auto) member = [&]() -> decltype(auto) {
   
   struct from<CSV, T>
   {
      using U = typename T::value_type;

      template <auto Opts, class It>
      static void op(auto&& value, is_context auto&& ctx, It&& it, auto end)
      {
         static constexpr auto N = reflect<U>::size;
         static constexpr auto HashInfo = hash_info<U>;

         // Clear existing data if not appending
         if constexpr (!check_append_arrays(Opts)) {
            value.clear();
         }

         if constexpr (check_layout(Opts) == colwise) {
            // Read column headers
     auto read_key = [&](auto&& start, auto&& it) {
         sv key{start, size_t(it - start)};

         size_t csv_index{};

         const auto brace_pos = key.find('[');
         if (brace_pos != sv::npos) {
            const auto close_brace = key.find(']');
            const auto index = key.substr(brace_pos + 1, close_brace - (brace_pos + 1));
            key = key.substr(0, brace_pos);
            const auto [ptr, ec] = std::from_chars(index.data(), index.data() + index.size(), csv_index);
            if (ec != std::errc()) {
_begin = it;
            while (it != end && *it != csv_delimiter<Opts>() && *it != '\n' && *it != '\r') {
               ++it;
            }
            field = std::string_view(content_begin, static_cast<std::size_t>(it - content_begin));
         }

         if (field.empty()) {
            value = storage_t{};
            return;
         }

         storage_t parsed{};
         bool has_char = false;

         if (quoted) {
            std::size_t idx = 0;
            while (idx < field.size()) {
               const char c = ; // Skip the opening quote

            if constexpr (check_raw_string(Opts)) {
               // Raw string mode: don't process escape sequences
               while (it != end) {
                  if (*it == '"') {
                     ++it; // Skip the quote
                     if (it == end || *it != '"') {
                        // Single quote - end of field
                        break;
                     }
                     // Double quote - add one quote and continue
                     value.push_back('"');
           else {
                     return get<I>(reflect<T>::values);
                  }
               }();

               if constexpr (writable_array_t<value_type>) {
                  decltype(auto) member = get_member(value, mem);
                  const auto count = member.size();
                  const auto size = member[0].size();
                  for (size_t i = 0; i < size; ++i) {
                     if constexpr (check_use_headers(Opts)) {
                        if (!ensure_space(ctx, b, ix + key.size() + 32 + writ   // Add trailing newline for consistency
            if (max_cols > 0) {
               if (!ensure_space(ctx, b, ix + 1 + write_padding_bytes)) [[unlikely]] {
                  return;
               }
               dump('\n', b, ix);
            }
         }
      }
   };

   // Helper function to check if a string needs CSV quoting
   template <char delim = ',', class Str>
   inline bool needs_csv_quoting(const Str& str)
   {
      for (const auto c : str) {
         if (c == delim || c == '"' || c == '\n' || c == '\r') {
   clude <cstddef>
#include <initializer_list>
#include <type_traits>

namespace glz
{
   template <class T>
   concept is_volatile_array = requires { std::decay_t<T>::glaze_volatile_array; };

   template <typename T, std::size_t N>
   class volatile_array
   {
     public:
      static constexpr auto glaze_volatile_array = true;
      static constexpr auto length = N;
      using value_type = T;
      using size_type = std::size_t;
      using difference_type = std::ptrdiff_t;
      using reference = volatile T&;
      using const_r::make_unique<typename T::element_type>();
               }
               else if constexpr (is_specialization_v<T, std::shared_ptr>) {
                  value = std::make_shared<typename T::element_type>();
               }
               else if constexpr (constructible<T>) {
                  value = meta_construct_v<T>();
               }
               else if constexpr (std::is_pointer_v<T> && can_allocate_raw_pointer<Opts, std::decay_t<decltype(ctx)>>) {
                  if (!try_allocate_raw_pointer<Opts>(value, ctx)) {
          uint8_t peek;
               std::memcpy(&peek, it, 1);

               if (peek == initial_byte(major::simple, simple::break_code)) {
                  ++it;
                  break;
               }

               if constexpr (resizable<T>) {
                  value.emplace_back();
                  parse<CBOR>::op<Opts>(value.back(), ctx, it, end);
               }
               else {
                  if (i >= value.size()) [[unlikely]] {
                     ctx.error = error_code::exceeded_static_array_size;
            uint8_t initial;
         std::memcpy(&initial, it, 1);

         const uint8_t major_type = get_major_type(initial);
         const uint8_t additional_info = get_additional_info(initial);

         // Check for RFC 8746 typed array (tag + byte string)
         if constexpr (num_t<V> && !std::same_as<V, bool> && contiguous<T>) {
            if (major_type == major::tag) {
               ++it; // consume the tag initial byte

               // Decode the tag number
               const uint64_t tag_num = cbor_detail::decode_emcpy(value.data(), it, length);
               if (length < value.size()) {
                  std::memset(value.data() + static_cast<size_t>(length), 0,
                              value.size() - static_cast<size_t>(length));
               }
            }
            else {
               value.assign(reinterpret_cast<const char*>(it), length);
            }
            it += length;
         }
      }
   };

   // Byte strings - any contiguous byte-like range (std::vector<std::byte>, std::vector<uint8_t>,
   // std::array<std: class T, is_context Ctx, class It0, class It1>
      GLZ_ALWAYS_INLINE static void op(T&& value, Ctx&& ctx, It0&& it, It1 end)
      {
         if constexpr (const_value_v<T>) {
            if constexpr (check_error_on_const_read(Opts)) {
               ctx.error = error_code::attempt_const_read;
            }
            else {
               skip_value<CBOR>::op<Opts>(std::forward<Ctx>(ctx), std::forward<It0>(it), end);
            }
         }
         else {
            using V = std::remove_cvref_t<T>;
            from<CBOR,  context ctx{};

      while (it < end) {
         detail::cbor_to_json_value<Opts>(ctx, it, end, out, ix, 0);
         if (bool(ctx.error)) {
            return {0, ctx.error};
         }
      }

      if constexpr (resizable<JSONBuffer>) {
         out.resize(ix);
      }

      return {};
   }

   // Convenience function returning string
   template <auto Opts = glz::opts{}, class CBORBuffer>
   [[nodiscard]] inline expected<std::string, error_ctx> cbor_to_json(const CBORBuffer& cbor)
   {
      std::string out;
      auto ec =    to<JSON, std::string_view>::template op<Opts>(str, ctx, out, ix);
            }
            else {
               const uint64_t length = cbor_to_json_decode_arg(ctx, it, end, additional_info);
               if (bool(ctx.error)) [[unlikely]]
                  return;

               if (static_cast<uint64_t>(end - it) < length) [[unlikely]] {
                  ctx.error = error_code::unexpected_end;
                  return;
               }

               const sv value{reinterpret_cast<const char*>(it), static_cast<size_t>(ed>(tod.minutes().count());
         const auto sc = static_cast<unsigned>(tod.seconds().count());

         auto write_digits = [&]<size_t N>(uint64_t val) {
            for (size_t i = N; i > 0; --i) {
               b[ix + i - 1] = static_cast<typename std::decay_t<decltype(b)>::value_type>('0' + val % 10);
               val /= 10;
            }
            ix += N;
         };

         write_digits.template operator()<4>(static_cast<uint64_t>(yr));
         b[ix++] = '-';
         write_digits.template operator()<2>(mo);
    b), std::forward<IX>(ix));
      }
   };

   // Enums with glaze reflection
   template <glaze_enum_t T>
   struct to<CBOR, T> final
   {
      template <auto Opts>
      GLZ_ALWAYS_INLINE static void op(auto&& value, is_context auto&& ctx, auto&& b, auto& ix)
      {
         using V = std::underlying_type_t<std::decay_t<T>>;
         if constexpr (std::is_signed_v<V>) {
            const auto v = static_cast<V>(value);
            if (v >= 0) {
               cbor_detail::encode_arg(ctx, cbor::major::uint, static_cast<uint64_t>(vT>
      requires((glaze_object_t<T> || reflectable<T>) && !custom_write<T>)
   struct to<CBOR, T> final
   {
      static constexpr auto N = reflect<T>::size;

      template <auto Opts, size_t I>
      static consteval bool should_skip_field()
      {
         using V = field_t<T, I>;

         if constexpr (always_skipped<V>) {
            return true;
         }
         else if constexpr (is_any_function_ptr<V>) {
            return !check_write_function_pointers(Opts);
         }
         else {
            return false;
     // Write real part
         using V = typename std::remove_cvref_t<T>::value_type;
         to<CBOR, V>::template op<Opts>(value.real(), ctx, b, ix);
         if (bool(ctx.error)) [[unlikely]]
            return;
         // Write imaginary part
         to<CBOR, V>::template op<Opts>(value.imag(), ctx, b, ix);
      }
   };

   // Boolean
   template <boolean_like T>
   struct to<CBOR, T> final
   {
      template <auto Opts>
      GLZ_ALWAYS_INLINE static void op(const bool value, is_context auto&& ctx, auto&& b, auto& ix)
     yntax_error;
            break;
         }
      }
   };
}
// Glaze Library
// For the license information refer to glaze.hpp

#pragma once

#include "glaze/cbor/header.hpp"
#include "glaze/core/buffer_traits.hpp"
#include "glaze/core/chrono.hpp"
#include "glaze/core/opts.hpp"
#include "glaze/core/reflect.hpp"
#include "glaze/core/to.hpp"
#include "glaze/core/write.hpp"
#include "glaze/util/dump.hpp"
#include "glaze/util/for_each.hpp"
#include "glaze/util/variant.hpp"

namespace glz
{
   template <>
   struct serialize<CBOR>
   {
 _code::syntax_error; // Reserved (28-30)
            return 0;
         }
      }

      // Main entry point: skip one complete CBOR data item
      template <auto Opts>
      static void op(is_context auto& ctx, auto& it, auto end) noexcept
      {
         using namespace cbor;

         if (it >= end) [[unlikely]] {
            ctx.error = error_code::unexpected_end;
            return;
         }

         uint8_t initial;
         std::memcpy(&initial, it, 1);
         ++it;

         const uint8_t major_type = get_major_type(
   {
      if (std::isnan(value) || std::isinf(value)) {
         return true;
      }

      const float f = static_cast<float>(value);
      return static_cast<double>(f) == value;
   }

   // RFC 8746 Typed Array helpers
   namespace typed_array
   {
      // Select the appropriate tag for a type based on native endianness
      template <class T>
      [[nodiscard]] consteval uint64_t native_tag() noexcept
      {
         constexpr bool is_le = (std::endian::native == std::endian::little);

         // Unsigned integers
              if constexpr (Opts.format == JSON) {
            throw std::runtime_error("read error: " + glz::format_error(ec, buffer));
         }
         else {
            throw std::runtime_error("read error");
         }
      }
   }

   template <auto Opts, class T, output_buffer Buffer>
   void write(T&& value, Buffer& buffer) noexcept
   {
      glz::write<Opts>(std::forwa