text
stringlengths
1
2.12k
source
dict
c++, performance, multithreading, lock-free, producer-consumer Title: Multi producer/consumer lock-free queue Question: I would be grateful if you could review my code for a multi producer/consumer lock-free queue in C++. I am mainly after performance improvements, but all input is welcome. #pragma once #include <array> #include <string> #include <chrono> #include <atomic> #include <thread> #include <optional> #include <cmath> template<typename QueueItemT, size_t bufferSize> class LockFreeQueue { using SleepGranularity = std::chrono::nanoseconds; public: LockFreeQueue() = delete; /** A constructor which takes the total number of consumer+producer threads * as argument. This will subsequently be used to define how many times a * thread will spin before going to sleep. * * If a custom spin count is provided, the number of threads is ignored and * the custom spin count is used, as is, instead. * * @arg numberOfThreads - the total number of consumer+producer threads. * @arg customSpinCount - the times a thread will spin before going to sleep. */ LockFreeQueue(std::optional<size_t> numberOfThreads = std::nullopt, std::optional<size_t> customSpinCount = std::nullopt) : sleepDurationStart{numberOfThreads.has_value()?-spinCount(*numberOfThreads): customSpinCount.has_value()?*customSpinCount: 10} // If no number of threads or custom spin count was defined, we will default to a spin count of 10. {} ~LockFreeQueue() = default; // Make the queue non copyable. LockFreeQueue(const LockFreeQueue&) = delete; LockFreeQueue& operator=(const LockFreeQueue&) = delete;
{ "domain": "codereview.stackexchange", "id": 45210, "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++, performance, multithreading, lock-free, producer-consumer", "url": null }
c++, performance, multithreading, lock-free, producer-consumer /** Push data into the queue. * * The purpose of the "push" function is to push data into the queue. * * If there is no space, the thread will return false and will not * wait for space to become available. * * However, once a space has been claimed, access to the queue is * released and other threads can use the queue while the data is * copied into the claimed space. * * @arg bufferItem - the data to be pushed into the queue. */ bool push(QueueItemT bufferItem) { size_t newTail{}; bool keepTrying{ true }; SleepGranularity sleepDuration{ sleepDurationStart }; std::optional<size_t> pushIndex{ std::nullopt }; _pendingData.fetch_add(2, std::memory_order_relaxed); // We are going to add data in the queue. // We intentionally use 2 here in order to // also use the atomic to prevent memory // reordering in what follows. do { if (_canUpdate.exchange(false, std::memory_order_acquire)) { // Gain access and check index positions. newTail = (_tail.load(std::memory_order_relaxed) + 1) % bufferSize; // Calculate the new tail if (newTail != _head.load(std::memory_order_relaxed)) { // When _tail + 1 == _head we can not add. if (!_isBusy.at(_tail.load(std::memory_order_relaxed) ).exchange(true, std::memory_order_relaxed)) { // Check that the index is not busy pushIndex = _tail.load(std::memory_order_relaxed); _tail.store(newTail, std::memory_order_relaxed);
{ "domain": "codereview.stackexchange", "id": 45210, "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++, performance, multithreading, lock-free, producer-consumer", "url": null }
c++, performance, multithreading, lock-free, producer-consumer keepTrying = false; } } else { keepTrying = false; } _canUpdate.store(true, std::memory_order_release); // Allow access to the critical section for other // threads to update the indexes } if (keepTrying) { sleepDuration = backOff(sleepDuration); // If we keep retrying, try not to overload the CPU } } while (keepTrying); // Do work until tail is updated and we can push the data if (pushIndex.has_value()) { _buffer.at(*pushIndex) = bufferItem; _pendingData.fetch_sub(1, std::memory_order_acq_rel); // We succesfully pushed data. Decrement the counter to // what it should be and also use the atomic to prevent // memory reordering. // Use memory_order_acq_rel to prevent read/writes move. _isBusy.at(*pushIndex).store(false, std::memory_order_relaxed); // Flag that we are done with the index return true; // We succesfully placed the data in the queue. } _pendingData.fetch_sub(2, std::memory_order_relaxed); // We failed to add data in the queue. return false; // We did not have space to put the data into the queue. }
{ "domain": "codereview.stackexchange", "id": 45210, "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++, performance, multithreading, lock-free, producer-consumer", "url": null }
c++, performance, multithreading, lock-free, producer-consumer return false; // We did not have space to put the data into the queue. } /** Pop data from the queue. * * The purpose of the "pop" function is to extract data from the queue. * * The assigned thread will claim the space containing the next available * data. If there is no data, the thread will return false and will not * wait for data to become available. * * However, once a space has been claimed, access to the queue is * released and other threads can use the queue while the data is * returned back to the caller. * * @arg popedData - the location to put the extracted data into. * * @return return true if there was data available to return back * to the caller, otherwise return false. */ bool pop(QueueItemT& popedData) { bool keepTrying{ true }; SleepGranularity sleepDuration{ sleepDurationStart }; std::optional<size_t> popIndex{ std::nullopt }; do { if (_canUpdate.exchange(false, std::memory_order_acquire)) { // Gain access and check index positions. if (_head.load(std::memory_order_relaxed) != _tail.load(std::memory_order_relaxed)) { // When head == tail we can not remove if (!_isBusy.at(_head.load(std::memory_order_relaxed) ).exchange(true, std::memory_order_relaxed)) { // Check that the producer thread managed // to commit data to the _head index and the // index is now not busy. popIndex = _head.load(std::memory_order_relaxed);
{ "domain": "codereview.stackexchange", "id": 45210, "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++, performance, multithreading, lock-free, producer-consumer", "url": null }
c++, performance, multithreading, lock-free, producer-consumer popIndex = _head.load(std::memory_order_relaxed); _head.store((_head.load(std::memory_order_relaxed) + 1) % bufferSize, std::memory_order_relaxed); // Update the head; keepTrying = false; } } else { keepTrying = false; } _canUpdate.store(true, std::memory_order_release); // Allow access to the critical section for other // threads to update the indexes } if (keepTrying) { sleepDuration = backOff(sleepDuration); // If we keep retrying, try not to overload the CPU } } while (keepTrying); // Do work until head is updated and there is no more data to pop in the queue if (popIndex.has_value()) { popedData = _buffer.at(*popIndex); _pendingData.fetch_sub(1, std::memory_order_acq_rel); // We removed data from the queue. // Use memory_order_acq_rel to prevent read/writes move. _isBusy.at(*popIndex).store(false, std::memory_order_relaxed); // Flag that we are done with the index return true; // We succesfully poped data. } return false; // There was no new data available. } /** Check if there is data in the queue. * * @return true if there is data in the queue, false otherwise. */ bool hasData() { return _pendingData.load(std::memory_order_acquire) != 0; }
{ "domain": "codereview.stackexchange", "id": 45210, "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++, performance, multithreading, lock-free, producer-consumer", "url": null }
c++, performance, multithreading, lock-free, producer-consumer private: /** Put the thread to sleep. * * The purpose of the "backOff" function is to put the thread to sleep. * The sleep duration increases linearly until a threashold is reached. * * @arg sleepDuration - the current value of the sleep duration. * * @return the updated value of the sleep duration */ SleepGranularity backOff(SleepGranularity sleepDuration) { std::this_thread::yield(); if (sleepDuration < sleepDurationStep) { return sleepDuration + sleepDurationStep; } std::this_thread::sleep_for(sleepDuration); return (sleepDuration < _maxSleepDuration)? sleepDuration + sleepDurationStep: // increment the sleep duration if we are below the max threashhold sleepDurationStart; // otherwise reset the sleep duration to sleepDurationStart } /** Approximate spins. * * The purpose of the "spinCount" function is to aproximate the * number of times a consumer/producer thread is going to spin * before going to sleep. * * @arg numberOfThreads - total number of consumer+producer threads. * * @return the number of times a consumer/producer thread is going * to spin before going to sleep. */ int spinCount(size_t numberOfThreads) { return 86.404/std::pow(numberOfThreads, 0.691); // This is an approximation based on ~10million pops per 2 minutes // performance within reasonable CPU load. The approximation was // derived using a 4-core CPU. This approximation will probably need // to be re-evaluated based on the CPU cores. }
{ "domain": "codereview.stackexchange", "id": 45210, "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++, performance, multithreading, lock-free, producer-consumer", "url": null }
c++, performance, multithreading, lock-free, producer-consumer std::array<QueueItemT, bufferSize> _buffer{}; // the ring buffer std::array<std::atomic_bool, bufferSize> _isBusy{ false }; // the buffer if there is work pending on each index std::atomic<size_t> _head{ 0 }; // consumer index std::atomic<size_t> _tail{ 0 }; // producer index std::atomic<long long> _pendingData{ 0 }; // count pending data in the queue std::atomic_bool _canUpdate{ true }; // critical section protection SleepGranularity sleepDurationStart{}; // the initial value of the sleepDuration. Adding sleepDurationStep, // until it reaches 1, translates to how many times we are going to // spin before going to sleep. eg, sleepDurationStart = -10 and // sleepDurationStep = 1 => we are going to spin 10 times before // going to sleep for some value of sleepDuration. SleepGranularity sleepDurationStep{ 1 }; // the value by which we increment sleepDurationStart every time we spin. SleepGranularity _maxSleepDuration{ 1 }; // the maximum time the thread can go to sleep for. };
{ "domain": "codereview.stackexchange", "id": 45210, "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++, performance, multithreading, lock-free, producer-consumer", "url": null }
c++, performance, multithreading, lock-free, producer-consumer Answer: This is not lock-free Unfortunately, your queue is not lock-free. Basically, your _canUpdate is used as a lock. Consider a thread that has taken the lock, so it's inside the if-statement that did the atomic exchange. Then, the operating system might suspend that thread for whatever reason. Other threads that want to push or pop items can now no longer progress. Your locking strategy is possibly worse than a std::mutex. If you try to lock a std::mutex, it also does an atomic exchange to mark the mutex locked. If it was already locked by another thread, it will then make a system call to suspend the thread until the mutex is unlocked. In your case, you also do a system call when _canUpdate was already false via std::this_thread::sleep_for(). However, this waits either too short or too long. If it waits too long your queue's throughput is reduced, if it waits too short it is making multiple system calls that are wasting energy and reduce the amount of time for other threads to run on the same core.
{ "domain": "codereview.stackexchange", "id": 45210, "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++, performance, multithreading, lock-free, producer-consumer", "url": null }
c, image, bmp Title: Filter: BMP Image Filtering Tool - follow-up Question: This is a follow-up of this quesiton: Filter: BMP Image Filtering Tool Changes: Added comments where necessary. Added checks for integer overflow. Added support for input and output redirection. Added support for more than one filter in a single invocation. Eliminated casts, magic numbers, and Windows typedefs for standard types. Changed the algorithm for blurring the image. Some other points raised by the reviewers. Review Goals: Should the functions doing the input/output be moved to bmp.c? Style, potential undefined behavior, et cetera. Code: bmp.h: #ifndef BMP_H #define BMP_H /* BMP-related data types based on Microsoft's own. */ #include <stdbool.h> #include <stdint.h> /* The BITMAPFILEHEADER structure contains information about the type, size, * and layout of a file that contains a DIB [device-independent bitmap]. * Adapted from http://msdn.microsoft.com/en-us/library/dd183374(VS.85).aspx. */ typedef struct { uint16_t bf_type; uint32_t bf_size; uint16_t bf_reserved1; uint16_t bf_reserved2; uint32_t bf_offbits; } BITMAPFILEHEADER; /* The BITMAPINFOHEADER structure contains information about the * dimensions and color format of a DIB [device-independent bitmap]. * Adapted from http://msdn.microsoft.com/en-us/library/dd183376(VS.85).aspx. */ typedef struct { uint32_t bi_size; int32_t bi_width; int32_t bi_height; uint16_t bi_planes; uint16_t bi_bitcount; uint32_t bi_compression; uint32_t bi_size_image; int32_t bi_x_resolution_ppm; int32_t bi_y_resolution_ppm; uint32_t bi_clr_used; uint32_t bi_clr_important; } BITMAPINFOHEADER; /* The RGBTRIPLE structure describes a color consisting of relative intensities of * red, green, and blue. Adapted from http://msdn.microsoft.com/en-us/library/aa922590.aspx. */ typedef struct { uint8_t rgbt_blue; uint8_t rgbt_green; uint8_t rgbt_red; } RGBTRIPLE;
{ "domain": "codereview.stackexchange", "id": 45211, "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, image, bmp", "url": null }
c, image, bmp bool bmp_check_header(const BITMAPFILEHEADER * restrict bf, const BITMAPINFOHEADER * restrict bi); #endif /* BMP_H */ bmp.c: #include "bmp.h" #include <stdbool.h> #define SUPPORTED_BF_TYPE 0x4d42 #define SUPPORTED_BF_OFF_BITS 54 #define SUPPORTED_BI_SIZE 40 #define SUPPORTED_BI_BIT_COUNT 24 #define SUPPORTED_BI_COMPRESSION 0 bool bmp_check_header(const BITMAPFILEHEADER * restrict bf, const BITMAPINFOHEADER * restrict bi) { return bf->bf_type == SUPPORTED_BF_TYPE && bf->bf_offbits == SUPPORTED_BF_OFF_BITS && bi->bi_size == SUPPORTED_BI_SIZE && bi->bi_bitcount == SUPPORTED_BI_BIT_COUNT && bi->bi_compression == SUPPORTED_BI_COMPRESSION; } helpers.c: #include "helpers.h" #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define NEIGHBORHOOD_SIZE 9 #define SCALE 8192 #define SCALE_UP(x) ((uint_fast32_t) ((x) * SCALE + 0.5)) static inline int min(int x, int y) { return x < y ? x : y; } void grayscale(size_t height, size_t width, RGBTRIPLE image[height][width]) { for (size_t i = 0; i < height; ++i) { for (size_t j = 0; j < width; ++j) { const int average = (image[i][j].rgbt_blue + image[i][j].rgbt_red + image[i][j].rgbt_green + 1) / 3; image[i][j].rgbt_red = image[i][j].rgbt_green = image[i][j].rgbt_blue = (uint8_t) average; } } }
{ "domain": "codereview.stackexchange", "id": 45211, "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, image, bmp", "url": null }
c, image, bmp void sepia(size_t height, size_t width, RGBTRIPLE image[height][width]) { for (size_t i = 0; i < height; ++i) { for (size_t j = 0; j < width; ++j) { const int sepia_red = ((SCALE_UP(0.393) * image[i][j].rgbt_red + SCALE_UP(0.769) * image[i][j].rgbt_green + SCALE_UP(0.189) * image[i][j].rgbt_blue) + SCALE / 2) / SCALE; const int sepia_green = ((SCALE_UP(0.349) * image[i][j].rgbt_red + SCALE_UP(0.686) * image[i][j].rgbt_green + SCALE_UP(0.168) * image[i][j].rgbt_blue) + SCALE / 2) / SCALE; const int sepia_blue = ((SCALE_UP(0.272) * image[i][j].rgbt_red + SCALE_UP(0.534) * image[i][j].rgbt_green + SCALE_UP(0.131) * image[i][j].rgbt_blue) + SCALE / 2) / SCALE; image[i][j].rgbt_red = (uint8_t) min(255, sepia_red); image[i][j].rgbt_blue = (uint8_t) min(255, sepia_blue); image[i][j].rgbt_green = (uint8_t) min(255, sepia_green); } } } static inline void swap(RGBTRIPLE *restrict lhs, RGBTRIPLE *restrict rhs) { RGBTRIPLE tmp = *lhs; *lhs = *rhs; *rhs = tmp; } void reflect(size_t height, size_t width, RGBTRIPLE image[height][width]) { for (size_t i = 0; i < height; ++i) { size_t start = 0; size_t end = width - 1; while (start < end) { swap(&image[i][start], &image[i][end]); --end; ++start; } } } void box_blur(size_t height, size_t width, RGBTRIPLE image[height][width]) { RGBTRIPLE(*temp)[width + 2] = (errno = 0, calloc(height + 2, sizeof *temp)); if (!temp) { errno ? perror("calloc()") : (void) fputs("Error - failed to allocate memory for the image.", stderr); exit(EXIT_FAILURE); }
{ "domain": "codereview.stackexchange", "id": 45211, "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, image, bmp", "url": null }
c, image, bmp for (size_t i = 0; i < height; ++i) { for (size_t j = 0; j < width; ++j) { temp[i + 1][j + 1] = image[i][j]; } } for (size_t i = 0; i < height + 2; ++i) { temp[i][0] = temp[i][1]; /* Copy left edge. */ temp[i][width + 1] = temp[i][width]; /* Copy right edge. */ } for (size_t j = 0; j < width + 2; ++j) { temp[0][j] = temp[1][j]; /* Copy top edge. */ temp[height + 1][j] = temp[height][j]; /* Copy bottom edge. */ } for (size_t i = 1; i < height + 1; ++i) { for (size_t j = 1; j < width + 1; ++j) { size_t blue = 0, red = 0, green = 0; for (size_t k = i - 1; k < i + 2; ++k) { for (size_t l = j - 1; l < j + 2; ++l) { red += temp[k][l].rgbt_red; green += temp[k][l].rgbt_green; blue += temp[k][l].rgbt_blue; } } image[i - 1][j - 1].rgbt_red = (uint8_t) ((red + NEIGHBORHOOD_SIZE/ 2) / NEIGHBORHOOD_SIZE); image[i - 1][j - 1].rgbt_blue = (uint8_t) ((blue + NEIGHBORHOOD_SIZE / 2) / NEIGHBORHOOD_SIZE); image[i - 1][j - 1].rgbt_green = (uint8_t) ((green + NEIGHBORHOOD_SIZE / 2) / NEIGHBORHOOD_SIZE); } } free(temp); } void blur(size_t height, size_t width, RGBTRIPLE image[height][width]) { /* We try to approximate a Gaussian blur. */ for (size_t i = 0; i < 3; ++i) { box_blur(height, width, image); } } #undef NEIGHBORHOOD_SIZE #undef SCALE #undef SCALE_UP helpers.h: #ifndef HELPERS_H #define HELPERS_H #include "bmp.h" #include <stddef.h> /* Convert image to grayscale. */ void grayscale(size_t height, size_t width, RGBTRIPLE image[height][width]); /* Convert image to sepia. */ void sepia(size_t height, size_t width, RGBTRIPLE image[height][width]);
{ "domain": "codereview.stackexchange", "id": 45211, "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, image, bmp", "url": null }
c, image, bmp /* Reflect image horizontally. */ void reflect(size_t height, size_t width, RGBTRIPLE image[height][width]); /* Blur image. */ void blur(size_t height, size_t width, RGBTRIPLE image[height][width]); #endif /* HELPERS_H */ filter.c: #ifdef _POSIX_C_SOURCE #undef _POSIX_C_SOURCE #endif #ifdef _XOPEN_SOURCE #undef _XOPEN_SOURCE #endif #define _POSIX_C_SOURCE 200819L #define _XOPEN_SOURCE 700 #include <assert.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <getopt.h> #include "helpers.h" /* ARRAY_CARDINALITY(x) calculates the number of elements in the array 'x'. * If 'x' is a pointer, it will trigger an assertion. */ #define ARRAY_CARDINALITY(x) \ (assert((void *)&(x) == (void *)(x)), sizeof (x) / sizeof *(x)) #define BMP_SCANLINE_PADDING 4 #define BF_UNPADDED_REGION_SIZE 12 struct flags { bool sflag; /* Sepia flag. */ bool rflag; /* Reverse flag. */ bool gflag; /* Greyscale flag. */ bool bflag; /* Blur flag. */ FILE *out_file; /* Output to file. */ }; static void help(void) { puts("Usage: filter [OPTIONS] <infile> <outfile>\n" "\n\tTransform your BMP images with powerful filters.\n\n" "Options:\n" " -s, --sepia Apply a sepia filter for a warm, vintage look.\n" " -r, --reverse Create a horizontal reflection for a mirror effect.\n" " -g, --grayscale Convert the image to classic greyscale.\n" " -b, --blur Add a soft blur to the image.\n" " -h, --help displays this message and exit.\n"); exit(EXIT_SUCCESS); } static void err_msg(void) { fputs("Usage: filter [OPTIONS] <infile> <outfile>\n" "Try filter -h for help.\n", stderr); exit(EXIT_FAILURE); }
{ "domain": "codereview.stackexchange", "id": 45211, "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, image, bmp", "url": null }
c, image, bmp static void parse_options(const struct option *restrict long_options, const char *restrict short_options, struct flags *restrict opt_ptr, int argc, char *const argv[]) { int c; while ((c = getopt_long(argc, argv, short_options, long_options, NULL)) != -1) { switch (c) { case 's': opt_ptr->sflag = true; break; case 'r': opt_ptr->rflag = true; break; case 'g': opt_ptr->gflag = true; break; case 'b': opt_ptr->bflag = true; break; case 'h': help(); break; case 'o': /* We'll seek to the beginning once we've read input, * in case it's the same file. */ opt_ptr->out_file = (errno = 0, fopen(optarg, "ab")); if (!opt_ptr->out_file) { errno ? perror(optarg) : (void) fputs("Error - failed to open output file.", stderr); } break; /* case '?' */ default: err_msg(); break; } } } static void apply_filter(const struct flags *options, size_t height, size_t width, RGBTRIPLE image[height][width]) { struct { bool flag; void (* const func)(size_t height, size_t width, RGBTRIPLE image[height][width]); } group[] = { { options->sflag, sepia }, { options->rflag, reflect }, { options->gflag, grayscale }, { options->bflag, blur }, }; for (size_t i = 0; i < ARRAY_CARDINALITY(group); ++i) { if (group[i].flag) { group[i].func(height, width, image); } } }
{ "domain": "codereview.stackexchange", "id": 45211, "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, image, bmp", "url": null }
c, image, bmp static size_t determine_padding(size_t width) { /* In BMP images, each scanline (a row of pixels) must be a multiple of * BMP_SCANLINE_PADDING bytes in size. If the width of the image in pixels * multipled by the size of each pixel (in bytes) is not a multiple of * BMP_SCANLINE_PADDING, padding is added to make it so. */ return (BMP_SCANLINE_PADDING - (width * sizeof (RGBTRIPLE)) % BMP_SCANLINE_PADDING) % BMP_SCANLINE_PADDING; } static int write_scanlines(FILE * out_file, size_t height, size_t width, const RGBTRIPLE image[][width], size_t padding) { const size_t pad_byte = 0x00; /* Write new pixels to outfile */ for (size_t i = 0; i < height; ++i) { /* Write row to outfile, with padding at the end. */ if (fwrite(image[i], sizeof image[i][0], width, out_file) != width || fwrite(&pad_byte, 1, padding, out_file) != padding) { return -1; } } return 0; } static int write_image(const BITMAPFILEHEADER * restrict bf, const BITMAPINFOHEADER * restrict bi, FILE * restrict out_file, size_t height, size_t width, const RGBTRIPLE image[height][width]) { if (out_file != stdout && (errno = 0, ftruncate(fileno(out_file), 0))) { errno ? perror("seek()") : (void) fputs("Error - failed to write to output file.\n", stderr); return -1; } if (fwrite(&bf->bf_type, sizeof bf->bf_type, 1, out_file) != 1 || fwrite(&bf->bf_size, BF_UNPADDED_REGION_SIZE, 1, out_file) != 1 || fwrite(bi, sizeof *bi, 1, out_file) != 1) { fputs("Error - failed to write to output file.\n", stderr); return -1; } const size_t padding = determine_padding(width);
{ "domain": "codereview.stackexchange", "id": 45211, "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, image, bmp", "url": null }
c, image, bmp const size_t padding = determine_padding(width); if (write_scanlines(out_file, height, width, image, padding) == -1) { fputs("Error - failed to write to output file.\n", stderr); return -1; } return out_file == stdout || !fclose(out_file); } static int read_scanlines(FILE * in_file, size_t height, size_t width, RGBTRIPLE image[][width], size_t padding) { /* Iterate over infile's scanlines */ for (size_t i = 0; i < height; i++) { /* Read row into pixel array */ if (fread(image[i], sizeof image[i][0], width, in_file) != width) { return -1; } /* Temporary buffer to read and discard padding. */ uint8_t padding_buffer[BMP_SCANLINE_PADDING]; if (fread(padding_buffer, 1, padding, in_file) != padding) { return -1; } } return 0; } static void *read_image(BITMAPFILEHEADER * restrict bf, BITMAPINFOHEADER * restrict bi, size_t *restrict height_ptr, size_t *restrict width_ptr, FILE * restrict in_file) { /* Read infile's BITMAPFILEHEADER and BITMAPINFOHEADER. */ if (fread(&bf->bf_type, sizeof bf->bf_type, 1, in_file) != 1 || fread(&bf->bf_size, BF_UNPADDED_REGION_SIZE, 1, in_file) != 1 || fread(bi, sizeof *bi, 1, in_file) != 1) { fputs("Error - failed to read input file.\n", stderr); return NULL; }
{ "domain": "codereview.stackexchange", "id": 45211, "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, image, bmp", "url": null }
c, image, bmp /* Ensure infile is (likely) a 24-bit uncompressed BMP 4.0 */ if (!bmp_check_header(bf, bi)) { fputs("Error - unsupported file format.\n", stderr); return NULL; } /* There seems to be no need to treating the data differently. * The code handles both top-down and bottom-up just fine. Or does it? */ #if 0 /* If bi_height is positive, the bitmap is a bottom-up DIB with the origin * at the lower left corner. It bi_height is negative, the bitmap is a top- * down DIB with the origin at the upper left corner. * We currenly only support images stored as top-down, so bail if the format * is elsewise. */ if (bi->bi_height > 0) { fputs("Error - Bottom-up BMP image format is not yet supported.\n", stderr); return NULL; } #endif /* Get image's dimensions. */ uint32_t abs_height = bi->bi_height < 0 ? 0u - (uint32_t) bi->bi_height : (uint32_t) bi->bi_height; /* If we are on a too small a machine, there is not much hope, so bail. */ if (abs_height > SIZE_MAX) { fputs ("Error - Image dimensions are too large for this system to process.\n", stderr); return NULL; } size_t height = (size_t) abs_height; size_t width = (size_t) bi->bi_width; if (!height || !width) { fputs("Error - corrupted BMP file: width or height is zero.\n", stderr); return NULL; } if (width > (SIZE_MAX - sizeof (RGBTRIPLE)) / sizeof (RGBTRIPLE)) { fputs("Error - image width is too large for this system to process.\n", stderr); return NULL; } /* Allocate memory for image */ RGBTRIPLE(*image)[width] = calloc(height, sizeof *image); if (!image) { fputs("Error - not enough memory to store image.\n", stderr); return NULL; } const size_t padding = determine_padding(width);
{ "domain": "codereview.stackexchange", "id": 45211, "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, image, bmp", "url": null }
c, image, bmp const size_t padding = determine_padding(width); if (read_scanlines(in_file, height, width, image, padding)) { fputs("Error - failed to read input file.\n", stderr); return NULL; } *height_ptr = height; *width_ptr = width; return image; } static int process_image(const struct flags *restrict options, FILE * restrict in_file, FILE * restrict out_file) { BITMAPFILEHEADER bf; BITMAPINFOHEADER bi; size_t height = 0; size_t width = 0; void *const image = read_image(&bf, &bi, &height, &width, in_file); if (!image) { return -1; } apply_filter(options, height, width, image); if (write_image(&bf, &bi, out_file, height, width, image) == -1) { return -1; } free(image); return 0; } int main(int argc, char *argv[]) { /* Sanity check. POSIX requires the invoking process to pass a non-NULL * argv[0]. */ if (!argv) { fputs("A NULL argv[0] was passed through an exec system call.\n", stderr); return EXIT_FAILURE; } /* Define allowable filters */ static const struct option long_options[] = { { "grayscale", no_argument, NULL, 'g' }, { "reverse", no_argument, NULL, 'r' }, { "sepia", no_argument, NULL, 's' }, { "blur", no_argument, NULL, 'b' }, { "help", no_argument, NULL, 'h' }, { "output", required_argument, NULL, 'o' }, { NULL, 0, NULL, 0 } }; FILE *in_file = stdin; struct flags options = { false, false, false, false, stdout }; int result = EXIT_SUCCESS; parse_options(long_options, "grsbho:", &options, argc, argv); if ((optind + 1) == argc) { in_file = (errno = 0, fopen(argv[optind], "rb"));
{ "domain": "codereview.stackexchange", "id": 45211, "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, image, bmp", "url": null }
c, image, bmp if ((optind + 1) == argc) { in_file = (errno = 0, fopen(argv[optind], "rb")); if (!in_file) { errno ? perror(argv[optind]) : (void) fputs("Error - failed to open input file.", stderr); return EXIT_FAILURE; } } else if (optind > argc) { err_msg(); } if (process_image(&options, in_file, options.out_file) == -1) { result = EXIT_FAILURE; } if (in_file != stdin) { fclose(in_file); } return result; } Answer: Should the functions doing the input/output be moved to bmp.c? I recommend a different approach. Think of all these image processing code as a set of routines in a library, maybe called hbmp. In order to use them, and not conflict with user code, the file names, functions, your new types, defines, ... should be prefixed with hbmp_ and the top level routines prototyped in hbmp.h. Form various .c files like hbmp_init.c, hbmp_io.c, hbmp_filter.c to place the related code. Common file names like filter.c are sure to collide. Corral your name space. The file with main() might be quite small. The larger point being: plan to use many of these routines in larger code sets. Style, potential undefined behavior, et cetera. #define with non-zero Consider #ifndef BMP_H #define BMP_H If other code uses #if BMP_H, that is true when BMP_H is defined and non-zero. It is false when BMP_H is not defined. It is also false when * Should the functions doing the input/output be moved to bmp.c? Style, potential undefined behavior, et cetera. BMP_H is defined and zero or unvalued. Better to create code guards that differ in testing when using #if as well as #ifdef/#indef. Recommend instead: #ifndef BMP_H #define BMP_H 1
{ "domain": "codereview.stackexchange", "id": 45211, "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, image, bmp", "url": null }
c, image, bmp Portability I would hope write_image(), read_image(), apply_filter(), (and most of filter.c) could exist in .c file that does not need non-C standard includes like <unistd.h>, <sys/types.h>, <getopt.h>. Save those includes for the main() and option processing .c file. int size I have not found a dependency on int size as 32-bits. I suspect code would work well with int as 16, 32, 64, ... bits. Good! Bug: wrong test // if (!argv) { fputs("A NULL argv[0] was passed through an exec system call.\n", ... if (!argv[0]) { fputs("A NULL argv[0] was passed through an exec system call.\n",... Curious, do you really need this check, something about parse_options()? Bubble up some fatal errors or exit() Well done: I see some deep errors calling exit() and others returns an error code. I might disagree with some choices, yet I find your selection mostly good. What is best is fairly subjective. Mixed types? int c; ... c = getopt_long(...) looks wrong. Hmmm, I see it is right Style: Interesting use of , operator in_file = (errno = 0, fopen(argv[optind], "rb")); I understand why it is there - to tightly bound the errno = 0; with the following errno function. Auto format? It looks like code, though neat, is not using an auto-formatter. Consider improving productively and auto-format. Round ties to even? Should you want a round ties to even rather than the current round ties down: // int average = (image[i][j].rgbt_blue + image[i][j].rgbt_red + // image[i][j].rgbt_green + 1) / 3; unsigned average = image[i][j].rgbt_blue + image[i][j].rgbt_red + image[i][j].rgbt_green; average = (average + (average & 1u) + 1u)/3u;
{ "domain": "codereview.stackexchange", "id": 45211, "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, image, bmp", "url": null }
c, image, bmp size_t subtraction I often get a little concerned with code like size_t end = width - 1; and wonder what would happen with width == 0 and then end === SIZE_MAX. Of course, such values are pathological, yet sometimes we can simply handle that edge case too. size_t start = 0; // size_t end = width - 1; size_t end = width; while (start < end) { --end; // add swap(&image[i][start], &image[i][end]); // --end; ++start; } Downside: On odd wide pics, we do one more loop per for(). I see that if (!height || !width) { would have caught that. Yet retain the higher level thought: be careful about subtracting size_t.
{ "domain": "codereview.stackexchange", "id": 45211, "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, image, bmp", "url": null }
c++, memory-management, c++20, heap Title: C++ heap allocator using an explicit free list Question: Description I've written a heap allocator in C++ using an explicit free list for organization. I've also written a series of unit tests and a microbenchmark using Catch2. At time of writing I've tested it with gcc and clang on Linux and MSVC and clang on Windows. The intended use case for this code is personal projects falling under the umbrella of real time simulations. The "problem" I'm solving is the same as why anyone writes an allocator, I'd imagine - consistent dynamic memory performance and insights into memory usage. Request I'd like feedback on a few thing in particular: Design - I want to leverage C++20 well and write code that's reasonably readable and maintainable. By reasonably I mean something like the legal notion, e.g., "a reasonable developer." Opinions backed by experience are always welcome, too. Performance - Writing portable, reusable code is more important than raw performance, but I don't want the design to needlessly hamper performance. Relatedly, I don't want to write code that hampers the compiler's ability to do its job with optimizations. Unit tests - Ensuring "complete testing coverage" is a tough exercise, even for a small project like this. Did I forget any edge cases? Are my tests overwhelmingly redundant? Benchmarking - I don't expect my code to outperform stdlib, but would you call the benchmark I wrote fair/useful/thorough? What other patterns would you test if this was your allocator? Or am I just mistaken and writing a bare-bones allocator like this should always yield better than stdlib performance? Project Code If you'd prefer to browse yourself, the full repository at time of writing is here. The BlockHeader struct is really just something to cast a chunk of memory into. #ifndef BRASSTACKS_MEMORY_BLOCKHEADER_HPP #define BRASSTACKS_MEMORY_BLOCKHEADER_HPP #include <cstddef> #include <cstdint> namespace btx::memory {
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap #include <cstddef> #include <cstdint> namespace btx::memory { struct alignas(16) BlockHeader final { public: // Convenience functions for common casting and pointer math [[nodiscard]] static inline BlockHeader * header(void *address) { return reinterpret_cast<BlockHeader *>( reinterpret_cast<uint8_t *>(address) - sizeof(BlockHeader) ); } [[nodiscard]] static inline void * payload(BlockHeader *header) { return reinterpret_cast<uint8_t *>(header) + sizeof(BlockHeader); } // No constructors because BlockHeader is intended to be used as a means by // which to interpret existing memory via casts. BlockHeader() = delete; ~BlockHeader() = delete; BlockHeader(BlockHeader &&) = delete; BlockHeader(BlockHeader const &) = delete; BlockHeader & operator=(BlockHeader &&) = delete; BlockHeader & operator=(BlockHeader const &) = delete; std::size_t size = 0; // The size stored here refers to the space available // for user allocation. Said another way, it's the // size of the whole block, minus sizeof(BlockHeader). BlockHeader *next = nullptr; BlockHeader *prev = nullptr; }; } // namespace btx::memory #endif // BRASSTACKS_MEMORY_BLOCKHEADER_HPP The Heap is the main actor. #ifndef BRASSTACKS_MEMORY_HEAP_HPP #define BRASSTACKS_MEMORY_HEAP_HPP #include "brasstacks/memory/BlockHeader.hpp" #include <cstddef> #include <cstdint> namespace btx::memory { struct BlockHeader; class Heap final { public: [[nodiscard]] void * alloc(std::size_t const req_bytes); void free(void *address);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap [[nodiscard]] std::size_t total_size() const { return _total_size; } [[nodiscard]] std::size_t current_used() const { return _current_used; } [[nodiscard]] std::size_t current_allocs() const { return _current_allocs; } [[nodiscard]] std::size_t peak_used() const { return _peak_used; } [[nodiscard]] std::size_t peak_allocs() const { return _peak_allocs; } [[nodiscard]] uint8_t const * raw_heap() const { return _raw_heap; } [[nodiscard]] BlockHeader const * free_head() const { return _free_head; } [[nodiscard]] float calc_fragmentation() const; Heap() = delete; ~Heap(); explicit Heap(std::size_t const req_bytes); Heap(Heap &&other) = delete; Heap(Heap const &) = delete; Heap & operator=(Heap &&other) = delete; Heap & operator=(Heap const &) = delete; private: uint8_t *_raw_heap; BlockHeader *_free_head; std::size_t _total_size; std::size_t _current_used; std::size_t _current_allocs; std::size_t _peak_used; std::size_t _peak_allocs; static std::size_t constexpr _min_alloc_bytes = sizeof(BlockHeader); void _split_free_block(BlockHeader *header, std::size_t const bytes); void _use_whole_free_block(BlockHeader *header); void _coalesce(BlockHeader *header); }; } // namespace btx::memory #endif // BRASSTACKS_MEMORY_HEAP_HPP Consequently, Heap.cpp is the bulk of the code. #include "brasstacks/memory/Heap.hpp" #include <cassert> #include <cstdlib> namespace btx::memory { // ============================================================================= float Heap::calc_fragmentation() const { std::size_t total_free = 0; std::size_t largest_free_block_size = 0; BlockHeader *current_header = _free_head;
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap while(current_header != nullptr) { if(current_header->size > largest_free_block_size) { largest_free_block_size = current_header->size; } total_free += current_header->size; current_header = current_header->next; } if(total_free == 0) { return 0.0f; } return 1.0f - ( static_cast<float>(largest_free_block_size) / static_cast<float>(total_free) ); } // ============================================================================= void * Heap::alloc(std::size_t const req_bytes) { if(req_bytes <= 0) { assert(false && "Cannot allocate zero or fewer bytes"); return nullptr; } std::size_t bytes = req_bytes; if(bytes < _min_alloc_bytes) { bytes = _min_alloc_bytes; } int32_t constexpr ALIGN = sizeof(void *); bytes = (bytes + ALIGN - 1) & -ALIGN; // Find a free block with sufficient space available auto *current_header = _free_head; while(current_header != nullptr) { std::size_t const size_of_new_block = bytes + sizeof(BlockHeader); // The most likely case that'll fit is the block we've found is bigger // than what we've asked for, so we need to split it. This implies // the creation of a new header for the new allocation as well if(current_header->size >= size_of_new_block) { // If splitting the block would result in less than 32 bytes of // free space, just use the whole thing if(current_header->size - size_of_new_block < _min_alloc_bytes) { _use_whole_free_block(current_header); } else { _split_free_block(current_header, bytes); } break; }
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // Much less likely, but still possible, is finding a block that fits // the request exactly, in which case we just need to fix the pointers if(current_header->size == bytes) { _use_whole_free_block(current_header); break; } // Carry on looking for a suitable block current_header = current_header->next; } // We couldn't find a block of sufficient size, so the allocation has // failed and the user will need to handle it how they see fit if(current_header == nullptr) { assert(false && "Failed to allocate block"); return nullptr; } // Update the heap's metrics _current_used += current_header->size; _current_allocs += 1; if(_current_used > _peak_used) { _peak_used = _current_used; } if(_current_allocs > _peak_allocs) { _peak_allocs = _current_allocs; } // And hand the bytes requested back to the user return BlockHeader::payload(current_header); } // ============================================================================= void Heap::free(void *address) { if(address == nullptr) { assert(false && "Attempting to free memory twice"); return; } // Grab the associated header from the user's pointer BlockHeader *header_to_free = BlockHeader::header(address); // Update heap stats _current_used -= header_to_free->size; _current_allocs -= 1; // If the free list is empty, then this block will serve as the new head if(_free_head == nullptr) { _free_head = header_to_free; } else if(header_to_free < _free_head) { // If the newly freed block has a earlier memory address than the free // list's current head, the freed block becomes the new head header_to_free->next = _free_head; header_to_free->prev = nullptr; _free_head->prev = header_to_free;
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap _free_head = header_to_free; } else { // Otherwise the newly freed block will land somewhere after the head. // Walk the list to find a block to insert the newly free block after, // and break if current_block is the last free block in the list. auto *current_header = _free_head; while(header_to_free < current_header) { if(current_header->next == nullptr) { break; } current_header = current_header->next; } // Fix the list pointers header_to_free->next = current_header->next; header_to_free->prev = current_header; if(header_to_free->next != nullptr) { header_to_free->next->prev = header_to_free; } if(header_to_free->prev != nullptr) { header_to_free->prev->next = header_to_free; } } _coalesce(header_to_free); address = nullptr; } // ============================================================================= Heap::Heap(std::size_t const req_bytes) : _raw_heap { nullptr }, _current_used { sizeof(BlockHeader) }, _current_allocs { 0 }, _peak_used { sizeof(BlockHeader) }, _peak_allocs { 0 } { if(req_bytes <= 0) { assert(false && "Cannot allocate zero sized heap"); return; } // So long as BlockHeader's size is a power of two, this rounding to a // multiple math is safe int32_t constexpr ALIGN = sizeof(BlockHeader) * 2; std::size_t const bytes = (req_bytes + ALIGN - 1) & -ALIGN; _total_size = bytes; _raw_heap = reinterpret_cast<uint8_t *>(::malloc(_total_size)); assert(_raw_heap != nullptr && "Heap allocation failed"); _free_head = reinterpret_cast<BlockHeader *>(_raw_heap); _free_head->size = bytes - sizeof(BlockHeader); _free_head->next = nullptr; _free_head->prev = nullptr; } Heap::~Heap() { ::free(_raw_heap); }
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap Heap::~Heap() { ::free(_raw_heap); } // ============================================================================= void Heap::_split_free_block(BlockHeader *header, std::size_t const bytes) { // Reinterpret the space just beyond what's requested as a new free block auto *new_free_header = reinterpret_cast<BlockHeader *>( reinterpret_cast<uint8_t *>(header) + sizeof(BlockHeader) + bytes ); // The heap's used size increases for each header, whether free or used _current_used += sizeof(BlockHeader); // The new block's size is set to what's left of the original block new_free_header->size = header->size - sizeof(BlockHeader) - bytes; // And the allocation we'll return is shrunk proportionately header->size -= new_free_header->size + sizeof(BlockHeader); // Fix up the linked list, removing the allocation from the free list new_free_header->next = header->next; new_free_header->prev = header->prev; header->next = nullptr; header->prev = nullptr; if(new_free_header->next != nullptr) { new_free_header->next->prev = new_free_header; } if(new_free_header->prev != nullptr) { new_free_header->prev->next = new_free_header; } // Finally, adjust _free_head if need be if(header == _free_head) { _free_head = new_free_header; } } // ============================================================================= void Heap::_use_whole_free_block(BlockHeader *header) { if(header->next != nullptr) { header->next->prev = header->prev; } if(header->prev != nullptr) { header->prev->next = header->next; } if(header == _free_head) { _free_head = _free_head->next; } header->next = nullptr; header->prev = nullptr; }
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap header->next = nullptr; header->prev = nullptr; } // ============================================================================= void Heap::_coalesce(BlockHeader *header) { if(header->next != nullptr) { // If the current block's payload plus its own size is the same // location as header->next, that means the blocks are contiguous and // can be merged auto *next_header_from_offset = reinterpret_cast<BlockHeader *>( reinterpret_cast<uint8_t *>(BlockHeader::payload(header)) + header->size ); if(next_header_from_offset == header->next) { // Grow the size of the current block by absorbing the next auto *next_header = header->next; header->size += sizeof(BlockHeader) + next_header->size; // Fix the pointers header->next = next_header->next; if(header->next != nullptr) { header->next->prev = header; } next_header->next = nullptr; next_header->prev = nullptr; // Since two blocks merged, there's one less header being used _current_used -= sizeof(BlockHeader); } } if(header->prev != nullptr) { // This is the same strategy as above, but measuring forward from // header->prev auto *prev_header_from_offset = reinterpret_cast<BlockHeader *>( reinterpret_cast<uint8_t *>(BlockHeader::payload(header->prev)) + header->prev->size ); if(prev_header_from_offset == header) { // Grow the size of the current block by absorbing the next auto *prev_header = header->prev; prev_header->size += sizeof(BlockHeader) + header->size; // Fix the pointers prev_header->next = header->next; if(header->next != nullptr) { header->next->prev = header->prev; }
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap header->next = nullptr; header->prev = nullptr; // Since two blocks merged, there's one less header being used _current_used -= sizeof(BlockHeader); } } } } // namespace btx::memory Unit Tests and Benchmark As for the Catch2 code, the source files share brief header #ifndef TEST_HELPERS_HPP #define TEST_HELPERS_HPP #include <catch2/catch_test_macros.hpp> #include <catch2/matchers/catch_matchers_floating_point.hpp> #include <catch2/benchmark/catch_benchmark.hpp> float constexpr epsilon = 1.0e-6f; #endif // TEST_HELPERS_HPP This is the benchmark I wrote: #include "brasstacks/memory/BlockHeader.hpp" #include "brasstacks/memory/Heap.hpp" #include "test_helpers.hpp" #include <random> #include <functional> #include <vector> #include <numeric> using namespace btx::memory; constexpr std::size_t alloc_count = 1000; constexpr std::size_t min_alloc_size = 1 << 4; constexpr std::size_t max_alloc_size = 1 << 8; TEST_CASE("Benchmarking") { // The first thing we need is a good ol' RNG on which to base our ranges std::random_device dev; std::default_random_engine rng(dev()); // Next, a vector of random allocation sizes std::vector<std::size_t> alloc_sizes; alloc_sizes.resize(alloc_count); auto alloc_size_rng = std::bind( std::uniform_int_distribution<std::size_t>(min_alloc_size, max_alloc_size), rng ); for(auto &alloc_size : alloc_sizes) { alloc_size = alloc_size_rng(); }
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap for(auto &alloc_size : alloc_sizes) { alloc_size = alloc_size_rng(); } // The benchmarks below will allocate 500 randomly sized blocks, then free // those 500 blocks in a random order, and repeat for the second 500 blocks. // In service of that, I'll make two vectors of indices (first half: 0-499, // second half 499-999) and shuffle them std::vector<std::size_t> free_order_first_half(alloc_count/2); std::iota( free_order_first_half.begin(), free_order_first_half.end(), 0 ); std::shuffle( free_order_first_half.begin(), free_order_first_half.end(), rng ); std::vector<std::size_t> free_order_second_half(alloc_count/2); std::iota( free_order_second_half.begin(), free_order_second_half.end(), alloc_count/2 ); std::shuffle( free_order_second_half.begin(), free_order_second_half.end(), rng ); // Finally, a vector of pointers to store the allocations std::vector<void *> allocs(alloc_count); std::fill(allocs.begin(), allocs.end(), nullptr); // Test plain malloc() and free() BENCHMARK("libstdc malloc and free benchmark") { return [&] { std::size_t alloc = 0; // Allocate the first half do { allocs[alloc] = ::malloc(alloc_sizes[alloc]); // Zero the memory ::memset(allocs[alloc], 0, alloc_sizes[alloc]); // Write some "useful" information auto *new_block = static_cast<std::size_t *>(allocs[alloc]); *new_block = alloc_sizes[alloc]; ++alloc; } while(alloc < alloc_count/2); // Free the first half in random order for(auto const index : free_order_first_half) { ::free(allocs[index]); }
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // Allocate the second half do { allocs[alloc] = ::malloc(alloc_sizes[alloc]); // Same nonosense as above ::memset(allocs[alloc], 0, alloc_sizes[alloc]); auto *new_block = static_cast<std::size_t *>(allocs[alloc]); *new_block = alloc_sizes[alloc]; ++alloc; } while(alloc < alloc_count); // Free the second half in random order for(auto const index : free_order_second_half) { ::free(allocs[index]); } }; }; // Create a heap that's guaranteed to be able to hold all of our random // allocations auto heap_size_rng = std::bind( std::uniform_int_distribution<std::size_t>( max_alloc_size * alloc_count + 32u, max_alloc_size * alloc_count * 2 ), rng ); Heap heap(heap_size_rng()); // And test its performance BENCHMARK("btx::memory alloc and free benchmark") { return [&] { std::size_t alloc = 0; // Allocate the first half do { allocs[alloc] = heap.alloc(alloc_sizes[alloc]); // Zero the memory ::memset(allocs[alloc], 0, alloc_sizes[alloc]); // Write some "useful" information auto *new_block = static_cast<std::size_t *>(allocs[alloc]); *new_block = alloc_sizes[alloc]; ++alloc; } while(alloc < alloc_count/2); // Free the first half in random order for(auto const index : free_order_first_half) { heap.free(allocs[index]); } // Allocate the second half do { allocs[alloc] = heap.alloc(alloc_sizes[alloc]);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // Same nonosense as above ::memset(allocs[alloc], 0, alloc_sizes[alloc]); auto *new_block = static_cast<std::size_t *>(allocs[alloc]); *new_block = alloc_sizes[alloc]; ++alloc; } while(alloc < alloc_count); // Free the second half in random order for(auto const index : free_order_second_half) { heap.free(allocs[index]); } }; }; } Testing basic Heap functions. #include "brasstacks/memory/BlockHeader.hpp" #include "brasstacks/memory/Heap.hpp" #include "test_helpers.hpp" using namespace btx::memory; using namespace Catch::Matchers; TEST_CASE("Heap creation and initial state metrics") { std::size_t const heap_size = 512; Heap heap(heap_size); // First check the heap's internal metrics REQUIRE(heap.current_used() == sizeof(BlockHeader)); REQUIRE(heap.current_allocs() == 0); REQUIRE(heap.peak_used() == heap.current_used()); REQUIRE(heap.peak_allocs() == heap.current_allocs()); REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon)); // Next check the heap's structure auto const *raw_heap = heap.raw_heap(); auto const *free_header = reinterpret_cast<BlockHeader const *>(raw_heap); REQUIRE(free_header->size == heap_size - sizeof(BlockHeader)); REQUIRE(free_header->prev == nullptr); REQUIRE(free_header->next == nullptr); } Testing just one block. #include "brasstacks/memory/BlockHeader.hpp" #include "brasstacks/memory/Heap.hpp" #include "test_helpers.hpp" using namespace btx::memory; using namespace Catch::Matchers; TEST_CASE("Allocate and free a single block") { std::size_t const heap_size = 512; Heap heap(heap_size); // Allocate one block std::size_t const size_a = 64; void *alloc_a = heap.alloc(size_a);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // Allocate one block std::size_t const size_a = 64; void *alloc_a = heap.alloc(size_a); // Check the heap's internal metrics REQUIRE(heap.total_size() == heap_size); REQUIRE(heap.current_used() == size_a + 2 * sizeof(BlockHeader)); REQUIRE(heap.current_allocs() == 1); REQUIRE(heap.peak_used() == heap.current_used()); REQUIRE(heap.peak_allocs() == heap.current_allocs()); REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon)); // Check that the BlockHeader helper functions produce interchangable // addresses, and that header_a->next is nullptr BlockHeader *header_a = BlockHeader::header(alloc_a); REQUIRE(header_a->size == size_a); REQUIRE(alloc_a == BlockHeader::payload(header_a)); REQUIRE(header_a->next == nullptr); // The header for our sole allocation is at the very beginning of the heap auto const *raw_heap = heap.raw_heap(); REQUIRE(reinterpret_cast<uint8_t *>(header_a) == raw_heap); // The free block header is now at +96 bytes auto const *free_header = reinterpret_cast<BlockHeader const *>( raw_heap + sizeof(BlockHeader) + header_a->size ); // And the free block is 384 bytes in size REQUIRE(free_header->size == heap_size - (header_a->size + 2 * sizeof(BlockHeader)) ); // free_header->next should point nowhere REQUIRE(free_header->next == nullptr); // Now free the block heap.free(alloc_a); // The heap's internal metrics should be back to their initial state REQUIRE(heap.total_size() == 512); REQUIRE(heap.current_used() == sizeof(BlockHeader)); REQUIRE(heap.current_allocs() == 0); REQUIRE(heap.peak_used() == size_a + 2 * sizeof(BlockHeader)); REQUIRE(heap.peak_allocs() == 1); REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon)); } TEST_CASE("Allocate and free a single block, filling the heap") { std::size_t const heap_size = 512; Heap heap(heap_size);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // Allocate one block std::size_t const size_a = heap_size - sizeof(BlockHeader); void *alloc_a = heap.alloc(size_a); // Check the heap's internal metrics REQUIRE(heap.total_size() == heap_size); REQUIRE(heap.current_used() == size_a + sizeof(BlockHeader)); REQUIRE(heap.current_allocs() == 1); REQUIRE(heap.peak_used() == heap.current_used()); REQUIRE(heap.peak_allocs() == heap.current_allocs()); REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon)); // Check that the BlockHeader helper functions produce interchangable // addresses, and that header_a->next is nullptr BlockHeader *header_a = BlockHeader::header(alloc_a); REQUIRE(header_a->size == size_a); REQUIRE(alloc_a == BlockHeader::payload(header_a)); REQUIRE(header_a->next == nullptr); // The header for our sole allocation is at the very beginning of the heap auto const *raw_heap = heap.raw_heap(); REQUIRE(reinterpret_cast<uint8_t *>(header_a) == raw_heap); // Now free the block heap.free(alloc_a); // The heap's internal metrics should be back to their initial state REQUIRE(heap.total_size() == 512); REQUIRE(heap.current_used() == sizeof(BlockHeader)); REQUIRE(heap.current_allocs() == 0); REQUIRE(heap.peak_used() == size_a + sizeof(BlockHeader)); REQUIRE(heap.peak_allocs() == 1); REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon)); } Testing two blocks. #include "brasstacks/memory/BlockHeader.hpp" #include "brasstacks/memory/Heap.hpp" #include "test_helpers.hpp" using namespace btx::memory; using namespace Catch::Matchers; TEST_CASE("Allocate and free two blocks, free a->b") { std::size_t const heap_size = 256; Heap heap(heap_size); // Allocate two blocks std::size_t const size_a = 64; std::size_t const size_b = 96; void *alloc_a = heap.alloc(size_a); void *alloc_b = heap.alloc(size_b);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap void *alloc_a = heap.alloc(size_a); void *alloc_b = heap.alloc(size_b); // Check the heap's internal metrics REQUIRE(heap.current_used() == 256); REQUIRE(heap.current_allocs() == 2); REQUIRE(heap.peak_used() == heap.current_used()); REQUIRE(heap.peak_allocs() == heap.current_allocs()); // Check that the BlockHeader helper functions produce interchangable // addresses BlockHeader *header_a = BlockHeader::header(alloc_a); REQUIRE(header_a->size == size_a); REQUIRE(alloc_a == BlockHeader::payload(header_a)); BlockHeader *header_b = BlockHeader::header(alloc_b); // alloc_b will have absorbed the zero-byte free block below it, meaning // alloc_b is 32 bytes larger than the requested size REQUIRE(header_b->size == 128); REQUIRE(alloc_b == BlockHeader::payload(header_b)); // Both headers' pointers should be null REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(heap.free_head() == nullptr); // The first header is at the very beginning of the heap uint8_t const *raw_heap = heap.raw_heap(); REQUIRE(reinterpret_cast<uint8_t *>(header_a) == raw_heap); // The second header is at +96 bytes REQUIRE(reinterpret_cast<uint8_t *>(header_b) == raw_heap + sizeof(BlockHeader) + size_a ); // Since the free header was absorbed, it should be null REQUIRE(heap.free_head() == nullptr); // Now free the first block heap.free(alloc_a); // Check the heap stats REQUIRE(heap.current_used() == 192); REQUIRE(heap.current_allocs() == 1); REQUIRE(heap.peak_used() == 256); REQUIRE(heap.peak_allocs() == 2);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // Given that header_a is now free, it should be the new head of the free // list. Its size is unchanged and its pointers are null because it's the // only member of the list REQUIRE(heap.free_head() == header_a); REQUIRE(header_a->size == size_a); REQUIRE(header_a->prev == nullptr); REQUIRE(header_a->prev == nullptr); // Free the second block heap.free(alloc_b); // Check the heap stats REQUIRE(heap.current_used() == sizeof(BlockHeader)); REQUIRE(heap.current_allocs() == 0); REQUIRE(heap.peak_used() == 256); REQUIRE(heap.peak_allocs() == 2); // Given that the second block was between the first and free blocks, the // entire heap should now be back to a single free block REQUIRE(header_a->size == heap_size - sizeof(BlockHeader)); REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); } TEST_CASE("Allocate and free two blocks, free b->a") { std::size_t const heap_size = 256; Heap heap(heap_size); // Allocate two blocks std::size_t const size_a = 64; std::size_t const size_b = 96; void *alloc_a = heap.alloc(size_a); void *alloc_b = heap.alloc(size_b); // Check the heap's internal metrics REQUIRE(heap.current_used() == 3 * sizeof(BlockHeader) + size_a + size_b); REQUIRE(heap.current_allocs() == 2); REQUIRE(heap.peak_used() == heap.current_used()); REQUIRE(heap.peak_allocs() == heap.current_allocs()); // Check that the BlockHeader helper functions produce interchangable // addresses BlockHeader *header_a = BlockHeader::header(alloc_a); REQUIRE(header_a->size == size_a); REQUIRE(alloc_a == BlockHeader::payload(header_a)); BlockHeader *header_b = BlockHeader::header(alloc_b); REQUIRE(header_b->size == 128); REQUIRE(alloc_b == BlockHeader::payload(header_b)); // Both headers' next pointer should be null REQUIRE(header_a->next == nullptr); REQUIRE(header_b->next == nullptr);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // The first header is at the very beginning of the heap uint8_t const *raw_heap = heap.raw_heap(); REQUIRE(reinterpret_cast<uint8_t *>(header_a) == raw_heap); // The second header is at +96 bytes REQUIRE(reinterpret_cast<uint8_t *>(header_b) == raw_heap + sizeof(BlockHeader) + size_a ); // Since the free header was absorbed, it should be null REQUIRE(heap.free_head() == nullptr); // Now free the second block heap.free(alloc_b); // Check the heap stats REQUIRE(heap.current_used() == size_a + 2 * sizeof(BlockHeader)); REQUIRE(heap.current_allocs() == 1); REQUIRE(heap.peak_used() == 3 * sizeof(BlockHeader) + size_a + size_b); REQUIRE(heap.peak_allocs() == 2); // At this point, the free list is just header_b plus the 32 bytes it // absorbed when we coalesced the zero-byte block previosuly called // free_header REQUIRE(header_b->next == nullptr); REQUIRE(header_b->size == size_b + sizeof(BlockHeader)); REQUIRE(header_a->size == size_a); // Free the first block heap.free(alloc_a); // Check the heap stats REQUIRE(heap.current_used() == sizeof(BlockHeader)); REQUIRE(heap.current_allocs() == 0); REQUIRE(heap.peak_used() == 3 * sizeof(BlockHeader) + size_a + size_b); REQUIRE(heap.peak_allocs() == 2); // The entire heap should now be back to a single free block REQUIRE(header_a->size == heap_size - sizeof(BlockHeader)); REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); } Testing three blocks. #include "brasstacks/memory/BlockHeader.hpp" #include "brasstacks/memory/Heap.hpp" #include "test_helpers.hpp" using namespace btx::memory; using namespace Catch::Matchers; TEST_CASE("Allocate and free three blocks, free a->b->c") { std::size_t const heap_size = 512; Heap heap(heap_size); std::size_t const size_a = 64; std::size_t const size_b = 96; std::size_t const size_c = 128;
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap void *alloc_a = heap.alloc(size_a); void *alloc_b = heap.alloc(size_b); void *alloc_c = heap.alloc(size_c); // Check the heap's internal metrics REQUIRE(heap.current_used() == 416); REQUIRE(heap.current_allocs() == 3); REQUIRE(heap.peak_used() == heap.current_used()); REQUIRE(heap.peak_allocs() == heap.current_allocs()); // Check that the BlockHeader helper functions produce interchangable // addresses BlockHeader *header_a = BlockHeader::header(alloc_a); REQUIRE(header_a->size == size_a); REQUIRE(alloc_a == BlockHeader::payload(header_a)); BlockHeader *header_b = BlockHeader::header(alloc_b); REQUIRE(header_b->size == size_b); REQUIRE(alloc_b == BlockHeader::payload(header_b)); BlockHeader *header_c = BlockHeader::header(alloc_c); REQUIRE(header_c->size == size_c); REQUIRE(alloc_c == BlockHeader::payload(header_c)); // Check the physical locations in memory auto const *raw_heap = heap.raw_heap(); REQUIRE(reinterpret_cast<uint8_t *>(header_a) == raw_heap); REQUIRE(reinterpret_cast<uint8_t *>(header_b) == raw_heap + 96); REQUIRE(reinterpret_cast<uint8_t *>(header_c) == raw_heap + 224); // And the free block is 96 bytes in size, given a 32 byte BlockHeader auto const *free_header = heap.free_head(); REQUIRE(free_header->size == 96); //-------------------------------------------------------------------------- // Free the first block heap.free(alloc_a); // The internal metrics will largely be the same, except with size_a fewer // used bytes and one fewer allocs REQUIRE(heap.current_used() == 352); REQUIRE(heap.current_allocs() == 2); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // Given 64+96=160 bytes total free, fragmentation is ~0.4 REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.4f, epsilon));
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // header_a has become the "true" free_header, which means the next pointer // directs us to the free chunk at the end of the heap REQUIRE(header_a->next == free_header); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == header_a); // header_a, while now free, has the same size as it did before REQUIRE(header_a->size == 64); //-------------------------------------------------------------------------- // Free the second block heap.free(alloc_b); // This time, the used bytes count drops by size_b and the size of a // BlockHeader, since a and b should be merged now REQUIRE(heap.current_used() == 224); REQUIRE(heap.current_allocs() == 1); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // Given 192+96=288 bytes total free, fragmentation is ~0.33 REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs((1.0f/3.0f), epsilon)); // header_a->next still points to the free block at the end of the heap // since it just absorbed alloc_b REQUIRE(header_a->next == free_header); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == header_a); // But the size has grown by size_b and sizeof(BlockHeader) REQUIRE(header_a->size == 192); //-------------------------------------------------------------------------- // Free the third block heap.free(alloc_c);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // Finally, everything's free so only the 32 bytes of the heap's header are // used REQUIRE(heap.current_used() == 32); REQUIRE(heap.current_allocs() == 0); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // Everything is free, so fragmentation should be at zero REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon)); // There's no more free block at the end of the heap, so header_a->next // points nowhere REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == nullptr); // And the size of header_a should be the whole available heap REQUIRE(header_a->size == 480); } TEST_CASE("Allocate and free three blocks, free a->c->b") { std::size_t const heap_size = 512; Heap heap(heap_size); std::size_t const size_a = 64; std::size_t const size_b = 96; std::size_t const size_c = 128; void *alloc_a = heap.alloc(size_a); void *alloc_b = heap.alloc(size_b); void *alloc_c = heap.alloc(size_c); BlockHeader *header_a = BlockHeader::header(alloc_a); BlockHeader *header_b = BlockHeader::header(alloc_b); BlockHeader *header_c = BlockHeader::header(alloc_c); auto const *free_header = heap.free_head(); //-------------------------------------------------------------------------- // Free the first block heap.free(alloc_a); // The internal metrics will largely be the same, except with size_a fewer // used bytes and one fewer allocs REQUIRE(heap.current_used() == 352); REQUIRE(heap.current_allocs() == 2); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // Given 64+96=160 bytes total free, fragmentation is ~0.4 REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.4f, epsilon)); // header_a has become the "true" free_header, which means the next pointer // directs us to the free chunk at the end of the heap REQUIRE(header_a->next == free_header); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == header_a); // header_a, while now free, has the same size as it did before REQUIRE(header_a->size == 64); //-------------------------------------------------------------------------- // Free the second block heap.free(alloc_c); // header_c and free_header have merged REQUIRE(heap.current_used() == 192); REQUIRE(heap.current_allocs() == 1); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // header_a is still the top of the free list, but now it points to b REQUIRE(header_a->next == header_c); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == header_a); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == nullptr); // 64+256=320 bytes total free, fragmentation is ~0.2 REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.2f, epsilon)); //-------------------------------------------------------------------------- // Free the third block heap.free(alloc_b); // Finally, everything's free so only the 32 bytes of the heap's header are // used REQUIRE(heap.current_used() == 32); REQUIRE(heap.current_allocs() == 0); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // No fragmentation REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon)); // There's no more free block at the end of the heap, so header_a->next // points nowhere REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == nullptr); // And the size of header_a should be the whole available heap REQUIRE(header_a->size == 480); } TEST_CASE("Allocate and free three blocks, free b->a->c") { std::size_t const heap_size = 512; Heap heap(heap_size); std::size_t const size_a = 64; std::size_t const size_b = 96; std::size_t const size_c = 128; void *alloc_a = heap.alloc(size_a); void *alloc_b = heap.alloc(size_b); void *alloc_c = heap.alloc(size_c); BlockHeader *header_a = BlockHeader::header(alloc_a); BlockHeader *header_b = BlockHeader::header(alloc_b); BlockHeader *header_c = BlockHeader::header(alloc_c); auto const *free_header = heap.free_head(); //-------------------------------------------------------------------------- // Free the first block heap.free(alloc_b); // The 96 bytes of alloc_b will have been subtracted from the total used REQUIRE(heap.current_used() == 320); REQUIRE(heap.current_allocs() == 2); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // alloc_b is now free and is 96 bytes, so we're at ~0.5 fragmentation REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.5f, epsilon));
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // With header_b now technically a free header, its next pointer will // lead to the original free_header REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == free_header); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == header_b); // Both header_b and free_header will have the same sizes as before REQUIRE(header_b->size == 96); REQUIRE(free_header->size == 96); //-------------------------------------------------------------------------- // Free the second block heap.free(alloc_a); // Now we've got a and b merged, plus the straggler free block at the end REQUIRE(heap.current_used() == 224); REQUIRE(heap.current_allocs() == 1); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // a and b taken together gives us 192 bytes, so ~0.3 fragmentation REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs((1.0f/3.0f), epsilon)); // header_a->next now jumps to the original free_header REQUIRE(header_a->next == free_header); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == header_a); // header_a->size has grown to encompass both a and b, but free_header // stays the same REQUIRE(header_a->size == 192); REQUIRE(free_header->size == 96); //-------------------------------------------------------------------------- // Free the third block heap.free(alloc_c);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // Finally, everything's free so only the 32 bytes of the heap's header are // used REQUIRE(heap.current_used() == 32); REQUIRE(heap.current_allocs() == 0); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // And 0 fragmentation when it's all said and done REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon)); // There's no more free block at the end of the heap, so header_a->next // points nowhere REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == nullptr); // And the size of header_a should be the whole available heap REQUIRE(header_a->size == 480); } TEST_CASE("Allocate and free three blocks, free b->c->a") { std::size_t const heap_size = 512; Heap heap(heap_size); std::size_t const size_a = 64; std::size_t const size_b = 96; std::size_t const size_c = 128; void *alloc_a = heap.alloc(size_a); void *alloc_b = heap.alloc(size_b); void *alloc_c = heap.alloc(size_c); BlockHeader *header_a = BlockHeader::header(alloc_a); BlockHeader *header_b = BlockHeader::header(alloc_b); BlockHeader *header_c = BlockHeader::header(alloc_c); auto const *free_header = heap.free_head(); //-------------------------------------------------------------------------- // Free the first block heap.free(alloc_b); // The 96 bytes of alloc_b will have been subtracted from the total used REQUIRE(heap.current_used() == 320); REQUIRE(heap.current_allocs() == 2); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // alloc_b is now free and is 96 bytes, so we're at ~0.5 fragmentation REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.5f, epsilon)); // With header_b now technically the free header, its next pointer will // lead to the original free_header REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == free_header); REQUIRE(header_b->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == header_b); // Both header_b and free_header will have the same sizes as before REQUIRE(header_b->size == 96); REQUIRE(free_header->size == 96); //-------------------------------------------------------------------------- // Free the second block heap.free(alloc_c); // Now we've just got a and b, with all the free space after b coallesced REQUIRE(heap.current_used() == 128); REQUIRE(heap.current_allocs() == 1); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // b and c will have merged with the original free block, so there's no // fragmentation REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon)); // All the free space is coallesced, so header_b is the whole free list REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == nullptr); // header_b->size has grown to encompass c and the original free_header REQUIRE(header_b->size == 384); //-------------------------------------------------------------------------- // Free the third block heap.free(alloc_a);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // Finally, everything's free so only the 32 bytes of the heap's header are // used REQUIRE(heap.current_used() == 32); REQUIRE(heap.current_allocs() == 0); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // And again, no fragmentation when everything's free REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon)); // Everything's free REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == nullptr); // And the size of header_a should be the whole available heap REQUIRE(header_a->size == 480); } TEST_CASE("Allocate and free three blocks, free c->a->b") { std::size_t const heap_size = 512; Heap heap(heap_size); std::size_t const size_a = 64; std::size_t const size_b = 96; std::size_t const size_c = 128; void *alloc_a = heap.alloc(size_a); void *alloc_b = heap.alloc(size_b); void *alloc_c = heap.alloc(size_c); BlockHeader *header_a = BlockHeader::header(alloc_a); BlockHeader *header_b = BlockHeader::header(alloc_b); BlockHeader *header_c = BlockHeader::header(alloc_c); auto const *free_header = heap.free_head(); //-------------------------------------------------------------------------- // Free the first block heap.free(alloc_c); // The free block at the end of the heap and alloc_c will have merged REQUIRE(heap.current_used() == 256); REQUIRE(heap.current_allocs() == 2); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // Given the free blocks are coallesced, fragmentation is 0 REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon));
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // Since the original free block and alloc_c have merged, and header_c // is the new free header, the pointers are cleared out REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == nullptr); // The header_c/the free header's size has grown REQUIRE(header_c->size == 256); //-------------------------------------------------------------------------- // Free the second block heap.free(alloc_a); // header_a is the new free header, so we've only reclaimed 64 bytes REQUIRE(heap.current_used() == 192); REQUIRE(heap.current_allocs() == 1); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // The free list pointers skip over alloc_b REQUIRE(header_a->next == header_c); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == header_a); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == nullptr); // 64+256=320, and 256/320 = 0.8, so we've got ~20% fragmentation REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.2f, epsilon)); //-------------------------------------------------------------------------- // Free the third block heap.free(alloc_b); // Finally, everything's free so only the 32 bytes of the heap's header are // used REQUIRE(heap.current_used() == 32); REQUIRE(heap.current_allocs() == 0); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // And again, no fragmentation when everything's free REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon));
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // There's no more free block at the end of the heap, so header_a->next // points nowhere REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == nullptr); // And the size of header_a should be the whole available heap REQUIRE(header_a->size == 480); } TEST_CASE("Allocate and free three blocks, free c->b->a") { std::size_t const heap_size = 512; Heap heap(heap_size); std::size_t const size_a = 64; std::size_t const size_b = 96; std::size_t const size_c = 128; void *alloc_a = heap.alloc(size_a); void *alloc_b = heap.alloc(size_b); void *alloc_c = heap.alloc(size_c); BlockHeader *header_a = BlockHeader::header(alloc_a); BlockHeader *header_b = BlockHeader::header(alloc_b); BlockHeader *header_c = BlockHeader::header(alloc_c); auto const *free_header = heap.free_head(); //-------------------------------------------------------------------------- // Free the first block heap.free(alloc_c); // The free block at the end of the heap and alloc_c will have merged REQUIRE(heap.current_used() == 256); REQUIRE(heap.current_allocs() == 2); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // Given the free blocks are coallesced, fragmentation is 0 REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon));
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // Since the original free block and alloc_c have merged, and header_c // is the new free header, the pointers are cleared out REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == nullptr); // The header_c/the free header's size has grown REQUIRE(header_c->size == 256); //-------------------------------------------------------------------------- // Free the second block heap.free(alloc_b); // Again, the used bytes count decreases by sizeof(BlockHeader) and alloc_b // due to the coallescing of free space REQUIRE(heap.current_used() == 128); REQUIRE(heap.current_allocs() == 1); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3); // Still zero fragmentation REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon)); // Now header_b is the "new" free_header REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == nullptr); // header_c, serving as the "new" free_header, will have grown in size REQUIRE(header_b->size == 384); //-------------------------------------------------------------------------- // Free the third block heap.free(alloc_a); // Finally, everything's free so only the 32 bytes of the heap's header are // used REQUIRE(heap.current_used() == 32); REQUIRE(heap.current_allocs() == 0); REQUIRE(heap.peak_used() == 416); REQUIRE(heap.peak_allocs() == 3);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // And certainly zero fragmentation with everything free REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.0f, epsilon)); // There's no more free block at the end of the heap, so header_a->next // points nowhere REQUIRE(header_a->next == nullptr); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == nullptr); // And the size of header_a should be the whole available heap REQUIRE(header_a->size == 480); } And testing four blocks. #include "brasstacks/memory/BlockHeader.hpp" #include "brasstacks/memory/Heap.hpp" #include "test_helpers.hpp" using namespace btx::memory; using namespace Catch::Matchers; TEST_CASE("Allocate four blocks, free a and c, then allocate a block that's " "less than c, testing fragmentation") { std::size_t const heap_size = 1280; Heap heap(heap_size); std::size_t const size_a = 96; std::size_t const size_b = 128; std::size_t const size_c = 256; std::size_t const size_d = 512; void *alloc_a = heap.alloc(size_a); void *alloc_b = heap.alloc(size_b); void *alloc_c = heap.alloc(size_c); void *alloc_d = heap.alloc(size_d); // Check the heap's internal metrics REQUIRE(heap.current_used() == 1152); REQUIRE(heap.current_allocs() == 4); REQUIRE(heap.peak_used() == heap.current_used()); REQUIRE(heap.peak_allocs() == heap.current_allocs()); // Check that the BlockHeader helper functions produce interchangable // addresses BlockHeader *header_a = BlockHeader::header(alloc_a); REQUIRE(header_a->size == size_a); REQUIRE(alloc_a == BlockHeader::payload(header_a)); BlockHeader *header_b = BlockHeader::header(alloc_b); REQUIRE(header_b->size == size_b); REQUIRE(alloc_b == BlockHeader::payload(header_b));
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap BlockHeader *header_c = BlockHeader::header(alloc_c); REQUIRE(header_c->size == size_c); REQUIRE(alloc_c == BlockHeader::payload(header_c)); BlockHeader *header_d = BlockHeader::header(alloc_d); REQUIRE(header_d->size == size_d); REQUIRE(alloc_d == BlockHeader::payload(header_d)); // And the free block is 32 bytes in size, given a 32 byte BlockHeader BlockHeader const *free_header = heap.free_head(); REQUIRE(free_header->size == 128); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == nullptr); // Check the physical locations in memory uint8_t const *raw_heap = heap.raw_heap(); REQUIRE(reinterpret_cast<uint8_t *>(header_a) == raw_heap); REQUIRE(reinterpret_cast<uint8_t *>(header_b) == raw_heap + 128); REQUIRE(reinterpret_cast<uint8_t *>(header_c) == raw_heap + 288); REQUIRE(reinterpret_cast<uint8_t *>(header_d) == raw_heap + 576); REQUIRE(reinterpret_cast<uint8_t const *>(free_header) == raw_heap + 1120); //-------------------------------------------------------------------------- // Free alloc_a heap.free(alloc_a); // The internal metrics will largely be the same, except with size_a fewer // used bytes and one fewer allocs REQUIRE(heap.current_used() == 1056); REQUIRE(heap.current_allocs() == 3); REQUIRE(heap.peak_used() == 1152); REQUIRE(heap.peak_allocs() == 4); // 96+128=224 bytes free, so that's ~0.43 fragmentation REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.42857143f, epsilon)); // header_a, while now free, has the same size as it did before REQUIRE(header_a->size == 96); // As does free_header REQUIRE(free_header->size == 128);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // As does free_header REQUIRE(free_header->size == 128); // header_a has become the "true" free_header, which means the next pointer // directs us to the free chunk at the end of the heap REQUIRE(header_a->next == free_header); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == nullptr); REQUIRE(header_c->prev == nullptr); REQUIRE(header_d->next == nullptr); REQUIRE(header_d->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == header_a); //-------------------------------------------------------------------------- // Free alloc_c heap.free(alloc_c); // The internal metrics will largely be the same, except with size_a fewer // used bytes and one fewer allocs REQUIRE(heap.current_used() == 800); REQUIRE(heap.current_allocs() == 2); REQUIRE(heap.peak_used() == 1152); REQUIRE(heap.peak_allocs() == 4); // 96+256+128=480 bytes free, so that's ~0.467 fragmentation REQUIRE_THAT(heap.calc_fragmentation(), WithinAbs(0.46666667f, epsilon)); // alloc_c was before the free block at the end, so header_a->next now // points to alloc_c REQUIRE(header_a->next == header_c); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_c->next == free_header); REQUIRE(header_c->prev == header_a); REQUIRE(header_d->next == nullptr); REQUIRE(header_d->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == header_c);
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap //-------------------------------------------------------------------------- // Allocate a smaller chunk where alloc_d used to be, but larger than // alloc_a std::size_t const size_e = 128; void *alloc_e = heap.alloc(size_e); BlockHeader *header_e = BlockHeader::header(alloc_e); REQUIRE(alloc_e == BlockHeader::payload(header_e)); REQUIRE(header_e->size == size_e); // The newest allocation, f, will live where d once was. REQUIRE(alloc_e == alloc_c); REQUIRE(header_e == header_c); auto *free_half_of_c = reinterpret_cast<BlockHeader *>( reinterpret_cast<uint8_t *>(header_e) + sizeof(BlockHeader) + size_e ); // Now we can test the pointer layout REQUIRE(header_a->next == free_half_of_c); REQUIRE(header_a->prev == nullptr); REQUIRE(header_b->next == nullptr); REQUIRE(header_b->prev == nullptr); REQUIRE(header_e->next == nullptr); REQUIRE(header_e->prev == nullptr); REQUIRE(free_half_of_c->next == free_header); REQUIRE(free_half_of_c->prev == header_a); REQUIRE(header_d->next == nullptr); REQUIRE(header_d->prev == nullptr); REQUIRE(free_header->next == nullptr); REQUIRE(free_header->prev == free_half_of_c); // And the size of the new free half of C REQUIRE(free_half_of_c->size == 96); }
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap // And the size of the new free half of C REQUIRE(free_half_of_c->size == 96); } Answer: You are overthinking alignment malloc() and new will return a pointer that is already suitably aligned for any built-in type, including pointers and std::size_t. So you don't have to worry about properly aligning it to store the first BlockHeader. This also means you can get rid of the alignas for BlockHeader (it is meaningless anyway, since you are not using new to allocate it). You also didn't actually handle alignment at all in the constructor; you just adjust the amount of bytes you reserve, but if malloc() would return something not aligned to ALIGN, the reinterpret_cast<BlockHeader*>(_raw_heap) would be very wrong. Use new and placement-new malloc() is a C function, if you want to write proper C++ code you should use new. To allocate memory for the heap you can just do: _raw_heap = new uint8_t[_total_size]; You could even make _raw_heap a std::unique_ptr<uint8_t[]> so you don't have to worry about delete. When creating an instance of a BlockHeader, use placement-new. This ensures the constructor will be called, and more importantly, will ensure the compiler and/or static-analysis tools can see that there is a valid live BlockHeader object: _free_head = new (_raw_heap) BlockHeader; Of course you should then also ensure you don't delete the constructor of BlockHeader. Simplify casts You can avoid some unnecessary casts by doing pointer arithmetic on BlockHeader* instead of uint8_t*: [[nodiscard]] static inline BlockHeader * header(void *address) { return static_cast<BlockHeader *>(address) - 1; } [[nodiscard]] static inline void * payload(BlockHeader *header) { return header + 1; // implicit conversion to void* is perfecly fine }
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap You can move the declaration of BlockHeader into Heap BlockHeader is only used as an implementation detail of Heap. It therefore doesn't need to be in the global namespace. You can nest structs in C++, so I would write this in Heap.hpp: class Heap final { struct BlockHeader; // forward declaration … }; And the actual definition can be in Heap.cpp: struct Heap::BlockHeader { [[nodiscard]] static BlockHeader *header(void *address) { return static_cast<BlockHeader *>(address) - 1; } [[nodiscard]] static void *payload(BlockHeader *header) { return header + 1; // implicit conversion to void* is perfecly fine } std::size_t size{}; BlockHeader *next{}; BlockHeader *prev{}; };
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
c++, memory-management, c++20, heap Use of assert() You should only use assert() to catch bugs in the program. However, some errors are not caused by bugs. For example, malloc() might return nullptr because there is not enough memory. If you compiled your code with -DNDEBUG (which many build systems automatically add in release builds), then your assert() calls are not doing anything anymore. Your program will then crash due to a NULL-pointer dereference. It's better to throw an exception, or if you don't want to use exceptions, write an error to std::cerr and call std::abort(). About the unit tests Opinions about testing varies a lot. However, I would avoid being overly specific in your test cases. For example, in the test for allocating and freeing a single block, you not only test that functionality, you also test if the BlockHeader contains the expected values. The problem is then that if you ever change the implementation of BlockHeader, your test is no longer valid. Of course, there is value in testing that the internal datastructures are consistent. However, at the very least I would put that into a separate test. What I am missing is more rigorous testing of the things that should be visible to the user. For example, that alloc_a != nullptr, and that if you make multiple allocations, that they don't overlap. I would also write to the allocated memory: this checks that the pointer is to a valid memory region, and that no header blocks are being overwritten.
{ "domain": "codereview.stackexchange", "id": 45212, "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++, memory-management, c++20, heap", "url": null }
beginner, tree, rust Title: Hashing a fixed size binary stream with a tree structure in Rust Question: For a research project, I want to assign a unique identifier to a stream of bits. I can assume that all the streams will always have the same size. Because of this nice property, my idea has been to use a binary tree structure to assign to each stream a leaf storing its unique identifier. In the following, I call these identifiers hashes, as I intend to use them in a HashMap later on (or an array, since these identifiers are just increasing integers). It is important in my application that no collision happen. Thus, upon being given a stream it has never seen, the tree will expand accordingly to the values of the bits until the stream has been consumed. There, a leaf is created and the unique hash of the stream is stored. At some point I thought that it may be a good idea to pack the bits in u8 values and to use a tree where each Node would have 256 children. However, I think that this creates a lot of unused pointers, but I may be wrong on this. I designed the code so that if I need to deal with streams of octets instead of bits, only one constant needs to be changed. All in all, the final goal is to have a method that can assign a unique identifier to a stream of bits with a fixed size in the fastest way possible. In the future, this function will be queried by several threads, but I haven't taken this into account for now. I'm a beginner in Rust and this project has two goals: Performance, since this code will be used in a computationally expensive algorithm; Improve in Rust. Thus, if there is a data structure that I'm unaware of that provides the same functionality, by all means tell me! Whether there is or not, I'm looking for feedback on all possible aspects that could make a good code: performance, good practices, etc... // main.rs mod hasher; fn main() {} // hasher.rs use crate::hasher::TreeHasher::{Leaf, Node};
{ "domain": "codereview.stackexchange", "id": 45213, "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, tree, rust", "url": null }
beginner, tree, rust fn main() {} // hasher.rs use crate::hasher::TreeHasher::{Leaf, Node}; /// Each Node in the TreeHasher has the same number of children. This value must be equal to the /// largest integer the hasher will ever meet in the stream. /// /// Since we are dealing with binary streams, its value is currently set to 2. const TREE_BRANCHES: usize = 2; /// The enum that represents the tree used for hashing. The data is stored in the leaves only, the /// nodes are only meant to lead to the leaves. /// /// The rationale is that it is possible to both access and create an entry in $n$ steps, where $n$ /// is the length of the stream. Note that this hasher assumes that every stream to be hashed has /// the same length $n$. Otherwise, the `hash` function will panic. enum TreeHasher { Leaf(u64), Node(Option<[Box<TreeHasher>; TREE_BRANCHES]>), } /// The Hasher is the struct the user will be exposed to in order to hash streams. pub(crate) struct Hasher { /// The `tree_hasher` is the structure that contains all previous hashes and is in charge of /// creating new ones. tree_hasher: TreeHasher, /// The `next_hash` simply represents the hash that will be affected to the next stream to which /// no hash is associated yet. next_hash: u64, } impl TreeHasher { /// Creates the root of a new TreeHasher. fn new() -> Self { Node(None) }
{ "domain": "codereview.stackexchange", "id": 45213, "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, tree, rust", "url": null }
beginner, tree, rust fn hash<'a>(&mut self, mut data: impl Iterator<Item = &'a u8>, next_hash: &mut u64) -> u64 { // If the iterator hasn't been entirely consumed yet if let Some(next_elt) = data.next() { // Since the iterator hasn't been consumed, it is normally impossible to reach a Leaf at // this point. If this is the case, it means that the iterator was longer than some // previous ones. if let Node(children_option) = self { // If the node has already been expanded, we simply follow the associated pointer if let Some(children) = children_option { children[*next_elt as usize].hash(data, next_hash) // Otherwise, we have to create the children of this node } else { *self = Node(Some(core::array::from_fn::< Box<TreeHasher>, TREE_BRANCHES, _, >(|_| Box::new(Node(None)))));
{ "domain": "codereview.stackexchange", "id": 45213, "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, tree, rust", "url": null }
beginner, tree, rust // Is there a better way? It feels kind of artificial to perform an if condition // and to add an else clause that we know won't ever be used if let Node(Some(children)) = self { children[*next_elt as usize].hash(data, next_hash) } else { // This can't happen, since the if statement is only used to get access to // the pointer we're interested in, it always evaluate to True panic!() } } } else { panic!("Reached a Leaf without having reached the end of the iterator.") } } else if let Leaf(index) = self { // In this case, the iterator has been consumed and we've found a Leaf, so it means that // its hash has already been computed, and has been stored there *index } else if let Node(None) = self { // In this case, the iterator has been consumed but no Leaf has been created yet. It // means that we have to store its hash in a Leaf here let res = *next_hash; *self = Leaf(*next_hash); *next_hash += 1; res } else { // Isn't reachable, all the cases have been dealt with panic!("Reached the end of the iterator without a Leaf having been found.") } } } impl Hasher { pub(crate) fn new() -> Self { Self { tree_hasher: TreeHasher::new(), next_hash: 0, } }
{ "domain": "codereview.stackexchange", "id": 45213, "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, tree, rust", "url": null }
beginner, tree, rust /// Computes the hash of a stream of data. /// /// The goal of this function is to set a unique hash to every stream of data it is given. It /// does so by storing the stream in a tree-like structure, which allows efficient search and /// creation. It is guaranteed that the same stream will always be associated to the same hash /// and that two different streams will never be associated to the same hash, as long as the /// number of different streams don't exceed $2^64$. /// /// # Arguments /// /// * `data` - The stream of data to compute a hash for. Note that it must satisfy two strict /// conditions: /// - Each stream of data must be of the same length. /// - Each stream of data mustn't contain integers larger than `TREE_BRANCHES`. /// If one of these conditions isn't satisfied, this function may panic. pub(crate) fn hash<'a>(&mut self, data: impl Iterator<Item = &'a u8>) -> u64 { self.tree_hasher.hash(data, &mut self.next_hash) } } #[cfg(test)] mod tests { use crate::hasher::Hasher; #[test] fn test_hasher() { let mut hasher = Hasher::new(); let a1: [u8; 4] = [0, 0, 0, 0]; assert_eq!(hasher.hash(a1.iter()), 0); assert_eq!(hasher.hash(a1.iter()), 0); let a2: [u8; 4] = [0, 0, 0, 1]; assert_eq!(hasher.hash(a2.iter()), 1); assert_eq!(hasher.hash(a1.iter()), 0); assert_eq!(hasher.hash(a2.iter()), 1); let a3: [u8; 4] = [0, 1, 0, 0]; assert_eq!(hasher.hash(a3.iter()), 2); assert_eq!(hasher.hash(a1.iter()), 0); assert_eq!(hasher.hash(a2.iter()), 1); assert_eq!(hasher.hash(a3.iter()), 2); } } In particular, there are several questions that I couldn't answer:
{ "domain": "codereview.stackexchange", "id": 45213, "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, tree, rust", "url": null }
beginner, tree, rust In particular, there are several questions that I couldn't answer: Is using an array rather than a vec for storing the children really useful? That's the first idea I got since I do know the size of the array at compile time, but I'm unsure whether this produces better code, or whether this has an impact on performance Does the fact that I do know the length of the streams at compile time be useful? I thought it wasn't since I'm consuming them in an iterator way, but I may have missed something obvious. Is there another way than doing if let to access an enum's value? This leads to if let statements that will always be true and else clauses that can't be reached. In the hash function of Hasher, why isn't data forced to be declared with mut? The function definitely consume the iterator. Answer: This is language-agnostic advice, nothing rust-specific. want to assign a unique identifier to a stream of bits. The standard answer to this is: assign hash = SHA3(input) return prefix of that hash where we look at number of inputs, and risk tolerance, to decide how long that prefix should be. Often a prefix of 128 bits suffices for a UUID. You were a bit vague on length of input, number of inputs, risk tolerance, and maximum acceptable hash length. Knowing more details would make it easier to assess whether your use case is a good fit for the standard solution. It is important in my application that no collision happen.
{ "domain": "codereview.stackexchange", "id": 45213, "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, tree, rust", "url": null }
beginner, tree, rust It is important in my application that no collision happen. That adjective doesn't really map to a probability figure. There is certainly the notion of a perfect hash. But you didn't disclose an essential precondition. You didn't tell us that the ("offline") algorithm gets to see all possible inputs before returning its first hash value. As written the OP appears to describe requirements of an "online" algorithm. If offline operation is acceptable, then just set counter = 1 and verify that each SHA3(counter || input) is distinct. If collision is detected, simply increment the counter and keep trying again until you find a perfect hash. This will happen quickly if we emit 128 bits, and more slowly if we're required to emit fewer bits, especially when presented with a large number of inputs. For practical input values it should take zero or a tiny number of retries to obtain a perfect hash function. This doesn't appear to be a cryptographically strong hash -- I don't see diffusion and confusion happening here, no avalanche. I am hard pressed to believe that an adversary couldn't craft inputs that deliberately collide with one another. Incrementing "hash" makes it look more like "serial number". Given that you're returning a 64-bit hash, it appears you believe we won't see anywhere near four billion input bit sequences. This suggests that a 64-bit prefix of SHA3 would suffice. testing let a1: [u8; 4] = [0, 0, 0, 0]; ... let a2: [u8; 4] = [0, 0, 0, 1]; ... let a3: [u8; 4] = [0, 1, 0, 0];
{ "domain": "codereview.stackexchange", "id": 45213, "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, tree, rust", "url": null }
beginner, tree, rust Consider renaming these to more natural identifiers: a0, a1, a4. I found the sequence of .iter() calls confusing. I am convinced you deliberately planned them so as to teach me something. I confess I do not know what you wanted to teach; I am as yet unenlightened. Possibly doing non-interleaved hashing of the various arrays would be clearer. The fault perhaps lies less with the unit test code, which likely should not have a ton of comment lines, and more with TreeHasher's hash() function. Certainly there's a bunch of comments in there. But the overall datastructure eluded me. The comments are low level, and they're not guiding me to certain spots in a high level overview of the tree you're building. In particular, given an existing tree plus next bit to hash, I don't know how to resort to English prose to learn about appropriate tree update. I saw no diagrams of example trees. I understand that you were trying to communicate the details to me, but in this particular instance communication was not successful.
{ "domain": "codereview.stackexchange", "id": 45213, "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, tree, rust", "url": null }
java, file, error-handling Title: Handling exceptions of FileInputStream and XSSFWorkbook Question: Can you tear my code apart with code review comments? Below is a simple method which reads an XLSX file and does some stuff with it. I use FileInputStream and XSSFWorkbook to do the processing. The code block which I am concerned about is the exception handling (I have been told that it's buggy/not ideal). Note: I am not allowed to use try-with-resources for some reasons. /**Process XLSX file. * @param filePath Path of file to process * @throws Exception */ private void processXlsxFile (String filePath) throws IOException { String xlsxFileContent = ""; FileInputStream fis = null; XSSFWorkbook workbook = null; try { File file = new File(filePath); fis = new FileInputStream(file); workbook = new XSSFWorkbook(fis); XSSFSheet sheet = workbook.getSheetAt(0); //Do stuff and build 'xlsxFileContent'. } catch (FileNotFoundException fe) { logger.error(fe.getMessage()); } catch (IOException ie) { logger.error(ie.getMessage()); } finally { try { if (workbook != null) { workbook.close(); } } catch (IOException ex) { logger.error("Exception while closing XSSFWorkbook: " + ex.getMessage()); } try { if (fis != null) { fis.close(); } } catch (IOException ex) { logger.error("Exception while closing FileInputStream: " + ex.getMessage()); } } }
{ "domain": "codereview.stackexchange", "id": 45214, "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": "java, file, error-handling", "url": null }
java, file, error-handling Answer: "throws" declaration You declare your method to throw IOException, but you catch exceptions inside your method and don't re-throw them, so I see no way how your method might throw it to the outside, meaning that this declaration does not match your actual code. Informing your caller about failures If some code calls your method, it does it for some reason, and expects that the job (processing the XLSX file) has been done when the method returns, so that the caller can faithfully continue. The caller needs an information if the call wasn't successful, and your method fails to provide that information. Nowadays, the preferred way of communicating failure to a caller is by throwing an exception. Your code only produces a log output, which is not accessible to the caller, so it will "happily" continue although most probably the next step will fail as well, not having a processed XLSX file. So, as a general rule, whenever you exit a method, and it has not done its job, make sure that your caller gets an exception, typically by simply letting an exception bubble up that your code got from its inner calls (with the nice feature that this happens automatically, with zero lines of code from your side), or by throwing an exception that you newly created to describe the failure reason, or by throwing an exception "wrapped around" an original one, so you can provide more context. The main question is: If a strange situation X happens inside my method (e.g. getting an exception), will it (from a caller's point of view) still have done its job?
{ "domain": "codereview.stackexchange", "id": 45214, "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": "java, file, error-handling", "url": null }
java, file, error-handling Most of the time, the answer to this question will be "no", and then your code should throw an exception to its caller. Even not being able to close a file can be a show-stopper, as then the file might be unfinished in the file system, unable to be opened from another piece of code, etc. Excessive exception handling About 20 lines of code are about exception handling. That in itself is a code smell, often a result of a misconception about the best use of exceptions. Well-done exception handling allows to concentrate on the "happy path" and have the failure paths handled by the run time system. Logging If you throw an exception, don't log the situation. Someone up the caller stack will eventually catch the exception and log it. If the exception you got does not contain enough context information to describe the situation, then catch it, and throw a new one, containing the missing information, and providing the original exception as its cause ("wrapping" the exception). By the way, your log messages do not name the file where the problem occurred, and you cannot rely on the IOException to provide this information in its message. So, an administrator reading the log will have a hard time to find out where to look in the file system. Suggestion My method would look roughly like this: private void processXlsxFile (String filePath) throws IOException { // This whole outer try/catch is only meant to provide a better exception // object, one that names the file. // It's optional, up to your discretion (or coding standards) try { String xlsxFileContent = ""; FileInputStream fis = null; XSSFWorkbook workbook = null; try { File file = new File(filePath); fis = new FileInputStream(file); workbook = new XSSFWorkbook(fis); XSSFSheet sheet = workbook.getSheetAt(0); // Do stuff and build 'xlsxFileContent'. } finally {
{ "domain": "codereview.stackexchange", "id": 45214, "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": "java, file, error-handling", "url": null }
java, file, error-handling // Do stuff and build 'xlsxFileContent'. } finally { // do your best to close the workbook and file if (workbook != null) { workbook.close(); } // no need to catch exceptions at workbook.close() // if it couldn't be closed, closing the file underneath it // will probably fail as well, and not improve anything. if (fis != null) { fis.close(); } } } catch (IOException e) { // Maybe, other exceptions can arise as well, so feel free to // catch (Exception e) instead. // Make sure that your resulting exception names the file. throw new IOException("Exception when processing " + filePath, e); } }
{ "domain": "codereview.stackexchange", "id": 45214, "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": "java, file, error-handling", "url": null }
java, file, error-handling One final remark: Your original code catches both, FileNotFoundException and IOException, and does the same in both cases. That's completely redundant. FileNotFoundException is a subclass of IOException, so a catch (IOException e) will receive any FileNotFoundException as well.
{ "domain": "codereview.stackexchange", "id": 45214, "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": "java, file, error-handling", "url": null }
python, performance Title: Distance on a unit grid Question: I have a code that calculates Euclidean distance on a grid with border crossing or without that. def distance(x1: int, y1: int, x2: int, y2: int, grid_size: int, border_cross: bool): if border_cross: min_x = min(abs(x1 - x2), grid_size - abs(x1) - abs(x2)) min_y = min(abs(y1 - y2), grid_size - abs(y1) - abs(y2)) return (min_x**2 + min_y**2) ** 0.5 dist_x = (x1 - x2) ** 2 dist_y = (y1 - y2) ** 2 return (dist_x + dist_y) ** 0.5 Can this code be simplified or improved in terms of readability/performance? Answer: min_x = min(abs(x1 - x2), dist_x = (x1 - x2) ** 2 We can see the border cross algorithm and the standard algorithm are similar so we can change the if border_cross code to mutate the values. def distance(x1: int, y1: int, x2: int, y2: int, grid_size: int, border_cross: bool): x = abs(x1 - x2) y = abs(y1 - y2) if border_cross: x = min(x, grid_size - abs(x1) - abs(x2)) y = min(y, grid_size - abs(y1) - abs(y2)) return (x ** 2 + y ** 2) ** 0.5 The code is also WET (you write the same code for x and y) so we can write a helper function to get the distance and just call the function twice. def _distance(i: int, j: int, grid_size: int, border_cross: bool) -> int: return ( abs(i - j) if not border_cross else min(abs(i - j), grid_size - abs(i) - abs(j)) ) def distance(x1: int, y1: int, x2: int, y2: int, grid_size: int, border_cross: bool) -> float: x = _distance(x1, x2, grid_size, border_cross) y = _distance(y1, y2, grid_size, border_cross) return (x ** 2 + y ** 2) ** 0.5 Personally I'd remove one of border_cross or grid_size. By using using None to mean False and providing an integer to mean True. def _distance(i: int, j: int, border_cross: int | None) -> int: return ( abs(i - j) if border_cross is None else min(abs(i - j), border_cross - abs(i) - abs(j)) )
{ "domain": "codereview.stackexchange", "id": 45215, "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, performance", "url": null }
python, performance def distance(x1: int, y1: int, x2: int, y2: int, border_cross: int | None) -> float: x = _distance(x1, x2, border_cross) y = _distance(y1, y2, border_cross) return (x ** 2 + y ** 2) ** 0.5
{ "domain": "codereview.stackexchange", "id": 45215, "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, performance", "url": null }
java Title: Adhering to Object-Oriented Principles in Fruits and Vegetables Scale Program Question: I've been working on a project related to a fruit and vegetable scale program for about a month, and I'm relatively new to programming. In this project, I'm trying to adhere to object-oriented principles and make my code as object-oriented as possible. I started from a single class structure in my previous assignment and now have the freedom to create multiple classes. I'd appreciate it if experienced developers could review my code for adherence to object-oriented principles and provide constructive feedback on any improvements or areas where I could better follow these principles. I'm particularly interested in whether my use of classes and their interactions align with object-oriented best practices. Here is a brief overview of my project: I have implemented various classes to represent different aspects of a fruit and vegetable scale program. The code handles features like adding, browsing, and removing items from the catalog, as well as calculating and displaying the total price for items in the customer's basket. I've also introduced a new PromotionItem class for managing discounted items. The Product class serves as the base class for all products, and PromotionItem is a subclass that inherits from Product. I would be grateful for any feedback, suggestions, or advice you can provide on how to improve the object-oriented structure and design of my code. Thank you for your time and expertise. public class Main { public static Scanner input = new Scanner(System.in); public static boolean runProgram = true; public static InputOutput IO = new InputOutput(); public static Catalog catalog = new Catalog(); public static Customerbasket customerbasket = new Customerbasket(0); public static Menu menu = new Menu();
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java public static void main(String[] args) { String showIntroToMenu = InputOutput.inputUserString("\nWelcome to the Fruit and Vegetable program." + "\nPlease enter any key to continue to the menu."); runCustomerIntroMenu(); System.out.println("\nThank you for using the Fruit and Vegetable program. \nAll credit goes to Kerem Incorporated."); } public static void runCustomerIntroMenu() { do { menu.setMenuOptions(new String[]{"\n1. Search the catalog", "\n2. Browse the catalog." + "\n3. Checkout." + "\n4. Log in as a employee." + "\n5. Exit the program."}); System.out.println(Arrays.toString(menu.getMenuOptions())); System.out.println(Arrays.toString(menu.getMenuOptions()).replace("[", "").replace("]", " ")); System.out.print("Enter one of the following numbers to continue: "); Errormanager.inputMismatchErrorNumber(Main::printCustomerMenuChoices); } while (runProgram); } public static void printCustomerMenuChoices() { int employeeInput = input.nextInt(); input.nextLine(); switch (employeeInput) { case 1 -> searchTheCatalog(); case 2 -> browseTheCatalog(); case 3 -> Main.printCustomerBasket(); case 4 -> logInAsEmployee(); case 5 -> runProgram = false; default -> System.out.println("\nThe input is not valid, please enter a number between 1-5. "); } }
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java public static void runEmployeeIntroMenu() { do { menu.setMenuOptions(new String[]{"\nWelcome to the Employee Menu." + "\n1. Add a product." + "\n2. Remove a product." + "\n3. Display all products." + "\n4. Log out and return to customer menu." + "\n5. Exit the program."}); System.out.println(Arrays.toString(menu.getMenuOptions()).replace("[", "").replace("]", " ")); System.out.print("Enter one of the following numbers to continue: "); Errormanager.inputMismatchErrorNumber(Main::printEmployeeMenuChoices); } while (runProgram); } public static void printEmployeeMenuChoices() { int employeeInput = input.nextInt(); input.nextLine(); switch (employeeInput) { case 1 -> createProduct(); case 2 -> removeProduct(); case 3 -> System.out.println("to be done!"); case 4 -> runCustomerIntroMenu(); case 5 -> runProgram = false; default -> System.out.println("\nThe input is not valid, please enter a number between 1-5. "); } } public static void logInAsEmployee() { File userNames = new File("usernames.txt"); File passwords = new File("passwords.txt"); System.out.println("\nWelcome to the login menu."); System.out.print("Please enter username: "); String username = input.nextLine(); System.out.print("Please enter password: "); String password = input.nextLine();
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java do { try { Scanner userNamesFile = new Scanner(userNames); Scanner userPasswordFile = new Scanner(passwords); while (userNamesFile.hasNext() && userPasswordFile.hasNext()) { String userExist = userNamesFile.nextLine(); String passExist = userPasswordFile.nextLine(); if (userExist.equals(username) && passExist.equals(password)) { runEmployeeIntroMenu(); } } System.out.println("\nWrong username or password."); } catch (FileNotFoundException e) { System.out.println("File not found"); } String userChoiceToExit = InputOutput.inputUserString("Enter yes to try again or any key to exit to the customermenu: "); if (userChoiceToExit.equalsIgnoreCase("Yes")) { logInAsEmployee(); } runProgram = false; } while (runProgram); } public static void createProduct() { double userSetPrice = 0.0; String userSetPricePerPcsOrKg = ""; String userSetFruitOrVegetable = ""; String userSetProductType = ""; InputOutput iO = new InputOutput(); Product createdUserProduct; double userSetDiscount = 0.0; int userSetDiscountCondition = 0;
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java String userSetName = InputOutput.inputUserString("\nPlease enter the name of the product: "); String userChoicePrice = InputOutput.inputUserString("Do you want to add price? Please write yes to or any key to continue: "); if (userChoicePrice.equalsIgnoreCase("Yes")) { System.out.print("Please enter price: "); userSetPrice = input.nextDouble(); input.nextLine(); userSetPricePerPcsOrKg = InputOutput.inputUserString("Enter if price is per piece (pcs) or per kilogram (kg). Write pcs or kg: "); } String userChoiceFruitOrVegetable = InputOutput.inputUserString("Do you want add if product is a fruit or vegetable? Please write yes or any key to continue: "); if (userChoiceFruitOrVegetable.equalsIgnoreCase("Yes")) { userSetFruitOrVegetable = InputOutput.inputUserString("Please enter if product is a fruit or vegetable: "); } else { userSetFruitOrVegetable = ("Field is unassigned"); } String userChoiceProductType = InputOutput.inputUserString("Do you want to add the producttype? Please write yes or any key to continue: "); if (userChoiceProductType.equalsIgnoreCase("Yes")) { userSetProductType = InputOutput.inputUserString("Please enter the producttype: "); } else { userSetProductType = ("Field is unassigned"); } String userChoiceDiscountCondition = InputOutput.inputUserString("Do you want to add a discount condition to the product? Please write yes or any key to continue: "); if (userChoiceDiscountCondition.equalsIgnoreCase("Yes")) { System.out.print("Please enter discount condition: "); userSetDiscountCondition = input.nextInt(); input.nextLine(); }
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java String userChoiceSetDiscount = InputOutput.inputUserString("Do you want to add a discount to the product? Please write yes or any key to continue: "); if (userChoiceSetDiscount.equalsIgnoreCase("Yes")) { System.out.print("Please enter the discount (as a decimal, e.g., 0.1 for 10%): "); userSetDiscount = input.nextDouble(); input.nextLine(); } if (userSetDiscount == 0.0) { createdUserProduct = new Product(userSetName, userSetPrice, userSetPricePerPcsOrKg, userSetFruitOrVegetable, userSetProductType); } else { createdUserProduct = new DiscountedProduct(userSetName, userSetPrice, userSetPricePerPcsOrKg, userSetFruitOrVegetable, userSetProductType, userSetDiscount, userSetDiscountCondition); } System.out.println("\n\033[1mYou added: \033[0m" + createdUserProduct); catalog.setAllFruitsandVegetables(createdUserProduct); } public static void searchTheCatalog() { boolean runSearchCatalog = false; Customerbasket customerbasket = new Customerbasket(0); do { String searchTerm = InputOutput.inputUserString("\nPlease enter a keyword: ").trim(); if (searchTerm.isEmpty()) { System.out.println("\nYou cannot leave it blank, please try again."); return; } boolean resultFoundInCatalog = false;
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java boolean resultFoundInCatalog = false; for (Product tempCatalog : catalog.getAllFruitsandVegetables()) { if (tempCatalog.toString().toLowerCase().contains(searchTerm.toLowerCase())) { System.out.println("\n\033[1mThe result of your search:\033[0m"); System.out.println(tempCatalog.toString()); String userChoiceYesOrNo = InputOutput.inputUserString("\nDo you want to calculate price for the product?" + "\nPlease enter yes to accept or any key to decline: "); if (userChoiceYesOrNo.equalsIgnoreCase("yes")) { System.out.print("Please enter quantity: "); double userChoiceQuantity = input.nextDouble(); input.nextLine(); calculatePrice(userChoiceQuantity, tempCatalog.getPrice(), tempCatalog); } Main.addToCustomerBasket(); if (userChoiceYesOrNo.equalsIgnoreCase("yes")) { Main.addToCustomerBasket(); } resultFoundInCatalog = true; } } if (!resultFoundInCatalog) { System.out.println("\nNo search results found."); } String exitSearchCatalog = InputOutput.inputUserString("Do you want to exit to the main menu? Write Yes to exit or any key to try again: "); if (exitSearchCatalog.equalsIgnoreCase("Yes")) { runSearchCatalog = true; } } while (!runSearchCatalog); } public static void removeProduct() { boolean runRemoveProduct = false;
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java public static void removeProduct() { boolean runRemoveProduct = false; do { boolean doesProductExist = false; String userChoice = InputOutput.inputUserString("\nPlease enter the name of the product you want to remove: "); for (int i = 0; i < catalog.getAllFruitsandVegetables().size(); i++) { if (catalog.getAllFruitsandVegetables().get(i).getName().equalsIgnoreCase(userChoice)) { Product removedProduct = catalog.getAllFruitsandVegetables().remove(i); System.out.println("You removed " + removedProduct.getName() + "."); doesProductExist = true; } } if (!doesProductExist) { System.out.println("\nThis product does not exist."); } String userChoiceToExit = InputOutput.inputUserString("Type yes to exit or any key to begin again: "); if (userChoiceToExit.equalsIgnoreCase("Yes")) { runRemoveProduct = true; } } while (!runRemoveProduct); } public static void calculatePrice(double quantity, double price, Product thisProduct) { double sum = quantity * price; System.out.println("The total price will be: " + sum + " kr." + " (" + price + " kr/" + thisProduct.getPricePerPcsOrKg() + ")"); }
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java public static void browseTheCatalog() { boolean quitCatalog = false; do { menu.setMenuOptions(new String[]{"\nWelcome to the product catalog, do you want to:" + "\n1. Browse the catalog." + "\n2. Search the catalog." + "\n3. Go back to the main menu."}); System.out.println(Arrays.toString(menu.getMenuOptions()).replace("[", "").replace("]", " ")); System.out.print("Please enter a number: "); int userCatalogChoice = input.nextInt(); input.nextLine(); if (userCatalogChoice == 1) { findUniquePrimaryTypeInCatalog(); System.out.print("Please choose from the options: "); findUniqueProductTypeInCatalog(); System.out.print("Please choose from the options: "); printFullItemFromInputFromCatalog(); } else if (userCatalogChoice == 2) { searchTheCatalog(); } else if (userCatalogChoice == 3) { quitCatalog = true; } } while (!quitCatalog); } public static void findUniquePrimaryTypeInCatalog() { for (Product uniqueItem : catalog.getAllFruitsandVegetables()) { String templist = uniqueItem.getFruitOrVegetable(); catalog.getSetofPrimaryTypes().add(templist.toLowerCase()); for (Iterator<String> i = catalog.getSetofPrimaryTypes().iterator(); i.hasNext(); ) { String element = i.next(); if (element.equalsIgnoreCase("Field is Unassigned")) { i.remove(); } } } System.out.println(catalog.getSetofPrimaryTypes()); }
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java } public static void findUniqueProductTypeInCatalog() { String firstUserCatalogChoice = input.nextLine().toLowerCase(); for (Product uniqueItem : catalog.getAllFruitsandVegetables()) { if (uniqueItem.getFruitOrVegetable().toLowerCase().contains(firstUserCatalogChoice)) { String templist = uniqueItem.getProductType(); catalog.getSetOfProductTypes().add(templist.toLowerCase()); } } System.out.println(catalog.getSetOfProductTypes()); } public static void printFullItemFromInputFromCatalog() { String firstUserCatalogChoice = input.nextLine().toLowerCase(); if (catalog.getSetOfProductTypes().contains(firstUserCatalogChoice.toLowerCase())) { System.out.println("\n\033[1mFull products: \033[0m"); for (Product fullProduct : catalog.getAllFruitsandVegetables()) { if (fullProduct.getProductType().equalsIgnoreCase(firstUserCatalogChoice.toLowerCase())) { System.out.println(fullProduct); System.out.println(); } } } }
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java public static void addToCustomerBasket() { String userChoiceYesOrNo = InputOutput.inputUserString("\nDo you want to add the product to the customerbasket?" + "\nPlease type yes to add product to basket or any key to continue: "); if (userChoiceYesOrNo.equalsIgnoreCase("yes")) { String userEnterProduct = InputOutput.inputUserString("Please enter the full name of the product to add to basket: "); System.out.print("How much or how many do you want to add to basket, please enter the quantity: "); int userEnterQuantity = input.nextInt(); input.nextLine(); for (Product tempBasket : catalog.getAllFruitsandVegetables()) { if (tempBasket.getName().equalsIgnoreCase(userEnterProduct)) { if (tempBasket instanceof DiscountedProduct && ((DiscountedProduct) tempBasket).getDiscountCondition() == userEnterQuantity) { customerbasket.getAllItemsInCustomerBasket().add((tempBasket.getPrice() * userEnterQuantity) * ((DiscountedProduct) tempBasket).getDiscount()); customerbasket.setItemsInBasket(userEnterQuantity); } else { customerbasket.getAllItemsInCustomerBasket().add((tempBasket.getPrice() * userEnterQuantity)); customerbasket.setItemsInBasket(userEnterQuantity); } } } } } public static void printCustomerBasket() { double fullPrice = 0; for (Double list : customerbasket.getAllItemsInCustomerBasket()) { fullPrice += list; } System.out.println("\nWelcome to the checkout."); System.out.println("Your basket contains " + customerbasket.getItemsInBasket() + " items and the total price is " + fullPrice + " kr."); } } public class DiscountedProduct extends Product { private double discount; private int discountCondition;
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java public DiscountedProduct(String name, double price, String pricePerPcsOrKg, String fruitOrVegetable, String productType, double discount, int discountCondition) { super(name, price, pricePerPcsOrKg, fruitOrVegetable, productType); this.discount = discount; this.discountCondition = discountCondition; } public double getDiscount() { return discount; } public void setDiscount(double discount) { this.discount = discount; } public int getDiscountCondition() { return discountCondition; } public void setDiscountCondition(int discountCondition) { this.discountCondition = discountCondition; } @Override public String toString() { return super.toString() + "\nDiscount: " + "Buy " + discountCondition + " for " + (discount * 100) + "% " + "off"; } } import java.util.ArrayList; import java.util.HashSet; public class Catalog { private ArrayList<Product> allFruitsandVegetables; private HashSet<String> setofPrimaryTypes; private HashSet<String> setOfProductTypes; public Catalog() { this.allFruitsandVegetables = new ArrayList<>(); this.setofPrimaryTypes = new HashSet<>(); this.setOfProductTypes = new HashSet<>(); } public ArrayList<Product> getAllFruitsandVegetables() { return allFruitsandVegetables; } public void setAllFruitsandVegetables(Product product) { this.allFruitsandVegetables.add(product); } public HashSet<String> getSetofPrimaryTypes() { return setofPrimaryTypes; } public void setSetofPrimaryTypes(HashSet<String> setofPrimaryTypes) { this.setofPrimaryTypes = setofPrimaryTypes; } public HashSet<String> getSetOfProductTypes() { return setOfProductTypes; }
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java public HashSet<String> getSetOfProductTypes() { return setOfProductTypes; } public void setSetOfProductTypes(HashSet<String> setOfProductTypes) { this.setOfProductTypes = setOfProductTypes; } } import java.util.ArrayList; import java.util.HashSet; public class Catalog { private ArrayList<Product> allFruitsandVegetables; private HashSet<String> setofPrimaryTypes; private HashSet<String> setOfProductTypes; public Catalog() { this.allFruitsandVegetables = new ArrayList<>(); this.setofPrimaryTypes = new HashSet<>(); this.setOfProductTypes = new HashSet<>(); } public ArrayList<Product> getAllFruitsandVegetables() { return allFruitsandVegetables; } public void setAllFruitsandVegetables(Product product) { this.allFruitsandVegetables.add(product); } public HashSet<String> getSetofPrimaryTypes() { return setofPrimaryTypes; } public void setSetofPrimaryTypes(HashSet<String> setofPrimaryTypes) { this.setofPrimaryTypes = setofPrimaryTypes; } public HashSet<String> getSetOfProductTypes() { return setOfProductTypes; } public void setSetOfProductTypes(HashSet<String> setOfProductTypes) { this.setOfProductTypes = setOfProductTypes; } } import java.util.Arrays; public class Menu { private String[] menuOptions; public Menu() { this.menuOptions = new String[10]; } public String[] getMenuOptions() { return menuOptions; } public void setMenuOptions(String[] menuOptions) { this.menuOptions = menuOptions; } } import javax.sound.midi.Soundbank; import java.util.Scanner; public class InputOutput { private static Scanner input; public InputOutput(){ this.input = new Scanner(System.in); }
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java public static String inputUserString(String messageToUser) { System.out.print(messageToUser); return input.nextLine(); } } import java.util.InputMismatchException; public class Errormanager { public static void errormanager (String[] args){ } public static void inputMismatchErrorNumber (Runnable method){ try { method.run(); } catch (InputMismatchException e) { String errorMessage = InputOutput.inputUserString("\nThe input is not valid, you cannot enter a letter, please enter a number."); } } }import java.util.ArrayList; import java.util.Scanner; public class Customerbasket { private ArrayList<Double> allItemsInCustomerBasket; private int itemsInBasket; public static Scanner input = new Scanner(System.in); public Customerbasket(int itemsInBasket) { this.allItemsInCustomerBasket = new ArrayList<>(); this.itemsInBasket = itemsInBasket; } public ArrayList<Double> getAllItemsInCustomerBasket() { return allItemsInCustomerBasket; } public void setAllItemsInCustomerBasket(ArrayList<Double> allItemsInCustomerBasket) { this.allItemsInCustomerBasket = allItemsInCustomerBasket; } public double getItemsInBasket() { return itemsInBasket; } public void setItemsInBasket(int userQuantity) { itemsInBasket += userQuantity; } } /* Namn: Kerem Tazedal Mejl: kerem.tazedal@iths.se */ public class Product { private String name; private double price; private String pricePerPcsOrKg; private String fruitOrVegetable; private String productType;
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java public Product(String name, double price, String pricePerPcsOrKg, String fruitOrVegetable, String productType) { this.name = name; this.price = price; this.pricePerPcsOrKg = pricePerPcsOrKg; this.fruitOrVegetable = fruitOrVegetable; this.productType = productType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getPricePerPcsOrKg() { return pricePerPcsOrKg; } public void userSetPricePerPcsOrKg(String pricePerPcsOrKg) { this.pricePerPcsOrKg = pricePerPcsOrKg; } public String getFruitOrVegetable() { return fruitOrVegetable; } public void setFruitOrVegetable(String fruitOrVegetable) { this.fruitOrVegetable = fruitOrVegetable; } public String getProductType() { return productType; } public void setProductType(String productType) { this.productType = productType; } @Override public String toString() { return "\nName of the product: " + name + "\nPrice: " + price + " kr per " + pricePerPcsOrKg + "\nPrimarytype: " + fruitOrVegetable + "\nSecondarytype: " + productType; } } Answer: Warning about inheritance I saw your implementation of the DiscountedProduct. I would like to warn you for inheritance as taught at school or in courses. It is stressed too much. (I got in trouble during (the first try) of my graduation project because how they teached it.) Inheritance should be thought of as a technique that should rarely be used (e.g. like reflection). Problems you can encounter by overuse of inheritance (at the top of my mind):
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java With inheritance code that you use and understand as a whole can become spread out over multiple files. Here: The logic for determining the price is in two classes. Imagine you have to implement a Christmas discount for specific products - different from the distinction DiscountProduct or Product. My advise: Make sure what you are doing is more separation of concerns than splitting up the same concern :-)! Inheritance requires the code to be separated based on only one distictive criterion in your functionality. This can only be one distinction. Other distinctions will have to be made in another way or with doubling the number of classes in the hierarchy. This will make the code more confusing. Here: The criterion to split up the hierarchy is eligability for discount. It is not obvious to me, because it does only affect a small portion of the logic. Similar distinctions like pricePerKg/pricePerPiece are handled in a different way. This makes it more difficult to reason about (It feels like coding in multiple dimensions :-).) Example of a good criterion: I once coded a timeline with events: some events happen at a specific moment in time others for a period. There was quite some functionality and some was the same and some was different. This distinction was fundamental to the UI element. It affected most of the logic. Inheritance worked. My advise: in rare case you use inheritance, have an obvious and fundamental reason of division. Else it will make the code more confusing. When using inheritance switching the type of your object at run time is complex. Here: Imagine you want to be able to a add a discount for a product. Will your Product be replaced by a DiscountedProduct? Then you'll have to create a new DiscountedProduct object and copy properties. Which references will have to be updated? My advise: only use inheritance when switching type is not plausible. Inheritance often requires casting, which can cause bugs not be seen at compile time.
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
java Inheritance often requires casting, which can cause bugs not be seen at compile time. Improvements Discount You don't need both a Product and DiscountedProduct class. A discount set to 0 as a default works as well. O, see how much you can simplify now? Final price The code for calculating the total price is now inside the console code. I didn't look there. You can better put it inside the Product class or a PriceCalculator class. (Since it's not much and is related to a product, I would suggest the Product class.) Your code is good for having one month of experience. I hope you learn from my lessons. Best practices "Prefer composition over inheritance" "Prefer interfaces over abstract/super classes" KISS: Keep it simple, smarty! A (valuable) programming coin reads "Separation of concerns" on its heads. "Bundling the same concern" is on its tails.* Prefer compile time errors over runtime exceptions. *Is there an "official" phrase?
{ "domain": "codereview.stackexchange", "id": 45216, "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": "java", "url": null }
c++, c++11, multithreading, file-system Title: Class for locking shared disk directory Question: I'm writing an application to sync files between two directories. In order to prevent simultaneous access to the shared directory from several computers, I implemented blocking of the shared directory. The class below implements this lock. The application is built and at first glance works without errors. But I'm new to writing multithreaded and file system code and I'm not sure I did everything right. Please look at my directory locker class. Is everything right there? Are there any problems? If so, how can they be corrected? Can it be made better? Update from 12.11: I forgot to write: The application is platform independent and I prefer not to use platform specific functions. It is advisable to use functions from the standard library. The shared directory may be located on a network drive and system functions such as shlock or flock may not be available there. Header file: #pragma once #include <filesystem> #include <future> class DirectoryLocker { public: DirectoryLocker(); ~DirectoryLocker(); bool tryToLock(const std::wstring& dirPath); void freeLock(); bool isLockValid() const; static constexpr const wchar_t* LockFileName = L".momentasync.lock"; private: std::filesystem::path m_pathToLockFile; std::atomic<bool> m_stopLockFileRefresh; std::future<void> m_lockFileRefreshFuture; }; CPP file: #include "DirectoryLocker.h" #include <chrono> #include <fstream> using namespace std::chrono_literals; const auto LockLifeTime = 15min; const auto LockRefreshReserve = 1min; static void writeExpirationTimeToLockFile(FILE* lockFile); static std::chrono::system_clock::time_point getLockFileExpirationTime(const std::filesystem::path& pathToLockFile); static std::future<void> runLockFileRefreshTask(const std::atomic<bool>& stopLockFileRefresh, const std::filesystem::path& pathToLockFile); DirectoryLocker::DirectoryLocker() {}
{ "domain": "codereview.stackexchange", "id": 45217, "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++, c++11, multithreading, file-system", "url": null }
c++, c++11, multithreading, file-system DirectoryLocker::DirectoryLocker() {} DirectoryLocker::~DirectoryLocker() { // According to Effective C++ Item 8: Prevent Exceptions from Leaving Destructors // we provide separate function freeLock because freing lock can throw exceptions. try { if (isLockValid()) freeLock(); } catch (...) {} } bool DirectoryLocker::tryToLock(const std::wstring& dirPath) { m_pathToLockFile = dirPath; m_pathToLockFile /= LockFileName; FILE* fp = std::fopen(m_pathToLockFile.string().c_str(), "wx"); if (!fp) { if (getLockFileExpirationTime(m_pathToLockFile) >= std::chrono::system_clock::now()) return false; // Lock file is expired. Remove it and try to create again. std::filesystem::remove(m_pathToLockFile); fp = std::fopen(m_pathToLockFile.string().c_str(), "wx"); if (!fp) // Someone else created a new lock file before us. return false; } writeExpirationTimeToLockFile(fp); std::fclose(fp); m_stopLockFileRefresh.store(false, std::memory_order_seq_cst); m_lockFileRefreshFuture = runLockFileRefreshTask(m_stopLockFileRefresh, m_pathToLockFile); return true; } void DirectoryLocker::freeLock() { m_stopLockFileRefresh.store(true, std::memory_order_seq_cst); if (m_lockFileRefreshFuture.valid()) m_lockFileRefreshFuture.wait(); std::filesystem::remove(m_pathToLockFile); std::fstream f; f.close(); } bool DirectoryLocker::isLockValid() const { return m_lockFileRefreshFuture.valid() && m_lockFileRefreshFuture.wait_for(0ms) == std::future_status::timeout; }
{ "domain": "codereview.stackexchange", "id": 45217, "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++, c++11, multithreading, file-system", "url": null }
c++, c++11, multithreading, file-system static void writeExpirationTimeToLockFile(FILE* lockFile) { auto expirationTime = std::chrono::system_clock::now() + LockLifeTime; std::ostringstream out; out << std::chrono::duration_cast<std::chrono::seconds>(expirationTime.time_since_epoch()).count() << std::endl; out << expirationTime; fputs(out.str().c_str(), lockFile); } static void writeExpirationTimeToLockFile(const std::filesystem::path& pathToLockFile) { std::ofstream file(pathToLockFile); if (!file) throw std::runtime_error("Could not open lock file: " + pathToLockFile.string()); auto expirationTime = std::chrono::system_clock::now() + LockLifeTime; std::ostringstream out; file << std::chrono::duration_cast<std::chrono::seconds>(expirationTime.time_since_epoch()).count() << std::endl; file << expirationTime; } static std::chrono::system_clock::time_point getLockFileExpirationTime(const std::filesystem::path& pathToLockFile) { std::ifstream file(pathToLockFile); if (!file) throw std::runtime_error("Could not open lock file: " + pathToLockFile.string()); std::string line; if (!std::getline(file, line)) throw std::runtime_error("Lock file is empty: " + pathToLockFile.string()); try { long long sec = std::stol(line); auto timePoint = std::chrono::time_point<std::chrono::system_clock>(std::chrono::seconds(sec)); auto diffToFuture = timePoint - std::chrono::system_clock::now(); if (diffToFuture > LockLifeTime || sec <= 0) { std::ostringstream out; out << "Invalid expiration time in the lock file." << std::endl; out << "Expiration time: " << timePoint << std::endl; out << "Expiration time in seconds sicne epoch: " << sec << std::endl; out << "First line of the lock file: " << line << std::endl; throw std::runtime_error(out.str()); }
{ "domain": "codereview.stackexchange", "id": 45217, "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++, c++11, multithreading, file-system", "url": null }
c++, c++11, multithreading, file-system return timePoint; } catch (const std::invalid_argument&) { throw std::runtime_error("Invalid first line in the lock file.\nFirst line: \"" + line + "\".\nLock file: " + pathToLockFile.string()); } catch (const std::out_of_range&) { throw std::runtime_error("Number in the first line of the lock file is out of range.\nFirst line: \"" + line + "\".\nLock file: " + pathToLockFile.string()); } } static std::future<void> runLockFileRefreshTask(const std::atomic<bool>& stopLockFileRefresh, const std::filesystem::path& pathToLockFile) { return std::async(std::launch::async, [&stopLockFileRefresh, pathToLockFile]() { while (!stopLockFileRefresh.load(std::memory_order_seq_cst)) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); if (std::chrono::system_clock::now() > getLockFileExpirationTime(pathToLockFile) - LockRefreshReserve) { writeExpirationTimeToLockFile(pathToLockFile); } } }); } Usage example: DirectorySyncronizer::SyncResult DirectorySyncronizer::syncronizeFiles( const std::wstring& sharedPath, const std::atomic<bool>& stopSync, const std::function<void(const std::wstring&)>& localSyncProgress, const std::function<void(const std::wstring&)>& sharedSyncProgress) { try { DirectoryLocker dirLocker; if (!dirLocker.tryToLock(sharedPath)) return { false, "The shared directory already locked by another computer."}; // Imitation of file copying for (int i = 0; i < 360; ++i) { if (stopSync.load(std::memory_order_seq_cst)) { dirLocker.freeLock(); return { false, "Syncronization was stopped by the user." }; } if (!dirLocker.isLockValid()) break; std::this_thread::sleep_for(500ms);
{ "domain": "codereview.stackexchange", "id": 45217, "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++, c++11, multithreading, file-system", "url": null }
c++, c++11, multithreading, file-system std::this_thread::sleep_for(500ms); localSyncProgress(std::format(L"File updated: {}", i)); sharedSyncProgress(std::format(L"File updated: {}", i)); } dirLocker.freeLock(); return { true, "" }; } catch (const std::exception& error) { return { false, error.what() }; } } Answer: This is not safe Let's consider two threads that each call tryToLock() at the same time, and there is an expired lockfile on the disk: FILE* fp = std::fopen(m_pathToLockFile.string().c_str(), "wx"); if (!fp) { if (getLockFileExpirationTime(m_pathToLockFile) >= std::chrono::system_clock::now()) return false; // Lock file is expired. Remove it and try to create again. Both threads are now right at that comment. Now consider that one thread runs ahead of the other, and calls: std::filesystem::remove(m_pathToLockFile); fp = std::fopen(m_pathToLockFile.string().c_str(), "wx"); That works. But now the second thread catches up and it too executes: std::filesystem::remove(m_pathToLockFile); fp = std::fopen(m_pathToLockFile.string().c_str(), "wx");
{ "domain": "codereview.stackexchange", "id": 45217, "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++, c++11, multithreading, file-system", "url": null }
c++, c++11, multithreading, file-system So it will remove the file opened by the first thread. But that means the second fopen() will succeed. Both threads will now think they have the lock. Either you should use the file locking mechanisms of your operating system, like for example flock() (which might not be portable and/or not work on shared drives), or rely on rename() being atomic, like J_H mentioned in his answer. It is not robust There are lots of things that can go wrong that you are not handling in your code. What if someone renames the directory you are in while you are holding the lock? What if daylight saving time kicks in? What if the two processes run on different computers, and the two computers have the clock set to a different time? What if the lock file could be opened but writing to it fails because the disk is full? Part of these issues can be solved by adding some more checking to the code, but some problems are unsolvable without using a completely different way to do locking. Again, the operating system might have better functions available to do proper file locking. It also depends on the protocol used to share the drives. For example, flock() works on NFS, but other protocols might behave differently, and/or have different ways to lock files. Improve the interface Use the [[nodiscard]] attribute for tryToLock(); this will catch mistakes like calling tryToLock() but not using its return value. I would also suggest that you let the constructor take the path to the directory, and rename tryToLock() to try_lock(), and freeLock() to unlock(), and perhaps add a lock() that waits indefinitely until it can get the lock. That way it has the same interface as std::mutex, which also means you can use std::lock_guard, std::try_lock() and other utilities that work on lockable objects.
{ "domain": "codereview.stackexchange", "id": 45217, "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++, c++11, multithreading, file-system", "url": null }
rust, http Title: Get HTTP status of many URLs Question: I'm brand new to using rust, so please bear with me. I'm trying to write a rust program which takes two arguments: A URL, and a wordlist. This wordlist has the following contents, and is several hundred thousand lines long: ... example1.php example2.php example3.php ... I want to read all of these from the wordlist file, then as quickly as possible (asychronously??) send a head request to the URL + the filename in the wordlist (for example if we do rust_fuzzer https://example.com examplewordlist.com, it should send the requests to https://example.com/example1.php...) then check if the status code is a 200. If it is, add it to a string vec, then at the end of the program print the vec using "{:?}" formatter. So far, I have the following code, which seems to work much faster than the python equivalent I wrote (I'm much more familiar with python), however I do wonder if it could go faster, and if I've done the async stuff right. The code is sort of hacked together from existing stuff I found online and my own (very basic) understanding of the language. I would really appreciate some improvement suggestions (apart from the obvious like error handling which I'll figure out after the main part is done). use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; use std::env; use reqwest::Client; use reqwest::Url; fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>, { let file = File::open(filename)?; Ok(io::BufReader::new(file).lines()) } async fn fuzzer(url_string: &String, file_path: &String) -> Vec<String>{ let Ok(base_url) = Url::parse(url_string) else { todo!() }; let mut found_resources = Vec::new(); let client = Client::new();
{ "domain": "codereview.stackexchange", "id": 45218, "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, http", "url": null }
rust, http let mut found_resources = Vec::new(); let client = Client::new(); if let Ok(lines) = read_lines(file_path) { for line in lines { if let Ok(resource) = line { let Ok(target_url) = base_url.join(&resource) else { todo!() }; let response = client.head(target_url.as_str()).send().await; if !response.is_err() { if response.unwrap().status() == reqwest::StatusCode::OK { found_resources.push(resource); } } } } } else { println!("Something went wrong reading the file.."); } return found_resources; } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>>{ let args: Vec<String> = env::args().collect(); if args.len() == 3 { let found_resources = fuzzer(&args[1], &args[2]).await; println!("{:?}", found_resources); } else { println!("USAGE: ./rust_fuzzer <URL> <Wordlist>"); } Ok(()) } Essentially, I want this code to get the status codes and add the resources with a 200 code to the String Vec as fast as possible, but I know I may have to consider rate limiting and whatnot
{ "domain": "codereview.stackexchange", "id": 45218, "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, http", "url": null }
rust, http Answer: I said I'd take a crack at this, and so here we go. It's going to be kinda rough; both because my rust is very shallow, and because I don't have as much time as I'd hoped. Basically, I don't think you're doing the requests concurrently at all. I tried to get it to work using Tokio Streams, but that didn't work, so instead this is a straightforward adaptation of the technique suggested here: https://stackoverflow.com/a/51047786/10135377 I didn't read the whole thing, but you definitely should because it's clearly explaining a lot of detail relevant to the kind of optimization you're doing. use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; use std::env; use reqwest::Client; use reqwest::Url; use futures::{stream, StreamExt}; use tokio; const CONCURRENT_REQUESTS: usize = 2000; fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>, { let file = File::open(filename)?; Ok(io::BufReader::new(file).lines()) } async fn fuzzer(url_string: &String, file_path: &String) -> Vec<String>{ let Ok(base_url) = Url::parse(url_string) else { todo!() }; let client = Client::new(); if let Ok(lines) = read_lines(file_path) { stream::iter(lines).map(|line| { let Ok(resource) = line else { todo!() }; let Ok(target_url) = base_url.join(&resource) else { todo!() }; let client_ = &client; async move { let result = client_.head(target_url.as_str()).send().await; let response = result.ok()?; // trashing some important failures here!! if response.status() == reqwest::StatusCode::OK { Some(resource) } else { None } } }).buffer_unordered(CONCURRENT_REQUESTS).filter_map(|r| async {r}).collect().await } else { println!("Something went wrong reading the file.."); Vec::new() } }
{ "domain": "codereview.stackexchange", "id": 45218, "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, http", "url": null }
rust, http #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>>{ let args: Vec<String> = env::args().collect(); if args.len() == 3 { let found_resources = fuzzer(&args[1], &args[2]).await; println!("{:?}", found_resources); } else { println!("USAGE: ./rust_fuzzer <URL> <Wordlist>"); } Ok(()) } I benchmarked it against a localhost scotty server that just checks if the hash of the path is an even number. I used n0kovo_subdomains_tiny.txt Orignal: real 23.81 user 21.52 sys 7.50 Updated: real 8.30 user 19.10 sys 6.59 So there is some improvement. It's not a ton of improvement, and IDK if it's worth trying to do better. What in heck are you actually trying to do!? It seems like you're trying to crawl a website by asking it which of millions of paths are real. Don't do that. There are better ways to crawl a website. If you get rate-limited, your task will never finish. If you don't get rate-limited, there's a risk you'll DOS them. Making someone rate-limit you is a dick move; implementing rate-limiting is a chore that we wouldn't do if badly-written scrapers didn't try to DOS us. A very likely outcome of pointing your tool at a stranger's website is that some hapless admin somewhere spends their Tuesday figuring out what the hell you're doing and then rate-limiting you. (In case you can't tell, that's been me on occasion.) You'll never be able to make your tool faster than the server it's querying. Sorry this is casual and not super educational; it's late here.
{ "domain": "codereview.stackexchange", "id": 45218, "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, http", "url": null }
c++, brainfuck Title: BF Interpreter in C++ Question: Need to clear my brain. BF interpretor in C++. bf.h #include <vector> class BF { std::vector<char> memory; std::size_t dp; template<typename I> I findMatchingClose(I start); public: BF(std::size_t defaultMemorySize = 4096); void reset() {dp = 0;} template<typename I> // Not sure how to specify that `I` is limited to allow random access. // Suppose I could re-write to allow slips back and forward. void run(I begin, I end); }; bf.cpp #include "bf.h" #include <iostream> BF::BF(std::size_t defaultMemorySize) : memory(defaultMemorySize, 0) , dp(0) {} template<typename I> I BF::findMatchingClose(I loop) { std::size_t openCount = 1; for (++loop; openCount != 0; ++loop) { if (*loop == '[') { ++openCount; } else if (*loop == ']') { --openCount; } } return loop; } template<typename I> void BF::run(I begin, I end) { /* > Increment the data pointer by one (to point to the next cell to the right). < Decrement the data pointer by one (to point to the next cell to the left). + Increment the byte at the data pointer by one. - Decrement the byte at the data pointer by one. . Output the byte at the data pointer. , Accept one byte of input, storing its value in the byte at the data pointer. [ If the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it forward to the command after the matching ] command. ] If the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it back to the command after the matching [ command. */
{ "domain": "codereview.stackexchange", "id": 45219, "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++, brainfuck", "url": null }