-
Notifications
You must be signed in to change notification settings - Fork 118
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This commit adds a RAII wrapper for C-strings, called `unique_cstr`. Several places in the NRN Python bindings use `char *` when owning a malloc allocated string. This new class is then used to prevent leaking HOC strings on error paths.
- Loading branch information
Showing
3 changed files
with
64 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
#pragma once | ||
|
||
#include <cstdlib> | ||
#include <utility> | ||
|
||
namespace neuron { | ||
|
||
/** A RAII wrapper for C-style strings. | ||
* | ||
* The string must be null-terminated and allocated with `malloc`. The lifetime of the string is | ||
* bound to the life time of the `unique_cstr`. Certain patterns in NRN require passing on | ||
* ownership, this is achieved using `.release()`, which returns the contained C-string and makes | ||
* this object invalid. | ||
*/ | ||
class unique_cstr { | ||
public: | ||
unique_cstr(const unique_cstr&) = delete; | ||
unique_cstr(unique_cstr&& other) { | ||
*this = std::move(other); | ||
} | ||
|
||
const unique_cstr& operator=(const unique_cstr&) = delete; | ||
const unique_cstr& operator=(unique_cstr&& other) { | ||
this->str_ = std::exchange(other.str_, nullptr); | ||
return *this; | ||
} | ||
|
||
explicit unique_cstr(char* cstr) | ||
: str_(cstr) {} | ||
|
||
~unique_cstr() { | ||
std::free((void*) str_); | ||
} | ||
|
||
/** Releases ownership of the string. | ||
* | ||
* Returns the string and makes this object invalid. | ||
*/ | ||
[[nodiscard]] char* release() { | ||
return std::exchange(str_, nullptr); | ||
} | ||
|
||
char* c_str() const { | ||
return str_; | ||
} | ||
bool is_valid() const { | ||
return str_ != nullptr; | ||
} | ||
|
||
private: | ||
char* str_ = nullptr; | ||
}; | ||
|
||
} // namespace neuron |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters