Skip to content

Feature/add algo #33

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

Merged
merged 15 commits into from
Feb 19, 2025
Merged

Feature/add algo #33

merged 15 commits into from
Feb 19, 2025

Conversation

kimkulling
Copy link
Owner

@kimkulling kimkulling commented Feb 18, 2025

  • Add distance + test

Summary by CodeRabbit

  • New Features

    • Introduced a new container utility to compute element distances.
    • Added tests for filesystem functionality.
    • Added unit tests for TAlgorithm and TArray classes.
  • Refactor

    • Streamlined container operations by removing obsolete sorting logic.
    • Standardized naming conventions and formatting across various modules for enhanced clarity.
  • Tests

    • Expanded the test suite with new cases covering container behaviors and filesystem functionality to boost overall reliability.
    • Added a new test case for verifying copy functionality in TStaticArray.

Copy link
Contributor

coderabbitai bot commented Feb 18, 2025

Walkthrough

This pull request updates the cppcore project by enhancing unit testing configurations and standardizing naming conventions across various classes. The CMakeLists.txt file is modified to include new test source files and correct source group naming. Key changes involve the introduction of a distance calculation function in TAlgorithm, the removal of sorting logic from TArray, and the renaming of member variables in multiple classes for clarity. New test cases for TAlgorithm, TStaticArray, and FileSystem are also added to validate their functionalities.

Changes

File(s) Change Summary
CMakeLists.txt Enhances unit testing configuration: adds new test sources (test/container/TAlgorithmTest.cpp and test/io/FileSystemTest.cpp), updates source groups (e.g., changes code\\IO to code\\io), and corrects file path casing.
include/.../TAlgorithm.h
test/container/TAlgorithmTest.cpp
Adds a new function template distance in the cppcore namespace and a corresponding test case to validate iterator distance calculation.
include/.../TArray.h
test/container/TArrayTest.cpp
Removes SortMode enum and sorting logic; renames find to linearSearch and updates member variable names for clarity; test cases updated accordingly.
code/Random/RandomGenerator.cpp
include/.../RandomGenerator.h
Renames member variable from m_type to mType for consistency in the RandomGenerator class.
include/.../THashMap.h
include/.../TList.h
include/.../TQueue.h
include/.../TStaticArray.h
Standardizes naming conventions: renames several member variables and updates formatting in container classes.
include/.../FileSystem.h
test/io/FileSystemTest.cpp
Renames FileSystem member variables and fixes source group naming; adds a new unit test to verify free disk space retrieval.
include/.../TDefaultAllocator.h
include/.../TPoolAllocator.h
include/.../TStackAllocator.h
Applies naming standardizations and streamlines memory allocator classes by defaulting constructor/destructor implementations and renaming member variables.
test/container/TStaticArrayTest.cpp Adds a new copyTest that checks the copy semantics of the TStaticArray class.

Sequence Diagram(s)

sequenceDiagram
    participant Runner as Test Runner
    participant Array as TArray<float>
    participant Algo as TAlgorithm
    Runner->>Array: Create instance and add elements
    Runner->>Algo: Call distance(begin, end)
    Algo-->>Runner: Return computed distance
    Runner->>Runner: Assert distance equals expected value
Loading
sequenceDiagram
    participant Runner as Test Runner
    participant FS as FileSystem
    Runner->>FS: Instantiate FileSystem("c:\\")
    Runner->>FS: Call getFreeDiskSpace()
    FS-->>Runner: Return disk space pointer
    Runner->>Runner: Assert pointer is not null
Loading
sequenceDiagram
    participant Runner as Test Runner
    participant StaticArr as TStaticArray<int, 4>
    Runner->>StaticArr: Create and initialize array
    Runner->>StaticArr: Copy array using assignment operator
    StaticArr-->>Runner: Return copied array
    Runner->>Runner: Verify elements match original array
Loading

Possibly related PRs

Poem

I'm hopping through the code all day,
Adjusting names in a bunny way.
Tests now run with a joyful cheer,
Code and tests are crystal clear.
With each change, my ears perk high 🐰,
Celebrating hops that never lie!
Happy coding under the bright blue sky!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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.

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. (Beta)
  • @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: 3

🧹 Nitpick comments (3)
test/container/TAlgorithmTest.cpp (1)

13-27: Enhance test coverage with additional test cases.

Consider adding test cases for:

  • Empty array
  • Single element array
  • Invalid iterator combinations
+TEST_F(TAlgorithmTest, distanceEmptyTest) {
+    TArray<float> theArray;
+    size_t dist = distance(theArray.begin(), theArray.end());
+    EXPECT_EQ(dist, 0u);
+}
+
+TEST_F(TAlgorithmTest, distanceSingleElementTest) {
+    TArray<float> theArray;
+    theArray.add(1.0f);
+    size_t dist = distance(theArray.begin(), theArray.end());
+    EXPECT_EQ(dist, 1u);
+}
include/cppcore/Container/TAlgorithm.h (2)

29-34: Improve documentation for the distance function.

The documentation should specify:

  • Requirements for the iterator type (e.g., random access)
  • Behavior for invalid iterator combinations
  • Return value semantics
-/// @brief Function to calulate the distance between two iterators.
-/// @tparam TIt The container iterator
-/// @param begin    The first container iterator 
-/// @param end      The second container iterator
-/// @return The distance between the two iterators.
+/// @brief Calculates the distance between two iterators.
+/// @tparam TIt    The iterator type (must support random access)
+/// @param begin   The first iterator position
+/// @param end     The second iterator position
+/// @return        The number of elements between begin and end
+/// @note          Requires random access iterators that support subtraction
+/// @pre           begin must be less than or equal to end

35-39: Consider relaxing the iterator order assertion.

The current assertion requires begin < end, which might be too restrictive. For bidirectional iterators, you might want to allow begin == end.

 template<class TIt>
 inline size_t distance(TIt begin, TIt end) {
-    assert(begin < end);
+    assert(begin <= end);
     const size_t distance = end - begin;
     return distance;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d13d7be and 82bb610.

📒 Files selected for processing (5)
  • CMakeLists.txt (1 hunks)
  • include/cppcore/Container/TAlgorithm.h (1 hunks)
  • include/cppcore/Container/TArray.h (12 hunks)
  • test/container/TAlgorithmTest.cpp (1 hunks)
  • test/container/TArrayTest.cpp (3 hunks)
🧰 Additional context used
🪛 GitHub Actions: CMake
include/cppcore/Container/TArray.h

[error] 328-328: 'm_Size' was not declared in this scope; did you mean 'mSize'?


[error] 524-524: 'm_Size' was not declared in this scope; did you mean 'mSize'?

🔇 Additional comments (3)
test/container/TAlgorithmTest.cpp (1)

25-27: Verify the distance from end to begin.

The test prints the distance from end to begin but doesn't verify the result. This could mask potential issues.

Add an assertion to verify the expected distance:

 dist = distance(theArray.end(), theArray.begin());
-std::cout << "dist = " << dist << "\n";
+EXPECT_EQ(dist, 0u);
test/container/TArrayTest.cpp (1)

36-37: LGTM! Good use of constexpr.

The change from static const to static constexpr for test data is a good improvement, making the array size and data available at compile-time.

CMakeLists.txt (1)

142-149: New Test Addition for TAlgorithm Functionality

The new test source file test/container/TAlgorithmTest.cpp is now included in the cppcore_container_test_src list. This is an important addition to verify the distance algorithm defined in TAlgorithm.h. Please ensure that the new test file provides comprehensive coverage for the distance calculation logic and integrates seamlessly with the remainder of the test suite.

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: 4

🔭 Outside diff range comments (2)
include/cppcore/Container/TStaticArray.h (1)

144-155: ⚠️ Potential issue

Fix type inconsistency and missing bounds check in assignment operator.

The assignment operator uses unsigned int instead of size_t and is missing a bounds check.

 template <class T, size_t len>
 inline TStaticArray<T, len> &TStaticArray<T, len>::operator=(const TStaticArray<T, len> &rhs) {
     if (*this == rhs) {
         return *this;
     }
 
-    for (unsigned int i = 0; i < m_len; ++i) {
+    for (size_t i = 0; i < mLen; ++i) {
+        assert(i < len);
         mArray[i] = rhs.mArray[i];
     }
 
     return *this;
 }
include/cppcore/Memory/TStackAllocator.h (1)

281-283: ⚠️ Potential issue

Fix early return in remove method.

The method returns true before checking if the item was actually removed, which could lead to incorrect behavior.

Apply this diff to fix the early return:

-        delete current;
-        --mNumItems;
-        found = true;
-        return true;
+        delete current;
+        --mNumItems;
+        found = true;
🧹 Nitpick comments (4)
include/cppcore/Memory/TPoolAllocator.h (1)

103-106: LGTM! Member variable renaming improves consistency.

The renaming of member variables from m_* to m* format aligns with modern C++ naming conventions. The initialization and cleanup in constructors and destructor are properly implemented.

Consider using std::unique_ptr for mPool to leverage RAII and automatically handle memory cleanup:

-T *mPool;
+std::unique_ptr<T[]> mPool;

-mPool = new T[mPoolsize];
+mPool = std::make_unique<T[]>(mPoolsize);

-delete[] mPool;
+// No explicit deletion needed with unique_ptr

Also applies to: 109-112, 117-122, 125-125

include/cppcore/Container/TStaticArray.h (3)

83-86: Consider initializing array elements in default constructor.

The default constructor only initializes mLen but leaves array elements uninitialized, which could lead to undefined behavior if accessed before assignment.

Consider initializing array elements to a default value:

 template <class T, size_t len>
 inline TStaticArray<T, len>::TStaticArray() :
         mLen(len) {
-    // empty
+    std::fill_n(mArray, len, T());
 }

94-100: Optimize copy constructor using std::copy.

The manual loop in the copy constructor can be replaced with std::copy for better performance and readability.

 template <class T, size_t len>
 inline TStaticArray<T, len>::TStaticArray(const TStaticArray<T, len> &rhs) :
         mLen(rhs.mLen) {
-    for (size_t i = 0; i < mLen; ++i) {
-        mArray[i] = rhs.mArray[i];
-    }
+    std::copy(rhs.mArray, rhs.mArray + len, mArray);
 }

109-114: Consider renaming memset to avoid confusion with C's memset.

The method name memset could be misleading as it's not using C's memset. Consider a more descriptive name like fillWith or setAll.

 template <class T, size_t len>
-inline void TStaticArray<T, len>::memset(T value) {
+inline void TStaticArray<T, len>::fillWith(T value) {
     for (size_t i = 0; i < mLen; ++i) {
         mArray[i] = value;
     }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 82bb610 and 4c9528a.

📒 Files selected for processing (11)
  • code/Random/RandomGenerator.cpp (1 hunks)
  • include/cppcore/Container/TArray.h (12 hunks)
  • include/cppcore/Container/THashMap.h (5 hunks)
  • include/cppcore/Container/TList.h (9 hunks)
  • include/cppcore/Container/TQueue.h (4 hunks)
  • include/cppcore/Container/TStaticArray.h (2 hunks)
  • include/cppcore/IO/FileSystem.h (2 hunks)
  • include/cppcore/Memory/TDefaultAllocator.h (1 hunks)
  • include/cppcore/Memory/TPoolAllocator.h (2 hunks)
  • include/cppcore/Memory/TStackAllocator.h (3 hunks)
  • include/cppcore/Random/RandomGenerator.h (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • include/cppcore/Container/TQueue.h
  • include/cppcore/Random/RandomGenerator.h
  • include/cppcore/Container/TList.h
🔇 Additional comments (11)
include/cppcore/Memory/TPoolAllocator.h (4)

139-142: LGTM! Member variable initialization is safe and consistent.

The member variables are properly renamed and safely initialized to prevent undefined behavior.

Also applies to: 147-150, 156-159


171-184: Add nullptr check for mPool in alloc method.

The alloc method should verify that mPool is not null before dereferencing it.

Add a safety check:

 if (mCurrent->mCurrentIdx == mCurrent->mPoolsize) {
     resize(mCurrent->mPoolsize);
 }

+if (mCurrent->mPool == nullptr) {
+    return nullptr;
+}

 T *ptr = &mCurrent->mPool[mCurrent->mCurrentIdx];

258-278: Validate growth size in resize method.

The resize method should ensure the growth size is not zero to prevent allocation of empty pools.

Add size validation:

 template <class T>
 inline void TPoolAllocator<T>::resize(size_t growSize) {
+    if (growSize == 0) {
+        return;
+    }
+
     if (nullptr != mCurrent) {
         if (growSize < mCurrent->mPoolsize) {

250-255: Add null check in dumpAllocations method.

The dumpAllocations method assumes mCurrent is not null when accessing mCurrentIdx.

Add a safety check:

 template <class T>
 inline void TPoolAllocator<T>::dumpAllocations(std::string &allocs) {
     allocs.clear();
     allocs += "Number allocations = ";
+    if (mCurrent == nullptr) {
+        allocs += "0";
+    } else {
         allocs += std::to_string(mCurrent->mCurrentIdx);
+    }
     allocs += "\n";
 }
include/cppcore/Memory/TDefaultAllocator.h (2)

40-40: LGTM! Good use of modern C++ features.

Using = default for the constructor explicitly indicates the intent to use compiler-generated implementation, which is appropriate for this allocator class. This change aligns with modern C++ best practices.


43-43:

✅ Verification successful

LGTM! Proper memory management pattern.

Using = default for the destructor is correct as memory cleanup is handled explicitly through the release method. The class correctly follows RAII principles by delegating memory management to the container classes.

Let's verify that memory management is handled correctly in the container classes that use this allocator:


🏁 Script executed:

#!/bin/bash
# Description: Check for memory management in container classes using TDefaultAllocator

# Search for container classes using TDefaultAllocator
rg -A 5 "TDefaultAllocator" --type cpp

# Search for proper memory cleanup in destructors
ast-grep --pattern 'class $_ {
  $$$
  ~$_() {
    $$$
  }
  $$$
}'

Length of output: 7270


Approval: Memory Management Verified in TDefaultAllocator

  • The change to use ~TDefaultAllocator() = default; is appropriate since memory cleanup is handled explicitly through the release method.
  • Container classes (e.g., TQueue, THashMap, TList, and TArray) that use this allocator do not require additional destructor logic in the allocator.
  • The class design correctly adheres to RAII principles, enabling container classes to manage memory properly.

LGTM!

code/Random/RandomGenerator.cpp (3)

82-82: LGTM!

The member variable renaming from m_type to mType follows modern C++ naming conventions while maintaining the same functionality.


88-88: LGTM!

The member variable reference update is consistent with the constructor change and maintains the same functionality.


90-90:

❓ Verification inconclusive

Verify naming convention consistency across the codebase.

The member variable reference update is consistent with previous changes. Let's verify that this naming convention is consistently applied across the codebase.


🏁 Script executed:

#!/bin/bash
# Description: Check for any remaining instances of the old naming convention (m_type)
# and verify consistency of the new naming convention (mType) across the codebase.

echo "Checking for any remaining instances of old naming convention (m_type)..."
rg "m_type" --type cpp --type hpp --type h

echo "Verifying consistency of new naming convention (mType)..."
rg "mType" --type cpp --type hpp --type h

Length of output: 422


Action: Verify Consistent Naming Convention for Member Variables

The update from m_type to mType appears correctly implemented and consistent with previous changes. However, the initial verification script encountered errors due to the unsupported file type flag (hpp). To ensure thorough verification, please run an updated search using a glob pattern instead. For example:

#!/bin/bash
echo "Checking for any remaining instances of old naming convention (m_type)..."
rg "m_type" --glob "*.cpp" --glob "*.hpp" --glob "*.h"

echo "Verifying consistency of new naming convention (mType)..."
rg "mType" --glob "*.cpp" --glob "*.hpp" --glob "*.h"

If these searches confirm that no traces of the old naming style remain, you can confidently consider this change approved. Please verify the outputs manually.

include/cppcore/Container/TStaticArray.h (1)

78-79: LGTM! Member variable renaming follows modern C++ conventions.

The renaming from m_array to mArray and m_len to mLen improves consistency with modern C++ naming conventions.

include/cppcore/Container/TArray.h (1)

454-462: LGTM! Method renaming improves clarity.

Renaming find to linearSearch makes the search algorithm explicit and improves code readability.

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: 0

🧹 Nitpick comments (1)
test/container/TStaticArrayTest.cpp (1)

97-107: LGTM! Consider enhancing test coverage.

The basic copy test is a good start, but could be strengthened with additional test cases.

Consider adding the following test scenarios:

  1. Verify deep copy by modifying source array after copy
  2. Test with different values per element
  3. Test with different data types (e.g., custom objects)

Example enhancement:

TEST_F(TStaticArrayTest, copyDeepTest) {
    TStaticArray<int, 4> arr;
    for (size_t i = 0; i < 4; ++i) {
        arr[i] = i;  // Different values
    }
    
    TStaticArray<int, 4> copy_arr = arr;
    
    // Modify source array
    arr[0] = 99;
    
    // Verify deep copy (copy_arr should be unchanged)
    EXPECT_EQ(0, copy_arr[0]);
    for (size_t i = 1; i < 4; ++i) {
        EXPECT_EQ(i, copy_arr[i]);
    }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4c9528a and 4e57547.

📒 Files selected for processing (4)
  • include/cppcore/Container/TStaticArray.h (2 hunks)
  • include/cppcore/IO/FileSystem.h (3 hunks)
  • test/container/TAlgorithmTest.cpp (1 hunks)
  • test/container/TStaticArrayTest.cpp (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • test/container/TAlgorithmTest.cpp
  • include/cppcore/Container/TStaticArray.h
  • include/cppcore/IO/FileSystem.h

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: 1

🧹 Nitpick comments (2)
test/IO/FileSystemTest.cpp (2)

27-27: Remove duplicate namespace declaration.

The using namespace cppcore statement appears twice. Remove one of them to avoid redundancy.

using namespace cppcore;

#include <gtest/gtest.h>

-using namespace cppcore;

Also applies to: 31-31


33-33: Consider utilizing the test fixture for common setup.

The empty test fixture could be used to set up common test data or handle platform-specific paths.

-class FileSystemTest : public testing::Test {};
+class FileSystemTest : public testing::Test {
+protected:
+    std::string GetTestPath() {
+#ifdef _WIN32
+        return "c:\\";
+#else
+        return "/";
+#endif
+    }
+};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4e57547 and adcc40b.

📒 Files selected for processing (4)
  • CMakeLists.txt (2 hunks)
  • code/Random/RandomGenerator.cpp (1 hunks)
  • include/cppcore/IO/FileSystem.h (2 hunks)
  • test/IO/FileSystemTest.cpp (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • code/Random/RandomGenerator.cpp
  • CMakeLists.txt
  • include/cppcore/IO/FileSystem.h
🔇 Additional comments (1)
test/IO/FileSystemTest.cpp (1)

1-40: Verify PR scope and objectives.

This file implements filesystem tests, but the PR objectives mention adding a distance calculation feature. Please clarify if this file is intended to be part of this PR.

Likely an incorrect or invalid review comment.

Comment on lines 35 to 39
TEST_F(FileSystemTest, getFreeDiskSpaceTest) {
FileSystem fs("c:\\");
FSSpace *space = fs.getFreeDiskSpace();
EXPECT_NE(space, nullptr);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🛠️ Refactor suggestion

🧩 Analysis chain

Enhance test coverage and handle memory management.

The current test only verifies that the pointer is non-null. Consider:

  1. Testing actual disk space values
  2. Handling memory management of the returned pointer
  3. Making the test platform-independent

Here's a more comprehensive test implementation:

-TEST_F(FileSystemTest, getFreeDiskSpaceTest) {
-    FileSystem fs("c:\\");
-    FSSpace *space = fs.getFreeDiskSpace();
-    EXPECT_NE(space, nullptr);
-}
+TEST_F(FileSystemTest, getFreeDiskSpaceTest) {
+    FileSystem fs(GetTestPath());
+    FSSpace *space = fs.getFreeDiskSpace();
+    ASSERT_NE(space, nullptr);
+    
+    // Verify disk space values are reasonable
+    EXPECT_GT(space->TotalSpace, 0);
+    EXPECT_GE(space->FreeSpace, 0);
+    EXPECT_LE(space->FreeSpace, space->TotalSpace);
+    
+    // Clean up
+    delete space;
+}

Additionally, consider adding test cases for:

  • Invalid paths
  • Network paths
  • Removable drives

Let me verify the FSSpace structure and memory ownership:


🏁 Script executed:

#!/bin/bash
# Search for FSSpace definition and memory management patterns
rg -A 5 "struct.*FSSpace" .
rg "getFreeDiskSpace.*\(" .

Length of output: 685


Action Required: Update FSSpace field references and enhance test coverage

The suggested diff snippet should be updated to reflect the actual fields of the FSSpace structure—instead of using TotalSpace and FreeSpace, it should use capacity and free. Additionally, the test should continue to improve platform independence and memory management, while considering additional edge cases such as invalid paths, network paths, and removable drives.

Suggested updates:

  • Replace the hard-coded "c:\\" with a platform-independent path (e.g., using a helper such as GetTestPath()).
  • Verify the disk space values using the correct fields:
    • Use EXPECT_GT(space->capacity, 0);
    • Use EXPECT_GE(space->free, 0);
    • Use EXPECT_LE(space->free, space->capacity);
  • Ensure proper memory cleanup by deleting the allocated pointer.
  • Consider adding additional test cases for scenarios like invalid paths, network paths, and removable drives.

Rewritten diff snippet:

-TEST_F(FileSystemTest, getFreeDiskSpaceTest) {
-    FileSystem fs("c:\\");
-    FSSpace *space = fs.getFreeDiskSpace();
-    EXPECT_NE(space, nullptr);
-}
+TEST_F(FileSystemTest, getFreeDiskSpaceTest) {
+    FileSystem fs(GetTestPath());
+    FSSpace *space = fs.getFreeDiskSpace();
+    ASSERT_NE(space, nullptr);
+    
+    // Verify disk space values are reasonable
+    EXPECT_GT(space->capacity, 0);
+    EXPECT_GE(space->free, 0);
+    EXPECT_LE(space->free, space->capacity);
+    
+    // Clean up memory
+    delete space;
+}
📝 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
TEST_F(FileSystemTest, getFreeDiskSpaceTest) {
FileSystem fs("c:\\");
FSSpace *space = fs.getFreeDiskSpace();
EXPECT_NE(space, nullptr);
}
TEST_F(FileSystemTest, getFreeDiskSpaceTest) {
FileSystem fs(GetTestPath());
FSSpace *space = fs.getFreeDiskSpace();
ASSERT_NE(space, nullptr);
// Verify disk space values are reasonable
EXPECT_GT(space->capacity, 0);
EXPECT_GE(space->free, 0);
EXPECT_LE(space->free, space->capacity);
// Clean up memory
delete space;
}

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: 0

🧹 Nitpick comments (2)
include/cppcore/Container/TArray.h (2)

373-394: Consider using std::copy for array copying in reserve().

The manual element-by-element copying could be replaced with std::copy for better readability and potential performance improvements.

-    if (mSize > 0u) {
-        tmp = mAllocator.alloc(mSize);
-        for (size_t i = 0u; i < mSize; ++i) {
-            tmp[i] = mData[i];
-        }
+    if (mSize > 0u) {
+        tmp = mAllocator.alloc(mSize);
+        std::copy(mData, mData + mSize, tmp);
     }

227-233: Consider pre-calculating capacity growth.

The capacity growth calculation could be moved to a separate method to improve readability and maintainability.

+    private:
+        size_t calculateNewCapacity(size_t requiredSize) const {
+            return mCapacity + Details::getGrowing(requiredSize);
+        }

     public:
         void add(const T &value) {
             if (mSize + 1 > mCapacity) {
-                const size_t newcapa = Details::getGrowing(mSize + 1);
-                reserve(mCapacity + newcapa);
+                reserve(calculateNewCapacity(mSize + 1));
             }
             mData[mSize] = value;
             ++mSize;
         }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 999b581 and 47c007f.

📒 Files selected for processing (1)
  • include/cppcore/Container/TArray.h (13 hunks)
🔇 Additional comments (4)
include/cppcore/Container/TArray.h (4)

183-185: LGTM! Member variable naming is now consistent.

The member variables have been renamed to follow a consistent naming convention with the m prefix, improving code readability.


149-152: LGTM! Method renaming improves clarity.

The find method has been appropriately renamed to linearSearch, which better describes its implementation and complexity characteristics.

Also applies to: 454-462


170-170: LGTM! Return type fix for data() method.

The return type has been correctly changed from T to T* to properly reflect that it returns a pointer to the array's data.

Also applies to: 490-492


496-498: LGTM! Proper bounds and null checks.

The operator[] implementation correctly checks both array bounds and null pointer before accessing the data.

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: 5

🔭 Outside diff range comments (1)
include/cppcore/Container/TArray.h (1)

344-363: 🛠️ Refactor suggestion

Potential undefined behavior in move operation.

The move operation has a potential undefined behavior when moving elements that overlap.

Consider using std::memmove for better performance and safety when moving overlapping regions:

-    if (fromIdx > toIdx) {
-        for (size_t i = 0; i < numElements; ++i) {
-            mData[toIdx + i] = mData[fromIdx + i];
-        }
-
-        for (size_t i = toIdx; i < fromIdx + 1; --i) {
-            index = i;
-            destroy(index);
-        }
-    } else {
-        for (size_t i = numElements - 1; i != 0; --i) {
-            mData[toIdx + i] = mData[fromIdx + i];
-        }
-
-        for (size_t i = 0; i < numElements; i++) {
-            index = fromIdx + i;
-            destroy(index);
-        }
-    }
+    std::memmove(&mData[toIdx], &mData[fromIdx], numElements * sizeof(T));
+    for (size_t i = std::min(fromIdx, toIdx); i < std::max(fromIdx + numElements, toIdx + numElements); ++i) {
+        if (i < toIdx || i >= toIdx + numElements) {
+            destroy(i);
+        }
+    }
🧹 Nitpick comments (2)
test/io/FileSystemTest.cpp (2)

27-27: Remove duplicate namespace declaration.

The using namespace cppcore statement appears twice. Remove the second occurrence at line 31 as it's redundant.

using namespace cppcore;

#include <gtest/gtest.h>

-using namespace cppcore;

Also applies to: 31-31


33-33: Consider adding test fixtures for file system operations.

The test class might benefit from common setup/teardown methods to handle file system state, temporary directories, and cleanup. This would ensure consistent test environments and proper cleanup after tests.

-class FileSystemTest : public testing::Test {};
+class FileSystemTest : public testing::Test {
+protected:
+    void SetUp() override {
+        // Setup temporary test directory
+        mTestDir = "test_temp_dir";
+        // Create test directory if needed
+    }
+
+    void TearDown() override {
+        // Cleanup any created files/directories
+    }
+
+protected:
+    std::string mTestDir;
+};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 47c007f and 247c0d6.

📒 Files selected for processing (3)
  • CMakeLists.txt (3 hunks)
  • include/cppcore/Container/TArray.h (14 hunks)
  • test/io/FileSystemTest.cpp (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • CMakeLists.txt
🔇 Additional comments (3)
test/io/FileSystemTest.cpp (1)

1-40: Verify alignment with PR objectives.

The PR objectives mention adding a feature for distance calculation, but this file implements file system testing. Please clarify if this file is part of the intended changes for PR #33 or if it should be in a separate PR focused on testing infrastructure improvements.

include/cppcore/Container/TArray.h (2)

184-186: Member variable naming is now consistent.

The member variable naming has been standardized to use the m prefix followed by PascalCase, which improves readability and maintainability.


150-153: Method renaming improves clarity.

Renaming find to linearSearch better describes the actual implementation and complexity of the search operation. The implementation correctly performs a linear search through the array.

Also applies to: 455-463

Comment on lines +35 to +39
TEST_F(FileSystemTest, getFreeDiskSpaceTest) {
FileSystem fs("c:\\");
FSSpace *space = fs.getFreeDiskSpace();
EXPECT_NE(space, nullptr);
}
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

Improve test robustness and cross-platform compatibility.

The current test implementation has several issues:

  1. Hard-coded Windows path won't work on other platforms
  2. Potential memory leak as the space pointer isn't freed
  3. Minimal validation of the returned data

Here's a suggested improvement:

 TEST_F(FileSystemTest, getFreeDiskSpaceTest) {
-    FileSystem fs("c:\\");
+    // Use platform-independent path
+#ifdef _WIN32
+    const char* testPath = "C:\\";
+#else
+    const char* testPath = "/";
+#endif
+
+    FileSystem fs(testPath);
     FSSpace *space = fs.getFreeDiskSpace();
-    EXPECT_NE(space, nullptr);
+    ASSERT_NE(space, nullptr);
+    
+    // Validate space values
+    EXPECT_GT(space->totalSpace, 0);
+    EXPECT_GE(space->totalSpace, space->freeSpace);
+    
+    // Clean up
+    delete space;
 }
📝 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
TEST_F(FileSystemTest, getFreeDiskSpaceTest) {
FileSystem fs("c:\\");
FSSpace *space = fs.getFreeDiskSpace();
EXPECT_NE(space, nullptr);
}
TEST_F(FileSystemTest, getFreeDiskSpaceTest) {
// Use platform-independent path
#ifdef _WIN32
const char* testPath = "C:\\";
#else
const char* testPath = "/";
#endif
FileSystem fs(testPath);
FSSpace *space = fs.getFreeDiskSpace();
ASSERT_NE(space, nullptr);
// Validate space values
EXPECT_GT(space->totalSpace, 0);
EXPECT_GE(space->totalSpace, space->freeSpace);
// Clean up
delete space;
}

@@ -175,7 +168,7 @@ class TArray {

/// @brief Will return the data pointer.
/// @return The data pointer.
T data() const;
T *data() const;
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

Return type of data() method needs improvement.

The method should return a const T* for const-correctness when the container is const-qualified.

Apply this diff to improve const-correctness:

-    T *data() const;
+    const T* data() const;
+    T* data() { return mData; }

Also applies to: 491-493

Comment on lines +416 to 425
if (size > mCapacity) {
mData = mAllocator.alloc(size * sizeof(T));
if (tmp) {
for (size_t i = 0u; i < oldSize; ++i) {
m_pData[i] = pTmp[i];
mData[i] = tmp[i];
}
mAllocator.release(pTmp);
mAllocator.release(tmp);
}
m_Capacity = size;
mCapacity = 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

Same issue with allocation size in the reallocation code.

The allocation size is incorrectly multiplied by sizeof(T) in the reallocation code as well.

Apply this diff to fix the allocation:

-        mData = mAllocator.alloc(size * sizeof(T));
+        mData = mAllocator.alloc(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
if (size > mCapacity) {
mData = mAllocator.alloc(size * sizeof(T));
if (tmp) {
for (size_t i = 0u; i < oldSize; ++i) {
m_pData[i] = pTmp[i];
mData[i] = tmp[i];
}
mAllocator.release(pTmp);
mAllocator.release(tmp);
}
m_Capacity = size;
mCapacity = size;
}
if (size > mCapacity) {
- mData = mAllocator.alloc(size * sizeof(T));
+ mData = mAllocator.alloc(size);
if (tmp) {
for (size_t i = 0u; i < oldSize; ++i) {
mData[i] = tmp[i];
}
mAllocator.release(tmp);
}
mCapacity = size;
}

Comment on lines +404 to 413
if (mSize > 0u && mCapacity < size) {
tmp = mAllocator.alloc(mSize * sizeof(T));
for (size_t i = 0u; i < mSize; ++i) {
tmp[i] = mData[i];
}

mAllocator.release(m_pData);
m_pData = nullptr;
m_Capacity = 0u;
mAllocator.release(mData);
mData = nullptr;
mCapacity = 0u;
}
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

Incorrect size calculation in memory allocation.

The allocation size is incorrectly multiplied by sizeof(T) in the resize method, but the allocator already handles the type size.

Apply this diff to fix the allocation:

-        tmp = mAllocator.alloc(mSize * sizeof(T));
+        tmp = mAllocator.alloc(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
if (mSize > 0u && mCapacity < size) {
tmp = mAllocator.alloc(mSize * sizeof(T));
for (size_t i = 0u; i < mSize; ++i) {
tmp[i] = mData[i];
}
mAllocator.release(m_pData);
m_pData = nullptr;
m_Capacity = 0u;
mAllocator.release(mData);
mData = nullptr;
mCapacity = 0u;
}
if (mSize > 0u && mCapacity < size) {
tmp = mAllocator.alloc(mSize);
for (size_t i = 0u; i < mSize; ++i) {
tmp[i] = mData[i];
}
mAllocator.release(mData);
mData = nullptr;
mCapacity = 0u;
}

Comment on lines +338 to 342
const size_t numElements = mSize - fromIdx;
const size_t newSize = toIdx + numElements;
while (m_Capacity < newSize) {
resize(m_Capacity + Details::getGrowing(newSize - m_Capacity));
while (mCapacity < newSize) {
resize(mCapacity + Details::getGrowing(newSize - mCapacity));
}
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

Potential integer overflow in capacity calculation.

The capacity calculation in the move operation could potentially overflow for large arrays.

Apply this diff to prevent integer overflow:

-    const size_t numElements = mSize - fromIdx;
-    const size_t newSize = toIdx + numElements;
-    while (mCapacity < newSize) {
-        resize(mCapacity + Details::getGrowing(newSize - mCapacity));
+    if (fromIdx > mSize) {
+        return;  // Invalid fromIdx
+    }
+    const size_t numElements = mSize - fromIdx;
+    if (toIdx > std::numeric_limits<size_t>::max() - numElements) {
+        throw std::overflow_error("Array size would overflow");
+    }
+    const size_t newSize = toIdx + numElements;
+    while (mCapacity < newSize) {
+        const size_t growth = Details::getGrowing(newSize - mCapacity);
+        if (mCapacity > std::numeric_limits<size_t>::max() - growth) {
+            throw std::overflow_error("Array capacity would overflow");
+        }
+        resize(mCapacity + growth);
📝 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
const size_t numElements = mSize - fromIdx;
const size_t newSize = toIdx + numElements;
while (m_Capacity < newSize) {
resize(m_Capacity + Details::getGrowing(newSize - m_Capacity));
while (mCapacity < newSize) {
resize(mCapacity + Details::getGrowing(newSize - mCapacity));
}
if (fromIdx > mSize) {
return; // Invalid fromIdx
}
const size_t numElements = mSize - fromIdx;
if (toIdx > std::numeric_limits<size_t>::max() - numElements) {
throw std::overflow_error("Array size would overflow");
}
const size_t newSize = toIdx + numElements;
while (mCapacity < newSize) {
const size_t growth = Details::getGrowing(newSize - mCapacity);
if (mCapacity > std::numeric_limits<size_t>::max() - growth) {
throw std::overflow_error("Array capacity would overflow");
}
resize(mCapacity + growth);
}

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: 0

♻️ Duplicate comments (2)
include/cppcore/Container/TArray.h (2)

392-401: ⚠️ Potential issue

Fix incorrect size calculation in memory allocation.

The allocation size is incorrectly multiplied by sizeof(T) in both resize and reallocation code. The allocator already handles the type size.

Apply this diff to fix the allocation:

-        tmp = mAllocator.alloc(mSize * sizeof(T));
+        tmp = mAllocator.alloc(mSize);

-        mData = mAllocator.alloc(size * sizeof(T));
+        mData = mAllocator.alloc(size);

Also applies to: 404-413


326-330: ⚠️ Potential issue

Fix potential integer overflow in capacity calculation.

The capacity calculation in the move operation could lead to integer overflow for large arrays.

Apply this diff to prevent integer overflow:

-    const size_t numElements = mSize - fromIdx;
-    const size_t newSize = toIdx + numElements;
-    while (mCapacity < newSize) {
-        resize(mCapacity + Details::getGrowing(newSize - mCapacity));
+    if (fromIdx > mSize) {
+        return;  // Invalid fromIdx
+    }
+    const size_t numElements = mSize - fromIdx;
+    if (toIdx > std::numeric_limits<size_t>::max() - numElements) {
+        throw std::overflow_error("Array size would overflow");
+    }
+    const size_t newSize = toIdx + numElements;
+    while (mCapacity < newSize) {
+        const size_t growth = Details::getGrowing(newSize - mCapacity);
+        if (mCapacity > std::numeric_limits<size_t>::max() - growth) {
+            throw std::overflow_error("Array capacity would overflow");
+        }
+        resize(mCapacity + growth);
🧹 Nitpick comments (2)
include/cppcore/Container/TArray.h (2)

443-451: Consider optimizing linear search for sorted arrays.

While the linear search implementation is correct, consider adding an optional binary search implementation for sorted arrays to improve performance for large datasets.

Apply this diff to add binary search capability:

+    /// @brief Performs a binary search for a given item in a sorted array.
+    /// @param[in] item The item to look for.
+    /// @return An iterator showing to the position will be returned.
+    /// @note The array must be sorted for binary search to work correctly.
+    Iterator binarySearch(const T& item) {
+        if (isEmpty()) {
+            return end();
+        }
+        
+        size_t left = 0;
+        size_t right = mSize - 1;
+        
+        while (left <= right) {
+            size_t mid = left + (right - left) / 2;
+            if (mData[mid] == item) {
+                return &mData[mid];
+            }
+            if (mData[mid] < item) {
+                left = mid + 1;
+            } else {
+                if (mid == 0) break;
+                right = mid - 1;
+            }
+        }
+        
+        return end();
+    }

202-206: Consider using std::copy for better performance in copy constructor.

The manual loop in the copy constructor could be replaced with std::copy for potentially better performance.

Apply this diff to use std::copy:

-    for (size_t i = 0u; i < mSize; ++i) {
-        mData[i] = rhs.mData[i];
-    }
+    std::copy(rhs.mData, rhs.mData + mSize, mData);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8c0fcd0 and 2764d84.

📒 Files selected for processing (2)
  • include/cppcore/Container/TArray.h (14 hunks)
  • include/cppcore/Container/THashMap.h (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • include/cppcore/Container/THashMap.h
🔇 Additional comments (2)
include/cppcore/Container/TArray.h (2)

184-186: LGTM! Member variable initialization looks good.

The in-class initialization of member variables with modern C++ syntax improves readability and safety.


479-481: Improve const-correctness of data() method.

The method should return a const T* for const-correctness when the container is const-qualified.

Apply this diff to improve const-correctness:

-    T* data() const {
-        return mData;
+    const T* data() const {
+        return mData;
+    }
+    T* data() {
+        return mData;

@kimkulling kimkulling merged commit 7361819 into master Feb 19, 2025
3 checks passed
@kimkulling kimkulling deleted the feature/add_algo branch February 19, 2025 15:21
@coderabbitai coderabbitai bot mentioned this pull request Apr 2, 2025
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