-
Notifications
You must be signed in to change notification settings - Fork 4
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
Feature/add algo #33
Conversation
WalkthroughThis pull request updates the cppcore project by enhancing unit testing configurations and standardizing naming conventions across various classes. The Changes
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
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
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
Possibly related PRs
Poem
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 allowbegin == 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
📒 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
tostatic 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 FunctionalityThe new test source file
test/container/TAlgorithmTest.cpp
is now included in thecppcore_container_test_src
list. This is an important addition to verify the distance algorithm defined inTAlgorithm.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.
There was a problem hiding this 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 issueFix type inconsistency and missing bounds check in assignment operator.
The assignment operator uses
unsigned int
instead ofsize_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 issueFix 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_*
tom*
format aligns with modern C++ naming conventions. The initialization and cleanup in constructors and destructor are properly implemented.Consider using
std::unique_ptr
formPool
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_ptrAlso 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 renamingmemset
to avoid confusion with C's memset.The method name
memset
could be misleading as it's not using C'smemset
. Consider a more descriptive name likefillWith
orsetAll
.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
📒 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 thatmPool
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 assumesmCurrent
is not null when accessingmCurrentIdx
.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 therelease
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 therelease
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
tomType
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 hLength of output: 422
Action: Verify Consistent Naming Convention for Member Variables
The update from
m_type
tomType
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
tomArray
andm_len
tomLen
improves consistency with modern C++ naming conventions.include/cppcore/Container/TArray.h (1)
454-462
: LGTM! Method renaming improves clarity.Renaming
find
tolinearSearch
makes the search algorithm explicit and improves code readability.
There was a problem hiding this 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:
- Verify deep copy by modifying source array after copy
- Test with different values per element
- 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
📒 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
There was a problem hiding this 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
📒 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.
test/IO/FileSystemTest.cpp
Outdated
TEST_F(FileSystemTest, getFreeDiskSpaceTest) { | ||
FileSystem fs("c:\\"); | ||
FSSpace *space = fs.getFreeDiskSpace(); | ||
EXPECT_NE(space, nullptr); | ||
} |
There was a problem hiding this comment.
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:
- Testing actual disk space values
- Handling memory management of the returned pointer
- 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 asGetTestPath()
). - 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);
- Use
- 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.
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; | |
} |
There was a problem hiding this 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
📒 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 tolinearSearch
, 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
toT*
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.
There was a problem hiding this 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 suggestionPotential 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
📒 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
tolinearSearch
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
TEST_F(FileSystemTest, getFreeDiskSpaceTest) { | ||
FileSystem fs("c:\\"); | ||
FSSpace *space = fs.getFreeDiskSpace(); | ||
EXPECT_NE(space, nullptr); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Improve test robustness and cross-platform compatibility.
The current test implementation has several issues:
- Hard-coded Windows path won't work on other platforms
- Potential memory leak as the space pointer isn't freed
- 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.
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; |
There was a problem hiding this comment.
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
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; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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; | |
} |
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; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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; | |
} |
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)); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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); | |
} |
|
There was a problem hiding this 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 issueFix 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 issueFix 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
📒 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;
Summary by CodeRabbit
New Features
TAlgorithm
andTArray
classes.Refactor
Tests
TStaticArray
.