text stringlengths 1 2.12k | source dict |
|---|---|
c++, reinventing-the-wheel, memory-management
[[nodiscard]] std::size_t small_size(std::size_t idx) const noexcept {
return (idx << bin_shift_) + min_small_size_;
}
// where to insert in the large bin
[[nodiscard]] auto large_iter(std::size_t num_bytes) const noexcept {
return std::ranges::lower_bound(large_bin_, num_bytes, std::ranges::less{},
GetSize{});
}
void unlink_from_bin(Chunk* chunk, Chunk*& bin) {
assert(chunk && chunk->prev_ && chunk->next_ && bin);
if (chunk == chunk->prev_) {
// make bin empty
assert(chunk == chunk->next_);
bin = nullptr;
} else {
if (chunk == bin) {
bin = chunk->next_;
}
chunk->next_->prev_ = chunk->prev_;
chunk->prev_->next_ = chunk->next_;
}
chunk->prev_ = nullptr;
chunk->next_ = nullptr;
}
void push_front_to_bin(Chunk* chunk, Chunk*& bin) {
push_back_to_bin(chunk, bin);
bin = chunk;
}
void push_back_to_bin(Chunk* chunk, Chunk*& bin) {
assert(chunk);
if (!bin) {
bin = chunk;
chunk->prev_ = chunk;
chunk->next_ = chunk;
} else {
chunk->next_ = bin;
chunk->prev_ = bin->prev_;
bin->prev_->next_ = chunk;
bin->prev_ = chunk;
}
}
Chunk* pop_back_from_bin(Chunk*& bin) {
auto chunk = bin;
if (chunk) {
assert(chunk->prev_ && chunk->next_);
chunk = chunk->prev_;
unlink_from_bin(chunk, bin);
}
return chunk;
}
Chunk* pop_front_from_bin(Chunk*& bin) {
auto chunk = bin;
if (chunk) {
assert(chunk->prev_ && chunk->next_);
unlink_from_bin(chunk, bin);
}
return chunk;
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
Chunk* pop_fastbin(Chunk*& bin) {
auto chunk = bin;
if (chunk) {
bin = bin->next_;
chunk->next_ = nullptr;
assert(!chunk->prev_);
}
return chunk;
}
void push_fastbin(Chunk* chunk, Chunk*& bin) {
assert(chunk && !chunk->prev_);
chunk->next_ = bin;
bin = chunk;
// we mark CHUNK_IN_USE for fastbin chunks
// so that they won't be consolidated.
set_flags(chunk, CHUNK_IN_USE);
}
Chunk* try_alloc_fastbin(std::size_t num_bytes) {
std::size_t fast_bin_index = fast_index(num_bytes);
assert(fast_bin_index < num_fast_bins_);
auto chunk = pop_fastbin(fast_bins_[fast_bin_index]);
assert(!chunk || get_flags(chunk) == CHUNK_IN_USE);
return chunk;
}
Chunk* try_alloc_smallbin(std::size_t num_bytes) {
assert(num_bytes >= min_small_size_);
std::size_t small_bin_index = small_index(num_bytes);
assert(small_bin_index < num_small_bins_);
auto chunk = pop_front_from_bin(small_bins_[small_bin_index]);
if (chunk) {
set_flags(chunk, CHUNK_IN_USE);
}
return chunk;
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
void unlink_chunk(Chunk* chunk) {
assert(chunk);
assert(!(get_flags(chunk) & CHUNK_IN_USE));
auto num_bytes = chunk->size_;
if (get_flags(chunk) & CHUNK_UNSORTED) {
assert(unsorted_bin_);
set_flags(chunk, 0);
unlink_from_bin(chunk, unsorted_bin_);
} else if (num_bytes < min_small_size_) {
// fastbin chunks should never be consolidated by adjacent chunks,
// they should be retrieved only upon malloc requests
assert(false);
} else if (num_bytes < min_large_size_) {
std::size_t small_bin_index = small_index(num_bytes);
assert(small_bin_index < num_small_bins_ && small_bins_[small_bin_index]);
unlink_from_bin(chunk, small_bins_[small_bin_index]);
} else if (chunk != top_chunk_) {
auto where = large_iter(num_bytes);
assert(where != large_bin_.end() && (*where)->size_ == num_bytes);
while (*where != chunk) {
++where;
}
assert(where != large_bin_.end() && *where == chunk);
large_bin_.erase(where);
} else {
assert(chunk == top_chunk_);
}
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
void consolidate_chunk(Chunk* chunk) {
assert(chunk);
auto size = chunk->size_;
auto next = next_chunk(chunk);
while (!is_begin(chunk) && !(chunk->prev_size_ & CHUNK_IN_USE)) {
auto prev = prev_chunk(chunk);
assert(prev->size_);
unlink_chunk(prev);
assert(get_flags(prev) == 0);
size += prev->size_;
chunk = prev;
}
bool next_was_top = false;
while (next && !(next->size_ & CHUNK_IN_USE)) {
assert(next->size_);
unlink_chunk(next);
assert(get_flags(next) == 0);
size += next->size_;
next_was_top = (next == top_chunk_);
next = next_chunk(next);
}
if (!next_was_top) {
set_size(chunk, size);
push_front_to_bin(chunk, unsorted_bin_);
set_flags(chunk, CHUNK_UNSORTED);
} else {
top_chunk_ = chunk;
set_size(chunk, size);
}
}
void consolidate_fastbin() {
for (std::size_t i = 0; i < num_fast_bins_; ++i) {
while (fast_bins_[i]) {
auto chunk = pop_fastbin(fast_bins_[i]);
set_flags(chunk, 0);
consolidate_chunk(chunk);
}
}
}
void place_in_bins(Chunk* chunk) {
assert(chunk && get_flags(chunk) == 0);
auto num_bytes = chunk->size_;
if (num_bytes < min_small_size_) {
push_fastbin(chunk, fast_bins_[fast_index(num_bytes)]);
} else if (num_bytes < min_large_size_) {
push_back_to_bin(chunk, small_bins_[small_index(num_bytes)]);
} else {
large_bin_.insert(large_iter(num_bytes), chunk);
}
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
Chunk* split_chunk_after(Chunk* chunk, std::size_t offset) {
assert(chunk && (chunk != top_chunk_) && offset >= chunk_alignment_ &&
(offset % chunk_alignment_) == 0 &&
realsize(chunk) >= offset + sizeof(Chunk) &&
(realsize(chunk) - offset) % chunk_alignment_ == 0);
auto split_size = realsize(chunk) - offset;
// set new size of the current (left) chunk and erase flags
set_size(chunk, offset);
Chunk* split_chunk = reinterpret_cast<Chunk*>(
reinterpret_cast<unsigned char*>(chunk) + offset);
assert(split_chunk->prev_size_ == offset);
split_chunk->prev_ = nullptr;
split_chunk->next_ = nullptr;
set_size(split_chunk, split_size);
assert(split_chunk == next_chunk(chunk));
assert(verify_size(split_chunk) == split_size);
return split_chunk;
}
Chunk* try_alloc_unsorted(std::size_t num_bytes) {
while (unsorted_bin_) {
auto chunk = pop_front_from_bin(unsorted_bin_);
assert(chunk && get_flags(chunk) == CHUNK_UNSORTED);
set_flags(chunk, 0);
// for small requests, if this is the last unsorted,
// then split and take if possible
if (!unsorted_bin_ && num_bytes < min_large_size_ &&
chunk->size_ >= num_bytes + chunk_alignment_) {
auto remainder = split_chunk_after(chunk, num_bytes);
set_flags(chunk, CHUNK_IN_USE);
set_flags(remainder, CHUNK_UNSORTED);
push_front_to_bin(remainder, unsorted_bin_);
return chunk;
}
// use this if exact fit
if (chunk->size_ == num_bytes) {
set_flags(chunk, CHUNK_IN_USE);
return chunk;
}
place_in_bins(chunk);
}
return nullptr;
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
place_in_bins(chunk);
}
return nullptr;
}
Chunk* try_alloc_largebin(std::size_t num_bytes) {
assert(num_bytes >= min_large_size_ && (num_bytes % chunk_alignment_) == 0);
auto where = large_iter(num_bytes);
if (where == large_bin_.end()) {
// no large bin chunk is available
return nullptr;
} else {
// best fit
auto chunk = *where;
assert(get_flags(chunk) == 0);
assert(chunk->size_ >= num_bytes);
large_bin_.erase(where);
if (chunk->size_ == num_bytes) {
// use if exact fit
set_flags(chunk, CHUNK_IN_USE);
return chunk;
} else if (chunk->size_ >= num_bytes + chunk_alignment_) {
assert((chunk->size_ - num_bytes) % chunk_alignment_ == 0);
// split to take remainder
auto remainder = split_chunk_after(chunk, num_bytes);
set_flags(chunk, CHUNK_IN_USE);
place_in_bins(remainder);
return chunk;
}
}
}
Chunk* alloc_top(std::size_t num_bytes) {
assert(num_bytes >= chunk_alignment_ &&
(num_bytes % chunk_alignment_) == 0);
assert(get_flags(top_chunk_) == 0);
if (top_chunk_->size_ < num_bytes + chunk_alignment_) {
// TODO: how to deal with this?
throw std::runtime_error("memory pool is not enough");
}
assert((top_chunk_->size_ % chunk_alignment_ == 0) &&
top_chunk_->size_ >= num_bytes + chunk_alignment_ &&
(top_chunk_->size_ - num_bytes) % chunk_alignment_ == 0);
auto chunk = top_chunk_; | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
auto chunk = top_chunk_;
auto split_size = top_chunk_->size_ - num_bytes;
// set new size of the current (left) chunk and erase flags
top_chunk_->size_ = num_bytes;
Chunk* split_chunk = reinterpret_cast<Chunk*>(
reinterpret_cast<unsigned char*>(top_chunk_) + num_bytes);
assert(split_chunk);
std::size_t* foot = reinterpret_cast<std::size_t*>(split_chunk);
*foot = num_bytes;
assert(split_chunk->prev_size_ == num_bytes);
split_chunk->prev_ = nullptr;
split_chunk->next_ = nullptr;
split_chunk->size_ = split_size;
top_chunk_ = split_chunk;
assert(split_chunk == next_chunk(chunk));
assert(split_chunk == top_chunk_);
set_flags(chunk, CHUNK_IN_USE);
return chunk;
}
std::size_t request_to_sz(std::size_t num_bytes) {
return ((num_bytes / chunk_alignment_) * chunk_alignment_) +
((num_bytes % chunk_alignment_) ? chunk_alignment_ : 0);
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
public:
void* alloc_chunk(std::size_t num_bytes) {
num_bytes = request_to_sz(num_bytes);
assert(num_bytes >= min_fast_size_ && num_bytes % chunk_alignment_ == 0);
if (num_bytes < min_small_size_) {
auto res = try_alloc_fastbin(num_bytes);
if (res) {
assert(res->size_ == (num_bytes | CHUNK_IN_USE));
assert(verify());
return reinterpret_cast<void*>(res);
}
} else if (num_bytes < min_large_size_) {
auto res = try_alloc_smallbin(num_bytes);
if (res) {
assert(res->size_ == (num_bytes | CHUNK_IN_USE));
assert(verify());
return reinterpret_cast<void*>(res);
}
} else {
consolidate_fastbin();
assert(verify());
}
{
auto res = try_alloc_unsorted(num_bytes);
if (res) {
assert(res->size_ == (num_bytes | CHUNK_IN_USE));
assert(verify());
return reinterpret_cast<void*>(res);
}
}
auto res = alloc_top(num_bytes);
assert(res && res->size_ == (num_bytes | CHUNK_IN_USE));
assert(verify());
return reinterpret_cast<void*>(res);
}
void dealloc_chunk(void* ptr) {
assert(ptr);
Chunk* chunk = reinterpret_cast<Chunk*>(ptr);
assert(get_flags(chunk) == CHUNK_IN_USE);
set_flags(chunk, 0);
assert(chunk != top_chunk_);
if (next_chunk(chunk) != top_chunk_ && chunk->size_ < min_small_size_) {
push_fastbin(chunk, fast_bins_[fast_index(chunk->size_)]);
} else {
consolidate_chunk(chunk);
}
assert(verify());
}
};
int main() {
AllocManager simulator(1UL << 24UL); | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
int main() {
AllocManager simulator(1UL << 24UL);
std::mt19937 gen(std::random_device{}());
// will be multiplied by alignment
std::gamma_distribution <> chunk_size_dist(2, 2);
constexpr std::size_t chunk_align = 8UL;
constexpr int num = 200'000;
std::bernoulli_distribution to_alloc_or_dealloc(0.65);
std::bernoulli_distribution large_or_small(0.05);
std::unordered_map <void*, std::size_t> allocated;
std::unordered_map <void*, std::size_t> allocated_std;
float my_alloc_duration = 0.0f;
float std_alloc_duration = 0.0f; | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
for (int i = 0; i < num; ++i) {
if (to_alloc_or_dealloc(gen)) {
auto sz = (1 + static_cast<std::size_t>(chunk_size_dist(gen))) * chunk_align;
if (large_or_small(gen)) {
sz += 1024;
}
auto start = std::chrono::steady_clock::now();
auto cnk = simulator.alloc_chunk(sz);
auto end = std::chrono::steady_clock::now();
my_alloc_duration += std::chrono::duration_cast <std::chrono::duration <float, std::micro>>(
end - start).count();
allocated[cnk] = sz;
start = std::chrono::steady_clock::now();
void* ptr = std::malloc(sz);
end = std::chrono::steady_clock::now();
std_alloc_duration += std::chrono::duration_cast <std::chrono::duration <float, std::micro>>(
end - start).count();
allocated_std[ptr] = sz;
} else {
if (!allocated.empty()) {
auto[cnk, sz] = *allocated.begin();
auto start = std::chrono::steady_clock::now();
simulator.dealloc_chunk(cnk);
auto end = std::chrono::steady_clock::now();
my_alloc_duration += std::chrono::duration_cast <std::chrono::duration <float, std::micro>>(
end - start).count();
allocated.erase(allocated.begin());
assert(!allocated_std.empty());
auto[ptr, sz2] = *allocated_std.begin();
start = std::chrono::steady_clock::now();
std::free(ptr);
end = std::chrono::steady_clock::now();
std_alloc_duration += std::chrono::duration_cast <std::chrono::duration <float, std::micro>>(
end - start).count();
allocated_std.erase(allocated_std.begin());
}
}
}
std::cout << "AllocManager elapsed " << my_alloc_duration / 1000.0f << "ms\n"; | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
}
}
std::cout << "AllocManager elapsed " << my_alloc_duration / 1000.0f << "ms\n";
std::cout << "std::malloc std::free elapsed " << std_alloc_duration / 1000.0f << "ms\n";
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
Result in my machine: (gcc 11.2 -O3)
frozenca::AllocManager elapsed 12.2252ms
std::malloc std::free elapsed 26.1129ms
Answer: General Observations
You did a lot of work and it is a very interesting question. You know more about the most recent versions (C++17 and C++20) of C++ than I do.
You do need to do learn more about object oriented design, the AllocManager manager class is too complex (does too much), quite possibly you could have an abstract bins class that each bin could inherit from, an example of this might be an abstract verify function that works differently for each bin. The Chunk struct might also be a class, you could move some of the code from the AllocManager class into the Chunk struct as well.
The organization of this code review is to go from general comments to specific issues. At the end of the answer the code has been reorganized into multiple files, which is a beginning to how I would have written the program.
Solid Programming
SOLID is 5 object oriented design principles. SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better. | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
The Single Responsibility Principle - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class.
The Open–closed Principle - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
The Liskov Substitution Principle - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.
The Interface segregation principle - states that no client should be forced to depend on methods it does not use.
The Dependency Inversion Principle - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details. | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
At a minimum this code violates the Single Responsibility Principle and may violate the Interface segregation principle.
Program Organization
Rather than putting all of the code into a single file the program should be organized with header files and source code files. The header files define the interfaces that the code will use, the source files contain most of the executable code. This allows faster build times for performing maintenance. It also allows the code to be modular and reusable.
In C++ classes are generally defined in header files, some very simple functions or methods can also be coded in the header file, but generally the executable code is in C++ source files so that bug fixing is limited to the specific area where a problem exists. This also makes adding features easier. This is different then coding in C# or Java.
Not all of the functions and methods a class uses need to be declared in in the class if the code is organized this way, if you look at the alternate AllocManager.cpp you will see that some of the functions are static functions declared in the file. This provides even more protection than private or protected variables and methods since static variables can't be accessed outside the program module.
Object Organization
A convention in all object oriented programming is that the public interfaces are all declared at the top of the class, this allows the users of the class to quickly find the interfaces they need without examining all of the code. Mixing up the public and private declarations can definitely cause confusion to the programmers that need to interface with the class.
Issues
Use the assert Macro Only in Debug Mode | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
Issues
Use the assert Macro Only in Debug Mode
The code depends on the assert macro very heavily, you need to be aware that if you compile this for production (optimized with no debug mode set) that all of the assert statements will be null. Any errors you want the code to generate in production/release mode need to use if statements and properly report the errors. Here are 2 references cplusplus.com and cppreference.com.
All Paths in a Function Should Return a Value
When I compile, I use the -Wall flag to report all warnings. I found this warning message: warning C4715: 'AllocManager::try_alloc_largebin': not all control paths return a value. This indicates that the function may return unknown values in some cases, one way to ensure the function returns a value is to only return a value at the end of the function, declare a variable of the proper type and initialize it to a default value, then set the variable in the code where you currently have the return statements. The following function generates a warning message in my compiler:
Chunk* try_alloc_largebin(std::size_t num_bytes) {
assert(num_bytes >= min_large_size_ && (num_bytes % chunk_alignment_) == 0);
auto where = large_iter(num_bytes); | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
if (where == large_bin_.end()) {
// no large bin chunk is available
return nullptr;
}
else {
// best fit
auto chunk = *where;
assert(get_flags(chunk) == 0);
assert(chunk->size_ >= num_bytes);
large_bin_.erase(where);
if (chunk->size_ == num_bytes) {
// use if exact fit
set_flags(chunk, CHUNK_IN_USE);
return chunk;
}
else if (chunk->size_ >= num_bytes + chunk_alignment_) {
assert((chunk->size_ - num_bytes) % chunk_alignment_ == 0);
// split to take remainder
auto remainder = split_chunk_after(chunk, num_bytes);
set_flags(chunk, CHUNK_IN_USE);
place_in_bins(remainder);
return chunk;
}
}
}
Reorganized Code
Chunk.h
#ifndef CHUNK_H
struct Chunk {
std::size_t prev_size_ = 0;
// invariant: size_ > 0
// invariant: rightmost three (or two) bits of size_ are flags (CHUNK_IN_USE,
// CHUNK_UNSORTED)
std::size_t size_ = 0;
// pointers to prev/next within bins, only used for free chunks.
// nothing to do with prev/next chunks within the global arena, beware!
Chunk* next_ = nullptr;
Chunk* prev_ = nullptr;
};
static_assert(sizeof(std::size_t) == 8 || sizeof(std::size_t) == 4);
constexpr std::size_t CHUNK_IN_USE = 0x1;
constexpr std::size_t CHUNK_UNSORTED = 0x2;
constexpr std::size_t CHUNK_FLAG_MASK = 0x7;
constexpr std::size_t CHUNK_FLAG_UNMASK =
(sizeof(std::size_t) == 8) ? 0xFFFFFFFFFFFFFFF8 : 0xFFFFFFF8;
#endif // !CHUNK_H
AllocManager.h
#ifndef ALLOCMANAGER_H
#include <vector>
#include "chunk.h"
class AllocManager
{
public:
AllocManager(std::size_t init_pool_size);
void* alloc_chunk(std::size_t num_bytes);
void dealloc_chunk(void* ptr);
private:
[[nodiscard]] bool is_begin(const Chunk* chunk) const noexcept;
Chunk* first_chunk() noexcept {
return reinterpret_cast<Chunk*>(all_chunks_.data());
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
const Chunk* first_chunk() const noexcept {
return reinterpret_cast<const Chunk*>(all_chunks_.data());
}
// don't need is_last, as top_chunk_ is always the last chunk
std::size_t* get_foot(Chunk* chunk) noexcept;
const std::size_t* get_foot(const Chunk* chunk) const noexcept;
[[nodiscard]] std::size_t get_flags(const Chunk* chunk) const noexcept;
void set_flags(Chunk* chunk, std::size_t flags);
// erase flags and make a nonzero mulitple of chunk_alignment_
std::size_t realsize(std::size_t sz) const noexcept;
std::size_t realsize(const Chunk* chunk) const noexcept;
void set_size(Chunk* chunk, std::size_t sz);
std::size_t verify_size(const Chunk* chunk) const noexcept;
Chunk* prev_chunk(Chunk* chunk) noexcept;
const Chunk* prev_chunk(const Chunk* chunk) const noexcept;
Chunk* next_chunk(Chunk* chunk) noexcept;
const Chunk* next_chunk(const Chunk* chunk) const noexcept;
bool verify_fastbins() const;
bool verify_smallbins() const;
bool verify_largebin() const;
bool verify_unsorted() const;
bool verify() const;
// where to insert in the large bin
[[nodiscard]] auto large_iter(std::size_t num_bytes) const noexcept;
void push_fastbin(Chunk* chunk, Chunk*& bin);
Chunk* try_alloc_fastbin(std::size_t num_bytes);
Chunk* try_alloc_smallbin(std::size_t num_bytes);
void unlink_chunk(Chunk* chunk);
void consolidate_chunk(Chunk* chunk);
void consolidate_fastbin();
void place_in_bins(Chunk* chunk);
Chunk* split_chunk_after(Chunk* chunk, std::size_t offset);
Chunk* try_alloc_unsorted(std::size_t num_bytes);
Chunk* try_alloc_largebin(std::size_t num_bytes);
Chunk* alloc_top(std::size_t num_bytes);
std::size_t curr_pool_size_ = 0; | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
Chunk* alloc_top(std::size_t num_bytes);
std::size_t curr_pool_size_ = 0;
// bins that store chunks of 32, 64, 96, ..., 224 bytes respectively
// (or 16, 32, ..., 112)
// LIFO singly linked list, NOT merged when freed
std::vector <Chunk*> fast_bins_;
// bins that store chunks of 256, 288, ..., 2016 bytes respectively
// (or 128, 144, ..., 1008)
// FIFO doubly linked list, chunks are merged with adjacent chunks when freed
// if adjacent
std::vector <Chunk*> small_bins_;
// a *single* bin that store chunks of 2048+ bytes (or 1024+)
// maintain the sorted order w.r.t. chunk size in *increasing* order
// chunks are merged with adjacent chunks when freed if adjacent
std::vector <Chunk*> large_bin_;
// a bin for freed chunks and remainder chunks
// when an allocation request fails to search chunk in other bins,
// this bin is searched
Chunk* unsorted_bin_ = nullptr;
Chunk* top_chunk_ = nullptr;
// store *all* chunks
std::vector <unsigned char> all_chunks_;
};
#endif !ALLOCMANAGER_H
AllocManager.cpp
#include <algorithm>
#include <bit>
#include <cassert>
#include <ranges>
#include <stdexcept>
#include "AllocManager.h"
static constexpr std::size_t chunk_alignment_ = sizeof(Chunk);
static_assert(std::has_single_bit(chunk_alignment_));
static constexpr std::size_t align_multiplier = (sizeof(std::size_t) == 8) ? 1UL : 2UL;
static constexpr std::size_t bin_shift_ = (sizeof(std::size_t) == 8) ? 5UL : 4UL;
static constexpr std::size_t num_fast_bins_ = 8UL * align_multiplier;
static constexpr std::size_t num_small_bins_ = 56UL * align_multiplier;
static constexpr std::size_t min_fast_size_ = chunk_alignment_;
static constexpr std::size_t min_small_size_ = chunk_alignment_ * num_fast_bins_;
static constexpr std::size_t min_large_size_ =
chunk_alignment_ * (num_small_bins_ + num_fast_bins_); | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
static std::size_t request_to_sz(std::size_t num_bytes) {
return ((num_bytes / chunk_alignment_) * chunk_alignment_) +
((num_bytes % chunk_alignment_) ? chunk_alignment_ : 0);
}
static [[nodiscard]] std::size_t fast_index(std::size_t num_bytes) noexcept {
return (num_bytes >> bin_shift_);
}
static [[nodiscard]] std::size_t fast_size(std::size_t idx) noexcept {
return (idx << bin_shift_);
}
static [[nodiscard]] std::size_t small_index(std::size_t num_bytes) noexcept;
static [[nodiscard]] std::size_t small_size(std::size_t idx) noexcept {
return (idx << bin_shift_) + min_small_size_;
}
static [[nodiscard]] std::size_t small_index(std::size_t num_bytes) noexcept {
assert(num_bytes >= min_small_size_);
return ((num_bytes - min_small_size_) >> bin_shift_);
}
static void unlink_from_bin(Chunk* chunk, Chunk*& bin) {
assert(chunk && chunk->prev_ && chunk->next_ && bin);
if (chunk == chunk->prev_) {
// make bin empty
assert(chunk == chunk->next_);
bin = nullptr;
}
else {
if (chunk == bin) {
bin = chunk->next_;
}
chunk->next_->prev_ = chunk->prev_;
chunk->prev_->next_ = chunk->next_;
}
chunk->prev_ = nullptr;
chunk->next_ = nullptr;
}
static void push_back_to_bin(Chunk* chunk, Chunk*& bin) {
assert(chunk);
if (!bin) {
bin = chunk;
chunk->prev_ = chunk;
chunk->next_ = chunk;
}
else {
chunk->next_ = bin;
chunk->prev_ = bin->prev_;
bin->prev_->next_ = chunk;
bin->prev_ = chunk;
}
}
static void push_front_to_bin(Chunk* chunk, Chunk*& bin) {
push_back_to_bin(chunk, bin);
bin = chunk;
}
static Chunk* pop_back_from_bin(Chunk*& bin) {
auto chunk = bin;
if (chunk) {
assert(chunk->prev_ && chunk->next_);
chunk = chunk->prev_;
unlink_from_bin(chunk, bin);
}
return chunk;
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
static Chunk* pop_front_from_bin(Chunk*& bin) {
auto chunk = bin;
if (chunk) {
assert(chunk->prev_ && chunk->next_);
unlink_from_bin(chunk, bin);
}
return chunk;
}
static Chunk* pop_fastbin(Chunk*& bin) {
auto chunk = bin;
if (chunk) {
bin = bin->next_;
chunk->next_ = nullptr;
assert(!chunk->prev_);
}
return chunk;
}
struct GetSize {
std::size_t operator()(Chunk* iter) const noexcept {
assert(iter);
return iter->size_;
}
};
AllocManager::AllocManager(std::size_t init_pool_size)
: curr_pool_size_{ init_pool_size }, fast_bins_(num_fast_bins_, nullptr),
small_bins_(num_small_bins_, nullptr), all_chunks_(init_pool_size) {
assert(init_pool_size% chunk_alignment_ == 0);
top_chunk_ = first_chunk();
set_size(top_chunk_, init_pool_size);
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
void* AllocManager::alloc_chunk(std::size_t num_bytes) {
num_bytes = request_to_sz(num_bytes);
assert(num_bytes >= min_fast_size_ && num_bytes % chunk_alignment_ == 0);
if (num_bytes < min_small_size_) {
auto res = try_alloc_fastbin(num_bytes);
if (res) {
assert(res->size_ == (num_bytes | CHUNK_IN_USE));
assert(verify());
return reinterpret_cast<void*>(res);
}
}
else if (num_bytes < min_large_size_) {
auto res = try_alloc_smallbin(num_bytes);
if (res) {
assert(res->size_ == (num_bytes | CHUNK_IN_USE));
assert(verify());
return reinterpret_cast<void*>(res);
}
}
else {
consolidate_fastbin();
assert(verify());
}
{
auto res = try_alloc_unsorted(num_bytes);
if (res) {
assert(res->size_ == (num_bytes | CHUNK_IN_USE));
assert(verify());
return reinterpret_cast<void*>(res);
}
}
auto res = alloc_top(num_bytes);
assert(res && res->size_ == (num_bytes | CHUNK_IN_USE));
assert(verify());
return reinterpret_cast<void*>(res);
}
void AllocManager::dealloc_chunk(void* ptr) {
assert(ptr);
Chunk* chunk = reinterpret_cast<Chunk*>(ptr);
assert(get_flags(chunk) == CHUNK_IN_USE);
set_flags(chunk, 0);
assert(chunk != top_chunk_);
if (next_chunk(chunk) != top_chunk_ && chunk->size_ < min_small_size_) {
push_fastbin(chunk, fast_bins_[fast_index(chunk->size_)]);
}
else {
consolidate_chunk(chunk);
}
assert(verify());
}
void AllocManager::set_flags(Chunk* chunk, std::size_t flags) {
assert(chunk && chunk != top_chunk_);
chunk->size_ &= CHUNK_FLAG_UNMASK;
chunk->size_ |= flags;
// add the foot
std::size_t* foot = get_foot(chunk);
*foot &= CHUNK_FLAG_UNMASK;
*foot |= flags;
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
[[nodiscard]] bool AllocManager::is_begin(const Chunk* chunk) const noexcept {
assert(chunk);
assert(reinterpret_cast<const unsigned char*>(chunk) >=
all_chunks_.data());
return reinterpret_cast<const unsigned char*>(chunk) == all_chunks_.data();
}
std::size_t* AllocManager::get_foot(Chunk* chunk) noexcept {
assert(chunk && chunk != top_chunk_);
return reinterpret_cast<std::size_t*>(reinterpret_cast<unsigned char*>(chunk) +
realsize(chunk));
}
const std::size_t* AllocManager::get_foot(const Chunk* chunk) const noexcept {
assert(chunk && chunk != top_chunk_);
return reinterpret_cast<const std::size_t*>(
reinterpret_cast<const unsigned char*>(chunk) + realsize(chunk));
}
[[nodiscard]] std::size_t AllocManager::get_flags(const Chunk* chunk) const noexcept {
assert(chunk);
return chunk->size_ & CHUNK_FLAG_MASK;
}
std::size_t AllocManager::realsize(std::size_t sz) const noexcept {
assert(sz >= chunk_alignment_);
return (sz >> bin_shift_) << bin_shift_;
}
std::size_t AllocManager::realsize(const Chunk* chunk) const noexcept {
assert(chunk && chunk->size_ >= chunk_alignment_);
return realsize(chunk->size_);
}
void AllocManager::set_size(Chunk* chunk, std::size_t sz) {
assert(chunk);
chunk->size_ = sz;
// add the foot
if (chunk != top_chunk_) {
std::size_t* foot = get_foot(chunk);
*foot = sz;
}
}
std::size_t AllocManager::verify_size(const Chunk* chunk) const noexcept {
assert(chunk && chunk->size_ >= chunk_alignment_);
// check the foot
assert(chunk == top_chunk_ || *get_foot(chunk) == chunk->size_);
return chunk->size_;
}
Chunk* AllocManager::prev_chunk(Chunk* chunk) noexcept {
if (!chunk || is_begin(chunk)) {
return nullptr;
}
return reinterpret_cast<Chunk*>(reinterpret_cast<unsigned char*>(chunk) -
realsize(chunk->prev_size_));
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
const Chunk* AllocManager::prev_chunk(const Chunk* chunk) const noexcept {
if (!chunk || is_begin(chunk)) {
return nullptr;
}
return reinterpret_cast<const Chunk*>(
reinterpret_cast<const unsigned char*>(chunk) -
realsize(chunk->prev_size_));
}
Chunk* AllocManager::next_chunk(Chunk* chunk) noexcept {
if (!chunk || chunk == top_chunk_) {
return nullptr;
}
return reinterpret_cast<Chunk*>(reinterpret_cast<unsigned char*>(chunk) +
realsize(chunk));
}
const Chunk* AllocManager::next_chunk(const Chunk* chunk) const noexcept {
if (!chunk || chunk == top_chunk_) {
return nullptr;
}
return reinterpret_cast<const Chunk*>(
reinterpret_cast<const unsigned char*>(chunk) + realsize(chunk));
}
bool AllocManager::verify_fastbins() const {
assert(fast_bins_.size() == num_fast_bins_);
for (std::size_t i = 0; i < num_fast_bins_; ++i) {
auto chunk = fast_bins_[i];
while (chunk) {
assert(realsize(verify_size(chunk)) == fast_size(i));
assert(get_flags(chunk) == CHUNK_IN_USE);
chunk = chunk->next_;
}
}
return true;
}
bool AllocManager::verify_smallbins() const {
assert(small_bins_.size() == num_small_bins_);
for (std::size_t i = 0; i < num_small_bins_; ++i) {
auto chunk = small_bins_[i];
while (chunk) {
assert(verify_size(chunk) == small_size(i));
assert(chunk->prev_ && chunk->next_ && chunk->prev_->next_ == chunk &&
chunk->next_->prev_ == chunk);
if (chunk == chunk->next_) {
assert(chunk == chunk->prev_);
break;
}
chunk = chunk->next_;
if (chunk == small_bins_[i]) {
break;
}
}
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
bool AllocManager::verify_largebin() const {
assert(std::ranges::is_sorted(large_bin_, std::ranges::less{}, GetSize{}));
assert(std::ranges::all_of(large_bin_, [this](const auto& chunk) {
return chunk && get_flags(chunk) == 0 &&
verify_size(chunk) >= min_large_size_ &&
(chunk->size_ % chunk_alignment_) == 0;
}));
return true;
}
bool AllocManager::verify_unsorted() const {
auto chunk = unsorted_bin_;
while (chunk) {
assert(verify_size(chunk) >= chunk_alignment_ &&
(realsize(chunk) % chunk_alignment_) == 0);
assert(get_flags(chunk) == CHUNK_UNSORTED);
assert(chunk->prev_ && chunk->next_ && chunk->prev_->next_ == chunk &&
chunk->next_->prev_ == chunk);
if (chunk == chunk->next_) {
assert(chunk == chunk->prev_);
break;
}
chunk = chunk->next_;
if (chunk == unsorted_bin_) {
break;
}
}
return true;
}
bool AllocManager::verify() const {
assert(!all_chunks_.empty() && all_chunks_.size() == curr_pool_size_);
const Chunk* chunk = first_chunk();
while (chunk) {
assert(chunk->size_ >= chunk_alignment_ &&
(realsize(chunk) % chunk_alignment_) == 0);
auto next = next_chunk(chunk);
if (!next) {
assert(chunk == top_chunk_ && get_flags(chunk) == 0);
assert(reinterpret_cast<const unsigned char*>(chunk) + chunk->size_ ==
all_chunks_.data() + all_chunks_.size());
}
chunk = next;
}
assert(verify_fastbins());
assert(verify_smallbins());
assert(verify_largebin());
assert(verify_unsorted());
return true;
}
[[nodiscard]] auto AllocManager::large_iter(std::size_t num_bytes) const noexcept {
return std::ranges::lower_bound(large_bin_, num_bytes, std::ranges::less{},
GetSize{});
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
void AllocManager::push_fastbin(Chunk* chunk, Chunk*& bin) {
assert(chunk && !chunk->prev_);
chunk->next_ = bin;
bin = chunk;
// we mark CHUNK_IN_USE for fastbin chunks
// so that they won't be consolidated.
set_flags(chunk, CHUNK_IN_USE);
}
Chunk* AllocManager::try_alloc_fastbin(std::size_t num_bytes) {
std::size_t fast_bin_index = fast_index(num_bytes);
assert(fast_bin_index < num_fast_bins_);
auto chunk = pop_fastbin(fast_bins_[fast_bin_index]);
assert(!chunk || get_flags(chunk) == CHUNK_IN_USE);
return chunk;
}
Chunk* AllocManager::try_alloc_smallbin(std::size_t num_bytes) {
assert(num_bytes >= min_small_size_);
std::size_t small_bin_index = small_index(num_bytes);
assert(small_bin_index < num_small_bins_);
auto chunk = pop_front_from_bin(small_bins_[small_bin_index]);
if (chunk) {
set_flags(chunk, CHUNK_IN_USE);
}
return chunk;
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
void AllocManager::unlink_chunk(Chunk* chunk) {
assert(chunk);
assert(!(get_flags(chunk) & CHUNK_IN_USE));
auto num_bytes = chunk->size_;
if (get_flags(chunk) & CHUNK_UNSORTED) {
assert(unsorted_bin_);
set_flags(chunk, 0);
unlink_from_bin(chunk, unsorted_bin_);
}
else if (num_bytes < min_small_size_) {
// fastbin chunks should never be consolidated by adjacent chunks,
// they should be retrieved only upon malloc requests
assert(false);
}
else if (num_bytes < min_large_size_) {
std::size_t small_bin_index = small_index(num_bytes);
assert(small_bin_index < num_small_bins_&& small_bins_[small_bin_index]);
unlink_from_bin(chunk, small_bins_[small_bin_index]);
}
else if (chunk != top_chunk_) {
auto where = large_iter(num_bytes);
assert(where != large_bin_.end() && (*where)->size_ == num_bytes);
while (*where != chunk) {
++where;
}
assert(where != large_bin_.end() && *where == chunk);
large_bin_.erase(where);
}
else {
assert(chunk == top_chunk_);
}
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
void AllocManager::consolidate_chunk(Chunk* chunk) {
assert(chunk);
auto size = chunk->size_;
auto next = next_chunk(chunk);
while (!is_begin(chunk) && !(chunk->prev_size_ & CHUNK_IN_USE)) {
auto prev = prev_chunk(chunk);
assert(prev->size_);
unlink_chunk(prev);
assert(get_flags(prev) == 0);
size += prev->size_;
chunk = prev;
}
bool next_was_top = false;
while (next && !(next->size_ & CHUNK_IN_USE)) {
assert(next->size_);
unlink_chunk(next);
assert(get_flags(next) == 0);
size += next->size_;
next_was_top = (next == top_chunk_);
next = next_chunk(next);
}
if (!next_was_top) {
set_size(chunk, size);
push_front_to_bin(chunk, unsorted_bin_);
set_flags(chunk, CHUNK_UNSORTED);
}
else {
top_chunk_ = chunk;
set_size(chunk, size);
}
}
void AllocManager::consolidate_fastbin() {
for (std::size_t i = 0; i < num_fast_bins_; ++i) {
while (fast_bins_[i]) {
auto chunk = pop_fastbin(fast_bins_[i]);
set_flags(chunk, 0);
consolidate_chunk(chunk);
}
}
}
void AllocManager::place_in_bins(Chunk* chunk) {
assert(chunk && get_flags(chunk) == 0);
auto num_bytes = chunk->size_;
if (num_bytes < min_small_size_) {
push_fastbin(chunk, fast_bins_[fast_index(num_bytes)]);
}
else if (num_bytes < min_large_size_) {
push_back_to_bin(chunk, small_bins_[small_index(num_bytes)]);
}
else {
large_bin_.insert(large_iter(num_bytes), chunk);
}
}
Chunk* AllocManager::split_chunk_after(Chunk* chunk, std::size_t offset) {
assert(chunk && (chunk != top_chunk_) && offset >= chunk_alignment_ &&
(offset % chunk_alignment_) == 0 &&
realsize(chunk) >= offset + sizeof(Chunk) &&
(realsize(chunk) - offset) % chunk_alignment_ == 0);
auto split_size = realsize(chunk) - offset; | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
auto split_size = realsize(chunk) - offset;
// set new size of the current (left) chunk and erase flags
set_size(chunk, offset);
Chunk* split_chunk = reinterpret_cast<Chunk*>(
reinterpret_cast<unsigned char*>(chunk) + offset);
assert(split_chunk->prev_size_ == offset);
split_chunk->prev_ = nullptr;
split_chunk->next_ = nullptr;
set_size(split_chunk, split_size);
assert(split_chunk == next_chunk(chunk));
assert(verify_size(split_chunk) == split_size);
return split_chunk;
}
Chunk* AllocManager::try_alloc_unsorted(std::size_t num_bytes) {
while (unsorted_bin_) {
auto chunk = pop_front_from_bin(unsorted_bin_);
assert(chunk && get_flags(chunk) == CHUNK_UNSORTED);
set_flags(chunk, 0);
// for small requests, if this is the last unsorted,
// then split and take if possible
if (!unsorted_bin_ && num_bytes < min_large_size_ &&
chunk->size_ >= num_bytes + chunk_alignment_) {
auto remainder = split_chunk_after(chunk, num_bytes);
set_flags(chunk, CHUNK_IN_USE);
set_flags(remainder, CHUNK_UNSORTED);
push_front_to_bin(remainder, unsorted_bin_);
return chunk;
}
// use this if exact fit
if (chunk->size_ == num_bytes) {
set_flags(chunk, CHUNK_IN_USE);
return chunk;
}
place_in_bins(chunk);
}
return nullptr;
}
Chunk* AllocManager::try_alloc_largebin(std::size_t num_bytes) {
assert(num_bytes >= min_large_size_ && (num_bytes % chunk_alignment_) == 0);
auto where = large_iter(num_bytes); | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
if (where == large_bin_.end()) {
// no large bin chunk is available
return nullptr;
}
else {
// best fit
auto chunk = *where;
assert(get_flags(chunk) == 0);
assert(chunk->size_ >= num_bytes);
large_bin_.erase(where);
if (chunk->size_ == num_bytes) {
// use if exact fit
set_flags(chunk, CHUNK_IN_USE);
return chunk;
}
else if (chunk->size_ >= num_bytes + chunk_alignment_) {
assert((chunk->size_ - num_bytes) % chunk_alignment_ == 0);
// split to take remainder
auto remainder = split_chunk_after(chunk, num_bytes);
set_flags(chunk, CHUNK_IN_USE);
place_in_bins(remainder);
return chunk;
}
}
}
Chunk* AllocManager::alloc_top(std::size_t num_bytes) {
assert(num_bytes >= chunk_alignment_ &&
(num_bytes % chunk_alignment_) == 0);
assert(get_flags(top_chunk_) == 0);
if (top_chunk_->size_ < num_bytes + chunk_alignment_) {
// TODO: how to deal with this?
throw std::runtime_error("memory pool is not enough");
}
assert((top_chunk_->size_ % chunk_alignment_ == 0) &&
top_chunk_->size_ >= num_bytes + chunk_alignment_ &&
(top_chunk_->size_ - num_bytes) % chunk_alignment_ == 0);
auto chunk = top_chunk_; | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
auto chunk = top_chunk_;
auto split_size = top_chunk_->size_ - num_bytes;
// set new size of the current (left) chunk and erase flags
top_chunk_->size_ = num_bytes;
Chunk* split_chunk = reinterpret_cast<Chunk*>(
reinterpret_cast<unsigned char*>(top_chunk_) + num_bytes);
assert(split_chunk);
std::size_t* foot = reinterpret_cast<std::size_t*>(split_chunk);
*foot = num_bytes;
assert(split_chunk->prev_size_ == num_bytes);
split_chunk->prev_ = nullptr;
split_chunk->next_ = nullptr;
split_chunk->size_ = split_size;
top_chunk_ = split_chunk;
assert(split_chunk == next_chunk(chunk));
assert(split_chunk == top_chunk_);
set_flags(chunk, CHUNK_IN_USE);
return chunk;
}
main.cpp
#include <chrono>
#include <cassert>
#include <iostream>
#include <random>
#include <unordered_map>
#include "AllocManager.h"
int main()
{
AllocManager simulator(1UL << 24UL);
std::mt19937 gen(std::random_device{}());
// will be multiplied by alignment
std::gamma_distribution <> chunk_size_dist(2, 2);
constexpr std::size_t chunk_align = 8UL;
constexpr int num = 200'000;
std::bernoulli_distribution to_alloc_or_dealloc(0.65);
std::bernoulli_distribution large_or_small(0.05);
std::unordered_map <void*, std::size_t> allocated;
std::unordered_map <void*, std::size_t> allocated_std;
float my_alloc_duration = 0.0f;
float std_alloc_duration = 0.0f; | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
for (int i = 0; i < num; ++i) {
if (to_alloc_or_dealloc(gen)) {
auto sz = (1 + static_cast<std::size_t>(chunk_size_dist(gen))) * chunk_align;
if (large_or_small(gen)) {
sz += 1024;
}
auto start = std::chrono::steady_clock::now();
auto cnk = simulator.alloc_chunk(sz);
auto end = std::chrono::steady_clock::now();
my_alloc_duration += std::chrono::duration_cast <std::chrono::duration <float, std::micro>>(
end - start).count();
allocated[cnk] = sz;
start = std::chrono::steady_clock::now();
void* ptr = std::malloc(sz);
end = std::chrono::steady_clock::now();
std_alloc_duration += std::chrono::duration_cast <std::chrono::duration <float, std::micro>>(
end - start).count();
allocated_std[ptr] = sz;
}
else {
if (!allocated.empty()) {
auto [cnk, sz] = *allocated.begin();
auto start = std::chrono::steady_clock::now();
simulator.dealloc_chunk(cnk);
auto end = std::chrono::steady_clock::now();
my_alloc_duration += std::chrono::duration_cast <std::chrono::duration <float, std::micro>>(
end - start).count();
allocated.erase(allocated.begin());
assert(!allocated_std.empty());
auto [ptr, sz2] = *allocated_std.begin();
start = std::chrono::steady_clock::now();
std::free(ptr);
end = std::chrono::steady_clock::now();
std_alloc_duration += std::chrono::duration_cast <std::chrono::duration <float, std::micro>>(
end - start).count();
allocated_std.erase(allocated_std.begin());
}
}
}
std::cout << "AllocManager elapsed " << my_alloc_duration / 1000.0f << "ms\n"; | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
}
}
std::cout << "AllocManager elapsed " << my_alloc_duration / 1000.0f << "ms\n";
std::cout << "std::malloc std::free elapsed " << std_alloc_duration / 1000.0f << "ms\n";
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, memory-management",
"url": null
} |
javascript, html, tic-tac-toe
Title: Tic Tac Toe front end
Question: I made a tic tac toe game using JavaScript. I tried to focus on a logical and well structured program. Could someone give me some feedback on the structuring of the JavaScript code?
//create and manage gameboard
const GameBoard = (function () {
//represents board on website
let board = ["0", "1", "2", "3", "4", "5", "6", "7", "8"];
/* col col col
row 0 0,0 0,1 0,2 -> row, col
row 1 1,0 1,1 1,2 -> row, col
row 2 2,0 2,1 2,2 -> row, col
*/
function getboard() {
return board;
}
function setboard(tile, value) {
board[tile] = value;
}
function resetboard() {
board = ["0", "1", "2", "3", "4", "5", "6", "7", "8"];
}
return { getboard, setboard, resetboard };
})();
//create and manage players
const players = (function () {
let player1 = {
symbol: "X",
}
let player2 = {
symbol: "O",
}
return { player1, player2 };
})();
//manage gameflow
const displayControl = (function () {
const winDrawOutput = document.querySelector(".win");//select field for output.
let counter = 0;
//get all 9 tiles:
const tile0 = document.querySelector(".tile.zero");
const tile1 = document.querySelector(".tile.one");
const tile2 = document.querySelector(".tile.two");
const tile3 = document.querySelector(".tile.three");
const tile4 = document.querySelector(".tile.four");
const tile5 = document.querySelector(".tile.five");
const tile6 = document.querySelector(".tile.six");
const tile7 = document.querySelector(".tile.seven");
const tile8 = document.querySelector(".tile.eight"); | {
"domain": "codereview.stackexchange",
"id": 43628,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
//add event listeners:
tile0.addEventListener("click", () => {
if(tile0.textContent === "") {//if empty, add symbol, otherwise dont
tile0.textContent = currentPlayerSymbol();//placeholder for now
GameBoard.setboard(0, currentPlayerSymbol());
checkForWin();
counter++;
}
});
tile1.addEventListener("click", () => {
if(tile1.textContent === "") {//if empty, add symbol, otherwise dont
tile1.textContent = currentPlayerSymbol();
GameBoard.setboard(1, currentPlayerSymbol());//set symbol to board array.
checkForWin();
counter++;
}
});
tile2.addEventListener("click", () => {
if(tile2.textContent === "") {//if empty, add symbol, otherwise dont
tile2.textContent = currentPlayerSymbol();
GameBoard.setboard(2, currentPlayerSymbol());//set symbol to board array.
checkForWin();
counter++;
}
});
tile3.addEventListener("click", () => {
if(tile3.textContent === "") {//if empty, add symbol, otherwise dont
tile3.textContent = currentPlayerSymbol();
GameBoard.setboard(3, currentPlayerSymbol());//set symbol to board array.
checkForWin();
counter++;
}
});
tile4.addEventListener("click", () => {
if(tile4.textContent === "") {//if empty, add symbol, otherwise dont
tile4.textContent = currentPlayerSymbol();
GameBoard.setboard(4, currentPlayerSymbol());//set symbol to board array.
checkForWin();
counter++;
}
});
tile5.addEventListener("click", () => {
if(tile5.textContent === "") {//if empty, add symbol, otherwise dont
tile5.textContent = currentPlayerSymbol();
GameBoard.setboard(5, currentPlayerSymbol());//set symbol to board array.
checkForWin(); | {
"domain": "codereview.stackexchange",
"id": 43628,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
counter++;
}
});
tile6.addEventListener("click", () => {
if(tile6.textContent === "") {//if empty, add symbol, otherwise dont
tile6.textContent = currentPlayerSymbol();
GameBoard.setboard(6, currentPlayerSymbol());//set symbol to board array.
checkForWin();
counter++;
}
});
tile7.addEventListener("click", () => {
if(tile7.textContent === "") {//if empty, add symbol, otherwise dont
tile7.textContent = currentPlayerSymbol();
GameBoard.setboard(7, currentPlayerSymbol());//set symbol to board array.
checkForWin();
counter++;
}
});
tile8.addEventListener("click", () => {
if(tile8.textContent === "") {//if empty, add symbol, otherwise dont
tile8.textContent = currentPlayerSymbol();
GameBoard.setboard(8, currentPlayerSymbol());//set symbol to board array.
checkForWin();
counter++;
}
});
function checkForWin() {
/*
what is possible?
-> horizontal win -> xxx/ooo: dont just check for occupied, check that symbols match
-> 0,0 and 0,1 and 0,2 -> first row horiz. win
-> 1,0 and 1,1 and 1,2 -> sec. row horiz. win
-> 2,0 and 2,1 and 2,2 -> third row horiz. win
-> vertical win ->
-> 0,0 and 1,0 and 2,0 -> first col
-> 0,1 and 1,1 and 2,1 -> second col
-> 0,2 and 1,2 and 2,2 -> third col
-> diagonal win ->
-> 0,0 and 1,1 and 2,2 -> top left to bottom right or vice versa
-> 2,0 and 1,1 and 0,2 -> bottom left to top right or vice versa | {
"domain": "codereview.stackexchange",
"id": 43628,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
-> draw -> everyting occupied but no win registered.
*/
const board = GameBoard.getboard();//get board.
//x win horizontal:
if((board[0] === "X" && board[1] === "X" && board[2] === "X") ||
(board[3] === "X" && board[4] === "X" && board[5] === "X") ||
(board[6] === "X" && board[7] === "X" && board[8] === "X") ||
(board[0] === "X" && board[3] === "X" && board[6] === "X") || //x win vertical
(board[1] === "X" && board[4] === "X" && board[7] === "X") ||
(board[2] === "X" && board[5] === "X" && board[8] === "X") ||
(board[0] === "X" && board[4] === "X" && board[8] === "X") || //x win diagonal
(board[6] === "X" && board[4] === "X" && board[2] === "X")) {
winDrawOutput.textContent = `X wins!`; //X wins
} //same for O:
else if ((board[0] === "X" && board[1] === "X" && board[2] === "X") ||
(board[3] === "X" && board[4] === "X" && board[5] === "X") ||
(board[6] === "X" && board[7] === "X" && board[8] === "X") ||
(board[0] === "X" && board[3] === "X" && board[6] === "X") ||
(board[1] === "X" && board[4] === "X" && board[7] === "X") ||
(board[2] === "X" && board[5] === "X" && board[8] === "X") ||
(board[0] === "X" && board[4] === "X" && board[8] === "X") ||
(board[6] === "X" && board[4] === "X" && board[2] === "X")) {
winDrawOutput.textContent = `O wins!`; //O wins
}//else if everything is occupied but no win has been registered -> draw
else if(board[0] !== "0" && board[1] !== "1" && board[2] !== "2" &&
board[3] !== "3" && board[4] !== "4" && board[5] !== "5" &&
board[6] !== "6" && board[7] !== "7" && board[8] !== "8") {
winDrawOutput.textContent = "It's a draw!";
}
} | {
"domain": "codereview.stackexchange",
"id": 43628,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
winDrawOutput.textContent = "It's a draw!";
}
}
function currentPlayerSymbol() {
let symbol = "";
if(counter === 0 || counter % 2 === 0) {
symbol = players.player1.symbol;
}
else if(counter % 2 !== 0) {
symbol = players.player2.symbol;
}
return symbol;
}
//reset functionality:
function resetView() {
tile0.textContent = "";
tile1.textContent = "";
tile2.textContent = "";
tile3.textContent = "";
tile4.textContent = "";
tile5.textContent = "";
tile6.textContent = "";
tile7.textContent = "";
tile8.textContent = "";
}
function reset() {
//add reset button, on click, reset board and array for board.
GameBoard.resetboard();
resetView();//reset content of all tiles.
winDrawOutput.textContent = "";//reset output field
counter = 0;
}
//on click, reset everything.
const resetButton = document.querySelector(".reset");
resetButton.addEventListener("click", () => {
reset();
resetView();
});
})();
* {
margin: none;
padding: none;
border-style: border-box;
font-family:'Courier New', Courier, monospace;
}
.wrapper {
display: flex;
height: 100vh;
width: 100vw;
flex-direction: column;
align-items: center;
gap: 30px;
}
.title {
font-size: large;
color: darkblue;
}
.title:hover {
color: lightseagreen;
transform: scale(1.1);
}
.board {
display: grid;
height: 24.5rem;
width: 24.5rem;
grid-template-columns: repeat(3,8rem);
grid-template-rows: repeat(3, 8rem);
}
.tile {
width: 8rem;
height: 8rem;
border: 5px solid grey;
display:flex;
justify-content: center;
align-items: center;
font-size: 50px;
}
.tile.zero {
border-top: none;
border-left: none;
}
.tile.one {
border-top: none;
} | {
"domain": "codereview.stackexchange",
"id": 43628,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
.tile.zero {
border-top: none;
border-left: none;
}
.tile.one {
border-top: none;
}
.tile.two {
border-top: none;
border-right: none;
border-left: none;
}
.tile.three {
border-left: none;
border-bottom: none;
}
.tile.four {
border-bottom: none;
}
.tile.five {
border-right: none;
border-left: none;
border-bottom: none;
}
.tile.six {
border-left: none;
border-bottom: none;
}
.tile.seven {
border-bottom: none;
}
.tile.eight {
border-left: none;
border-right: none;
border-bottom: none;
}
.win {
height: 100px;
width: 250px;
text-align: center;
}
button {
width: 8rem;
height: 4rem;
font-size: 1.5rem;
border-radius: 1rem;
background: white;
}
button:hover {
transform: scale(1.1);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic Tac Toe</title>
<link rel="stylesheet" href="./css/style.css">
<script defer src="./javaScript/doStuff.js"></script>
</head>
<body>
<div class="wrapper">
<div class="title">
<h1>Tic-Tac-Toe</h1>
</div>
<div class="gridContainer">
<div class="board">
<div class="tile zero"></div>
<div class="tile one"></div>
<div class="tile two"></div>
<div class="tile three"></div>
<div class="tile four"></div>
<div class="tile five"></div>
<div class="tile six"></div>
<div class="tile seven"></div>
<div class="tile eight"></div>
</div>
</div>
<div class="win"></div>
<button type="button "class="reset">Reset?</button>
</div>
</body>
</html> | {
"domain": "codereview.stackexchange",
"id": 43628,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
Edit: just realized that I forgot to change the Symbols that the program checks for in the win function to "O" instead of "X" for the if condition that checks whether "O" won. Ignore that please.
Answer: The biggest issue here is the repetition. Whenever there is repeated code that only varies by variable value, we can use loops or iteration to remove the repetition.
In the case of the DOM elements that represents the tiles, we know that DOM querySelectorAll will return the elements in the order in which they appear in the DOM, which is also their natural sequence. Instead of querySelector for each tile in turn, we can just get all of the tiles, and then iterator over them to apply the same event handler.
checkForWin simplification
There are specific known sequences that define a win (8 of them) and so again, instead of repeatedly querying the DOM elements and comparing them, we can iterate over the combinations and reduce is down to one of three values, either of the player symbols or undefined to indicate no winner.
This also allows us to simplify how we update the winDrawOutput element.
IIFE information hiding
The choice to use an IIFE to hide the private data associated with the board is interesting, bit it's not necessary for the players as there is nothing to be hidden. This could just as easily be written as:
const players = {
player1 = {
symbol: 'X'
},
player2 = {
symbol: 'O'
}
} | {
"domain": "codereview.stackexchange",
"id": 43628,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
It might also be good to bring all of the game state together into a single closure (board and count). I actually don't think you need count, it might be better to just store the active player and toggle back and forth after each turn. I didn't use count to calculate gameOver for example, but just counted the number of played tiles in the board.
Game Over
Once there is a winner or all of the tiles have been played (a draw) we should block the ability to continue to play tiles. I've not dealt with this.
Board initialisation
It's not necessary to populate the board with values, we can just use undefined as the starting point, and use Array.fill to simplify the statement.
Game State and UI content
At present, there is an overlap between the board state (the value assigned to board) and the UI state (the textContent value of each tile). This raises the possibility that they could get out of sync. It would be better to have a single source of truth and use the board state to populate the UI elements. When playing the tiles, the board state should be checked and updated, and then a render method could be used to update the DOM content according to the board state. I moved partially in this direction in checkForWin, using the board state rather than the DOM content. The click handlers could be updated to refer to board state and then update DOM content accordingly.
CSS
I've not touched the CSS, but its not strictly necessary to have a class for each tile element (.zero, .one, .two, ...) because we can use CSS's nth-child to similar effect.
//create and manage gameboard
const GameBoard = (function () {
//represents board on website
let board
function getboard() {
return board;
}
function setboard(tile, value) {
board[tile] = value;
}
function resetboard() {
board = Array(9).fill(undefined);
}
resetboard();
return { getboard, setboard, resetboard };
})(); | {
"domain": "codereview.stackexchange",
"id": 43628,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
resetboard();
return { getboard, setboard, resetboard };
})();
//create and manage players
const players = (function () {
let player1 = {
symbol: "X",
}
let player2 = {
symbol: "O",
}
return { player1, player2 };
})();
//manage gameflow
const displayControl = (function () {
const winDrawOutput = document.querySelector(".win");//select field for output.
let counter = 0;
//get all 9 tiles:
const tiles = document.querySelectorAll('.tile');
tiles.forEach((tile, index) => {
tile.addEventListener('click', () => {
if (tile.textContent === '') {
const player = currentPlayerSymbol();
tile.textContent = player;
GameBoard.setboard(index, player);
checkForWin();
counter++;
}
});
});
function checkForWin() {
const board = GameBoard.getboard();//get board.
const lines = [
[ 0, 1, 2 ],
[ 3, 4, 5 ],
[ 6, 7, 8 ],
[ 0, 3, 6 ],
[ 1, 4, 7 ],
[ 2, 5, 8 ],
[ 0, 4, 8 ],
[ 2, 4, 6 ]
];
const winner = lines.reduce((acc, line) => {
return acc || line.reduce((acc, tile) => acc === board[tile] ? acc : undefined, board[line[0]]);
}, undefined);
const gameOver = !!winner || board.reduce((acc, tile) => acc + (tile !== undefined), 0) === 9;
winDrawOutput.textContent = gameOver ? (winner ? `${winner} wins!` : `It's a draw!`) : '';
}
function currentPlayerSymbol() {
let symbol = "";
if(counter === 0 || counter % 2 === 0) {
symbol = players.player1.symbol;
}
else if(counter % 2 !== 0) {
symbol = players.player2.symbol;
}
return symbol;
} | {
"domain": "codereview.stackexchange",
"id": 43628,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
//reset functionality:
function resetView() {
document.querySelectorAll('.tile').forEach(tile => tile.textContent = '');
}
function reset() {
//add reset button, on click, reset board and array for board.
GameBoard.resetboard();
resetView();//reset content of all tiles.
winDrawOutput.textContent = "";//reset output field
counter = 0;
}
//on click, reset everything.
const resetButton = document.querySelector(".reset");
resetButton.addEventListener("click", () => {
reset();
resetView();
});
})();
* {
margin: none;
padding: none;
border-style: border-box;
font-family:'Courier New', Courier, monospace;
}
.wrapper {
display: flex;
height: 100vh;
width: 100vw;
flex-direction: column;
align-items: center;
gap: 30px;
}
.title {
font-size: large;
color: darkblue;
}
.title:hover {
color: lightseagreen;
transform: scale(1.1);
}
.board {
display: grid;
height: 24.5rem;
width: 24.5rem;
grid-template-columns: repeat(3,8rem);
grid-template-rows: repeat(3, 8rem);
}
.tile {
width: 8rem;
height: 8rem;
border: 5px solid grey;
display:flex;
justify-content: center;
align-items: center;
font-size: 50px;
}
.tile.zero {
border-top: none;
border-left: none;
}
.tile.one {
border-top: none;
}
.tile.two {
border-top: none;
border-right: none;
border-left: none;
}
.tile.three {
border-left: none;
border-bottom: none;
}
.tile.four {
border-bottom: none;
}
.tile.five {
border-right: none;
border-left: none;
border-bottom: none;
}
.tile.six {
border-left: none;
border-bottom: none;
}
.tile.seven {
border-bottom: none;
}
.tile.eight {
border-left: none;
border-right: none;
border-bottom: none;
}
.win {
height: 100px;
width: 250px;
text-align: center;
} | {
"domain": "codereview.stackexchange",
"id": 43628,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
.win {
height: 100px;
width: 250px;
text-align: center;
}
button {
width: 8rem;
height: 4rem;
font-size: 1.5rem;
border-radius: 1rem;
background: white;
}
button:hover {
transform: scale(1.1);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic Tac Toe</title>
</head>
<body>
<div class="wrapper">
<div class="title">
<h1>Tic-Tac-Toe</h1>
</div>
<div class="gridContainer">
<div class="board">
<div class="tile zero"></div>
<div class="tile one"></div>
<div class="tile two"></div>
<div class="tile three"></div>
<div class="tile four"></div>
<div class="tile five"></div>
<div class="tile six"></div>
<div class="tile seven"></div>
<div class="tile eight"></div>
</div>
</div>
<div class="win"></div>
<button type="button "class="reset">Reset?</button>
</div>
</body>
</html> | {
"domain": "codereview.stackexchange",
"id": 43628,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, tic-tac-toe",
"url": null
} |
c, pointers
Title: C Program - Camel Case (creates or splits camel case variables, methods and class names.)
Question: I have written a program in C, which does the following operations:
creates or splits Camel Case variable, method, class names.
Input format
Each line of the input file will begin with an operation (S or C) followed by a semi-colon followed by M, C, or V followed by a semi-colon followed by the words you'll need to operate on.
The operation will either be S (split) or C (combine)
M indicates method, C indicates class, and V indicates variable
In the case of a split operation, the words will be a camel case method, class or variable name that you need to split into a space-delimited list of words starting with a lowercase letter.
In the case of a combine operation, the words will be a space-delimited list of words starting with lowercase letters that you need to combine into the appropriate camel case String. Methods should end with an empty set of parentheses to differentiate them from variable names.
Output Format:
For each input line, your program should print either the space-delimited list of words (in the case of a split operation) or the appropriate camel case string (in the case of a combine operation).
Sample Input
S;M;plasticCup()
C;V;mobile phone
C;C;coffee machine
S;C;LargeSoftwareBook
C;M;white sheet of paper
S;V;pictureFrame
Sample Output
plastic cup
mobilePhone
CoffeeMachine
large software book
whiteSheetOfPaper()
picture frame
here is what I've written so far:
#include <asm-generic/errno-base.h>
#include <asm-generic/errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stddef.h>
#include <errno.h>
#include <err.h>
#include <sys/types.h>
#define SPACE ' '
#define SPLIT 'S'
#define COMBINE 'C'
#define METHOD 'M'
#define CLASS COMBINE
#define VARIABLE 'V' | {
"domain": "codereview.stackexchange",
"id": 43629,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, pointers",
"url": null
} |
c, pointers
static char *caseProblem(char *restrict);
static void *substr(const void *restrict, size_t);
static char *split(char *restrict, int);
static char *combine(char *restrict, int);
static void *__memmove(void *restrict, int, size_t);
int
main(void)
{
char *p = NULL;
ssize_t len;
size_t n = 0;
while ((len = getline(&p, &n, stdin)) != -1)
(void)fprintf(stdout, "%s", caseProblem(p));
free(p);
exit(EXIT_SUCCESS);
}
static void *
__memmove(void *restrict src, int delim, size_t n)
{
char *dest = NULL;
if ((dest = (char *)malloc(65535 * sizeof(char))) == NULL)
errx(EXIT_FAILURE, "%s", strerror(ENOMEM));
memmove(dest, src, strlen(src) - n);
dest[strlen(dest)] = delim;
return (dest);
}
static char *
caseProblem(char *restrict p)
{
char opt, type;
unsigned int i;
size_t size = strlen(p);
/* extract option (S or C) */
opt = p[0];
/* extract type (M, V or C) */
type = p[2];
p = substr(p, 4);
if (opt == SPLIT && type == METHOD)
p = __memmove(p, '\n', 3);
if (opt == COMBINE && type == METHOD) {
p = __memmove(p, 0, 1); // reject: '\n'?
strcat(p, "()\n");
}
i = 0;;
while (i < size) {
switch (opt) {
case SPLIT:
p = split(p, type);
break;
case COMBINE:
p = combine(p, type);
break;
default:
errx(EXIT_FAILURE, "Invalid Option...!\n");
}
++i;
}
p[i] = '\0';
return (char *)(p);
}
static void *
substr(const void *restrict src, size_t n)
{
char *dest = NULL;
if ((dest = (char *)malloc(65535 * sizeof(char))) == NULL)
errx(EXIT_FAILURE, "%s", strerror(ENOMEM));
return (memcpy(dest, (src + n), strlen(src)));
}
static char *
split(char *restrict in, int type)
{
char *out = NULL;
unsigned int i, o;
size_t size = strlen(in); | {
"domain": "codereview.stackexchange",
"id": 43629,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, pointers",
"url": null
} |
c, pointers
if ((out = (char *)malloc(65535 * sizeof(char))) == NULL)
errx(EXIT_FAILURE, "%s", strerror(ENOMEM));
i = o = 0;
while (i < size) {
if (type == METHOD || type == VARIABLE || type == CLASS) {
if (isupper(in[i])) {
in[i] = tolower(in[i]);
if (i != 0) {
out[o++] = SPACE;
out[o] = in[i];
}
}
} else {
errx(EXIT_FAILURE, "Invalid Type...!\n");
}
out[o++] = in[i];
++i;
}
out[o] = '\0';
return (char *)(out);
}
static char *
combine(char *restrict p, int type)
{
unsigned int i, j, space;
size_t size = strlen(p);
i = j = 0;
space = 0;
while (i < size) {
switch (type) {
case VARIABLE:
case METHOD:
if (p[i] == SPACE) {
++space;
if (islower(p[space]))
p[i + 1] = toupper(p[i + 1]);
}
break;
case CLASS:
if (i == 0)
p[i] = toupper(p[i]);
if (p[i] == SPACE) {
++space;
if (islower(p[space]))
p[i + 1] = toupper(p[i + 1]);
}
break;
default:
errx(EXIT_FAILURE, "Invalid Type...!\n");
break;
}
if (p[i] != SPACE)
p[j++] = p[i];
++i;
}
p[j] = '\0';
return (p);
}
I'd like to know if there is any way to improve it. | {
"domain": "codereview.stackexchange",
"id": 43629,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, pointers",
"url": null
} |
c, pointers
Answer: Memory leaks and unclear ownership
caseProblem's use of __memmove will lead to memory leaks, as it always overwrites the value of p.
Use of getline's internal allocation I feel is unclear and leads to the other problems, because its not clear who 'owns' and is responsible for the initial allocation.
Whilst the C Library is literred with examples of internal allocation, its generally not good practice. It's good practice for the caller to be responsible for allocation, which could be either heap or stack depending on the size of memory required (and in some contexts dynamic allocation can ultimately lead to failure due to fragmentation).
The C library has got better over time (whilst carrying the technical debt of earlier bad practices) and it usual to require a method to take both the source and destination address AND the size allocated (or used) by each, so that the method can enforce rules regarding overrun and overlap if required.
Fix memory allocations could lead to overflow or excess memory usage
Both substr and __memmove are allocating 65k of memory regardless of the input length. It should be clear when functions are allocating memory, usually by providing a specialise xxx_free function. Alternatively, avoid doing memory allocation within subroutines, allowing the caller to provide the destination address, which can then be memory allocated from stack or heap according to its needs.
Function naming
__memmove is poorly named. To avoid a conflict with the standard library memmove you've added double underscore, which is a convention to indicate a private and internal API. You've also changed the semantics in the process, especially regards the internal allocation, which guarantees that memcpy could have been used (as destinstation will never overlap source).
Personally I'd find a completely different name that more accurately describes what its doing (e.g. strncpyWithDelimiter). | {
"domain": "codereview.stackexchange",
"id": 43629,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, pointers",
"url": null
} |
c, pointers
It's not a great name for the standard library as it happens, it differs from memcpy only in that it allows for the source and destination addresses to overlap. But then the standard C is litered with poorly named functions in part due to its age.
substr seems to be doing almost exactly the same but without the delimiter.
caseProblem assumptions
This function assumes that the buffer p contains a certain number of characters. It's possible that the allocation is less than the 4 required for the input parameter (for example if the user just presses carriage return). This means that you are dipping into memory over which you have no knowledge of the contents and could lead to indeterminate behaviour. Always check that your buffer is at least the expected length before subscripting (you could use a strlen check at the top of the function).
I've not checked the actual logic used, I think these are the significant problems as it stands. | {
"domain": "codereview.stackexchange",
"id": 43629,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, pointers",
"url": null
} |
python, python-3.x, file-system
Title: Faster way to find duplicates in a directory using Python
Question: This is my first Python project in file management.
It's a finished and passed exercise from JetBrains (Duplicate File Handler).
The main job is reading a full path to folder from argument, list files of the folder, grouping them based on same size and md5 hash (md5 required for passing the test) and then asking for deletion based on the input number (ex 1 3 6) separated with space (input number is referring to the full path of the file that user wants to delete.
Is there any way to make the code more clever and avoid nested for loops to make it faster? Especially in duplicates_check function and in delete_duplicates function.
Also I was confused a bit in the grouping part duplicates_check function were we are called to print in groups of same bytes for example:
5550640 bytes
Hash: 909ba4ad2bda46b10aac3c5b7f01abd5
root_folder/poker_face.mp3
root_folder/poker_face_copy.mp3
3422208 bytes
Hash: a7f5f35426b927411fc9231b56382173
3. root_folder/audio/classic/unknown.mp3
4. root_folder/masterpiece/rick_astley_never_gonna_give_you_up.mp3
Hash: b6d767d2f8ed5d21a44b0e5886680cb9
5. root_folder/masterpiece/the_magic_flute_queen_of_the_night_aria.mp3
6. root_folder/masterpiece/the_magic_flute_queen_of_the_night_aria_copy.mp3
55540 bytes
Hash: 6b92a4ad2bda46b10aac3c5b7f013821
7. root_folder/poker_face.mp3
8. root_folder/poker_face_copy.mp3
You can see that if the bytes are the same and only the hash changes, the line with bytes doesn't get printed again so I created a new list to append the bytes that already has been iterated to pass the test.
I couldn't think of another way to check for example if in the duplicates_list variable that is a dictionary of
duplicates_list = {(hash1, bytes1): [path of files that those keys are referring to, ...],
(hash2, bytes1) : [path of files that those keys are referring to, ...]} | {
"domain": "codereview.stackexchange",
"id": 43630,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, file-system",
"url": null
} |
python, python-3.x, file-system
If bytes1 are the same for both keys don't print them on separate lines (as different keys) and instead print them as the example.
Right now everything works great I just want to see different more clever way to achieve this.
# write your code here
import argparse
import os
import hashlib
# import sys
# args = sys.argv
# if len(args) < 2:
# print('Directory is not specified')
parser = argparse.ArgumentParser(description="You must enter a folder to list files in dir and subdir")
parser.add_argument("folder", nargs="?")
args = parser.parse_args()
choice = args.folder
FILTER_BY_EXTENSION = False
# Function to get files in directory and create list with dictionaries (dic per file) with file attributes
# (filename, extension, bytes, full path and md5_hash)
def file_listing():
files_values = []
if choice is None:
print("Directory is not specified")
else:
for root, dirs, files in os.walk(choice):
for name in files:
hash_md5 = hashlib.md5()
with open(os.path.join(root, name), "rb") as f:
for chunk in iter(lambda: f.read(1024), b""):
hash_md5.update(chunk)
file_values = {
"filename": name,
"extension": name[name.rfind(".") + 1:],
"bytes": os.path.getsize(os.path.join(root, name)),
"full_path": os.path.join(root, name),
"md5_hash": hash_md5.hexdigest()
}
files_values.append(file_values)
return files_values
def file_filter_by_extension(files_values):
global FILTER_BY_EXTENSION
extension = input("Enter file format:\n")
if len(extension) == 0:
return False
extension_dictionary = []
for i in files_values:
if i["extension"] == extension:
extension_dictionary.append(i)
print()
FILTER_BY_EXTENSION = True
return extension_dictionary | {
"domain": "codereview.stackexchange",
"id": 43630,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, file-system",
"url": null
} |
python, python-3.x, file-system
# Grouping files by size and return a sorted list with pairs of (bytes, [{full path, md5_hash]}).
# If bytes are the same the pairs are (bytes, [{full path, md5_hash}...{full path, md5_hash}]
def bytes_filter(files_values):
sorting_type = input('''Size sorting options:
1. Descending
2. Ascending\n''')
print()
bytes_dictionary = {key["bytes"]: [] for key in files_values}
sorted_list = []
for i in files_values:
bytes_dictionary[i["bytes"]].append({"full_path": i["full_path"], "md5_hash": i["md5_hash"]})
while True:
if sorting_type in ["1", "2"]:
break
else:
print("Wrong option\nEnter a sorting option:\n")
sorting_type = input()
if sorting_type == "1":
for i, j in sorted(bytes_dictionary.items(), reverse=True):
print(f'{i} bytes')
sorted_list.append([i, j])
for files in range(len(j)):
print(j[files]["full_path"])
print()
if sorting_type == "2":
for i, j in sorted(bytes_dictionary.items()):
sorted_list.append([i, j])
print(f'{i} bytes')
for files in range(len(j)):
print(j[files]["full_path"])
print()
return sorted_list
# Checking for duplicates - Constructing a duplicates dicts and a list to print by group if bytes are the same.
# Printed values: Bytes \n Hash \n full path of files with line numbering.
# If the bytes are the same in the next different file pairs we dont print bytes again instead
# we print only hash and full path else we print again a completely new line Bytes \n Hash \n full path | {
"domain": "codereview.stackexchange",
"id": 43630,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, file-system",
"url": null
} |
python, python-3.x, file-system
def duplicates_check(files_values):
duplicates_ask = input('Check for duplicates?\n').lower()
while True:
if duplicates_ask in ["yes", "no"]:
if duplicates_ask == "yes":
break
elif duplicates_ask == "no":
return False
else:
print("Wrong option\n")
duplicates_ask = input()
duplicates_list = {}
line_number = 1
for i in files_values:
for j in i[1]:
if (j["md5_hash"], i[0]) not in duplicates_list:
duplicates_list[tuple((j["md5_hash"], i[0]))] = []
duplicates_list[(j["md5_hash"], i[0])].append(j["full_path"])
else:
duplicates_list[tuple((j["md5_hash"], i[0]))].append(j["full_path"])
# Constructing a final list to return with numbered duplicate files
temporary_bytes = []
final_duplicate_list = {}
for key, value in duplicates_list.items():
if len(duplicates_list[(key[0], key[1])]) > 1:
if key[1] not in temporary_bytes:
temporary_bytes.append(key[1])
print()
print(f'{key[1]} bytes\nHash: {key[0]}')
else:
print(f'Hash: {key[0]}')
for path_value in duplicates_list[(key[0], key[1])]:
print(f'{line_number}. {path_value}')
final_duplicate_list[str(line_number)] = path_value
line_number += 1
return final_duplicate_list | {
"domain": "codereview.stackexchange",
"id": 43630,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, file-system",
"url": null
} |
python, python-3.x, file-system
def delete_duplicates(list_duplicates, working_directory):
print()
total_bytes_removed = 0
duplicates_delete = input('Delete files?\n').lower()
while True:
if duplicates_delete in ["yes", "no"]:
if duplicates_delete == "yes":
break
elif duplicates_delete == "no":
return False
else:
print("\nWrong option")
duplicates_delete = input()
duplicates_index = input("\nEnter file numbers to delete:\n").strip().split(" ")
while True:
if set(duplicates_index).issubset(list_duplicates):
break
else:
print("\nWrong format")
duplicates_index = input().strip().split(" ")
for i in duplicates_index:
for j in range(len(working_directory)):
if list_duplicates[i] == working_directory[j]["full_path"]:
total_bytes_removed += working_directory[j]["bytes"]
os.remove(list_duplicates[i])
print(f'\nTotal freed up space: {total_bytes_removed} bytes')
def main():
directory = file_listing()
extension_filter = file_filter_by_extension(directory)
if FILTER_BY_EXTENSION:
bytes_filtering = bytes_filter(extension_filter)
duplicates = duplicates_check(bytes_filtering)
delete_duplicates(duplicates, directory)
else:
bytes_filtering = bytes_filter(directory)
duplicates = duplicates_check(bytes_filtering)
delete_duplicates(duplicates, directory)
if __name__ == main():
main()
Answer: Delete commented-out code blocks like
# import sys
# args = sys.argv
# if len(args) < 2:
# print('Directory is not specified')
This is the kind of thing that git branches should be used for.
Move this code:
parser = argparse.ArgumentParser(description="You must enter a folder to list files in dir and subdir")
parser.add_argument("folder", nargs="?")
args = parser.parse_args()
choice = args.folder | {
"domain": "codereview.stackexchange",
"id": 43630,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, file-system",
"url": null
} |
python, python-3.x, file-system
into a function. choice is not a good variable name in this case.
FILTER_BY_EXTENSION is not a constant, so don't capitalise it and don't leave it global; pass it around in function parameters.
choice should never be None. You should not use ? in your argument parsing; you should force the user to pass the argument.
Use pathlib.Path instead of os.path where alternatives exist.
For performance you should be using a much larger block size such as 16 MiB.
I forgot (or never knew) the sentinel-form of the iter() built-in, so thank you for teaching me!
Do not represent file records as dictionaries. Use a class. Since the class is immutable and needs to be sortable, NamedTuple makes this easy. Many of the fields in your file record should not be written out at all, since Path makes these easy to be calculated inline.
Whenever you .append()-and-return as you do in file_listing, consider using an iterator instead.
file_filter_by_extension should not return False-or-a-list. Instead, unconditionally return an iterable, and the size of the iterable should be conditional on the user's input.
Expressions like in ["1", "2"]: should use a set literal {} instead.
Use defaultdict(list) to simplify your duplicate aggregation logic.
Factor out a function to ask a yes-no question with a validation loop.
In your input validation loops, Wrong option is not a very good way to describe what happened, since there is not one right answer: instead the user input an invalid option.
Consider yielding the number of bytes deleted from a loop and applying sum() afterward.
This is buggy:
if __name__ == main():
main() | {
"domain": "codereview.stackexchange",
"id": 43630,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, file-system",
"url": null
} |
python, python-3.x, file-system
since it will unconditionally run main even if an importer doesn't want to; and will always evaluate to False. Instead, you need to compare to the string __main__.
To make your selection friendlier for the user, rather than 1/2 for your order options, why not ask for a/d?
Similarly, rather than gathering deletion indices all in one shot via your
input("\nEnter file numbers to delete:\n")
you should instead stagger this choice per file, and also ask for the single file to keep, not ask for all the files to delete.
You call hexdigest() too early, because you use a string for business logic when that string should only be used for presentation. Just call digest() instead, which uses a more compact bytes representation. This will be marginally faster for internal comparison, and you can in turn call .hex() on that to get a presentable string.
Suggested
import argparse
import os
import hashlib
from collections import defaultdict
from pathlib import Path
from typing import Iterator, Iterable, NamedTuple
CHUNK_SIZE = 4 * 1024 * 1024
class HashedFile(NamedTuple):
size: int
path: Path
md5_hash: bytes
def __str__(self) -> str:
return str(self.path)
@classmethod
def load(cls, root: Path, name: str) -> 'HashedFile':
path = root / name
md5_hash = hashlib.md5()
with path.open('rb') as f:
for chunk in iter(lambda: f.read(CHUNK_SIZE), b''):
md5_hash.update(chunk)
return cls(path.stat().st_size, path, md5_hash.digest())
def file_listing(directory: str) -> Iterator[HashedFile]:
for root, dirs, files in os.walk(directory):
root_path = Path(root)
for name in files:
yield HashedFile.load(root_path, name) | {
"domain": "codereview.stackexchange",
"id": 43630,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, file-system",
"url": null
} |
python, python-3.x, file-system
def filter_by_extension(files: Iterable[HashedFile]) -> Iterator[HashedFile]:
extension = input('Enter file extension to select, or press enter for all: ')
if len(extension) == 0:
yield from files
else:
for file in files:
if file.path.suffix == '.' + extension:
yield file
def print_by_size(files: Iterable[HashedFile]) -> None:
print('Size sorting options:'
'\n d. Descending'
'\n a. Ascending')
while True:
order = input('Enter a sorting option: ')
if order in {'a', 'd'}:
break
print('Invalid option')
print()
for file in sorted(files, reverse=order == 'd'):
print(f'{file.size:9} bytes: {file}')
def ask_yn(prompt: str) -> bool:
while True:
answer = input(f'{prompt} (y|n)? ')[:1].lower()
if answer in {'y', 'n'}:
return answer == 'y'
print('Invalid option')
def find_duplicates(files: Iterable[HashedFile]) -> Iterator[list[HashedFile]]:
duplicates = defaultdict(list)
for file in files:
duplicates[file.size, file.md5_hash].append(file)
for (size, md5_hash), dupe_files in duplicates.items():
if len(dupe_files) > 1:
print(f'Size: {size} bytes, MD5: {md5_hash.hex()}')
for i, file in enumerate(dupe_files, 1):
print(f'{i:4}. {file}')
yield dupe_files
def delete_duplicates(duplicate_groups: Iterable[list[HashedFile]]) -> Iterator[int]:
for files in duplicate_groups:
while True:
keep_str = input('Enter file number to keep: ')
if keep_str.isdigit():
keep_index = int(keep_str) - 1
if 0 <= keep_index < len(files):
keep = files[keep_index]
break
print('Invalid option') | {
"domain": "codereview.stackexchange",
"id": 43630,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, file-system",
"url": null
} |
python, python-3.x, file-system
for file in files:
if file is not keep:
print(f' Deleting {file}')
file.path.unlink()
yield file.size
def main() -> None:
parser = argparse.ArgumentParser(description='Handle duplicate files')
parser.add_argument('folder', help='folder to list files in dir and subdir')
args = parser.parse_args()
directory = file_listing(args.folder)
directory = tuple(filter_by_extension(directory))
print_by_size(directory)
print()
if ask_yn('Check for duplicates'):
duplicates = find_duplicates(directory)
if ask_yn('Delete duplicates'):
bytes_removed = sum(delete_duplicates(duplicates))
print(f'\nTotal freed up space: {bytes_removed} bytes')
else:
for _ in duplicates: # consume iterator to print
pass
if __name__ == '__main__':
main()
Output
Enter file extension to select, or press enter for all:
Size sorting options:
d. Descending
a. Ascending
Enter a sorting option: a
47 bytes: 277665/UserInput_277665/.idea/.gitignore
271 bytes: 277665/UserInput_277665/.idea/misc.xml
356 bytes: 277665/UserInput_277665/.idea/modules.xml
423 bytes: 277665/com.stackexchange.userinput/com.stackexchange.userinput.iml
640 bytes: 277665/Main.java
640 bytes: 277665/com.stackexchange.userinput/src/Main.java
2108 bytes: 277665/Main.class
2108 bytes: 277665/UserInput_277665/out/production/com.stackexchange.userinput/Main.class
2234 bytes: 277665/UserInput_277665/.idea/workspace.xml | {
"domain": "codereview.stackexchange",
"id": 43630,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, file-system",
"url": null
} |
python, python-3.x, file-system
Check for duplicates (y|n)? y
Delete duplicates (y|n)? y
Size: 2108 bytes, MD5: 89085fddc797fda5dd8319f85b206177
1. 277665/Main.class
2. 277665/UserInput_277665/out/production/com.stackexchange.userinput/Main.class
Enter file number to keep: 2
Deleting 277665/Main.class
Size: 640 bytes, MD5: a21c362935f1afb357bb8e9ce5d7acbb
1. 277665/Main.java
2. 277665/com.stackexchange.userinput/src/Main.java
Enter file number to keep: 2
Deleting 277665/Main.java
Total freed up space: 2748 bytes | {
"domain": "codereview.stackexchange",
"id": 43630,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, file-system",
"url": null
} |
c#, multithreading, regex, thread-safety, cache
Title: Thread-safe cached compiled Regex
Question: I have a use case where I want to keep a pre-compiled regex, cached, for performance reasons, but the regex pattern also needs to be updated infrequently. Instances of CachedRegexFilter class will be used by multiple threads. The actual pattern for the regex is supplied as a custom class, StringConfig, which is basically a global volatile string that can be updated by a different thread.
Example usage:
// Main thread:
StringConfig regex = new StringConfig() { Value = ".*"};
CachedRegexFilter filter = new CachedRegexFilter(regex);
// now the filter is passed on to multiple service classes
MyApi(apiFilter: filter);
MyCron(cronFilter: filter);
//The config is updated by a seperate service
ConfigUpdaterSerice(configToUpdate: regex);
I have come up with this solution but would appreciate a review to ensure it is truly thread safe!
// a thread safe class for filtering strings based on a dynamic regex represented by a StringConfig
public class CachedRegexFilter
{
private readonly StringConfig _overrideRegex;
private readonly object _regexReplaceLock = new object();
private volatile string _currentoverrideRegexPattern;
private volatile Regex _currentoverrideRegex;
public CachedRegexFilter(StringConfig overrideRegex)
{
_overrideRegex = Preconditions.IsNotNull(overrideRegex, nameof(overrideRegex)); ;
UpdateCachedPattern();
}
public bool Matches(string toMatch)
{
if (_currentoverrideRegexPattern != _overrideRegex.Value)
{
lock (_regexReplaceLock)
{
// now entering critical section. Check again
if (_currentoverrideRegexPattern != _overrideRegex.Value)
{
UpdateCachedPattern();
}
}
}
return _currentoverrideRegex?.IsMatch(toMatch) ?? false;
} | {
"domain": "codereview.stackexchange",
"id": 43631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, multithreading, regex, thread-safety, cache",
"url": null
} |
c#, multithreading, regex, thread-safety, cache
return _currentoverrideRegex?.IsMatch(toMatch) ?? false;
}
private void UpdateCachedPattern()
{
_currentoverrideRegexPattern = _overrideRegex.Value;
_currentoverrideRegex = string.IsNullOrEmpty(_currentoverrideRegexPattern)
? null
: new Regex(_currentoverrideRegexPattern, RegexOptions.Singleline | RegexOptions.Compiled);
}
}
Answer: It depends a bit on what you mean by thread-safe here. If you mean "won't throw an exception", then you're definitely safe. You do have some potentially bad behaviour depending on your use case.
Consider the case when the config has just been updated. Thread 1 calls Matches and enters the critical region to update the regex and gets paused here:
private void UpdateCachedPattern()
{
_currentoverrideRegexPattern = _overrideRegex.Value;
// Thread 1 paused here "between" these statements
_currentoverrideRegex = string.IsNullOrEmpty(_currentoverrideRegexPattern)
? null
: new Regex(_currentoverrideRegexPattern, RegexOptions.Singleline | RegexOptions.Compiled);
}
Thread 2 now starts executing Matches:
if (_currentoverrideRegexPattern != _overrideRegex.Value)
{
// ...
As thread 1 has already updated the _currentoverrideRegexPattern field, the check is false (i.e. they are already equal). Thread 2 continues executing and uses the out of date Regex.
You could solve this by swapping the order:
private void UpdateCachedPattern()
{
var newPattern = _overrideRegex.Value;
_currentoverrideRegex = string.IsNullOrEmpty(newPattern)
? null
: new Regex(newPattern, RegexOptions.Singleline | RegexOptions.Compiled);
_currentoverrideRegexPattern = newPattern;
} | {
"domain": "codereview.stackexchange",
"id": 43631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, multithreading, regex, thread-safety, cache",
"url": null
} |
c#, multithreading, regex, thread-safety, cache
Honestly, the pattern you're going for here seems like a recipe for disaster. What you want to do is be able to either pull the configuration each time or have a way of the configuration notifying interested parties that it has changed.
What you're currently doing is basically mutating global state which makes code harder to follow and easier to break. | {
"domain": "codereview.stackexchange",
"id": 43631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, multithreading, regex, thread-safety, cache",
"url": null
} |
rust, pig-latin
Title: Rust Pig Latin exercise solution
Question: I just finished the chapter about collections from the Rust book, and it recommended trying some exercises provided there, such as a Pig Latin translator.
Convert strings to pig latin. The first consonant of each word is moved to the end of the word and “ay” is added, so “first” becomes “irst-fay.” Words that start with a vowel have “hay” added to the end instead (“apple” becomes “apple-hay”). Keep in mind the details about UTF-8 encoding!
use std::io;
fn main() {
let mut inp = String::new();
io::stdin().read_line(&mut inp).expect("Could not read");
inp.remove(inp.len() - 1); // newline
let cha = inp.chars().next().expect("Empty string");
if is_consonant(cha) {
inp += "-hay";
} else {
inp.remove(0);
inp += &format!("-{}ay", cha);
}
println!("{}", inp);
}
fn is_consonant(c: char) -> bool {
['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'].contains(&c)
}
Does my code satisfy whatever is required for it to be idiomatic Rust?
Answer: Suggested improvements:
Use trim() to remove the newline and other white spaces.
let mut inp = inp.trim().to_string();
The function is_consonant() actually checks if a letter is a vowel so it should be renamed.
The vowels can be extracted into a const.
const VOWELS: [char; 10] = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
The is_vowel(c: char) function can take reference to a char since that it what it uses.
fn is_vowel(c: &char) -> bool {
VOWELS.contains(c)
}
Final Code:
use std::io;
const VOWELS: [char; 10] = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
fn main() {
let mut inp = String::new();
io::stdin().read_line(&mut inp).expect("Could not read");
let mut inp = inp.trim().to_string();
let cha = inp.chars().next().expect("Empty string");
if is_vowel(&cha) {
inp += "-hay";
} else {
inp.remove(0);
inp += &format!("-{}ay", cha);
} | {
"domain": "codereview.stackexchange",
"id": 43632,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, pig-latin",
"url": null
} |
rust, pig-latin
println!("{}", inp);
}
fn is_vowel(c: &char) -> bool {
VOWELS.contains(c)
}
Additional changes:
It is possible to avoid some String allocations but doing so makes the code a bit more unreadable (in my opinion). Nonetheless I feel like it is worth at least mentioning them.
Replace format! by pushing to the original string to avoid a String allocation.
inp.remove(0);
inp += &format!("-{}ay", cha);
Can be replaced with:
inp.remove(0);
inp.push('-');
inp.push(cha);
inp.push_str("ay");
Avoid cloning the input String after trimming the whitespaces.
let mut inp = inp.trim().to_string();
Can be replaced with:
inp.truncate(inp.trim().len());
Convert the first character to lower case before checking if it is a vowel.
let cha = inp.chars().next().expect("Empty string");
Can be replaced with:
let cha = inp.chars().next().expect("Empty string").to_lowercase().next().unwrap(); | {
"domain": "codereview.stackexchange",
"id": 43632,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, pig-latin",
"url": null
} |
php, css, security, url, dynamic-loading
Title: Dynamically loading CSS files based on URL or URI in PHP
Question: I have written out the following code in the head section of my document,
which should load 3 separate style sheets for each page based on the URL/URI that the user is visiting. It is working as intended as tested with the comment in the code but I am wondering if there is a more efficient way to do this. I initially started writing out a switch statement, but chose to try if else statements before.
Also I have added this part:
|| $_SERVER['PHP_URL_PATH']
to each statement in case there is an error of some kind with the first expression. It seems to be working whether I use just ['PHP_URL_PATH']
or the full $_SERVER['PHP_URL_PATH'].
My questions are:
Which out of the two would be more efficient (switch or if else)?
Is the second declaration of $_SERVER actually necessary, or will it work without this specificity?
Any improvements that people could point me to would be greatly appreciated.
PS: I have removed all the echo's for including the actually <link>'s to the CSS files.
This has been tested and is showing to work in Firefox Developer Edition so guessing it's ok, but could be improved maybe; what about scalability, or any security concerns? I am new so please advise or help.
// Create Logic here to include various different style sheets.
if($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/mainHubV8.1.php"){
echo "Loading Styles for MainHubV8.1.php";
}
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/advSearchV8.1.php"){
echo "Loading Styles for advSearchV8.1.php";
}
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/loginOrSignUpV8.1.php"){
echo "Loading Styles for loginOrSignUpV8.1.php";
}
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/profilePageV8.1.php"){
echo "Loading Styles for profilePageV8.1.php"; | {
"domain": "codereview.stackexchange",
"id": 43633,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, css, security, url, dynamic-loading",
"url": null
} |
php, css, security, url, dynamic-loading
}
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/chatApllicationV8.1.php"){
echo "Loading Styles for chatApllicationV8.1.php";
}
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/onlineUsersV8.1.php"){
echo "Loading Styles for onlineUsersV8.1.php";
}
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/index.php"){
echo "Loading Styles for index.php";
}
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/404"){
echo "Loading Styles for error page";
}
Is there a better alternative to achieving the same goal? If so could you please provide reference or articles/Question & answers anywhere on Stack Exchange or some other resource. Plus I do not want to use Javascript or JQuery really as these can be turned off and disabled. So PHP seems more appropriate.
Answer: Most of questions you are asking are not fit for this site and your code does not work as intended but this is an interesting case to review
The grave mistake
Adding anything to your code just in case there would be some imaginary "error of some kind" is the worst thing a programmer could do ever. You effectively ruined your code with adding that || $_SERVER['PHP_URL_PATH'] stuff:
there is no such thing $_SERVER['PHP_URL_PATH'] for starter: such a variable just doesn't exist
of course ['PHP_URL_PATH'] without the $_SERVER part makes no sense
neither the whole condition returns anything sensible due to PHP syntax rules you are yet to learn. | {
"domain": "codereview.stackexchange",
"id": 43633,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, css, security, url, dynamic-loading",
"url": null
} |
php, css, security, url, dynamic-loading
Yet this code works somehow, albeit not the way you expect.
The operator precedence
The way this code executes is a very interesting matter, once I wrote an article that explains it in detail, Operator precedence or how does 'or die()' work. Given you only started learning it could be too complex for you for the moment to wrap your head around, but in time you will find it very interesting to read.
$_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/mainHubV8.1.php" doesn't mean "if either PHP_SELF or PHP_URL_PATH equal to /mainHubV8.1.php". It means "if PHP_SELF contains any value OR PHP_URL_PATH is equal to /mainHubV8.1.php".
In short, an expression $_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/mainHubV8.1.php" evaluates to true when $_SERVER['PHP_SELF'] contains any value. Which means always.
Given PHP already has it's answer, it ceases to execute the further condition. This is why you can write either $_SERVER['PHP_URL_PATH'] or ['PHP_URL_PATH'] or don't even get a notice for the non-existent array index - this code is just never executed.
As a result, this code will always output just "Loading Styles for MainHubV8.1.php" no matter which page it is called on.
The right way
To elaborate on the Neoan's answer, given you have 3 styles to load, here is the proposed array structure
$stylesheets = [
'/mainHubV8.1.php' => [
'style1.css',
'style2.css',
'style3.css',
],
'/advSearchV8.1.php' => [
'style4.css',
'style5.css',
'style6.css',
],
// and so on
];
given this structure, you will be able to get the correct styles right from $_SERVER['PHP_SELF']:
foreach($stylesheets[$_SERVER['PHP_SELF']] as $file) {
echo "<link rel='stylesheet' type='text/css' href='$file'>\n";
} | {
"domain": "codereview.stackexchange",
"id": 43633,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, css, security, url, dynamic-loading",
"url": null
} |
python-3.x, design-patterns, pygame, observer-pattern
Title: PyGame Event Handling
Question: I'm new to pygame and tried to write my own Event Manager because I couldn't find a solution I was satisfied with. So I wrote my own inspired by the observer pattern:
from typing import Callable
from pygame.event import Event
EventHandler = Callable[[Event], None]
_managers = dict()
class EventManager:
def __init__(self, name):
self.name = name
self.handlers: dict[int, list[EventHandler]] = dict()
def notify(self, event: Event, selector=lambda event: event.type):
eventType = selector(event)
if eventType not in self.handlers:
return
for handler in self.handlers[eventType]:
handler(event)
def register(self, eventType: int, handler: EventHandler):
print(f"{self.name} registered {eventType}")
if eventType not in self.handlers:
self.handlers[eventType] = [handler]
else:
self.handlers[eventType].append(handler)
def deregister(self, eventType: int, handler: EventHandler):
if not self._is_registered(eventType, handler):
return
self.handlers[eventType].remove(handler)
def _is_registered(self, eventType, handler):
return eventType in self.handlers and handler in self.handlers[eventType]
@staticmethod
def get(id: str):
if id not in _managers:
_managers[id] = EventManager(id)
return _managers[id]
generalEventManager = EventManager.get("General Events")
keyEventManager = EventManager.get("Key Events")
it's used like this:
class Foo:
_running = True
def register_events(self):
generalEventManager.register(pygame.QUIT, lambda _: self.on_quit())
generalEventManager.register(pygame.KEYDOWN, lambda event: self.on_key_down(event))
# register key events with
# keyEventManager.register(pygame.K_RETURN, lambda _: self.on_k_return())
# ... | {
"domain": "codereview.stackexchange",
"id": 43634,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, design-patterns, pygame, observer-pattern",
"url": null
} |
python-3.x, design-patterns, pygame, observer-pattern
def on_key_down(self, event: Event):
keyEventManager.notify(event, selector=lambda event: event.key)
def on_quit(self):
self._running = False
def on_cleanup(self):
pygame.quit()
def on_execute(self):
while self._running:
for event in pygame.event.get():
self.on_event(event)
self.on_cleanup()
Is this pythonian? Are there better solutions in pygame? Are there generic python library solutions that I didn't find?
Answer: This seems fairly pythonic, and a decent use of the observer pattern.
One thing I would say is that you generally use class methods instead of static methods for alternate constructors, and then call the 'cls' attribute instead of calling the class by name. This is important if you ever want to make use of inheritance, in addition you may want to tie your _managers global dict to the class, for the same reason.
@classmethod
def get(cls, id: str):
if id not in cls._managers:
cls._managers[id] = cls(id)
return cls._managers[id]
In addition, you don't need to pass lambdas in every time. You can instead just pass functions themselves.
def register_events(self):
generalEventManager.register(pygame.QUIT, self.on_quit) # You'll need to modify the call signature here
generalEventManager.register(pygame.KEYDOWN, self.on_key_down)
# register key events with
# keyEventManager.register(pygame.K_RETURN, self.on_k_return)
# ...
Your names are a little undescriptive, I'd probably call your 'get' method something like 'from_id' for clarity, plus obviously 'Foo' should be something richer.
I'd also look into better ways of handling some of your other higher order functions instead of leaning on lambdas. Maybe try using the operator module, for instance:
from operator import attrgetter
# Code here
def notify(self, event: Event, selector=attrgetter('type')):
... | {
"domain": "codereview.stackexchange",
"id": 43634,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, design-patterns, pygame, observer-pattern",
"url": null
} |
python-3.x, design-patterns, pygame, observer-pattern
# Code here
def notify(self, event: Event, selector=attrgetter('type')):
...
Also, you might want to use a default dict to simplify the implementation a bit:
from collections import defaultdict
from operator import attrgetter
class EventManager:
def __init__(self, name):
self.name = name
self.handlers: dict[int, list[EventHandler]] = defaultdict(list)
def notify(self, event: Event, selector=attrgetter('type')):
for handler in self.handlers[selector(event)]:
handler(event)
def register(self, eventType: int, handler: EventHandler):
print(f"{self.name} registered {eventType}")
self.handlers[eventType].append(handler)
def deregister(self, eventType: int, handler: EventHandler):
if handler in self.handlers[eventType]:
self.handlers[eventType].remove(handler)
@classmethod
def from_id(cls, _id: str):
if _id not in _managers:
_managers[_id] = EventManager(_id)
return _managers[_id] | {
"domain": "codereview.stackexchange",
"id": 43634,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, design-patterns, pygame, observer-pattern",
"url": null
} |
beginner, c
Title: Program that calculates the first n powers of x
Question: I am a beginner. I wrote a C program that calculates the first n powers of x and I don't even know if this is legit C code or strictly C++ code. Please criticize it and help me improve it.
#include <stdlib.h> //to use malloc and delete
#include <stdio.h> //to use printf
#define uint64 unsigned long long int //for simplicity
/* this program calculates the first n powers of x*/
uint64* Pow (int x, unsigned char n)
{
uint64* retVal = (uint64*)malloc(sizeof(uint64));
*retVal = 1;
for (unsigned char i = 1; i <= n; i++)
{
*retVal *= x;
}
return retVal;
}
void calculateFirstNPowers(int x, unsigned char n)
{
uint64 sum = 0;
uint64* Pow_retValPtr;
for (unsigned char i = 1; i <= n; i++)
{
Pow_retValPtr = ::Pow(x, i);
printf("%d. Power of %d: ", i, x);
printf("%d\n", *Pow_retValPtr);
sum += *Pow_retValPtr;
free(Pow_retValPtr);
}
printf("\nsum of first %d powers of %d: %d", n, x, sum);
}
int main()
{
calculateFirstNPowers(2, 7);
return 0;
}
Answer: Welcome to Code Review!
C or C++
Technically, this could be compiled as both C and C++, were it not for line 28:
Pow_retValPtr = ::Pow(x, i);
The scope resolution operator :: is only defined in C++, compiling this as C doesn't work.
Since I don't know too much about good C++, I'll treat this as if it was a C program as it reads more like C to me. Maybe someone more knowledgeable can add something about C++ in another answer.
uint64
Use typedef instead of #define:
typedef uint64 unsigned long long int; | {
"domain": "codereview.stackexchange",
"id": 43635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c",
"url": null
} |
beginner, c
The name also might cause confusion with the typedef uint64_t found in inttypes.h. Consider using this header directly instead of defining your own type.
Pow()
Why does this function not return the value directly? This way, there wouldn't be the need to allocate memory inside the function and then remember to free it outside the function. If you forget the latter part, some memory will be leaking every time the function is called, which is undesirable. Here's how the function would look:
uint64 Pow (int x, unsigned char n)
{
uint64 retVal = 1;
for (unsigned char i = 1; i <= n; i++)
{
retVal *= x;
}
return retVal;
}
You could also pass a pointer to a result variable as an argument to the function, but that makes the function a bit weird to use. How to do this is left as an exercise for the reader.
Printing
This shouldn't compile without any warnings. Both sum and Pow_retValPtr are/refer to a value of the type uint64/unsigned long long int, but the format %d is used for signed integers. The correct format to use is %llu.
The last printf doesn't end with a line break which looks ugly when the program is run from a terminal:
mindoverflow@pc:~/$ ./a.out
1. Power of 2: 2
...
5. Power of 2: 32
sum of first 5 powers of 2: 62mindoverflow@pc:~/$
mindoverflow@pc:~/$
Please add one!
Variable naming
x and n could be more descriptive. I'd suggest something like this:
uint64 Pow (int base, unsigned char power) ...
void calculateFirstNPowers(int base, unsigned char n)...
In the second case, the N in the function name describes the argument, so I didn't change it.
Pow_retValPtr could also just be renamed to power, as this is descriptive enough in the context IMO, especially, if you change Pow() as described above.
There also is a joke about naming a variable powerptr somewhere here ... :) | {
"domain": "codereview.stackexchange",
"id": 43635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c",
"url": null
} |
c, strings
Title: C dynamic strings
Question: In the process of writing a compiler, I wrote this dynamic string library to help with keeping track of heap allocated strings and to have an easy way to format them.
Note:
The macros ALLOC(), CALLOC(), and REALLOC() used in the implementation are equivalent to the C stdlib functions malloc(), calloc(), and realloc(). They expand to the memory allocator used in the compiler that also does NULL checking, that is why the implementation doesn't check for NULL after allocating.
They are declared in the header memory.h.
Interface (Strings.h):
#ifndef STRINGS_H
#define STRINGS_H
#include <stddef.h> // size_t
#include <stdbool.h>
// NOTES
// =====
// The 'String' type is equivalent to a C string ('char *'), and therefore can
// be used with the regular C string functions.
// In this API, the String type is used when a string created by this library is expected,
// and 'char *' is used when both types can be used.
// 'const char *' is used when ONLY C strings are expected.
typedef char *String;
/***
* Create a new empty string 'length' long
* NOTE: strings returned by stringNew() can ONLY be freed with stringFree()
*
* @param length The length of the new string.
* @return A pointer to a new heap allocated string.
***/
String stringNew(size_t length);
/***
* Free a string created by stringNew() or stringCopy();
*
* @param s A string created with stringNew() or stringCopy().
***/
void stringFree(String s);
/***
* Check if a string was created by stringNew(), stringCopy(), or stringDuplicate().
*
* @param s A string.
* @return true if valid, false if not.
***/
bool stringIsValid(String s);
/***
* Return the length of a string allocated with stringNew() or stringCopy().
*
* @param s A string allocated by stringNew() or stringCopy().
* @return The length of the string.
***/
size_t stringLength(String s); | {
"domain": "codereview.stackexchange",
"id": 43636,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings",
"url": null
} |
c, strings
/***
* Resize a string allocated by stringNew() or stringCopy().
* NOTE: if 'newSize' is smaller than the current length, data will be lost!
*
* @param s A string allocated by stringNew() or stringCopy().
* @param newLength The new length. can't be 0.
* @return A new string of length 'newLength'.
***/
String stringResize(String s, size_t newLength);
/***
* Copy 'length' characters from 's' into a new string.
*
* @param s A string to copy.
* @param length How much characters to copy.
* @return A new copy of 'length' characters of 's'.
***/
String stringNCopy(const char *s, int length);
/***
* Copy a string into a new string.
*
* @param s A string to copy.
* @return A new copy of the string.
***/
String stringCopy(const char *s);
/***
* Duplicate a string allocated with stringNew() or stringCopy().
*
* @param s A string allocated by stringNew() or stringCopy().
* @return A new copy of the string.
***/
String stringDuplicate(String s);
/***
* Check if 2 strings are equal.
* The strings can be regular C strings as well.
*
* @param s1 A string
* @param s2 Another string
* @return true if equal, false if not
***/
bool stringEqual(char *s1, char *s2);
/***
* Format a string (using printf-like format specifiers) and return it.
*
* @param format The format string.
* @return A new String containing the formatted format string.
***/
String stringFormat(const char *format, ...);
/***
* Append format to dest (printf-like formatting supported)
* NOTE: the string might be reallocated.
*
* @param dest the destination string.
* @param format the string to append (printf-like format specifiers supported).
***/
void stringAppend(String *dest, const char *format, ...);
#endif // STRINGS_H
Implementation (Strings.c):
#include <stdio.h>
#include <string.h> // memcpy(), memset()
#include <stdarg.h>
#include <assert.h>
#include <stdbool.h>
#include "memory.h"
#include "Strings.h" | {
"domain": "codereview.stackexchange",
"id": 43636,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings",
"url": null
} |
c, strings
// C = capacity
// L = length
// M = magic number
// D = data
// ________________________
// | | | | | | | ...
// | C | L | M | D | D | D | ...
// |___|___|___|___|___|___| ...
//
enum slots {
CAPACITY = 0,
LENGTH = 1,
MAGIC = 2,
SLOT_COUNT = 3
};
static inline size_t *from_str(char *s) {
return ((size_t *)s) - SLOT_COUNT;
}
static inline char *to_str(size_t *ptr) {
return (char *)(ptr + SLOT_COUNT);
}
String stringNew(size_t capacity) {
assert(capacity > 0);
size_t *ptr = CALLOC(sizeof(size_t) * SLOT_COUNT + sizeof(char) * (capacity + 1));
ptr[CAPACITY] = capacity + 1; // capacity
ptr[LENGTH] = 0; // length
ptr[MAGIC] = 0xDEADC0DE; // magic
return to_str(ptr);
}
void stringFree(String s) {
assert(stringIsValid(s));
// Remove the magic number in case the string is used again accidentally.
from_str(s)[MAGIC] = 0;
FREE(from_str(s));
}
bool stringIsValid(String s) {
return from_str(s)[MAGIC] == 0xDEADC0DE;
}
size_t stringLength(String s) {
return from_str(s)[LENGTH];
}
String stringResize(String s, size_t newCapacity) {
assert(newCapacity > 0);
size_t *ptr = from_str(s);
size_t oldCap = ptr[CAPACITY];
ptr = REALLOC(ptr, newCapacity);
memset(to_str(ptr) + oldCap, 0, labs(((ssize_t)oldCap) - ((ssize_t)newCapacity)));
ptr[CAPACITY] = newCapacity;
return to_str(ptr);
}
String stringNCopy(const char *s, int length) {
String str = stringNew(length);
memcpy(str, s, length);
from_str(str)[LENGTH] = length;
return str;
}
String stringCopy(const char *s) {
return stringNCopy(s, strlen(s));
}
String stringDuplicate(String s) {
assert(stringIsValid(s));
return stringNCopy((const char *)s, stringLength(s));
} | {
"domain": "codereview.stackexchange",
"id": 43636,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings",
"url": null
} |
c, strings
bool stringEqual(char *s1, char *s2) {
size_t length1, length2;
if(stringIsValid(s1)) {
length1 = stringLength(s1);
} else {
length1 = strlen(s1);
}
if(stringIsValid(s2)) {
length2 = stringLength(s2);
} else {
length2 = strlen(s2);
}
if(length1 != length2) {
return false;
}
return memcmp(s1, s2, length1) == 0;
}
static String vformat(const char *format, va_list ap) {
va_list copy;
va_copy(copy, ap);
// Get the total length of the formatted string.
// see man 3 printf.
int needed_length = vsnprintf(NULL, 0, format, copy);
va_end(copy);
String s = stringNew(needed_length + 1);
vsnprintf(s, needed_length + 1, format, ap);
from_str(s)[LENGTH] = needed_length;
return s;
}
String stringFormat(const char *format, ...) {
va_list ap;
va_start(ap, format);
String s = vformat(format, ap);
va_end(ap);
return s;
}
void stringAppend(String *dest, const char *format, ...) {
assert(stringIsValid(*dest));
va_list ap;
va_start(ap, format);
String buffer = vformat(format, ap);
va_end(ap);
if((size_t)(stringLength(buffer) + 1) > from_str(*dest)[CAPACITY]) {
*dest = stringResize(*dest, stringLength(*dest) + stringLength(buffer) + 1);
}
strncat(*dest, buffer, stringLength(buffer));
// *dest is zeroed by stringNew() & stringResize(), so no need to terminate the string.
from_str(*dest)[LENGTH] += stringLength(buffer);
stringFree(buffer);
}
```
Answer: A word of warning. Writing yet another string library is a goo programming exercise, but if your goal is to write a compiler, concentrate on the compilation tasks (grammar, optimization , code generation..), and don't get sidetracked. Use c++; std::string offers everything you need out of the box.
That said, | {
"domain": "codereview.stackexchange",
"id": 43636,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings",
"url": null
} |
c, strings
typedef char *String; means that the library accepts any char * as String. This is a ticket to disaster. Pass an unaligned char * to, say, stringResize, and enjoy an unaligned access exception on any arch but x86. Consider declaring
typedef struct {
size_t capacity;
// etc
....
} String;
and let your library distinguish String * from char *.
MAGIC is only used in stringIsValid, and most uses of stringIsValid are hidden behind assert. Recall that in the production code assert compiles to nothing, so it becomes a dead code indeed.
The only non-assert use is in stringEqual, and it is much more dangerous. If the magic field is corrupted, God knows what length1 and/or lenght2 evaluate to.
Using strncat in stringAppend is suboptimal. You already know where the buffer shall be copied to; there is no need to recompute this position. | {
"domain": "codereview.stackexchange",
"id": 43636,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings",
"url": null
} |
python, random, simulation, set
Title: Monty hall python simulation
Question: I have the following code that simulates the monty hall problem (see google for more details). I used sets to do it but is there a more intuitive or efficient way to do it?
import random as r
from sets import Set
def montysim(N):
K = 0
for i in range(N):
s = Set([1,2,3])
doorstoswitch = Set([1,2,3])
cardoor = r.randint(1,3)
chosendoor = r.randint(1,3)
doorstoswitch.remove(chosendoor)
if chosendoor != cardoor:
s.remove(chosendoor)
s.remove(cardoor)
montydoor = r.sample(s, 1)[0]
doorstoswitch.remove(montydoor)
newdoor = r.sample(doorstoswitch, 1)[0]
if newdoor == cardoor:
K+=1
return float(K) / float(N)
print montysim(10000)
Answer: There are a couple of changes you can make:
You can use random.choice(...) on a list, rather than random.sample(...)[0] on a set.
You shouldn't use sets:
Deprecated since version 2.6: The built-in set/frozenset types replace this module.
This means you can change Set to just set, or instead use the syntactic sugar: {1, 2, 3}.
You can make doorstoswitch at the end. You can do this by inverting the check. So rather than cardoor == r.choice(doorstoswitch) you can use cardoor not in {chosendoor, montydoor}.
You can then simplify the above to just cardoor != chosendoor, as montydoor can't be the car.
You can remove the sets, as there's no need for them anymore.
And so your code can be:
import random
def montysim(n):
k = 0
for _ in range(n):
k += random.randrange(3) != random.randrange(3)
return float(k) / n | {
"domain": "codereview.stackexchange",
"id": 43637,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, random, simulation, set",
"url": null
} |
c, datetime
Title: timeConversion - C function to convert 12-hour AM/PM format into military time
Question: I have written a program in C, which given a time in 12-hour AM/PM format, converts it to military time (24 hours).
Function Description
The timeConversion function should return a new string representing the input time in 24-hour format.
timeConversion has the following parameter(s):
string s: a time in 12 hour format
Returns
string: the time in 24 hour format
Input Format
A single string s that represents a time in 12-hour clock format (i.e.:hh:mm:ssAM or hh:mm:ssPM)
1)
Sample Input
07:05:45PM
Sample Output
19:05:45
2)
Sample Input
12:01:00PM
Sample Output
12:01:00
3)
Sample Input
12:01:00AM
Sample Output
00:01:00
Code:
#include <asm-generic/errno-base.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <sys/types.h>
#include <errno.h>
#include <err.h>
#include <stdbool.h>
static char *timeConversion(char *restrict);
int
main(void)
{
char *s = NULL;
size_t n = 0;
getline(&s, &n, stdin);
char *res = timeConversion(s);
(void)fprintf(stdout, "%s\n", res);
exit(EXIT_SUCCESS);
}
static char *
timeConversion(char *restrict s)
{
int h1 = (int)s[0] - '0';
int h2 = (int)s[1] - '0';
int HH = h1 * 10 + h2 % 10;
char t[] = { s[8], s[9] }, *fmt = s;
char *out = malloc(BUFSIZ * sizeof(char));
if (out == NULL)
errx(EXIT_FAILURE, "%s", strerror(ENOMEM));
memmove(fmt, fmt+2, strlen(fmt));
fmt[strcspn(fmt, "\r\t\n")] = 0;
fmt[strlen(fmt) - 2] = '\0';
_Bool status = strcmp(t, "AM");
if (!status) {
if (HH == 12)
HH = 0;
} else {
HH += 12;
if (HH == 24)
HH -= 12;
}
sprintf(out, "%02d%s", HH, fmt);
return (char *)(out);
} | {
"domain": "codereview.stackexchange",
"id": 43638,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, datetime",
"url": null
} |
c, datetime
I know this may not be the best solution, but it was more or less what came my mind. And well, I wrote it on a Linux Machine (Gentoo), and I see that it works as expected, with the inputs above. But when I tried to test it on another machine (Mac OS), the results were:
Sample Input
07:05:45AM
Sample Output
19:05:45
I'd like to know if there is any way to improve it or a solution to "fix" the behavior of this program?
Answer: There is a problem comparing a literal string "AM" and a char array not ended with '\0' ==> t[]
char t[] = { s[8], s[9] }
//int strcmp(const char *str1, const char *str2)
_Bool status = strcmp(t, "AM");
If you want to compare char t[] with "AM", you need to add an extra char at the end to sepecify that the string is ended.
char t[] = { s[8], s[9], '\0'};
Note: you can see your current t[] values just printing them, and you will see the extra characters that strcmp is using when comparing with "AM".
sprintf(out, "output: %s", t);
output: AM╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠└ñÌ☺ | {
"domain": "codereview.stackexchange",
"id": 43638,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, datetime",
"url": null
} |
c, multithreading, memory-management, linux, socket
Title: Priority Job/Task Queue for Linux (sockets and multithreading)
Question: Preface
Please review my implementation of a job queue for linux/unix systems. This is my first time coding in C, although I have quite some experience in C++.
I know this is a moderate amount of loc, so please focus on jobq.c, jobq_server. c, manager.c, and server.c. I have uploaded the other files for context. I am mainly intersted in feedback in my design choices and possible memory management problems. Anything beyond this is also greatly appreciated, but not expected.
The setting of CPU affinities is ultimately done over taskset, although I feel I could have implemented that myself aswell, but it is what it is. Maybe in a future update.
Introduction
In the scenario where multiple people want to run calculations on the same machine, scheduling can become an issue. For multiprocessing applications, a single user can potentially block the entire computing capacity. The jobq server and client should do the following things:
Allow each user to submit a job, specifying number of threads and a timeout after which their job will be forcefully terminated
Allow configuration for maximum number of cores, max timelimits and additionally definition of a "long job", which may not acquire more than n cores.
If the next job in the queue can not start, because too few cores are available, it will be marked as a priority element and start as soon as the current latest job has finished. (It could technically start sooner, but I was too lazy to implement a smarter solution. This solution always works, albeit it's not the best).
More specifically, this is what the /etc/jobq/.config file looks like
port=7331
host=127.0.0.1
maxcores=20
maxtime=432000
longjob=43200
longmaxcores=11
colours.h
#ifndef JOBQ_COLOURS_H
#define JOBQ_COLOURS_H | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
colours.h
#ifndef JOBQ_COLOURS_H
#define JOBQ_COLOURS_H
#define RED "\x1B[31m"
#define GREEN "\x1B[32m"
#define YELLOW "\x1B[33m"
#define BLUE "\x1B[34m"
#define MAGENTA "\x1B[35m"
#define CYAN "\x1B[36m"
#define WHITE "\x1B[37m"
#define RESET "\x1B[0m"
#endif //JOBQ_COLOURS_H
config.h
This just contains some constants and defines struct Config.
#ifndef JOBQ_CONFIG_H
#define JOBQ_CONFIG_H
#define CONFIG_FILE "/etc/jobq/.config"
#define DIRECTORY_BUFFER 256
#define USERNAME_BUFFER 32
#define ANSWER_BUFFER 4096
#define MAX_CMD_LENGTH 512
#define MAX_PENDING_CONNECTIONS 4
#define MSG_SUBMIT 'x'
#define MSG_STOP 'y'
#define MSG_STATUS 'z'
struct Config{
long port;
char server_ip[40];
long maxcores;
long maxtime;
long longjob;
long longmaxcores;
};
#endif //JOBQ_CONFIG_H
job.h
Defines struct Job and a doubly linked list.
#ifndef JOBQ_JOB_H
#define JOBQ_JOB_H
#include "config.h"
#include <time.h>
#include <unistd.h>
struct Job{
long id;
pid_t pid;
long cores;
long time_limit;
time_t start_time;
time_t end_time;
uid_t user_id;
gid_t group_id;
char user_name[USERNAME_BUFFER];
char working_directory[DIRECTORY_BUFFER];
char cmd[MAX_CMD_LENGTH];
unsigned long long int core_mask;
};
struct Job_List{
struct Node{
struct Job job;
struct Node* next;
struct Node* prev;
} *first, *last;
};
struct Node* push_back(struct Job_List* this, struct Job j);
struct Node* erase(struct Job_List* this, struct Node** elem);
#endif //JOBQ_JOB_H
manager.h
This is a struct to manage communication between the two threads, so that I do not need to point to a million variables but just a single struct.
#ifndef JOBQ_MANAGER_H
#define JOBQ_MANAGER_H
#include <pthread.h>
#include <time.h>
struct Job_List;
struct Node; | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
#include <pthread.h>
#include <time.h>
struct Job_List;
struct Node;
struct Manager{
struct Job_List* running_queue;
struct Job_List* waiting_queue;
struct Node* priority_job;
time_t latest_end_time;
unsigned long long int available_cores;
pthread_mutex_t *running_lock;
pthread_mutex_t *waiting_lock;
};
struct Node* start_job(struct Manager* m, struct Node* node);
void clear_finished_and_overdue_jobs(struct Manager* m);
time_t get_latest_end_time(struct Manager* m);
long get_free_cores(struct Manager* m);
void start_jobs(struct Manager* m);
#endif //JOBQ_MANAGER_H
parse_config.h
Just declarations
#ifndef JOBQ_PARSE_CONFIG_H
#define JOBQ_PARSE_CONFIG_H
struct Config;
void parse_config(const char* file_name, struct Config* config);
#endif //JOBQ_PARSE_CONFIG_H
queue.h
Just declarations
#ifndef JOBQ_QUEUE_H
#define JOBQ_QUEUE_H
void* queue(void* buffer);
#endif //JOBQ_QUEUE_H
server.h
Just declarations
#ifndef JOBQ_SERVER_H
#define JOBQ_SERVER_H
void* server(void* pointers);
#endif //JOBQ_SERVER_H
utils.h
Just some declarations
#ifndef JOBQ_UTIL_H
#define JOBQ_UTIL_H
int parse_long(const char* str, long* value);
void quit(const char* msg);
void quit_with_error(const char* msg);
char** split(char* str, char tok, int* len);
#endif //JOBQ_UTIL_H
jobq.c
Implementation of push and erase
#include "job.h"
#include <malloc.h>
struct Node* push_back(struct Job_List* this, struct Job j){
struct Node *node = malloc(sizeof(struct Node));
node->job = j;
node->next = NULL;
node->prev = NULL;
if( this->first == NULL ){
this->first = node;
this->last = node;
}else{
node->prev = this->last;
this->last->next = node;
this->last = node;
}
return node;
} | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
struct Node* erase(struct Job_List* this, struct Node** node){
if( this == NULL || node == NULL || *node == NULL ){
return NULL;
}
if( (*node)->next != NULL ){
(*node)->next->prev = (*node)->prev;
}
if( (*node)->prev != NULL ){
(*node)->prev->next = (*node)->next;
}
if( this->first == *node ){
this->first = (*node)->next;
}
if( this->last == *node ){
this->last = (*node)->prev;
}
struct Node* next = (*node)->next;
free(*node);
*node = NULL;
node = NULL;
return next;
}
jobq.c (please review this)
This is the client for the application.
#include "config.h"
#include "job.h"
#include "parse_config.h"
#include "util.h"
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#define CMD_SUBMIT "submit"
#define CMD_STOP "stop"
#define CMD_STATUS "status"
void print_usage(){
printf("jobq usage:\n");
printf("jobq %s <n_cores> <time_limit in seconds> \"<command>\"\n", CMD_SUBMIT);
printf("jobq %s <job_id>\n", CMD_STOP);
printf("jobq %s\n", CMD_STATUS);
printf("Please note that the quotation marks are mandatory, if you want to supply arguments to your executable.\n");
}
void prepare_submit_message(char* message_buffer, const char** argv, struct Config* config){
struct Job job;
job.id = 0;
job.pid = 0;
job.user_id = geteuid();
job.group_id = getegid();
job.start_time = 0;
job.end_time = 0;
job.core_mask = 0;
memset(&job.user_name, 0, USERNAME_BUFFER);
memset(&job.working_directory, 0, DIRECTORY_BUFFER);
memset(&job.cmd[0], 0, MAX_CMD_LENGTH);
struct passwd *pass = getpwuid(getuid());
if( pass == NULL ){
quit_with_error("getpwuid failure");
}
memcpy(&job.user_name[0], (pass->pw_name), strlen(pass->pw_name)); | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
if( getcwd(&job.working_directory[0], DIRECTORY_BUFFER) == NULL ){
printf("Working directory path must not exceed %i characters.", DIRECTORY_BUFFER);
exit(EXIT_FAILURE);
}
if( !parse_long(argv[2], &job.cores) ){
printf("Number of cores must be valid integer: %s\n", argv[2]);
exit(EXIT_FAILURE);
}
if( job.cores < 1 || job.cores > config->maxcores ){
printf("Number of cores must be 0 < n < %ld. Given: %ld\n", config->maxcores, job.cores);
exit(EXIT_FAILURE);
}
if( !parse_long(argv[3], &job.time_limit) ){
printf("Time limit must be valid integer: %s\n", argv[3]);
exit(EXIT_FAILURE);
}
if( job.time_limit < 1 || job.time_limit > config->maxtime ){
printf("Time limit must be 0 < n < %ld. Given: %ld\n", config->maxtime, job.time_limit);
exit(EXIT_FAILURE);
}
if( job.time_limit > config->longjob && job.cores > config->longmaxcores ){
printf("Jobs taking longer than %ld must not acquire more than %ld cores.\n", config->longjob, config->longmaxcores);
exit(EXIT_FAILURE);
}
size_t cmd_length = strlen(argv[4]);
if( cmd_length < 1 || cmd_length > MAX_CMD_LENGTH){
printf("Command length must be between 1 < n < %d. Given: %lu", MAX_CMD_LENGTH, cmd_length);
exit(EXIT_FAILURE);
}
memcpy(&job.cmd, argv[4], cmd_length);
message_buffer[0] = MSG_SUBMIT;
memcpy(&message_buffer[1], &job, sizeof(struct Job));
}
void prepare_status_message(char* message_buffer){
message_buffer[0] = MSG_STATUS;
} | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
void prepare_status_message(char* message_buffer){
message_buffer[0] = MSG_STATUS;
}
void prepare_stop_message(char* message_buffer, const char** argv){
struct Job job;
job.id = 0;
job.pid = 0;
job.user_id = geteuid();
job.group_id = getegid();
job.start_time = 0;
job.end_time = 0;
job.core_mask = 0;
job.cores = 0;
job.time_limit = 0;
memset(&job.user_name, 0, USERNAME_BUFFER);
memset(&job.working_directory, 0, DIRECTORY_BUFFER);
memset(&job.cmd[0], 0, MAX_CMD_LENGTH);
struct passwd *pass = getpwuid(getuid());
if( pass == NULL ){
quit_with_error("getpwuid failure");
}
memcpy(&job.user_name[0], (pass->pw_name), strlen(pass->pw_name));
if( !parse_long(argv[2], &job.id) ){
printf("jobq_id must be valid integer. Given: %s\n", argv[2]);
exit(EXIT_FAILURE);
}
message_buffer[0] = MSG_STOP;
memcpy(&message_buffer[1], &job, sizeof(struct Job));
}
enum Action{
SUBMIT = 0,
STOP = 1,
STATUS = 2
};
int main(int argc, char const* argv[]){
if( argc <= 1 ){
print_usage();
exit(EXIT_SUCCESS);
}
enum Action action;
if( strcmp(argv[1], CMD_SUBMIT) == 0 && argc == 5 ){
action = SUBMIT;
}
else if( strcmp(argv[1], CMD_STOP) == 0 && argc == 3 ){
action = STOP;
}
else if( strcmp(argv[1], CMD_STATUS) == 0 && argc == 2){
action = STATUS;
}
else{
printf("Error: invalid arguments.\n");
print_usage();
exit(EXIT_FAILURE);
}
struct Config config;
parse_config(CONFIG_FILE, &config);
int socket_descriptor = socket(AF_INET, SOCK_STREAM, 0);
if( socket_descriptor == -1 ){
quit_with_error("Socket failure");
}
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(config.port);
int inet = inet_pton(AF_INET, config.server_ip, &server_address.sin_addr); | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
int inet = inet_pton(AF_INET, config.server_ip, &server_address.sin_addr);
if( inet == 0 ){
printf("%s is not a valid server ip.\n", config.server_ip);
exit(EXIT_FAILURE);
}
else if( inet == -1 ){
quit_with_error("Inet_pton failure");
}
int client_descriptor = connect(socket_descriptor, (struct sockaddr*)&server_address, sizeof(server_address));
if( client_descriptor == -1 ){
quit_with_error("Connect failure");
}
char message_buffer[sizeof(struct Job)] = {0};
switch( action ){
case SUBMIT:{
prepare_submit_message(&message_buffer[0], argv, &config);
break;
}
case STATUS:{
prepare_status_message(&message_buffer[0]);
break;
}
case STOP:{
prepare_stop_message(&message_buffer[0], argv);
break;
}
default:{
}
}
ssize_t result = send(socket_descriptor, message_buffer, sizeof(struct Job), 0);
if( result == -1 ){
quit_with_error("Send failure");
}
char answer_buffer[ANSWER_BUFFER] = {0};
size_t answer = read(socket_descriptor, answer_buffer, ANSWER_BUFFER);
if( answer == -1 ){
quit_with_error("Read failure");
}
puts(answer_buffer);
close(client_descriptor);
close(socket_descriptor);
return EXIT_SUCCESS;
}
jobq_server (please review this)
The server for the application. This will start two threads as discussed above.
#include "config.h"
#include "job.h"
#include "manager.h"
#include "parse_config.h"
#include "queue.h"
#include "server.h"
#include "util.h"
#include <pthread.h>
#include <string.h>
#define MAX_PENDING_CONNECTIONS 4 | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
#include <pthread.h>
#include <string.h>
#define MAX_PENDING_CONNECTIONS 4
int main(int argc, char** argv){
char* message_buffer[sizeof(struct Job)+1];
struct Config config;
parse_config(CONFIG_FILE, &config);
struct Job_List waiting_queue;
waiting_queue.first = NULL;
waiting_queue.last = NULL;
struct Job_List running_queue;
running_queue.first = NULL;
running_queue.last = NULL;
pthread_mutex_t running_lock;
pthread_mutex_t waiting_lock;
if( pthread_mutex_init(&running_lock, NULL) != 0){
quit_with_error("Could not initialize mutex");
}
if( pthread_mutex_init(&waiting_lock, NULL) != 0){
quit_with_error("Could not initialize mutex");
}
struct Manager manager;
manager.running_queue = &running_queue;
manager.waiting_queue = &waiting_queue;
manager.priority_job = NULL;
manager.latest_end_time = 0;
manager.available_cores = 0xffffffffffffffffULL >> (64 - config.maxcores);
manager.running_lock = &running_lock;
manager.waiting_lock = &waiting_lock;
void* pointers[4] = {(void*) message_buffer, (void*) &config, (void*) &manager};
pthread_t socket_thread_id, queue_thread_id;
pthread_create(&socket_thread_id, NULL, server, &pointers[0]);
pthread_create(&queue_thread_id, NULL, queue, &pointers[0]);
pthread_join(socket_thread_id, NULL);
pthread_join(queue_thread_id, NULL);
return EXIT_SUCCESS;
}
manager.c (please review this)
This manages cleans and updates the running queue of finished and overdue jobs, sets the priority element and loads new jobs from the waiting queue.
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <signal.h>
#include <sys/wait.h>
#include <stdlib.h>
#include "job.h"
#include "manager.h"
#include "util.h" | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
#include "job.h"
#include "manager.h"
#include "util.h"
struct Node* start_job(struct Manager* m, struct Node* node){
if( m == NULL || node == NULL || m->running_queue == NULL || m->waiting_queue == NULL ){
return NULL;
}
node->job.core_mask = 0;
unsigned long long int it = m->available_cores;
for( int i = 0, j = 0; i < node->job.cores; j++, it >>= 1 ){
if( (it & 1) == 1 ){
node->job.core_mask |= (1ULL << j);
i++;
}
}
m->available_cores ^= node->job.core_mask;
node->job.start_time = time(NULL);
node->job.end_time = node->job.start_time + node->job.time_limit; | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
node->job.pid = fork();
if( node->job.pid == -1 ){
fprintf(stderr, "Failed to fork\n");
}
else if( node->job.pid == 0 ){
if( chdir(node->job.working_directory) < 0 ){
quit_with_error("chdir failure");
}
if( setegid(node->job.group_id) < 0 ){
quit_with_error("setegid failure");
}
if( setgid(node->job.group_id) < 0 ){
quit_with_error("setgid failure");
}
if( setuid(node->job.user_id) < 0){
quit_with_error("setuid failure");
}
if( seteuid(node->job.user_id) < 0){
quit_with_error("seteuid failure");
}
char out[24] = {0};
char err[24] = {0};
sprintf(&out[0], "out_%ld.txt", node->job.id);
sprintf(&err[0], "err_%ld.txt", node->job.id);
int fd_out = open(out, O_WRONLY | O_CREAT, S_IRWXU);
if( fd_out < 0 ){
quit_with_error("error open stdout");
}
int fd_err = open(err, O_WRONLY | O_CREAT, S_IRWXU);
if( fd_err < 0 ){
quit_with_error("error open stderr");
}
if( dup2(fd_out, STDOUT_FILENO) < 0 ){
quit_with_error("dup2 failure out");
}
if( dup2(fd_err, STDERR_FILENO) < 0 ){
quit_with_error("dup2 failure err");
}
char* command = &node->job.cmd[0];
int len = 0;
char** split_str = split(command, ' ', &len);
char* arr[] = {"taskset", "-a", NULL};
int memory_len = snprintf(NULL,0,"0x%llX", node->job.core_mask);
arr[2] = malloc(memory_len + 1);
snprintf(arr[2], memory_len+1,"0x%llX", node->job.core_mask);
char* params[3+len];
memcpy(¶ms[0], &arr[0], 3 * sizeof(char*));
memcpy(¶ms[3], &split_str[0], len * sizeof(char*));
execv("/usr/bin/taskset", params);
}
char time_buffer[15] = {0};
time_t now = time(NULL); | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
}
char time_buffer[15] = {0};
time_t now = time(NULL);
strftime(&time_buffer[0], 15, "%d-%m %H:%M:%S", localtime(&now));
fprintf(stderr, "[%s] Starting job: %ld %ld\n", &time_buffer[0], node->job.id, (long)node->job.pid);
pthread_mutex_lock(m->running_lock);
push_back(m->running_queue, node->job);
pthread_mutex_unlock(m->running_lock);
struct Node* next = erase(m->waiting_queue, &node);
return next;
} | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
void clear_finished_and_overdue_jobs(struct Manager* m){
if( m == NULL ){
return;
}
pthread_mutex_lock(m->running_lock);
struct Node* node = m->running_queue->first;
while( node != NULL ){
if( node->job.end_time < time(NULL) ){
if( kill(node->job.pid, 9) < 0 ){
quit_with_error("Could not kill process");
}else{
usleep(1000000);
char time_buffer[15] = {0};
time_t now = time(NULL);
strftime(&time_buffer[0], 15, "%d-%m %H:%M:%S", localtime(&now));
fprintf(stderr, "[%s] Terminated job: %ld %ld\n", &time_buffer[0], node->job.id, (long) node->job.pid);
}
}
int status = 0;
pid_t pid = waitpid(node->job.pid, &status, WNOHANG);
if( pid == node->job.pid ){
char time_buffer[15] = {0};
time_t now = time(NULL);
strftime(&time_buffer[0], 15, "%d-%m %H:%M:%S", localtime(&now));
fprintf(stderr,"[%s] Job finished: %ld %ld.\n", &time_buffer[0], node->job.id, (long)node->job.pid);
m->available_cores |= node->job.core_mask;
node = erase(m->running_queue, &node);
}else{
node = node->next;
}
}
pthread_mutex_unlock(m->running_lock);
}
time_t get_latest_end_time(struct Manager* m){
time_t latest = 0;
pthread_mutex_lock(m->running_lock);
struct Node* node = m->running_queue->first;
while( node != NULL ){
if( node->job.end_time > latest ){
latest = node->job.end_time;
}
node = node->next;
}
pthread_mutex_unlock(m->running_lock);
return latest;
}
long get_free_cores(struct Manager* m){
if( m == NULL ){
return 0;
}
long result = 0;
unsigned long long int n = m->available_cores;
while( n ){
result += (long)(n&1ULL);
n>>=1;
}
return result;
} | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
void start_jobs(struct Manager* m){
long n_free_cores = get_free_cores(m);
if( m->priority_job != NULL && m->priority_job->job.cores <= n_free_cores ){
start_job(m, m->priority_job);
m->latest_end_time = get_latest_end_time(m);
m->priority_job = NULL;
}
pthread_mutex_lock(m->waiting_lock);
struct Node *waiting_node = m->waiting_queue->first;
while( waiting_node != NULL)
{
if( m->priority_job == NULL )
{
if( waiting_node->job.cores <= get_free_cores(m) )
{
waiting_node = start_job(m, waiting_node);
m->latest_end_time = get_latest_end_time(m);
}else
{
m->priority_job = malloc(sizeof(struct Node));
if( m->priority_job == NULL ){
fprintf(stderr, "Could not allocate for priority node\n");
exit(EXIT_FAILURE);
}
*m->priority_job = *waiting_node;
m->priority_job->job.start_time = m->latest_end_time;
m->priority_job->job.end_time = m->latest_end_time + m->priority_job->job.time_limit;
waiting_node = erase(m->waiting_queue, &waiting_node);
}
}else{
if( waiting_node->job.time_limit + time(NULL) < m->priority_job->job.start_time && waiting_node->job.cores <= get_free_cores(m) )
{
waiting_node = start_job(m, waiting_node);
}else{
waiting_node = waiting_node->next;
}
}
}
pthread_mutex_unlock(m->waiting_lock);
}
queue.c
Thread that calls the functions from manager.c
#include "job.h"
#include "manager.h"
#include "queue.h"
#include <unistd.h>
#include <stdbool.h>
#include <string.h>
void *queue(void *pointers){
void** p = (void**) pointers;
struct Manager* m = p[2]; | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
void *queue(void *pointers){
void** p = (void**) pointers;
struct Manager* m = p[2];
while( true ){
clear_finished_and_overdue_jobs(m);
start_jobs(m);
sleep(1);
}
return NULL;
}
server.c (please review this)
This checks for incoming requests of jobq and sends out status messages, puts jobs into the waiting queue or stops them / removes them.
#include "colours.h"
#include "config.h"
#include "job.h"
#include "manager.h"
#include "server.h"
#include "time.h"
#include "util.h"
#include <netinet/in.h> // struct socket_in
#include <sys/socket.h>
#include <malloc.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
void* server(void* pointers){
void** p = (void**) pointers;
struct Config* config = p[1];
struct Manager* m = p[2];
int socket_descriptor = socket(AF_INET, SOCK_STREAM, 0);
if( socket_descriptor == -1 ){
quit_with_error("Socket failure");
}
struct sockaddr_in socket_address;
int option = 1;
if( setsockopt(socket_descriptor, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &option, sizeof(option))) {
quit_with_error("Setsockopt failure");
}
socket_address.sin_family = AF_INET;
socket_address.sin_addr.s_addr = INADDR_ANY;
socket_address.sin_port = htons(config->port);
if( bind(socket_descriptor, (struct sockaddr*)&socket_address, sizeof(socket_address)) == -1 ){
quit_with_error("Bind failure");
}
if( listen(socket_descriptor, MAX_PENDING_CONNECTIONS) == -1 ){
quit_with_error("Listen failure");
}
socklen_t socket_address_length = sizeof(socket_address);
long job_id = 0;
while( true ){
int temp_descriptor = accept(socket_descriptor, (struct sockaddr*)&socket_address, &socket_address_length);
char buffer[sizeof(struct Job)+1] = {0};
ssize_t read_bytes = read(temp_descriptor, &buffer, sizeof(struct Job)); | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
if(read_bytes < 0 ){
quit_with_error("Read failure.");
}
if( read_bytes == 0 ){
continue;
}
if( buffer[0] == MSG_SUBMIT ){
struct Job job;
memcpy(&job, &buffer[1], sizeof(struct Job));
job.id = job_id++;
pthread_mutex_lock(m->waiting_lock);
char time_buffer[15] = {0};
time_t now = time(NULL);
strftime(&time_buffer[0], 15, "%d-%m %H:%M:%S", localtime(&now));
fprintf(stderr, "[%s] Adding job to waiting_queue: %ld\n", &time_buffer[0], job.id);
push_back(m->waiting_queue, job);
pthread_mutex_unlock(m->waiting_lock);
char answer_buffer[ANSWER_BUFFER] = {0};
sprintf(&answer_buffer[0], "Job submitted. Id: %ld\nEnter jobq status to check status.\n", job.id);
send(temp_descriptor, answer_buffer, strlen(answer_buffer), 0);
}
if( buffer[0] == MSG_STOP ){
char answer_buffer[ANSWER_BUFFER] = {0};
struct Job job;
memcpy(&job, &buffer[1], sizeof(struct Job));
int found_job = 0;
{
pthread_mutex_lock(m->running_lock);
struct Node *r_node = m->running_queue->first;
while( r_node != NULL)
{
if( r_node->job.id == job.id )
{
found_job = 1;
if( r_node->job.user_id != job.user_id )
{
sprintf(&answer_buffer[0], RED "Error: Can not stop job %ld. Insufficient permissions. (Not your job)\n", job.id);
}else
{
if( kill(r_node->job.pid, 9) < 0 )
{
quit_with_error("Could not kill process.");
}else
{ | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
}else
{
usleep(1000000);
char time_buffer[15] = {0};
time_t now = time(NULL);
strftime(&time_buffer[0], 15, "%d-%m %H:%M:%S", localtime(&now));
fprintf(stderr, "[%s] User stopped job: %ld %ld\n", &time_buffer[0], r_node->job.id, (long) r_node->job.pid);
m->available_cores |= r_node->job.core_mask;
erase(m->running_queue, &r_node);
sprintf(&answer_buffer[0], GREEN "Success" RESET ": Stopped job %ld\n", job.id);
}
}
break;
}
r_node = r_node->next;
}
pthread_mutex_unlock(m->running_lock);
}
pthread_mutex_lock(m->waiting_lock);
if( !found_job )
{
if( m->priority_job != NULL)
{
if( m->priority_job->job.id == job.id )
{
found_job = 1;
if( m->priority_job->job.user_id != job.user_id )
{
sprintf(&answer_buffer[0], RED "Error" RESET ": Can not stop job %ld. Insufficient permissions. (Not your job)\n", job.id);
}else
{
char time_buffer[15] = {0};
time_t now = time(NULL);
strftime(&time_buffer[0], 15, "%d-%m %H:%M:%S", localtime(&now));
fprintf(stderr, "[%s] User stopped job: %ld %ld\n", &time_buffer[0], m->priority_job->job.id, (long) m->priority_job->job.pid);
m->priority_job = NULL; | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
m->priority_job = NULL;
sprintf(&answer_buffer[0], GREEN "Success" RESET ": Stopped job %ld\n", job.id);
}
}
}
}
if( !found_job ){
struct Node *w_node = m->waiting_queue->first;
while( w_node != NULL)
{
if( w_node->job.id == job.id )
{
found_job = 1;
if( w_node->job.user_id != job.user_id )
{
sprintf(&answer_buffer[0], RED "Error: Can not stop job %ld. Insufficient permissions. (Not your job)\n", job.id);
}else
{
char time_buffer[15] = {0};
time_t now = time(NULL);
strftime(&time_buffer[0], 15, "%d-%m %H:%M:%S", localtime(&now));
fprintf(stderr, "[%s] User stopped job: %ld %ld\n", &time_buffer[0], w_node->job.id, (long) w_node->job.pid);
erase(m->waiting_queue, &w_node);
sprintf(&answer_buffer[0], GREEN "Success" RESET ": Stopped job %ld\n", job.id);
}
break;
}
w_node = w_node->next;
}
}
pthread_mutex_unlock(m->waiting_lock);
if( !found_job ){
sprintf(&answer_buffer[0], YELLOW "Warning" RESET ": Job id %ld does not exist.\n", job.id);
}
send(temp_descriptor, answer_buffer, strlen(answer_buffer), 0);
}
if( buffer[0] == MSG_STATUS ){
char answer_buffer[ANSWER_BUFFER] = {0};
int n = 0;
n += snprintf(&answer_buffer[n], ANSWER_BUFFER-n, "available cores: %ld\n", get_free_cores(m)); | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
n += snprintf(&answer_buffer[n], ANSWER_BUFFER-n, "job id\tstatus\t\tuser\t\tcores\tstart\t\tend\t\tcommand\n");
pthread_mutex_lock(m->running_lock);
struct Node* running_nodeent = m->running_queue->first;
while( running_nodeent != NULL ){
struct Job j = running_nodeent->job;
char start_time[20] = {0};
char end_time[20] = {0};
strftime(&start_time[0], 15, "%d-%m %H:%M:%S", localtime(&j.start_time));
strftime(&end_time[0], 15, "%d-%m %H:%M:%S", localtime(&j.end_time));
n += snprintf(&answer_buffer[n], ANSWER_BUFFER-n,"%ld\t%s[running]%s\t%s\t%ld\t%s\t%s\t%s\n", (long)j.id, GREEN, RESET, j.user_name, j.cores, &start_time[0], &end_time[0], &j.cmd[0]);
running_nodeent = running_nodeent->next;
}
pthread_mutex_unlock(m->running_lock);
if( m->priority_job != NULL ){
struct Job j = m->priority_job->job;
char start_time[20] = {0};
char end_time[20] = {0};
strftime(&start_time[0], 15, "%d-%m %H:%M:%S", localtime(&j.start_time));
strftime(&end_time[0], 15, "%d-%m %H:%M:%S", localtime(&j.end_time));
n += snprintf(&answer_buffer[n], ANSWER_BUFFER - n, "%ld\t%s[priority]%s\t%s\t%ld\t%s\t%s\t%s\n", (long) j.id, CYAN, RESET, j.user_name, j.cores, &start_time[0], &end_time[0], &j.cmd[0]);
}
pthread_mutex_lock(m->waiting_lock);
struct Node* waiting_node = m->waiting_queue->first;
while( waiting_node != NULL ){
struct Job j = waiting_node->job;
n += snprintf(&answer_buffer[n], ANSWER_BUFFER - n, "%ld\t%s[waiting]%s\t%s\t%ld\t%s\t%s\t%s\n", (long) j.id, RED, RESET, j.user_name, j.cores, "n/a\t", "n/a\t", &j.cmd[0]);
waiting_node = waiting_node->next;
} | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
waiting_node = waiting_node->next;
}
pthread_mutex_unlock(m->waiting_lock); | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
send(temp_descriptor, answer_buffer, strlen(answer_buffer), 0);
}
sleep(1);
}
return NULL;
}
util.c
just some helper functions
#include <errno.h>
#include <math.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "util.h"
int parse_long(const char* str, long* return_value){
errno = 0;
char* dummy;
long value = strtol(str, &dummy, 0);
if( dummy == str || *dummy != '\0' || ((value == LONG_MIN || value == LONG_MAX) && errno == ERANGE) ){
return 0;
}
*return_value = value;
return 1;
}
void quit(const char* msg){
printf("%s", msg);
exit(EXIT_FAILURE);
}
void quit_with_error(const char* msg){
perror(msg);
exit(EXIT_FAILURE);
}
char** split(char* str, char tok, int *num){
int len = strlen(str);
*num = 2;
char* it = str;
for( int i = 0; i < len; ++i ){
if( *it == tok ){
*it = '\0';
(*num)++;
}
it++;
}
char** result = (char**)malloc(*num * sizeof(char*));
int j = 0;
int save = 1;
it = str;
for( int i = 0; i < len; ++i, ++it ){
if( *it == '\0' ){
save = 1;
}
else if( save == 1 ){
result[j++] = it;
save = 0;
}
}
result[j] = (char*)NULL;
return result;
}
````
Answer: Use the appropriate types
You use long and long long in several places. The C standard specifies the relative size between short/int/long/long long, but the exact size depends on the platform, and might be smaller or larger than you think. Make sure you choose the appropriate type. Here is a list of variables whose types should be changed: | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
c, multithreading, memory-management, linux, socket
long port: a TCP port number is only 16 bits. A long is often way too big. Use uint16_t instead.
long time_limit, long maxtime: on 64-bit Windows platforms and most 32-bit platforms, storing UNIX time in seconds in a long will cause it to wrap in 2038. Apart from that, it doesn't match the return type of time(). Be consistent and use time_t instead.
unsigned long long core_mask: on most platforms this is only 64 bits, but this is not enough if you have an AMD 3990X CPU in your desktop PC, which has 128 logical cores, or if you are running on a multi-processor server which might have even more cores. On Linux, consider using cpu_set_t to store core masks.
char server_ip[40]: prefer parsing any textual IP address before storing it in a struct. That avoids any issues with string lengths. 40 is way too much if you only support numeric IPv4 addresses, but if you want to support hostnames, it is too short. It might have been just enough for numeric IPv6 addresses, but it doesn't seem like you support IPv6 in your code. I would use struct sockaddr_storage, which stores both address and port, and supports IPv4 and IPv6.
You mentioned in the comments that you used long because that matches the return value of strtol(), which makes sense in a way. However, it is better to store values in the type associated with the intended use later on, as that will avoid implicit casts which might be problematic. It might also be a good idea to parse numbers into a temporary long variable, then check if the value is not too large (for example, a port number should never be larger than 65535) before storing it into the variable of the correct type.
Simplify zeroing structs
In prepare_submit_message(), you spend a lot of lines of code initializing job. You can simplify this a lot by using designated initializers:
struct Job job = {
.user_id = geteuid(),
.group_id = getegid(),
}; | {
"domain": "codereview.stackexchange",
"id": 43639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, multithreading, memory-management, linux, socket",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.