Skip to content

refactor(worker): Use std::vector for function maps and fix static function throwing error. - #123

Closed
sitaowang1998 wants to merge 5 commits into
y-scope:mainfrom
sitaowang1998:static_map
Closed

refactor(worker): Use std::vector for function maps and fix static function throwing error.#123
sitaowang1998 wants to merge 5 commits into
y-scope:mainfrom
sitaowang1998:static_map

Conversation

@sitaowang1998

@sitaowang1998 sitaowang1998 commented May 5, 2025

Copy link
Copy Markdown
Collaborator

Description

This pr replaces absl::flat_hash_map with std::vector to fix the crash caused by differences in memory layout across different abseil versions.

This pr also replaces std::string const& with std::string_view and adds noexcept in functions called during static variable initialization to fix #113.

Checklist

  • The PR satisfies the contribution guidelines.
  • This is a breaking change and that has been indicated in the PR title, OR this isn't a
    breaking change.
  • Necessary docs have been updated, OR no docs need to be updated.

Validation performed

  • Integration tests using task libraries compiled in different version of g++ succeeds.

Summary by CodeRabbit

  • Refactor
    • Improved internal handling of function registration and lookup for enhanced efficiency and reliability.
    • Updated string handling to use more efficient types for function management.
    • Marked certain methods as non-throwing for improved robustness.
    • Replaced hash map storage with vector-based storage for function and function name management.
    • Enhanced function pointer handling by using integer representations for lookups.
  • Style
    • Removed linter directive comments from example and test files for cleaner code presentation.

@sitaowang1998
sitaowang1998 requested a review from a team as a code owner May 5, 2025 16:57
@coderabbitai

coderabbitai Bot commented May 5, 2025

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@sitaowang1998 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 14 minutes and 44 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 563cedf and 0f300b5.

📒 Files selected for processing (1)
  • src/spider/worker/FunctionManager.hpp (3 hunks)
## Walkthrough

The changes refactor the internal storage of function registration in both `FunctionManager` and `FunctionNameManager` from hash maps to vectors of pairs, and update registration and lookup methods to use `std::string_view` for more efficient string handling. Methods that cannot throw are now marked `noexcept`. Linter suppression comments related to `cert-err58-cpp` are removed from several files, as the static initialization pattern has been refactored to avoid the need for such annotations. No functional code outside of registration and lookup mechanisms is altered.

## Changes

| File(s)                                                                                       | Change Summary |
|-----------------------------------------------------------------------------------------------|---------------|
| src/spider/worker/FunctionManager.cpp, src/spider/worker/FunctionManager.hpp                  | Replaced internal function map with `std::vector<std::pair<std::string_view, Function>>`, updated registration and lookup methods to use `std::string_view`, added linear search for existence checks, marked methods `noexcept`, and removed Abseil hash map dependency. |
| src/spider/worker/FunctionNameManager.cpp, src/spider/worker/FunctionNameManager.hpp          | Replaced internal name map with `std::vector<std::pair<std::uintptr_t, std::string_view>>`, updated registration to use `std::string_view`, added linear search for duplicate detection, marked methods `noexcept`, and removed Abseil hash map dependency. |
| examples/quick-start/src/tasks.cpp, tests/worker/signal-test.cpp, tests/worker/worker-test.cpp | Removed `// NOLINTNEXTLINE(cert-err58-cpp)` and related linter suppression comments before or around `SPIDER_REGISTER_TASK` macro invocations. No code logic changed. |
| src/spider/core/TaskGraphImpl.hpp                                                             | Changed reinterpret_cast argument type from `void const*` to `uintptr_t` for function name lookup in `create_task` method. |
| tests/worker/test-FunctionManager.cpp                                                         | Updated test casts from `void*` to `uintptr_t` for function pointer conversions and included `<cstdint>`. |

## Sequence Diagram(s)

```mermaid
sequenceDiagram
    participant User
    participant FunctionManager
    participant FunctionNameManager

    User->>FunctionManager: register_function(name: string_view, func)
    FunctionManager->>FunctionManager: contains(name)
    alt Name not found
        FunctionManager->>FunctionManager: emplace_back(name, func)
        FunctionManager-->>User: true
    else Name exists
        FunctionManager-->>User: false
    end

    User->>FunctionManager: get_function(name: string_view)
    FunctionManager->>FunctionManager: linear search for name
    alt Found
        FunctionManager-->>User: pointer to Function
    else Not found
        FunctionManager-->>User: nullptr
    end

    User->>FunctionNameManager: register_function(name: string_view, ptr)
    FunctionNameManager->>FunctionNameManager: linear search for ptr
    alt Ptr not found
        FunctionNameManager->>FunctionNameManager: emplace_back(ptr, name)
        FunctionNameManager-->>User: true
    else Ptr exists
        FunctionNameManager-->>User: false
    end

Assessment against linked issues

Objective Addressed Explanation
Avoid static initialization that can throw; refactor registration to guarantee no exceptions during static initialization (#113)
Remove need for NOLINTNEXTLINE annotations for SPIDER_REGISTER_TASK macros (#113)
Update registration and lookup to use safer and more efficient mechanisms (#113)
Improve naming and safety of registration system, avoid reliance on compiler-specific features (#113)

Possibly related PRs

Suggested reviewers

  • kirkrodrigues
  • davidlion

<!-- walkthrough_end -->
<!-- internal state start -->


<!-- DwQgtGAEAqAWCWBnSTIEMB26CuAXA9mAOYCmGJATmriQCaQDG+Ats2bgFyQAOFk+AIwBWJBrngA3EsgEBPRvlqU0AgfFwA6NPEgQAfACgjoCEYDEZyAAUASpETZWaCrKNwSPbABsvkCiQBHbGlcSHFcLzpIACJ/ADM0MXwKAAoAd2SAa0oASi4AVUQPAANEXFoODikkimLIOOT67AwxeHwsZjRuZEx6OPgAD3tcangGJpbxdrDYCnw0+AwiSEo5imjIOUhsIr5EdTR5zCIARgBOM4AOdFpaf0Qi5FwMyE7FlAfg5HfcWA8mJQCNBFDSQABi8AoZQANChQv5uF5EtIZh4dh58HFIMUVIgvJU4kjcAB9WDA2DEzrcOoLX7YsoVKqiAi1eqNOLNVrTKmIUFwVAMMlLDzaZhPfD1QaMKiIP7IBhodH0La0eBxOKUMgMFHvNjMZLyJGyfB4dAMOYPSCq9WajChKRQtoYZCY1GQACCAiK8F8XngAioLlBAGVRO1aLDfh5bNtuLRqCiOZMnTxnGg2DQofU5sx6eVKmUKItlkxnbgAGR1Ah5xmF4vEiTwEhpOq9G60J5/bEYfAkAba7i4OqIbiiNVNvjVpNc50zajofyMNA+KK0bBFpbDUbjCTOeAqSIoDDqfd+gBeo3afLl/yFpGQ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Fg2XMKKbIYoQobgpxgqfoVoa4zRZRGypIFysJWJAVBqSVGlUECZyZMRXT0SzYHeakyUkyMUXNHIhoF+JBdWp2VZc8nZa6E5Y2XKysH6hWZkeNxKC5jDrqDjswqXBqSH0fo3TqBUdE1TAeHcmaUvoIJ3K00uPHnWuRkUH+FCrmpBedc+Lsj4qs2qykQ4x6EFuGqD1KT4RFAoCElRn9ZJsALvr3ImSc3OTJRHqCtItIywApTwWzY8ARHuCAU3AajjvyWV3uAkncaeatl8cDIRZ4iRfqBRdcWGIvhxYFsLylQJbFvLxiar3ifVUpaScbwea+YfhL0ieJcaDwehwltialredXblvCAYjpe3UyeyZwaQUIbAB0IvWIa6LIXIeljKaFdfRFaqa7EIa8erNvZdofaffwW/LdfFdCNwo4RyoIrytldjaeLKurczFDwYpauYlg8zHg7lYeyeqTcippEZKXB8ComJLMNLY+v3PjlBHdFuBPDhZ8FkAdatxsytgEQYAZDsm50Imp2sgR1YnRQRoicRIY7NLZoI5et2pmQ6tdIdHkRVJ4FbdsTedxB1NdHVb2Mxh8zO2lfSVw+ADXr0BSC0xLpTZoC0p2Sw8oBw9CuHtHuM9M5Q9yF2sHdH1U0RafDHfcV5xNjtMneHn4AwFe1XnuIuVOQRdCoS25uc6zB+BvGciwbdcjandxdnddPnd3cXe9OPbJZlsSYvZAVSZICveqNJnJmulUzultXfe/iaa4CoExkFbzjxmjYJjUCJjBnK4hmSvKisQ7GJFtebDoGJBghZhJjJh67OAYAjgAAY0AzgAB2AAFhUAADZluQJ8p8oTgGBZuzgI5pvbhzhZuI40BTvDuTgI4NI1uJuDAeuI41utu6A4hTvLhFvLhZvaATg4hLg1vaBFvZuGA1vTvVASABAThFuSArvaABANvHu7v7urpev1A3UBuhvxHaBiQboJugA=== -->

<!-- internal state end -->
<!-- finishing_touch_checkbox_start -->

<details open="true">
<summary>✨ Finishing Touches</summary>

- [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=y-scope/spider&utm_content=123):

- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
  - `I pushed a fix in commit <commit_id>, please review it.`
  - `Generate unit testing code for this file.`
  - `Open a follow-up GitHub issue for this discussion.`
- Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples:
  - `@coderabbitai generate unit testing code for this file.`
  -	`@coderabbitai modularize this function.`
- PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
  - `@coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.`
  - `@coderabbitai read src/utils.ts and generate unit testing code.`
  - `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.`
  - `@coderabbitai help me debug CodeRabbit configuration file.`

### Support

Need help? Create a ticket on our [support page](https://www.coderabbit.ai/contact-us/support) for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

### CodeRabbit Commands (Invoked using PR comments)

- `@coderabbitai pause` to pause the reviews on a PR.
- `@coderabbitai resume` to resume the paused reviews.
- `@coderabbitai review` to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
- `@coderabbitai full review` to do a full review from scratch and review all the files again.
- `@coderabbitai summary` to regenerate the summary of the PR.
- `@coderabbitai generate docstrings` to [generate docstrings](https://docs.coderabbit.ai/finishing-touches/docstrings) for this PR.
- `@coderabbitai generate sequence diagram` to generate a sequence diagram of the changes in this PR.
- `@coderabbitai resolve` resolve all the CodeRabbit review comments.
- `@coderabbitai configuration` to show the current CodeRabbit configuration for the repository.
- `@coderabbitai help` to get help.

### Other keywords and placeholders

- Add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed.
- Add `@coderabbitai summary` to generate the high-level summary at a specific location in the PR description.
- Add `@coderabbitai` anywhere in the PR title to generate the title automatically.

### CodeRabbit Configuration File (`.coderabbit.yaml`)

- You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository.
- Please see the [configuration documentation](https://docs.coderabbit.ai/guides/configure-coderabbit) for more information.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json`

### Documentation and Community

- Visit our [Documentation](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (3)
src/spider/worker/FunctionNameManager.cpp (1)

15-18: Linear search is functional but may scale poorly

Replacing the hash lookup with a linear scan trades determinism for O(N) look-ups.
If m_name_map ever grows beyond a few hundred items (e.g., >1 k tasks in a plugin), look-up latency could become noticeable at hot call-sites.

-for (auto const& it : m_name_map) {
-    if (it.first == ptr) {
-        return std::string{it.second};
-    }
-}
+if (auto it = std::ranges::find_if(
+        m_name_map,
+        [ptr](auto const& pair) { return pair.first == ptr; }); 
+    it != m_name_map.end())
+{
+    return std::string{it->second};
+}

This keeps the vector but leverages <algorithm> and short-circuits earlier.
If higher throughput is needed later, consider a parallel sorted vector + lower_bound() or a small open-addressing map in std/boost instead.

src/spider/worker/FunctionManager.hpp (2)

50-50: Vector-based map could become a scalability bottleneck

Switching from absl::flat_hash_map to std::vector<std::pair<…>> removes the ABI headache, but it downgrades look-up to O(n).
If the number of registered tasks grows into the hundreds/thousands (not uncommon in plugin-heavy deployments) latency on every invocation will scale linearly. Consider one of the following:

  • keep the std::vector but maintain it sorted and use std::lower_bound → O(log n);
  • or store an additional std::unordered_map<std::string_view,size_t> index;
  • or switch to another header-only open-addressing implementation (e.g., robin_hood::unordered_flat_map) that does not suffer from the Abseil ABI issue.

At the very least, please document the expected upper bound of registered functions so maintainers know the trade-off.


394-398: Linear search is simple but could be micro-optimised

std::ranges::any_of provides clarity, but if you adopt the earlier suggestion of owning a sorted vector, you can switch to std::lower_bound for O(log n) look-ups. No action required if function count is guaranteed small, otherwise worth considering.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8f634bc and 9c50a97.

📒 Files selected for processing (7)
  • examples/quick-start/src/tasks.cpp (0 hunks)
  • src/spider/worker/FunctionManager.cpp (2 hunks)
  • src/spider/worker/FunctionManager.hpp (3 hunks)
  • src/spider/worker/FunctionNameManager.cpp (1 hunks)
  • src/spider/worker/FunctionNameManager.hpp (3 hunks)
  • tests/worker/signal-test.cpp (0 hunks)
  • tests/worker/worker-test.cpp (0 hunks)
💤 Files with no reviewable changes (3)
  • examples/quick-start/src/tasks.cpp
  • tests/worker/signal-test.cpp
  • tests/worker/worker-test.cpp
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/spider/worker/FunctionNameManager.cpp (3)
src/spider/worker/FunctionManager.cpp (2)
  • get_instance (105-108)
  • get_instance (105-105)
src/spider/worker/DllLoader.hpp (1)
  • instance (12-17)
src/spider/worker/FunctionNameManager.hpp (1)
  • ptr (54-54)
src/spider/worker/FunctionManager.cpp (4)
src/spider/worker/FunctionNameManager.cpp (2)
  • get_instance (9-12)
  • get_instance (9-9)
tests/worker/signal-test.cpp (2)
  • get_instance (11-14)
  • get_instance (11-11)
src/spider/worker/DllLoader.hpp (1)
  • instance (12-17)
src/spider/worker/FunctionManager.hpp (4)
  • name (381-387)
  • name (381-381)
  • name (389-389)
  • name (394-394)
src/spider/worker/FunctionNameManager.hpp (1)
src/spider/worker/FunctionManager.hpp (4)
  • name (381-387)
  • name (381-381)
  • name (389-389)
  • name (394-394)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: non-storage-unit-tests (ubuntu-22.04)
  • GitHub Check: non-storage-unit-tests (ubuntu-24.04)
  • GitHub Check: lint
🔇 Additional comments (2)
src/spider/worker/FunctionNameManager.cpp (1)

9-12: Singleton marked noexcept – looks good

Marking get_instance() as noexcept is correct; the call site can now be used in static initialisation without tripping cert-err58-cpp.

src/spider/worker/FunctionManager.cpp (1)

105-108: get_instance() correctly annotated

Adding noexcept aligns with the pattern in the other singletons and removes the need for the previous linter suppression.

Comment on lines +110 to +114
auto FunctionManager::get_function(std::string_view name) const -> Function const* {
for (auto const& pair : m_function_map) {
if (pair.first == name) {
return &pair.second;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Potential dangling std::string_view in stored map – risk of UB

m_function_map stores std::string_view values supplied by caller code.
When register_function_invoker() is called with a temporary or a std::string that goes out of scope, the stored view will dangle.
Subsequent get_function() look-ups will then dereference invalid memory (undefined behaviour).

Suggested fix: own the key.

-using FunctionMap = std::vector<std::pair<std::string_view, Function>>;
+using FunctionMap = std::vector<std::pair<std::string, Function>>;

and in the registrar:

-m_function_map.emplace_back(name, f);
+m_function_map.emplace_back(std::string{name}, f);

If zero-copy is required, document that the caller must pass a string literal or other static storage and enforce it with static_assert(!std::is_same_v<std::decay_t<decltype(name)>, std::string>).

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
auto FunctionManager::get_function(std::string_view name) const -> Function const* {
for (auto const& pair : m_function_map) {
if (pair.first == name) {
return &pair.second;
}
// Change the map alias to own its keys
- using FunctionMap = std::vector<std::pair<std::string_view, Function>>;
+ using FunctionMap = std::vector<std::pair<std::string, Function>>;
// In the registrar where functions are added
- m_function_map.emplace_back(name, f);
+ m_function_map.emplace_back(std::string{name}, f);

Comment on lines +50 to +51
m_name_map.emplace_back(reinterpret_cast<void*>(function_pointer), name);
return true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Same dangling string_view concern as in FunctionManager

name is forwarded unowned into the vector; if the argument is not a string literal the view may dangle after the call. Either:

  1. Change the container to hold std::string, or
  2. Constrain the API so only compile-time string literals are accepted (e.g., via a user-defined literal or const char(&)[N]).

Comment thread src/spider/worker/FunctionNameManager.hpp
Comment on lines 364 to 379
template <class F>
auto register_function(std::string const& name, F f) -> bool {
if (m_function_map.contains(name)) {
auto register_function(std::string_view name, F f) noexcept -> bool {
if (contains(name)) {
return false;
}
return m_function_map
.emplace(
name,
std::bind(
&FunctionInvoker<F>::apply,
std::move(f),
std::placeholders::_1,
std::placeholders::_2
)
m_function_map.emplace_back(
name,
std::bind(
&FunctionInvoker<F>::apply,
std::move(f),
std::placeholders::_1,
std::placeholders::_2
)
.second;
);
return true;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

noexcept + std::string_view here is unsafe and may terminate the process

  1. register_function is declared noexcept, yet:

    • std::ranges::any_of, emplace_back, std::bind, and the allocator inside std::vector can all throw (bad_alloc, etc.).
    • Any exception will invoke std::terminate, hiding the root cause.
  2. std::string_view is stored in the vector.
    If the caller passes anything with a shorter lifetime than static storage (e.g., std::string name returned from a factory), the stored view will dangle → UB.

Proposed fix:

-auto register_function(std::string_view name, F f) noexcept -> bool {
+template <class F>
+auto register_function(std::string_view name, F f) -> bool {
@@
-    m_function_map.emplace_back(
-            name,
+    // Own the key to avoid dangling views
+    m_function_map.emplace_back(
+            std::string{name},
             std::bind(
                     &FunctionInvoker<F>::apply,
                     std::move(f),
                     std::placeholders::_1,
                     std::placeholders::_2
             )
     );
     return true;
 }

(This removes noexcept and takes ownership of the key.)

Alternatively, keep the string_view but constrain the API so only string literals can be passed (harder to police).

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
template <class F>
auto register_function(std::string const& name, F f) -> bool {
if (m_function_map.contains(name)) {
auto register_function(std::string_view name, F f) noexcept -> bool {
if (contains(name)) {
return false;
}
return m_function_map
.emplace(
name,
std::bind(
&FunctionInvoker<F>::apply,
std::move(f),
std::placeholders::_1,
std::placeholders::_2
)
m_function_map.emplace_back(
name,
std::bind(
&FunctionInvoker<F>::apply,
std::move(f),
std::placeholders::_1,
std::placeholders::_2
)
.second;
);
return true;
}
template <class F>
auto register_function(std::string_view name, F f) -> bool {
if (contains(name)) {
return false;
}
m_function_map.emplace_back(
std::string{name},
std::bind(
&FunctionInvoker<F>::apply,
std::move(f),
std::placeholders::_1,
std::placeholders::_2
)
);
return true;
}

Comment on lines +381 to 387
auto register_function_invoker(std::string_view name, Function const& f) -> bool {
if (contains(name)) {
return false;
}
m_function_map.emplace_back(name, f);
return true;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Same lifetime problem applies to register_function_invoker

register_function_invoker stores std::string_view without owning its data. Please apply the same remediation (store std::string or clearly document and enforce that callers pass only string literals).

-m_function_map.emplace_back(name, f);
+m_function_map.emplace_back(std::string{name}, f);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
auto register_function_invoker(std::string_view name, Function const& f) -> bool {
if (contains(name)) {
return false;
}
m_function_map.emplace_back(name, f);
return true;
}
auto register_function_invoker(std::string_view name, Function const& f) -> bool {
if (contains(name)) {
return false;
}
m_function_map.emplace_back(std::string{name}, f);
return true;
}

@sitaowang1998
sitaowang1998 requested review from davidlion and removed request for davidlion May 5, 2025 17:41
@sitaowang1998

Copy link
Copy Markdown
Collaborator Author

Closed to split into separate PRs.

@sitaowang1998
sitaowang1998 deleted the static_map branch May 8, 2025 14:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rework SPIDER_ macros to be safer and avoid clang-tidy issues

1 participant