libkazv
immer-utils.hpp
Go to the documentation of this file.
1 /*
2  * This file is part of libkazv.
3  * SPDX-FileCopyrightText: 2023 tusooa <tusooa@kazv.moe>
4  * SPDX-License-Identifier: AGPL-3.0-or-later
5  */
6 
7 #pragma once
8 #include "libkazv-config.hpp"
9 
10 #include <tuple>
11 
12 namespace Kazv
13 {
14  template<class T>
15  [[nodiscard]] auto getIn(T &&item)
16  {
17  return std::forward<T>(item);
18  }
19 
20  template<class ImmerT, class K, class ...Keys>
21  [[nodiscard]] auto getIn(ImmerT &&container, K &&key, Keys &&...keys)
22  {
23  return getIn(std::forward<ImmerT>(container)[std::forward<K>(key)], std::forward<Keys>(keys)...);
24  }
25 
26  template<class T>
27  [[nodiscard]] auto setIn(T, T newVal)
28  {
29  return newVal;
30  }
31 
32  template<class ImmerT, class K>
33  [[nodiscard]] auto setIn(ImmerT container, std::decay_t<decltype(getIn(std::declval<ImmerT>(), std::declval<K>()))> newVal, K &&key) -> std::decay_t<ImmerT>
34  {
35  return std::move(container).set(std::forward<K>(key), std::move(newVal));
36  }
37 
38  template<class ImmerT, class K, class ...Keys>
39  [[nodiscard]] auto setIn(ImmerT container, std::decay_t<decltype(getIn(std::declval<ImmerT>(), std::declval<K>(), std::declval<Keys>()...))> newVal, K &&key, Keys &&...keys) -> std::decay_t<ImmerT>
40  {
41  auto oldItem = getIn(container, key);
42  return std::move(container).set(
43  std::forward<K>(key),
44  setIn(oldItem, std::move(newVal), std::forward<Keys>(keys)...)
45  );
46  }
47 
48  template<class T, class Func>
49  [[nodiscard]] auto updateIn(T oldVal, Func func) -> T
50  {
51  return std::move(func)(oldVal);
52  }
53 
54  template<class ImmerT, class Func, class ...Keys>
55  [[nodiscard]] auto updateIn(ImmerT container, Func func, Keys &&...keys) -> ImmerT
56  {
57  auto oldVal = getIn(container, keys...);
58  auto newVal = std::move(func)(std::move(oldVal));
59  return setIn(std::move(container), std::move(newVal), std::forward<Keys>(keys)...);
60  }
61 }
Definition: location.hpp:10
auto setIn(T, T newVal)
Definition: immer-utils.hpp:27
auto updateIn(T oldVal, Func func) -> T
Definition: immer-utils.hpp:49
auto getIn(T &&item)
Definition: immer-utils.hpp:15