cpp-common/bt2: add `bt2::OptionalBorrowedObject`
authorPhilippe Proulx <eeppeliteloop@gmail.com>
Fri, 24 Nov 2023 18:05:58 +0000 (13:05 -0500)
committerSimon Marchi <simon.marchi@efficios.com>
Thu, 14 Dec 2023 15:57:04 +0000 (10:57 -0500)
commitdb5a19380c09923ce224aaafde1e44fc441db16b
tree66a4cbaaa7c3c6b26b05cf706b2acf344fb29f5a
parentd246c45795719ead7e4fa616e752c839d6979565
cpp-common/bt2: add `bt2::OptionalBorrowedObject`

An instance of this new class template manages an optional contained
borrowed object of type `ObjT`, that is, a borrowed object that may or
may not be present.

Such an object considers that a `nullptr` libbabeltrace2 object pointer
means none. Therefore, using a `bt2::OptionalBorrowedObject` isn't more
costly, in time and space, as using a libbabeltrace2 object pointer in
C, but offers the typical C++ optional interface.

There's no `bt2s::nullopt` equivalent: just call reset().

An optional borrowed object stores the library pointer itself, only
constructing `ObjT` when it's known that the library pointer isn't
`nullptr`.

The class is pretty straightforward, except that:

* It has a few constructors and assignment operators to make things such
  as this work:

      bt2::OptionalBorrowedObject<bt2::ConstValue> f(const bt2::StringValue val)
      {
          if (std::string {*val} == "meow") {
              return val;
          }

          return {};
      }

  Also, you may assign a `bt2::OptionalBorrowedObject<Y>` instance to a
  `bt2::OptionalBorrowedObject<X>` instance if `Y` inherits `X`.

* operator->() would need to return the address of some `ObjT` instance,
  but an optional borrowed object has none, so return a proxy instead.

The result is a very natural usage:

    std::uint64_t getCsValue(const bt2::OptionalBorrowedObject<bt2::ConstClockSnapshot> optCs)
    {
        return optCs ? optCs->value() : 0;
    }

When optimized, the resulting instructions are the same as for an
equivalent C function:

    getCsValue(bt2::Optional<bt2::ConstClockSnapshot>):
            test    rdi, rdi
            je      .L2
            jmp     bt_clock_snapshot_get_value
    .L2:
            xor     eax, eax
            ret

Signed-off-by: Philippe Proulx <eeppeliteloop@gmail.com>
Change-Id: Ic873ea4ff8b0f084189ece3ac139680469c907d3
Reviewed-on: https://review.lttng.org/c/babeltrace/+/11438
Reviewed-by: Simon Marchi <simon.marchi@efficios.com>
Tested-by: jenkins <jenkins@lttng.org>
CI-Build: Simon Marchi <simon.marchi@efficios.com>
src/Makefile.am
src/cpp-common/bt2/borrowed-object.hpp
src/cpp-common/bt2/optional-borrowed-object.hpp [new file with mode: 0644]
This page took 0.026311 seconds and 4 git commands to generate.