randombit / botan

Cryptography Toolkit
https://botan.randombit.net
BSD 2-Clause "Simplified" License
2.6k stars 570 forks source link

Add maybe utility #4450

Open randombit opened 2 days ago

randombit commented 2 days ago

Perhaps its worth adding a utility for this pattern at one point. Something along those lines:

template <typename InnerT, typename T>
   requires std::constructible_from<InnerT, T> && requires(T t) {
      { static_cast<bool>(t) } -> std::same_as<bool>;
   }
auto maybe(T&& v) {
   std::optional<InnerT> result = std::nullopt;
   if(v) {
      result.emplace(std::forward<T>(v));
   }
   return result;
}

... the implementation of this function would then look like that:

   return maybe<EC_AffinePoint>(p._inner().group()->mul_px_qy(p._inner(), x._inner(), q._inner(), y._inner(), rng));

... and it would also be RVO-friendlier.

One downside: similarly to std::make_unique (and friends), this needs the constructor of InnerT (here: EC_AffinePoint(std::unique_ptr<EC_AffinePoint_Data>)) to be public. 😞 This would currently not be the case for this particular example.

_Originally posted by @reneme in https://github.com/randombit/botan/pull/4446#discussion_r1860073710_