Skip to content

New string concept #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open

New string concept #39

wants to merge 8 commits into from

Conversation

kimkulling
Copy link
Owner

@kimkulling kimkulling commented Jun 24, 2025

  • Reimplement string
  • Add testcase
  • Introduce hash for comparison

Summary by CodeRabbit

  • New Features

    • Introduced a lightweight, non-owning string view class for efficient string handling.
    • Added a new public type alias for hash identifiers.
  • Refactor

    • Simplified and improved the internal design of the string base class, enhancing memory management and string comparison.
  • Style

    • Improved formatting and consistency in code and comments across several files.
  • Tests

    • Added comprehensive tests for the new string view and updated string base classes.
  • Chores

    • Updated build configuration to include new source and test files.

Copy link
Contributor

coderabbitai bot commented Jun 24, 2025

Walkthrough

The updates introduce a new TStringView header and corresponding unit tests, refactor TStringBase to simplify memory management and interface, and add a public HashId alias. Several files receive formatting and stylistic improvements, while CMake and test sources are updated to include new string-related functionality and tests.

Changes

File(s) Change Summary
CMakeLists.txt Added TStringView.h and new test files to sources; corrected sanitizer variable names; standardized formatting.
include/cppcore/CPPCoreCommon.h Formatting improvements; added public type alias HashId = uint64_t in namespace cppcore.
include/cppcore/Common/Sort.h Documentation comment formatting adjustment.
include/cppcore/Common/TStringBase.h Major refactor: simplified memory management, interface changes, removed Allocator and old TStringView, added methods, changed equality logic.
include/cppcore/Common/TStringView.h New file: defines lightweight, non-owning TStringView<T> class template.
include/cppcore/Memory/MemUtils.h Removed unnecessary <string.h> include.
test/common/TStringBaseTest.cpp New test: validates TStringBase<char> creation, set, reset, and equality.
test/common/TStringViewTest.cpp New test: validates TStringView<char> construction and iteration.
test/container/THashMapTest.cpp Style: switched to brace-based initialization, compacted function calls.
test/container/TQueueTest.cpp Style: removed trailing blank line.
test/common/HashTest.cpp Removed empty protected section.
test/common/TOptionalTest.cpp Changed constexpr variable initialization from copy to direct list initialization.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Unit Test
    participant TStringBase as TStringBase<char>
    participant TStringView as TStringView<char>

    Test->>TStringBase: Create default instance
    Test->>TStringBase: set(ptr, size)
    Test->>TStringBase: Check size(), c_str(), equality
    Test->>TStringBase: reset()
    Test->>TStringBase: Check size() == 0

    Test->>TStringView: Create with ptr, len
    Test->>TStringView: begin(), end()
    Test->>TStringView: Iterate and check elements
Loading

Poem

In the garden of code where string views bloom,
A rabbit hops with a buffer and room.
Hash IDs now sparkle, equality’s swift,
With tests that ensure no logic will drift.
Refactored and tidy, the carrots align—
Hooray for clean strings and code that’s divine!
🥕


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d204826 and 76bd06a.

📒 Files selected for processing (1)
  • include/cppcore/Common/TStringBase.h (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • include/cppcore/Common/TStringBase.h
✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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 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 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 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 for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
include/cppcore/Common/TStringView.h (1)

33-34: Add a description to the @brief tag.

The documentation comment is missing a description. Please add a brief explanation of what TStringView does.

Apply this diff to add documentation:

-/// @brief 
+/// @brief Provides a lightweight, non-owning view over a contiguous sequence of elements.
include/cppcore/Common/TStringBase.h (1)

145-152: Consider the risk of hash collisions in equality comparison.

The equality operator relies solely on hash comparison after size check. While hash collisions are rare, they can occur. Consider adding actual data comparison for critical use cases or document this behavior.

For complete correctness, consider comparing the actual string data:

 template <class T>
 inline bool TStringBase<T>::operator == (const TStringBase<T> &rhs) const {
     if (rhs.mSize != mSize) {
         return false;
     }
 
-    
-    return mHashId == rhs.mHashId;
+    if (mHashId != rhs.mHashId) {
+        return false;
+    }
+    
+    // Compare actual data to handle hash collisions
+    const T* lhsData = c_str();
+    const T* rhsData = rhs.c_str();
+    return memcmp(lhsData, rhsData, mSize * sizeof(T)) == 0;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dc9135c and af8eff6.

📒 Files selected for processing (10)
  • CMakeLists.txt (2 hunks)
  • include/cppcore/CPPCoreCommon.h (2 hunks)
  • include/cppcore/Common/Sort.h (1 hunks)
  • include/cppcore/Common/TStringBase.h (2 hunks)
  • include/cppcore/Common/TStringView.h (1 hunks)
  • include/cppcore/Memory/MemUtils.h (0 hunks)
  • test/common/TStringBaseTest.cpp (1 hunks)
  • test/common/TStringViewTest.cpp (1 hunks)
  • test/container/THashMapTest.cpp (1 hunks)
  • test/container/TQueueTest.cpp (0 hunks)
💤 Files with no reviewable changes (2)
  • test/container/TQueueTest.cpp
  • include/cppcore/Memory/MemUtils.h
🔇 Additional comments (12)
include/cppcore/Common/Sort.h (1)

179-181: Documentation spacing tweak LGTM
The alignment change after @tparam improves readability; no functional impact.

CMakeLists.txt (2)

79-79: LGTM: Build system integration for new string view class.

The addition of TStringView.h to the common source group properly integrates the new string view functionality into the build system.


141-142: LGTM: Test integration for new string classes.

The addition of test files for both TStringView and TStringBase ensures proper test coverage for the new string functionality.

test/container/THashMapTest.cpp (1)

33-34: LGTM: Consistent formatting improvements.

The changes consistently use brace initialization and improve spacing in macros, enhancing code style consistency without affecting functionality.

Also applies to: 42-42, 45-45, 47-49, 53-53, 58-58

include/cppcore/CPPCoreCommon.h (2)

48-61: LGTM: Macro formatting improvements.

The formatting improvements to DLL export/import macros and stack allocation macros enhance readability while maintaining functionality.


110-111: LGTM: Well-designed hash identifier type.

The introduction of HashId as a uint64_t alias provides a standardized type for hash identifiers across the codebase, supporting the new string functionality with consistent hash-based operations.

test/common/TStringViewTest.cpp (2)

33-42: LGTM: Well-structured construction test.

The test correctly validates TStringView construction and iterator functionality by checking that the distance between begin and end iterators matches the expected size.


44-52: LGTM: Comprehensive iteration test.

The test thoroughly validates iterator functionality by comparing each character accessed through the TStringView with the original string data, ensuring correct element access behavior.

test/common/TStringBaseTest.cpp (2)

33-38: LGTM: Effective equality comparison test.

The test correctly validates TStringBase construction and equality comparison by creating two strings with the same content through different methods and verifying they compare as equal.


40-49: LGTM: Comprehensive functionality test.

The test thoroughly validates the core TStringBase operations including default initialization, setting data, size/capacity queries, content verification, and reset functionality. The default capacity of 256 appears reasonable for a string implementation.

include/cppcore/Common/TStringView.h (1)

83-86: Verify handling of null pointer arithmetic.

The end() method performs pointer arithmetic without checking if mPtr is null. While null + 0 is well-defined, null + non-zero is undefined behavior.

Consider adding a check or documenting that the constructor should ensure mPtr is non-null when mLen > 0.

include/cppcore/Common/TStringBase.h (1)

128-142: ```shell
#!/bin/bash

Display constructors, set, copyFrom, and c_str implementations

sed -n '1,300p' include/cppcore/Common/TStringBase.h


</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 7

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between af8eff6 and 7db585e.

📒 Files selected for processing (6)
  • CMakeLists.txt (6 hunks)
  • include/cppcore/Common/TStringBase.h (2 hunks)
  • include/cppcore/Common/TStringView.h (1 hunks)
  • test/common/HashTest.cpp (0 hunks)
  • test/common/TOptionalTest.cpp (1 hunks)
  • test/common/TStringViewTest.cpp (1 hunks)
💤 Files with no reviewable changes (1)
  • test/common/HashTest.cpp
✅ Files skipped from review due to trivial changes (2)
  • test/common/TOptionalTest.cpp
  • include/cppcore/Common/TStringView.h
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/common/TStringViewTest.cpp
  • CMakeLists.txt
🔇 Additional comments (4)
include/cppcore/Common/TStringBase.h (4)

104-106: LGTM!

The capacity method implementation is correct and straightforward.


109-115: LGTM!

The c_str() method correctly returns the appropriate buffer pointer based on whether dynamic allocation is used.


81-83: LGTM!

The destructor correctly delegates cleanup to the clear() method, following good RAII practices.


99-101: LGTM!

The size method implementation is correct and straightforward.

Comment on lines 118 to 125
inline void TStringBase<T>::clear() {
if (mStringBuffer != nullptr) {
delete [] mStringBuffer;
mStringBuffer = nullptr;
mCapacity = InitSize;
}
mSize = 0;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Reset hash ID when clearing string data.

The clear() method should also reset the hash ID to maintain consistency.

 inline void TStringBase<T>::clear() {
     if (mStringBuffer != nullptr) {
         delete [] mStringBuffer;
         mStringBuffer = nullptr;
         mCapacity = InitSize;
     }
     mSize = 0;
+    mHashId = 0;
 }
📝 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
inline void TStringBase<T>::clear() {
if (mStringBuffer != nullptr) {
delete [] mStringBuffer;
mStringBuffer = nullptr;
mCapacity = InitSize;
}
mSize = 0;
}
inline void TStringBase<T>::clear() {
if (mStringBuffer != nullptr) {
delete [] mStringBuffer;
mStringBuffer = nullptr;
mCapacity = InitSize;
}
mSize = 0;
mHashId = 0;
}
🤖 Prompt for AI Agents
In include/cppcore/Common/TStringBase.h around lines 118 to 125, the clear()
method deletes the string buffer and resets size and capacity but does not reset
the hash ID. Modify the clear() method to also reset the hash ID member variable
to its initial state to ensure consistency after clearing the string data.

Comment on lines +128 to 142
inline void TStringBase<T>::copyFrom(TStringBase<T> &base, const T *ptr, size_t size) {
if (ptr != nullptr) {
T *targetPtr = base.mBuffer;

if (size > 0) {
if (size > base.mCapacity) {
base.mStringBuffer = new T[size];
base.mCapacity = size;
targetPtr = base.mStringBuffer;
}
memcpy(targetPtr, ptr, size);
base.mSize = size;
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Address unsafe memory operations and missing null termination.

The copyFrom method has several critical issues:

  1. Using memcpy for potentially non-trivial types is unsafe
  2. No null termination for C-style strings
  3. Missing size validation
 inline void TStringBase<T>::copyFrom(TStringBase<T> &base, const T *ptr, size_t size) {
+    static_assert(std::is_trivially_copyable_v<T>, "T must be trivially copyable");
     if (ptr != nullptr) {
         T *targetPtr = base.mBuffer;
         
         if (size > 0) {
-            if (size > base.mCapacity) {
-                base.mStringBuffer = new T[size];
-                base.mCapacity = size;
+            size_t requiredCapacity = size + 1; // +1 for null terminator
+            if (requiredCapacity > base.mCapacity) {
+                base.mStringBuffer = new T[requiredCapacity];
+                base.mCapacity = requiredCapacity;
                 targetPtr = base.mStringBuffer;
             }
             memcpy(targetPtr, ptr, size);
+            targetPtr[size] = T{}; // Null termination
             base.mSize = size;
         }
     }
 }
📝 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
inline void TStringBase<T>::copyFrom(TStringBase<T> &base, const T *ptr, size_t size) {
if (ptr != nullptr) {
T *targetPtr = base.mBuffer;
if (size > 0) {
if (size > base.mCapacity) {
base.mStringBuffer = new T[size];
base.mCapacity = size;
targetPtr = base.mStringBuffer;
}
memcpy(targetPtr, ptr, size);
base.mSize = size;
}
}
}
inline void TStringBase<T>::copyFrom(TStringBase<T> &base, const T *ptr, size_t size) {
static_assert(std::is_trivially_copyable_v<T>, "T must be trivially copyable");
if (ptr != nullptr) {
T *targetPtr = base.mBuffer;
if (size > 0) {
size_t requiredCapacity = size + 1; // +1 for null terminator
if (requiredCapacity > base.mCapacity) {
base.mStringBuffer = new T[requiredCapacity];
base.mCapacity = requiredCapacity;
targetPtr = base.mStringBuffer;
}
memcpy(targetPtr, ptr, size);
targetPtr[size] = T{}; // Null termination
base.mSize = size;
}
}
}
🤖 Prompt for AI Agents
In include/cppcore/Common/TStringBase.h around lines 128 to 142, the copyFrom
method uses memcpy which is unsafe for non-trivial types, lacks null termination
for C-style strings, and does not validate the size properly. Replace memcpy
with element-wise copy or std::copy to safely handle non-trivial types, ensure
the copied string is null-terminated by adding a terminator if applicable, and
add checks to validate that size does not exceed capacity or other logical
constraints before copying.

Comment on lines +75 to 78
inline TStringBase<T>::TStringBase(const T *pPtr, size_t size) {
copyFrom(*this, pPtr, size);
mHashId = THash<HashId>::toHash(pPtr, mSize);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix hash calculation in constructor.

The hash is calculated using the input pointer pPtr and mSize before copyFrom completes. This could result in incorrect hash values since mSize may not be properly set yet, and the hash should be calculated from the stored data, not the input data.

 inline TStringBase<T>::TStringBase(const T *pPtr, size_t size) {
     copyFrom(*this, pPtr, size);
-    mHashId = THash<HashId>::toHash(pPtr, mSize);
+    mHashId = THash<HashId>::toHash(c_str(), mSize);
 }
📝 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
inline TStringBase<T>::TStringBase(const T *pPtr, size_t size) {
copyFrom(*this, pPtr, size);
mHashId = THash<HashId>::toHash(pPtr, mSize);
}
inline TStringBase<T>::TStringBase(const T *pPtr, size_t size) {
copyFrom(*this, pPtr, size);
mHashId = THash<HashId>::toHash(c_str(), mSize);
}
🤖 Prompt for AI Agents
In include/cppcore/Common/TStringBase.h around lines 75 to 78, the constructor
calculates the hash using pPtr and mSize before copyFrom sets mSize and copies
the data. To fix this, move the hash calculation to after the copyFrom call and
use the internal data pointer and mSize to compute the hash, ensuring the hash
reflects the stored data correctly.

Copy link

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.

2 participants