fixed_size_value_store.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_TOOLCHAIN_BASE_FIXED_SIZE_VALUE_STORE_H_
  5. #define CARBON_TOOLCHAIN_BASE_FIXED_SIZE_VALUE_STORE_H_
  6. #include "common/check.h"
  7. #include "common/move_only.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "llvm/ADT/StringRef.h"
  10. #include "toolchain/base/mem_usage.h"
  11. #include "toolchain/base/value_store.h"
  12. namespace Carbon {
  13. // A value store with a predetermined size.
  14. template <typename IdT, typename ValueT>
  15. class FixedSizeValueStore : public MoveOnly<FixedSizeValueStore<IdT, ValueT>> {
  16. public:
  17. using ValueType = ValueStoreTypes<IdT, ValueT>::ValueType;
  18. using RefType = ValueStoreTypes<IdT, ValueT>::RefType;
  19. using ConstRefType = ValueStoreTypes<IdT, ValueT>::ConstRefType;
  20. // Makes a ValueStore of the specified size, but without initializing values.
  21. // Entries must be set before reading.
  22. static auto MakeForOverwrite(size_t size) -> FixedSizeValueStore {
  23. FixedSizeValueStore store;
  24. store.values_.resize_for_overwrite(size);
  25. return store;
  26. }
  27. // Makes a ValueStore of the specified size, initialized to a default.
  28. explicit FixedSizeValueStore(size_t size, ValueT default_value) {
  29. values_.resize(size, default_value);
  30. }
  31. // Sets the value for an ID.
  32. auto Set(IdT id, ValueType value) -> void {
  33. CARBON_DCHECK(id.index >= 0, "{0}", id);
  34. values_[id.index] = value;
  35. }
  36. // Returns a mutable value for an ID.
  37. auto Get(IdT id) -> RefType {
  38. CARBON_DCHECK(id.index >= 0, "{0}", id);
  39. return values_[id.index];
  40. }
  41. // Returns the value for an ID.
  42. auto Get(IdT id) const -> ConstRefType {
  43. CARBON_DCHECK(id.index >= 0, "{0}", id);
  44. return values_[id.index];
  45. }
  46. // Collects memory usage of the values.
  47. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  48. -> void {
  49. mem_usage.Collect(label.str(), values_);
  50. }
  51. auto size() const -> size_t { return values_.size(); }
  52. private:
  53. // Allow default construction for `MakeForOverwrite`.
  54. FixedSizeValueStore() = default;
  55. // Storage for the `ValueT` objects, indexed by the id.
  56. llvm::SmallVector<ValueT, 0> values_;
  57. };
  58. } // namespace Carbon
  59. #endif // CARBON_TOOLCHAIN_BASE_FIXED_SIZE_VALUE_STORE_H_