mariusbancila / stduuid

A C++17 cross-platform implementation for UUIDs
MIT License
758 stars 112 forks source link

Provide ability to serialize UUID to non-owning buffer #83

Open justend29 opened 1 year ago

justend29 commented 1 year ago

stduuid is great, and I like how it provides uuids::to_string() and operator<< to serialize the contents.

However, both of these functions create a std::string as the destination buffer for the serialized results. When serializing UUIDs as part of a larger sequence, such as serializing to JSON or an error message, this is inefficient. From the implementation of uuids::to_string(), shown below, it appears that any forward output range could be used.

Would it be possible to offer a more generic serialization function/overloads such that any range/iterators with the necessary traits could be used? This would not only make serializing UUIDs to larger buffers more efficient but would also support serializing to sequences other than std::string.

Am I interpreting the existing code correctly? If so, I'm happy to contribute any necessary changes, but I'm not sure how contributions must be made as this is a reference implementation for standards.

   template <class CharT,
             class Traits,
             class Allocator>
   [[nodiscard]] inline std::basic_string<CharT, Traits, Allocator> to_string(uuid const & id)
   {
      std::basic_string<CharT, Traits, Allocator> uustr{detail::empty_guid<CharT>};

      for (size_t i = 0, index = 0; i < 36; ++i)
      {
         if (i == 8 || i == 13 || i == 18 || i == 23)
         {
            continue;
         }
         uustr[i] = detail::guid_encoder<CharT>[id.data[index] >> 4 & 0x0f];
         uustr[++i] = detail::guid_encoder<CharT>[id.data[index] & 0x0f];
         index++;
      }

      return uustr;
   }