perf(runtime): share bind paths and hold bound values inline when instancing artboards (#15411)

* perf(runtime): share a data bind's source path with its source

Each clone of a data bind copied its source path, a vector of ids, into a
new allocation, though the instances of an artboard bind to the same
paths. A bind's path, and a view model operation converter's, now sits in
a SharedSidecar that a clone shares with the bind it was cloned from. A
name based path that resolves to something else gets its own copy when
it does. Reading a path sizes it once from its encoded ids instead of
growing it an id at a time.

In the HUD perf tray, an added leaderboard row makes 9 fewer allocations
(503 to 494); a lap row makes 6 fewer.

* perf(runtime): size a cloned converter group's items once

A cloned converter group added its cloned items one at a time, growing
its list as it went. It now sizes the list from its source first.

In the HUD perf tray, an added leaderboard row makes 2 fewer allocations
(494 to 492), as does a lap row.

* perf(runtime): keep a bound value inside its data bind's context value

Binding a data bind made its context value, then a data value for the
source's value in an allocation of its own, which the context value holds
for as long as it lives. The value is now built in storage inside the
context value: 32 bytes, the largest a source makes (a string or a list),
checked at compile time for each type built there. A context value grows
from 32 to 64 bytes, so a string's bind takes the same memory in one
allocation, and a number's takes 16 bytes more.

In the HUD perf tray, an added leaderboard row makes 9 fewer allocations
(492 to 483), and allocates 128 bytes more; a lap row makes 6 fewer.

* fix(runtime): size a context value's storage from the values it holds

A context value held its source's value in 32 bytes, the size of a
string or list data value with libc++. With libstdc++ a std::string is
32 bytes, so a string data value is 40 and the build stopped on the
size check. The storage is now sized and aligned for the string and the
list data values, the largest a source makes and the ones whose size
depends on the standard library.

Rive-Mono-Commit: 6459c00d00fb7e53bc7fe99827cbd16fbc269d3c
diff --git a/include/rive/core/binary_reader.hpp b/include/rive/core/binary_reader.hpp
index 4b3f122..30b8796 100644
--- a/include/rive/core/binary_reader.hpp
+++ b/include/rive/core/binary_reader.hpp
@@ -57,6 +57,18 @@
     return static_cast<T>(value);
   }
   void reset();
+
+  // How many LEB128 varuints [bytes] holds: each ends at a byte without its
+  // high bit set.
+  static size_t countVarUints(Span<const uint8_t> bytes)
+  {
+    size_t count = 0;
+    for (uint8_t byte : bytes)
+    {
+      count += (byte & 0x80) == 0 ? 1 : 0;
+    }
+    return count;
+  }
 };
 } // namespace rive
 
diff --git a/include/rive/data_bind/context/context_value.hpp b/include/rive/data_bind/context/context_value.hpp
index b874220..204f2ec 100644
--- a/include/rive/data_bind/context/context_value.hpp
+++ b/include/rive/data_bind/context/context_value.hpp
@@ -4,13 +4,19 @@
 #include "rive/data_bind/converters/data_converter.hpp"
 #include "rive/data_bind/data_bind.hpp"
 #include "rive/data_bind/data_values/data_value_number.hpp"
+#include "rive/data_bind/data_values/data_value_string.hpp"
+#include "rive/data_bind/data_values/data_value_list.hpp"
 #include "rive/data_bind/context/context_target_value.hpp"
+#include <algorithm>
+#include <new>
 #include <stdio.h>
+#include <utility>
 namespace rive
 {
 class DataBindContextValue
 {
 protected:
+  // Points into m_dataValueStorage once the source's value is made.
   DataValue* m_dataValue = nullptr;
   DataBindContextTargetValue m_targetValue;
   bool m_isValid = false;
@@ -25,9 +31,12 @@
   {
     if (m_dataValue != nullptr)
     {
-      delete m_dataValue;
+      m_dataValue->~DataValue();
     }
   };
+  // m_dataValue points into this object's own storage.
+  DataBindContextValue(const DataBindContextValue&) = delete;
+  DataBindContextValue& operator=(const DataBindContextValue&) = delete;
   virtual void applyToSource(
       Core* component,
       uint32_t propertyKey,
@@ -122,6 +131,30 @@
       }
     }
   };
+
+private:
+  // The source's value, held here rather than in an allocation of its own:
+  // a context value holds exactly one, for as long as it lives. A string
+  // and a list are the largest a source makes (see the constructor), and
+  // their sizes depend on the standard library, so they size the storage.
+  static constexpr size_t kDataValueStorageSize = std::max(
+      sizeof(DataValueString),
+      sizeof(DataValueList));
+  static constexpr size_t kDataValueStorageAlign = std::max(
+      alignof(DataValueString),
+      alignof(DataValueList));
+  alignas(kDataValueStorageAlign) unsigned char m_dataValueStorage
+      [kDataValueStorageSize];
+
+protected:
+  template <typename T, typename... Args> T* makeDataValue(Args&&... args)
+  {
+    static_assert(
+        sizeof(T) <= kDataValueStorageSize &&
+            alignof(T) <= kDataValueStorageAlign,
+        "a data value outgrew DataBindContextValue's storage");
+    return new (m_dataValueStorage) T(std::forward<Args>(args)...);
+  }
 };
 } // namespace rive
 
diff --git a/include/rive/data_bind/converters/data_converter_operation_viewmodel.hpp b/include/rive/data_bind/converters/data_converter_operation_viewmodel.hpp
index b32f550..5523eb3 100644
--- a/include/rive/data_bind/converters/data_converter_operation_viewmodel.hpp
+++ b/include/rive/data_bind/converters/data_converter_operation_viewmodel.hpp
@@ -4,6 +4,7 @@
 #include "rive/data_bind/data_context.hpp"
 #include "rive/viewmodel/viewmodel_instance_number.hpp"
 #include "rive/viewmodel/viewmodel_value_dependent.hpp"
+#include "rive/sidecar.hpp"
 #include <stdio.h>
 namespace rive
 {
@@ -17,7 +18,8 @@
   rcp<ViewModelInstanceNumber> m_source = nullptr;
 
 protected:
-  std::vector<uint32_t> m_SourcePathIdsBuffer;
+  // Shared with the converter this one was cloned from.
+  SharedSidecar<std::vector<uint32_t>> m_sourcePathIds;
 
 public:
   ~DataConverterOperationViewModel();
@@ -26,7 +28,12 @@
   void decodeSourcePathIds(Span<const uint8_t> value) override;
   void copySourcePathIds(
       const DataConverterOperationViewModelBase& object) override;
-  const std::vector<uint32_t>& sourcePathIds() { return m_SourcePathIdsBuffer; }
+  const std::vector<uint32_t>& sourcePathIds() const
+  {
+    static const std::vector<uint32_t> empty;
+    auto ids = m_sourcePathIds.get();
+    return ids != nullptr ? *ids : empty;
+  }
   void bindFromContext(DataContext* dataContext, DataBind* dataBind) override;
   void unbind() override;
   void addDirt(ComponentDirt value, bool recurse) override;
diff --git a/include/rive/data_bind/data_bind_context.hpp b/include/rive/data_bind/data_bind_context.hpp
index b75be55..de32e01 100644
--- a/include/rive/data_bind/data_bind_context.hpp
+++ b/include/rive/data_bind/data_bind_context.hpp
@@ -5,13 +5,17 @@
 #include "rive/data_bind/context/context_value.hpp"
 #include "rive/data_bind/data_context.hpp"
 #include "rive/refcnt.hpp"
+#include "rive/sidecar.hpp"
 #include <stdio.h>
 namespace rive
 {
 class DataBindContext : public DataBindContextBase
 {
 protected:
-  std::vector<uint32_t> m_SourcePathIdsBuffer;
+  // Shared with the bind this one was cloned from: instances of an artboard
+  // bind to the same paths, and only a name based path that resolves
+  // differently needs one of its own.
+  SharedSidecar<std::vector<uint32_t>> m_sourcePathIds;
 #ifdef WITH_RIVE_EDITOR
   std::vector<Id> m_editorSourcePath;
   bool m_hasEditorSourcePath = false;
@@ -27,7 +31,9 @@
 #endif
   const std::vector<uint32_t>& sourcePathIds() const
   {
-    return m_SourcePathIdsBuffer;
+    static const std::vector<uint32_t> empty;
+    auto ids = m_sourcePathIds.get();
+    return ids != nullptr ? *ids : empty;
   }
   // The source path's length. A path the editor hydrated is kept apart and
   // leaves sourcePathIds empty.
@@ -39,7 +45,7 @@
       return m_editorSourcePath.size();
     }
 #endif
-    return m_SourcePathIdsBuffer.size();
+    return sourcePathIds().size();
   }
 
 private:
diff --git a/src/data_bind/context/context_value.cpp b/src/data_bind/context/context_value.cpp
index 5f657d1..a78fa9a 100644
--- a/src/data_bind/context/context_value.cpp
+++ b/src/data_bind/context/context_value.cpp
@@ -36,19 +36,19 @@
     switch (source->coreType())
     {
       case ViewModelInstanceNumberBase::typeKey:
-        m_dataValue = new DataValueNumber(
+        m_dataValue = makeDataValue<DataValueNumber>(
             source->as<ViewModelInstanceNumber>()->propertyValue());
         break;
       case ViewModelInstanceStringBase::typeKey:
-        m_dataValue = new DataValueString(
+        m_dataValue = makeDataValue<DataValueString>(
             source->as<ViewModelInstanceString>()->propertyValue());
         break;
       case ViewModelInstanceColorBase::typeKey:
-        m_dataValue = new DataValueColor(
+        m_dataValue = makeDataValue<DataValueColor>(
             source->as<ViewModelInstanceColor>()->propertyValue());
         break;
       case ViewModelInstanceBooleanBase::typeKey:
-        m_dataValue = new DataValueBoolean(
+        m_dataValue = makeDataValue<DataValueBoolean>(
             source->as<ViewModelInstanceBoolean>()->propertyValue());
         break;
       case ViewModelInstanceEnumBase::typeKey:
@@ -61,43 +61,43 @@
                                          ? viewModelProperty
                                                ->as<ViewModelPropertyEnum>()
                                          : nullptr;
-        m_dataValue = new DataValueEnum(
+        m_dataValue = makeDataValue<DataValueEnum>(
             viewmodelInstanceEnum->propertyValue(),
             viewModelPropertyEnum != nullptr ? viewModelPropertyEnum->dataEnum()
                                              : nullptr);
       }
       break;
       case ViewModelInstanceTriggerBase::typeKey:
-        m_dataValue = new DataValueTrigger(
+        m_dataValue = makeDataValue<DataValueTrigger>(
             source->as<ViewModelInstanceTrigger>()->propertyValue());
         break;
       case ViewModelInstanceListBase::typeKey:
-        m_dataValue = new DataValueList();
+        m_dataValue = makeDataValue<DataValueList>();
         break;
       case ViewModelInstanceSymbolListIndexBase::typeKey:
-        m_dataValue = new DataValueSymbolListIndex();
+        m_dataValue = makeDataValue<DataValueSymbolListIndex>();
         break;
       case ViewModelInstanceAssetImageBase::typeKey:
-        m_dataValue = new DataValueAssetImage(
+        m_dataValue = makeDataValue<DataValueAssetImage>(
             source->as<ViewModelInstanceAssetImage>()->propertyValue());
         break;
       case ViewModelInstanceAssetFontBase::typeKey:
-        m_dataValue = new DataValueAssetFont(
+        m_dataValue = makeDataValue<DataValueAssetFont>(
             source->as<ViewModelInstanceAssetFont>()->propertyValue());
         break;
       case ViewModelInstanceAssetBlobBase::typeKey:
-        m_dataValue = new DataValueAssetBlob(
+        m_dataValue = makeDataValue<DataValueAssetBlob>(
             source->as<ViewModelInstanceAssetBlob>()->propertyValue());
         break;
       case ViewModelInstanceArtboardBase::typeKey:
-        m_dataValue = new DataValueArtboard(
+        m_dataValue = makeDataValue<DataValueArtboard>(
             source->as<ViewModelInstanceArtboard>()->propertyValue());
         break;
       case ViewModelInstanceViewModelBase::typeKey:
-        m_dataValue = new DataValueViewModel();
+        m_dataValue = makeDataValue<DataValueViewModel>();
         break;
       default:
-        m_dataValue = new DataValue();
+        m_dataValue = makeDataValue<DataValue>();
     }
   }
 }
diff --git a/src/data_bind/converters/data_converter_group.cpp b/src/data_bind/converters/data_converter_group.cpp
index 8714f0a..a8d793e 100644
--- a/src/data_bind/converters/data_converter_group.cpp
+++ b/src/data_bind/converters/data_converter_group.cpp
@@ -52,6 +52,7 @@
 Core* DataConverterGroup::clone() const
 {
   auto cloned = DataConverterGroupBase::clone()->as<DataConverterGroup>();
+  cloned->m_items.reserve(m_items.size());
   for (auto& item : m_items)
   {
     if (item->converter() == nullptr)
diff --git a/src/data_bind/converters/data_converter_operation_viewmodel.cpp b/src/data_bind/converters/data_converter_operation_viewmodel.cpp
index 5c2850e..0b9802d 100644
--- a/src/data_bind/converters/data_converter_operation_viewmodel.cpp
+++ b/src/data_bind/converters/data_converter_operation_viewmodel.cpp
@@ -32,19 +32,25 @@
 void DataConverterOperationViewModel::decodeSourcePathIds(
     Span<const uint8_t> value)
 {
+  if (value.size() == 0)
+  {
+    return;
+  }
   BinaryReader reader(value);
+  auto ids = m_sourcePathIds.ensureAllocated();
+  ids->reserve(BinaryReader::countVarUints(value));
   while (!reader.reachedEnd())
   {
     auto val = reader.readVarUintAs<uint32_t>();
-    m_SourcePathIdsBuffer.push_back(val);
+    ids->push_back(val);
   }
 }
 
 void DataConverterOperationViewModel::copySourcePathIds(
     const DataConverterOperationViewModelBase& object)
 {
-  m_SourcePathIdsBuffer = object.as<DataConverterOperationViewModel>()
-                              ->m_SourcePathIdsBuffer;
+  m_sourcePathIds = object.as<DataConverterOperationViewModel>()
+                        ->m_sourcePathIds;
 }
 
 DataConverterOperationViewModel::~DataConverterOperationViewModel()
@@ -69,8 +75,7 @@
   ViewModelInstanceNumber* source = nullptr;
   if (dataContext != nullptr)
   {
-    auto propertyValue = dataContext->getViewModelProperty(
-        m_SourcePathIdsBuffer);
+    auto propertyValue = dataContext->getViewModelProperty(sourcePathIds());
     if (propertyValue != nullptr &&
         propertyValue->is<ViewModelInstanceNumber>())
     {
diff --git a/src/data_bind/data_bind_context.cpp b/src/data_bind/data_bind_context.cpp
index 9f04dec..4c6aac4 100644
--- a/src/data_bind/data_bind_context.cpp
+++ b/src/data_bind/data_bind_context.cpp
@@ -19,17 +19,23 @@
 
 void DataBindContext::decodeSourcePathIds(Span<const uint8_t> value)
 {
+  if (value.size() == 0)
+  {
+    return;
+  }
   BinaryReader reader(value);
+  auto ids = m_sourcePathIds.ensureAllocated();
+  ids->reserve(BinaryReader::countVarUints(value));
   while (!reader.reachedEnd())
   {
     auto val = reader.readVarUintAs<uint32_t>();
-    m_SourcePathIdsBuffer.push_back(val);
+    ids->push_back(val);
   }
 }
 
 void DataBindContext::copySourcePathIds(const DataBindContextBase& object)
 {
-  m_SourcePathIdsBuffer = object.as<DataBindContext>()->m_SourcePathIdsBuffer;
+  m_sourcePathIds = object.as<DataBindContext>()->m_sourcePathIds;
   m_isPathResolved = object.as<DataBindContext>()->m_isPathResolved;
 #ifdef WITH_RIVE_EDITOR
   m_editorSourcePath = object.as<DataBindContext>()->m_editorSourcePath;
@@ -61,9 +67,10 @@
     return;
   }
   m_isPathResolved = true;
-  if (m_SourcePathIdsBuffer.size() > 0)
+  const std::vector<uint32_t>& ids = sourcePathIds();
+  if (ids.size() > 0)
   {
-    auto pathId = m_SourcePathIdsBuffer[0];
+    auto pathId = ids[0];
     if (m_file)
     {
       auto dataResolver = m_file->dataResolver();
@@ -72,7 +79,7 @@
         auto resolvedPath = dataResolver->resolvePath(pathId);
         if (!resolvedPath.empty())
         {
-          m_SourcePathIdsBuffer = resolvedPath;
+          *m_sourcePathIds.ensureAllocated() = resolvedPath;
         }
       }
     }
@@ -92,9 +99,9 @@
 #endif
         isNameBased() && file()
             ? dataContext->getRelativeViewModelProperty(
-                  m_SourcePathIdsBuffer,
+                  sourcePathIds(),
                   file()->dataResolver())
-            : dataContext->getViewModelProperty(m_SourcePathIdsBuffer);
+            : dataContext->getViewModelProperty(sourcePathIds());
     if (m_Source == nullptr || vmSource != m_Source.get())
     {
       if (vmSource != nullptr)
diff --git a/tests/unit_tests/runtime/data_bind_container_test.cpp b/tests/unit_tests/runtime/data_bind_container_test.cpp
index 5ffd948..da365a3 100644
--- a/tests/unit_tests/runtime/data_bind_container_test.cpp
+++ b/tests/unit_tests/runtime/data_bind_container_test.cpp
@@ -59,7 +59,10 @@
 class TestOperationViewModel : public DataConverterOperationViewModel
 {
 public:
-  void sourcePath(std::vector<uint32_t> path) { m_SourcePathIdsBuffer = path; }
+  void sourcePath(std::vector<uint32_t> path)
+  {
+    *m_sourcePathIds.ensureAllocated() = path;
+  }
 };
 
 bool isDependent(ViewModelInstanceValue* value, ViewModelValueDependent* d)
diff --git a/tests/unit_tests/runtime/data_bind_sharing_test.cpp b/tests/unit_tests/runtime/data_bind_sharing_test.cpp
new file mode 100644
index 0000000..73cffcf
--- /dev/null
+++ b/tests/unit_tests/runtime/data_bind_sharing_test.cpp
@@ -0,0 +1,133 @@
+#include "rive/artboard.hpp"
+#include "rive/data_bind/converters/data_converter_group.hpp"
+#include "rive/data_bind/converters/data_converter_group_item.hpp"
+#include "rive/data_bind/converters/data_converter_to_string.hpp"
+#include "rive/data_bind/context/context_value.hpp"
+#include "rive/data_bind/data_bind_context.hpp"
+#include "rive/data_bind/data_values/data_value_list.hpp"
+#include "rive/data_bind/data_values/data_value_number.hpp"
+#include "rive/data_bind/data_values/data_value_string.hpp"
+#include "rive/viewmodel/viewmodel_instance_list.hpp"
+#include "rive/viewmodel/viewmodel_instance_number.hpp"
+#include "rive/viewmodel/viewmodel_instance_string.hpp"
+#include "rive/file.hpp"
+#include "rive_file_reader.hpp"
+#include "rive_testing.hpp"
+#include <unordered_set>
+
+TEST_CASE(
+    "An artboard instance's data binds share their source paths",
+    "[data binding]")
+{
+  size_t shared = 0;
+  for (const char* path :
+       {"assets/data_binding_test.riv", "assets/data_binding_test_2.riv"})
+  {
+    auto file = ReadRiveFile(path);
+    for (size_t i = 0; i < file->artboardCount(); i++)
+    {
+      auto source = file->artboard(i);
+      std::unordered_set<const std::vector<uint32_t>*> sourcePaths;
+      for (auto dataBind : source->dataBinds())
+      {
+        if (dataBind->is<rive::DataBindContext>() &&
+            !dataBind->as<rive::DataBindContext>()->sourcePathIds().empty())
+        {
+          sourcePaths.insert(
+              &dataBind->as<rive::DataBindContext>()->sourcePathIds());
+        }
+      }
+      auto instance = source->instance();
+      for (auto dataBind : instance->dataBinds())
+      {
+        if (!dataBind->is<rive::DataBindContext>())
+        {
+          continue;
+        }
+        auto& ids = dataBind->as<rive::DataBindContext>()->sourcePathIds();
+        if (ids.empty())
+        {
+          continue;
+        }
+        // The very vector the source's bind reads, not a copy of it.
+        CHECK(sourcePaths.count(&ids) == 1);
+        shared++;
+      }
+    }
+  }
+  CHECK(shared > 0);
+}
+
+TEST_CASE("A cloned converter group sizes its items once", "[data binding]")
+{
+  rive::DataConverterToString first, second, third;
+  rive::DataConverterGroup group;
+  for (auto* converter : {&first, &second, &third})
+  {
+    auto item = new rive::DataConverterGroupItem();
+    item->converter(converter);
+    group.addItem(item);
+  }
+  auto clone = group.clone()->as<rive::DataConverterGroup>();
+  CHECK(clone->items().size() == 3);
+  // Sized once, not grown an item at a time.
+  CHECK(clone->items().capacity() == 3);
+  delete clone;
+}
+
+namespace
+{
+class TestContextValue : public rive::DataBindContextValue
+{
+public:
+  using rive::DataBindContextValue::DataBindContextValue;
+  rive::DataValue* value() const { return m_dataValue; }
+  // Whether [value] sits inside this object rather than in an allocation of
+  // its own.
+  bool holds(const rive::DataValue* value) const
+  {
+    auto begin = reinterpret_cast<const char*>(this);
+    auto at = reinterpret_cast<const char*>(value);
+    return at >= begin && at < begin + sizeof(*this);
+  }
+};
+} // namespace
+
+TEST_CASE(
+    "A data bind's context value holds its source's value",
+    "[data binding]")
+{
+  {
+    rive::DataBindContext bind;
+    auto number = rive::make_rcp<rive::ViewModelInstanceNumber>();
+    number->propertyValue(12.0f);
+    bind.source(number);
+    TestContextValue context(&bind);
+    REQUIRE(context.value() != nullptr);
+    CHECK(context.holds(context.value()));
+    REQUIRE(context.value()->is<rive::DataValueNumber>());
+    CHECK(context.value()->as<rive::DataValueNumber>()->value() == 12.0f);
+  }
+  {
+    // The largest values a source makes.
+    rive::DataBindContext bind;
+    auto string = rive::make_rcp<rive::ViewModelInstanceString>();
+    string->propertyValue("a string past the small string size");
+    bind.source(string);
+    TestContextValue context(&bind);
+    REQUIRE(context.value() != nullptr);
+    CHECK(context.holds(context.value()));
+    REQUIRE(context.value()->is<rive::DataValueString>());
+    CHECK(
+        context.value()->as<rive::DataValueString>()->value() ==
+        "a string past the small string size");
+  }
+  {
+    rive::DataBindContext bind;
+    bind.source(rive::make_rcp<rive::ViewModelInstanceList>());
+    TestContextValue context(&bind);
+    REQUIRE(context.value() != nullptr);
+    CHECK(context.holds(context.value()));
+    CHECK(context.value()->is<rive::DataValueList>());
+  }
+}