martin-g commented on code in PR #3545:
URL: https://github.com/apache/avro/pull/3545#discussion_r2522416884
##########
lang/c++/include/avro/Specific.hh:
##########
@@ -165,6 +166,44 @@ struct codec_traits<double> {
}
};
+/**
+* codec_traits for Avro optional.
+*/
+template<typename T>
+struct codec_traits<std::optional<T>> {
+ /**
+ * Encodes a given value.
+ */
+ static void encode(Encoder &e, const std::optional<T> &b) {
Review Comment:
This makes an assumption that the schema is `["null", T]`.
This is true most of the time but it is not mandatory. Without having the
schema in scope I see no way how to improve it.
##########
lang/c++/include/avro/Specific.hh:
##########
Review Comment:
```suggestion
#include "Encoder.hh"
#include "Exception.hh"
```
for the new usage at
https://github.com/apache/avro/pull/3545/files#diff-6a9c42629e99021e3a2ea7e61e2c364940c9e04228a8b382ea47032f04d44c74R192
##########
lang/c++/include/avro/Specific.hh:
##########
@@ -165,6 +166,44 @@ struct codec_traits<double> {
}
};
+/**
+* codec_traits for Avro optional.
+*/
+template<typename T>
+struct codec_traits<std::optional<T>> {
+ /**
+ * Encodes a given value.
+ */
+ static void encode(Encoder &e, const std::optional<T> &b) {
+ if (b) {
+ e.encodeUnionIndex(1);
+ avro::encode(e, b.value());
+ } else {
+ e.encodeUnionIndex(0);
+ e.encodeNull();
+ }
+ }
+
+ /**
+ * Decodes into a given value.
+ */
+ static void decode(Decoder &d, std::optional<T> &s) {
+ size_t n = d.decodeUnionIndex();
+ if (n >= 2) { throw avro::Exception("Union index too big"); }
Review Comment:
```suggestion
if (n >= 2) { throw avro::Exception("Union index too big for
optional (expected 0 or 1, got " + std::to_string(n) + ")"); }
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]