text stringlengths 1 2.12k | source dict |
|---|---|
c, file-system, linux
const char *path = (argc == 2) ? argv[1] : "./";
return myrls(path);
}
Answer: Reduce allocations and long string copies
Rather than stpcpy(full_path, dir_name);, which gets longer and longer on recursion, allocate once a max path length buffer and pass in it the current directory and its length. Then no copying of the dir_name is needed and copying the file name only needs to copy from the end as that buffer is re-used.
In my experience, this approach significantly increases performance.
// Return non-zero on error.
// len: current used length.
// sz: max size of buffer.
// path: buffer to form the path.
// f(): some function to perform on state and path.
// state: Some context for f().
int DirFunc(size_t len, size_t sz, char path[sz],
int (f)(void *state, const char *filepathname), void *state) {
int retval = 0;
DIR *dir;
if ((dir = opendir(path)) != NULL) {
struct dirent *in_file;
while ((in_file = readdir(dir)) != NULL) {
// Appned file name.
int le = snprintf(&path[len], sz - len, "%s", in_file->d_name);
// Look for excessively long paths.
if (le < 0 || (unsigned) le >= sz - len) {
return -1;
}
retval = f(state, path); // Do something with path.
if (retval) {
return retval;
}
if (in_file->d_type & DT_DIR) {
if (path[len] != '.'
|| (strcmp(&path[len], ".") && strcmp(&path[len], ".."))) {
strcpy(&path[len + le], "/");
retval = DirFunc(len + le + 1, sz, path, f, state);
path[len] = '\0'; // Lop off appended filename.
if (retval) {
return retval;
}
}
}
}
retval = closedir(dir);
if (retval) {
return retval;
}
}
return retval;
} | {
"domain": "codereview.stackexchange",
"id": 45162,
"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, file-system, linux",
"url": null
} |
c, file-system, linux
Use matching specifier
snprintf(NULL, 0, "%ld", info.st.st_size); assumes info.st.st_size is a long. It is type off_t which may be like long or wider or narrower. Instead cast this signed type to widest signed type and then print.
// snprintf(NULL, 0, "%ld", info.st.st_size);
snprintf(NULL, 0, "%jd", (intmax_t) info.st.st_size);
Likewise with uid
... *get_owner(uid_t uid) {
// sprintf(user_info->name, "%u", uid);
sprintf(user_info->name, "%ju", (uintmax_t) uid);
Avoid overflow
Since strcpy(user_info->name, pwd->pw_name) may overflow the destination buffer, perhaps create a int xstrcpy(size_t n, char dest[n], const char *s). Perhaps a copy that never overflows and returns a success flag.
int xstrcpy(size_t n, char dest[n], const char *s) {
if (strlen(s) >= n) {
if (n > 0) {
dest[0] = '\0';
}
return -1; //failure
}
strcpy(dest, s);
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45162,
"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, file-system, linux",
"url": null
} |
rust
Title: Create a String from the part of the vector
Question: I want to create a String from the part of the vector.
My code:
fn main() {
let v = vec!['a', 'b', 'c', 'd'];
let mut res = String::new(); // expect to have "cd"
let start_pos: usize = 2;
for i in start_pos..v.len() {
res.push(v[i]);
}
println!("{}", res); // "cd"
}
Is it possible to do the same shorter?
Answer: You could convert the Vec into an iterator, and write this in fluent style.
fn main() {
let v = vec!['a', 'b', 'c', 'd'];
let res : String = v
.into_iter()
.skip(2)
.collect();
println!("{}", res); // "cd"
}
Instead of skip(2) on the iterator, you could convert a slice of the Vec:
fn main() {
let v = vec!['a', 'b', 'c', 'd'];
let res : String = v[2..]
.into_iter()
.collect();
println!("{}", res); // "cd"
}
I find this very readable, and it generates fast code. One advantage it has is that res no longer needs to be mut, but can be a static single assignment. To achieve that with the loop implementation, you would need to move the loop into a helper, or “phi,” function.
In real-world code, a container like v, whose data are compile-time constants and never modified, would be a const or static array, not a Vec.
Recall that a Rust String holds UTF-8 bytes, not an array of UCS-4 char. There’s a function to move a Vec<u8> that holds valid UTF-8 bytes into a String: String::from_utf8. It’s likely that your input will be in UTF-8 as well, so if you can avoid the overhead of converting between UCS-4 and UTF-8 or vice versa, that will be far more efficient. | {
"domain": "codereview.stackexchange",
"id": 45163,
"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",
"url": null
} |
performance, beginner, scratch
Title: Exponentiation in Scratch
Question: This was back when I was new to coding on Scratch (as in the case of coding projects entirely from scratch) around 7-8 months ago with my Cookie Clicker in Scratch project that I made pretty much entirely myself. Now, what seemed to be a huge barrier for me was summing values so I could add a Buy 100 function for the in-game "buildings" which I never did. Now, right now, as you can see in this screenshot here, while I have code (that works) for it, I really feel like there's a way to optimize the code so that it's more readable. I understand what the code is doing, I'm just not sure that this is the most optimized version of the code. Is it true that this code can be improved, or is this truly the most optimized the code can be?
Code in [scratchblocks] format:
[scratchblocks]
define pow(base)(power)
set [result v] to [1]
set [base v] to (base)
set [power v] to (round (power))
set [done v] to [0]
if <(power) < [0]> then
set [base v] to [((1) / (base))]
set [power v] to [-1(() *(round (power))]
end
repeat until <[done v] = [1]>
if <(([power v]) mod (2)) = [0]> then
set [result v] to (([result v]) * ([base v]))
change [power v] by (-1)
end
if <(([power v]) mod (2)) > [0]> then
set [done v] to [1]
end
if <<not <<[done v] = [1]>>>
set [base v] to (([base v]) * ([base v]))
set [power v] to (([power v]) / (2))
end
end
[/scratchblocks]
Answer: I think that your implementation is probably fine in terms of the method you're using, but this can be computed directly. Although scratch does not have an operator for an arbitrary-base power built in, they can pretty simply be converted to the existing e^ operator by the relation bp = ep*ln(b) (or similar for the 10^ operator). In a scratch custom block that would look like this. | {
"domain": "codereview.stackexchange",
"id": 45164,
"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": "performance, beginner, scratch",
"url": null
} |
performance, beginner, scratch
This indeed ran much faster, about 13x as fast when I tested it on my machine. It also works for non-integer powers, although if you don't want this behavior you could round it like you currently are. A possible caveat to this approach is a slight loss of precision. For example, 2³² gives 4294967295.999997 compared to 4294967296 in the original, although this should usually not be an issue.
Edit: This method also won't work for a negative base due to the logarithm being undefined and giving NaN, although a base of 0 seemed to work fine. You could potentially check for this first by seeing if the power is even or odd, and and either cancel or pull out the negative respectively, then use the absolute value of the base. This won't work for negative bases and non-integer powers, which are undefined regardless. | {
"domain": "codereview.stackexchange",
"id": 45164,
"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": "performance, beginner, scratch",
"url": null
} |
c, formatting, integer, bitwise, gcc
Title: Register "%b" conversion specifier
Question: I'm writing a library to register the b, B conversion specifiers and make them work the closest possible to o, u, x, X.
Requirements:
All "flag characters" should behave as in x, X (or as close as possible, while being meaningful).
"Field width" and "precision" should behave as in x, X (or as close as possible, while being meaningful).
All "length modifiers" that are valid on o, u, x, X should be valid.
They should work on any printf family function (such as fprintf, snprintf, ...).
There are some flags that override others in the case of o, u, x, X. Those behaviours should be kept the same.
Basically, they should work so that a user can predict the output from reading the man printf page.
I decided that the ' flag character, which normally should group the output in thousands, would be more meaningful here if it grouped nibbles (half bytes), and instead of using the locale for thousands separator, it should use _. But I'm open to improvements here.
Here goes the code:
/* 2019 - Alejandro Colomar Andrés */
/******************************************************************************
******* headers **************************************************************
******************************************************************************/
#include "libalx/base/stdio/printf.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <printf.h>
/******************************************************************************
******* macros ***************************************************************
******************************************************************************/
/******************************************************************************
******* enums ****************************************************************
******************************************************************************/ | {
"domain": "codereview.stackexchange",
"id": 45165,
"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, formatting, integer, bitwise, gcc",
"url": null
} |
c, formatting, integer, bitwise, gcc
/******************************************************************************
******* structs / unions *****************************************************
******************************************************************************/
/******************************************************************************
******* variables ************************************************************
******************************************************************************/
/******************************************************************************
******* static functions (prototypes) ****************************************
******************************************************************************/
static int printf_output_b (FILE *stream,
const struct printf_info *info,
const void *const *args);
static int printf_arginf_sz_b (const struct printf_info *info,
size_t n, int *argtypes, int *size);
/******************************************************************************
******* global functions *****************************************************
******************************************************************************/
int alx_printf_init (void)
{
if (register_printf_specifier('b', printf_output_b, printf_arginf_sz_b))
return -1;
if (register_printf_specifier('B', printf_output_b, printf_arginf_sz_b))
return -1;
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45165,
"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, formatting, integer, bitwise, gcc",
"url": null
} |
c, formatting, integer, bitwise, gcc
return 0;
}
/******************************************************************************
******* static functions (definitions) ***************************************
******************************************************************************/
static int printf_output_b (FILE *stream,
const struct printf_info *info,
const void *const *args)
{
uintmax_t val;
uintmax_t utmp;
bool bin[sizeof(val) * 8];
int min_len;
int bin_len;
int pad_len;
int tmp;
char pad_ch;
size_t len;
len = 0;
if (info->is_long_double)
val = *(unsigned long long *)args[0];
else if (info->is_long)
val = *(unsigned long *)args[0];
else if (info->is_char)
val = *(unsigned char *)args[0];
else if (info->is_short)
val = *(unsigned short *)args[0];
else
val = *(unsigned *)args[0];
/* Binary representation */
memset(bin, 0, sizeof(bin));
utmp = val;
for (min_len = 0; utmp; min_len++) {
if (utmp % 2)
bin[min_len] = 1;
utmp >>= 1;
}
if (info->prec > min_len)
bin_len = info->prec;
else
bin_len = min_len;
/* Padding char */
if ((info->prec != -1) || (info->pad == ' ') || info->left)
pad_ch = ' ';
else
pad_ch = '0';
/* Padding length */
if (pad_ch == ' ') {
pad_len = info->width - bin_len;
if (info->alt)
pad_len -= 2;
if (info->group)
pad_len -= (bin_len - 1) / 4;
if (pad_len < 0)
pad_len = 0;
}
/* Padding with ' ' (right aligned) */
if ((pad_ch == ' ') && !info->left) {
for (int i = pad_len; i; i--) {
if (fputc(' ', stream) == EOF)
return EOF;
}
len += pad_len;
} | {
"domain": "codereview.stackexchange",
"id": 45165,
"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, formatting, integer, bitwise, gcc",
"url": null
} |
c, formatting, integer, bitwise, gcc
/* "0b"/"0B" prefix */
if (info->alt && val) {
if (fputc('0', stream) == EOF)
return EOF;
if (fputc(info->spec, stream) == EOF)
return EOF;
len += 2;
}
/* Padding with '0' */
if (pad_ch == '0') {
tmp = info->width - (info->alt * 2);
if (info->group)
tmp -= (tmp - min_len + 3) / 4;
for (int i = tmp - 1; i > min_len - 1; i--) {
if (fputc('0', stream) == EOF)
return EOF;
if (info->group && !(i % 4) && i) {
if (fputc('_', stream) == EOF)
return EOF;
len++;
}
}
len += tmp - min_len;
}
/* Print leading zeros to fill precission */
for (int i = bin_len - 1; i > min_len - 1; i--) {
if (fputc('0', stream) == EOF)
return EOF;
if (info->group && !(i % 4) && i) {
if (fputc('_', stream) == EOF)
return EOF;
len++;
}
}
len += bin_len - min_len;
/* Print number */
for (int i = min_len - 1; i; i--) {
if (fputc('0' + bin[i], stream) == EOF)
return EOF;
if (info->group && !(i % 4) && i) {
if (fputc('_', stream) == EOF)
return EOF;
len++;
}
}
if (fputc('0' + bin[0], stream) == EOF)
return EOF;
len += min_len;
/* Padding with ' ' (left aligned) */
if (info->left) {
for (int i = pad_len; i; i--) {
if (fputc(' ', stream) == EOF)
return EOF;
}
len += pad_len;
}
return len;
}
static int printf_arginf_sz_b (const struct printf_info *info,
size_t n, int *argtypes, int *size)
{
if (n > 0)
argtypes[0] = PA_INT;
return 1;
} | {
"domain": "codereview.stackexchange",
"id": 45165,
"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, formatting, integer, bitwise, gcc",
"url": null
} |
c, formatting, integer, bitwise, gcc
if (n > 0)
argtypes[0] = PA_INT;
return 1;
}
/******************************************************************************
******* end of file **********************************************************
******************************************************************************/
It seems that it works as expected (at least on my tests), but I feel like the code is very heavy and long and could be simplified.
Here is what I've tested:
#include "libalx/base/stdio/printf.h"
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
int main()
{
alx_printf_init(); | {
"domain": "codereview.stackexchange",
"id": 45165,
"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, formatting, integer, bitwise, gcc",
"url": null
} |
c, formatting, integer, bitwise, gcc
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
int main()
{
alx_printf_init();
printf("....----....----....----....----\n");
printf("%llb;\n", 0x5Ellu);
printf("%lB;\n", 0x5Elu);
printf("%b;\n", 0x5Eu);
printf("%hB;\n", 0x5Eu);
printf("%hhb;\n", 0x5Eu);
printf("%jb;\n", (uintmax_t)0x5E);
printf("%zb;\n", (size_t)0x5E);
printf("....----....----....----....----\n");
printf("%#b;\n", 0x5Eu);
printf("%#B;\n", 0x5Eu);
printf("....----....----....----....----\n");
printf("%10b;\n", 0x5Eu);
printf("%010b;\n", 0x5Eu);
printf("%.10b;\n", 0x5Eu);
printf("....----....----....----....----\n");
printf("%-10B;\n", 0x5Eu);
printf("....----....----....----....----\n");
printf("%'B;\n", 0x5Eu);
printf("....----....----....----....----\n");
printf("....----....----....----....----\n");
printf("%#16.12b;\n", 0xAB);
printf("%-#'20.12b;\n", 0xAB);
printf("%#'020B;\n", 0xAB);
printf("....----....----....----....----\n");
printf("%#020B;\n", 0xAB);
printf("%'020B;\n", 0xAB);
printf("%020B;\n", 0xAB);
printf("....----....----....----....----\n");
printf("%#021B;\n", 0xAB);
printf("%'021B;\n", 0xAB);
printf("%021B;\n", 0xAB);
printf("....----....----....----....----\n");
printf("%#022B;\n", 0xAB);
printf("%'022B;\n", 0xAB);
printf("%022B;\n", 0xAB);
printf("....----....----....----....----\n");
printf("%#023B;\n", 0xAB);
printf("%'023B;\n", 0xAB);
printf("%023B;\n", 0xAB);
printf("....----....----....----....----\n");
printf("%-#'19.11b;\n", 0xAB);
printf("%#'019B;\n", 0xAB);
printf("%#019B;\n", 0xAB);
printf("....----....----....----....----\n");
printf("%'019B;\n", 0xAB);
printf("%019B;\n", 0xAB);
printf("%#016b;\n", 0xAB);
printf("....----....----....----....----\n");
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45165,
"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, formatting, integer, bitwise, gcc",
"url": null
} |
c, formatting, integer, bitwise, gcc
And its output:
....----....----....----....----
1011110;
1011110;
1011110;
1011110;
1011110;
1011110;
1011110;
....----....----....----....----
0b1011110;
0B1011110;
....----....----....----....----
1011110;
0001011110;
0001011110;
....----....----....----....----
1011110 ;
....----....----....----....----
101_1110;
....----....----....----....----
....----....----....----....----
0b000010101011;
0b0000_1010_1011 ;
0B000_0000_1010_1011; | {
"domain": "codereview.stackexchange",
"id": 45165,
"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, formatting, integer, bitwise, gcc",
"url": null
} |
c, formatting, integer, bitwise, gcc
0B000_0000_1010_1011;
....----....----....----....----
0B000000000010101011;
0_0000_0000_1010_1011;
00000000000010101011;
....----....----....----....----
0B0000000000010101011;
0_0000_0000_1010_1011;
000000000000010101011;
....----....----....----....----
0B00000000000010101011;
00_0000_0000_1010_1011;
0000000000000010101011;
....----....----....----....----
0B000000000000010101011;
000_0000_0000_1010_1011;
00000000000000010101011;
....----....----....----....----
0b000_1010_1011 ;
0B00_0000_1010_1011;
0B00000000010101011;
....----....----....----....----
0000_0000_1010_1011;
0000000000010101011; | {
"domain": "codereview.stackexchange",
"id": 45165,
"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, formatting, integer, bitwise, gcc",
"url": null
} |
c, formatting, integer, bitwise, gcc
0000000000010101011;
0b00000010101011;
....----....----....----....---- | {
"domain": "codereview.stackexchange",
"id": 45165,
"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, formatting, integer, bitwise, gcc",
"url": null
} |
c, formatting, integer, bitwise, gcc
I understood the use of printf_output_b, but I still don't know very well the use of printf_arginf_sz_b, and if I'm missing anything.
Is there anything you miss here, or you think could be improved?
Also, let's say that uintmax_t or size_t are wider than unsigned long long. How would I handle that? I don't receive any information about those in the struct, AFAIK.
EDIT: Add the struct and enum definitions from <printf.h>
struct printf_info{
int prec; /* Precision. */
int width; /* Width. */
wchar_t spec; /* Format letter. */
unsigned int is_long_double:1;/* L flag. */
unsigned int is_short:1; /* h flag. */
unsigned int is_long:1; /* l flag. */
unsigned int alt:1; /* # flag. */
unsigned int space:1; /* Space flag. */
unsigned int left:1; /* - flag. */
unsigned int showsign:1; /* + flag. */
unsigned int group:1; /* ' flag. */
unsigned int extra:1; /* For special use. */
unsigned int is_char:1; /* hh flag. */
unsigned int wide:1; /* Nonzero for wide character streams. */
unsigned int i18n:1; /* I flag. */
unsigned int is_binary128:1; /* Floating-point argument is ABI-compatible with IEC 60559 binary128. */
unsigned int __pad:3; /* Unused so far. */
unsigned short int user; /* Bits for user-installed modifiers. */
wchar_t pad; /* Padding character. */
};
enum{ /* C type: */
PA_INT, /* int */
PA_CHAR, /* int, cast to char */
PA_WCHAR, /* wide char */
PA_STRING, /* const char *, a '\0'-terminated string */
PA_WSTRING, /* const wchar_t *, wide character string */
PA_POINTER, /* void * */
PA_FLOAT, /* float */
PA_DOUBLE, /* double */
PA_LAST
}; | {
"domain": "codereview.stackexchange",
"id": 45165,
"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, formatting, integer, bitwise, gcc",
"url": null
} |
c, formatting, integer, bitwise, gcc
Answer: zero
min_len is calculated as 0 when val == 0. I'd expect min_len to be 1.
Casual conversion
Pedantic: code returns size_t len as int with no range check in the conversion. Might as well just use int len.
len calculation
Code does not display the return value of printf() in its tests. I have suspicions about its correctness. Suggest instead to simply pair each fputc() with a len++. | {
"domain": "codereview.stackexchange",
"id": 45165,
"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, formatting, integer, bitwise, gcc",
"url": null
} |
python, python-3.x, error-handling
Title: Two versions of user-specified exception filters that log a different message on match
Question: I'd like to show you two versions of my two functions that support my logging tools. Their purpose is to log a different message (here abort) when an error occured and it matches the filter specified by the user. By default the error message is logged.
Version-1 of this code uses the classical if to handle the optional filter, while version-2 uses the a try/except.
Classical if
The first function is an optional filter that logs an abort trace when the exception matches any of the error types specified by the user and returns True in this case, otherwise False:
class LogAbortWhen:
def __init__(self, *error_types: type[Exception]):
self.error_types = error_types
def __call__(self, exc: Exception, logger: TraceLogger) -> bool:
if any((isinstance(exc, t) for t in self.error_types)):
logger.final.log_abort(message=f"Unable to complete due to <{type(exc).__name__}>: {str(exc) or '<N/A>'}")
return True
return False
The other one logs the default error trace when there is no custom filter or the filter returned False:
@contextlib.contextmanager
def telemetry_context(
activity: str,
source: Source,
on_error: Optional[OnError] = None,
) -> ContextManager[TraceLogger]: # noqa
parent = current_logger.get()
logger = BasicLogger(activity)
tracer = TraceLogger(logger)
tracer.initial.source.append(source)
token = current_logger.set(Node(logger, parent))
try:
yield tracer
except Exception as e: # noqa
if not on_error or not on_error(e, tracer):
tracer.final.log_error(message=f"Unhandled <{type(e).__name__}> has occurred: <{str(e) or 'N/A'}>")
raise
finally:
current_logger.reset(token) | {
"domain": "codereview.stackexchange",
"id": 45166,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, error-handling",
"url": null
} |
python, python-3.x, error-handling
Easier to ask for forgiveness than permission: try/except
But then I thought, how about rewriting it with the easier to ask for forgiveness than permission principle in mind, so I did the following (theoretical code):
The LogAbortWhen2 now throws the DoesNotApply error when it didn't do anything:
class DoesNotApply(Exception):
pass
class LogAbortWhen2:
def __init__(self, *error_types: type[Exception]):
self.error_types = error_types
def __call__(self, exc: Exception, logger: TraceLogger):
if any((isinstance(exc, t) for t in self.error_types)):
logger.final.log_abort(message=f"Unable to complete due to <{type(exc).__name__}>: {str(exc) or '<N/A>'}")
else:
raise DoesNotApply()
And the context-manager telemetry_context2 doesn't check the return value anymore, but handles the two errors that may occur: TypeError | DoesNotApply. (the TypeError is for when the on_error variable is None; I know, I should implement an empty empty filter always throwing the DoesNotApply error)
@contextlib.contextmanager
def telemetry_context2(
activity: str,
source: Source,
on_error: Optional[OnError] = None,
) -> ContextManager[TraceLogger]: # noqa
parent = current_logger.get()
logger = BasicLogger(activity)
tracer = TraceLogger(logger)
tracer.initial.source.append(source)
token = current_logger.set(Node(logger, parent))
try:
yield tracer
except Exception as e: # noqa
try:
on_error(e, tracer)
except TypeError | DoesNotApply:
tracer.final.log_error(message=f"Unhandled <{type(e).__name__}> has occurred: <{str(e) or 'N/A'}>")
raise
finally:
current_logger.reset(token)
Which version would you prefer? The first one with the bool return value and the additional if or the second one with the try/except? Also how strict are you about the EAFP principle? Do you often write your code if-free and favor try/excepts? | {
"domain": "codereview.stackexchange",
"id": 45166,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, error-handling",
"url": null
} |
python, python-3.x, error-handling
Answer:
You're not running your static typing tool in strict mode, limiting the benefits to static typing your code.
When to use *args can be a bit of a tricky one.
However if you're ok with taking a tuple[type[Exception], ...] then we can use dataclasses which can automatically build a number of dunders for you.
Additionally I think having the class be frozen (immutable) makes sense, and you can automatically make __slots__ for increases in performance and memory usage.
I think you want to use BaseException not Exception. Please familiarize yourself with Python's exception hierarchy, which shows all exception inherit from BaseException.
isinstance takes type[BaseException] | tuple[type[BaseException], ...] as the type argument, meaning you don't need to use any and a generator expression.
@dataclasses.dataclass(frozen=True, slots=True)
class LogAbortWhen:
exceptions: tuple[type[BaseException], ...]
def __call__(self, exc: BaseException, logger: TraceLogger) -> bool:
if isinstance(exc, self.exceptions):
logger.final.log_abort(message=f"Unable to complete due to <{type(exc).__name__}>: {str(exc) or '<N/A>'}")
return True
return False
# Example usage
abort = LogAbortWhen((KeyboardInterrupt, OSError))
assert abort(OSError("test error"), TraceLogger(...))
Personally I like to use a single level of indentation for arguments to functions. I have always found the ): and now ) -> ...: to be enough visual separation.
The parent to token section of the function doesn't seem to be using standard Python, so commenting is hard. However I don't think the code belongs in the function.
Why can't BasicLogger have a method to build and configure the TraceLogger?
I'm not sure what OnError looks like. However I imagine the class will look quite similar to LogAbortWhen and I'm concerned you have a lot of WET code and possibly some over engineering. | {
"domain": "codereview.stackexchange",
"id": 45166,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, error-handling",
"url": null
} |
python, python-3.x, error-handling
Overall I don't have too much to say at a 'micro' level. However at a more macro level I'm unsure why you don't add a context manager to LogAbortWhen.
@dataclasses.dataclass(frozen=True, slots=True)
class LogAbortWhen:
exceptions: tuple[type[BaseException], ...]
def log(self, exc: BaseException, logger: TraceLogger) -> bool:
logger.final.log_abort(message=f"Unable to complete due to <{type(exc).__name__}>: {str(exc) or '<N/A>'}")
def __call__(self, exc: BaseException, logger: TraceLogger) -> bool:
if isinstance(exc, self.exceptions):
self.log(exc, logger)
return True
return False
@contextlib.contextmanager
def handle_error(self, logger: TraceLogger) -> ContextManager[None]:
try:
yield None
except BaseException as e:
if isinstance(e, self.exceptions):
self.log(exc, logger)
raise
with LogAbortWhen((OSError,)).handle_error(TraceLogger(...)):
raise OSError("test error")
@contextlib.contextmanager
def telemetry_context(
activity: str,
source: Source,
on_error: Callable[[TraceLogger], ContextManager[Any]] = lambda t: contextlib.nullcontext(enter_result=None),
) -> ContextManager[TraceLogger]: # noqa
parent = current_logger.get()
logger = BasicLogger(activity)
tracer = TraceLogger(logger)
tracer.initial.source.append(source)
token = current_logger.set(Node(logger, parent))
try:
with on_error(tracer):
yield tracer
finally:
current_logger.reset(token)
with telemetry_context(..., on_error=LogAbortWhen((OSError,))) as tracer:
pass
Comparative Review
A classic LBYL/EAFP example is reading from a file.
# LBYL
if path.exists():
with open(path) as f:
data = f.read()
# EAFP
try:
f = open(path)
except OSError:
pass
else:
with f:
data = f.read() | {
"domain": "codereview.stackexchange",
"id": 45166,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, error-handling",
"url": null
} |
python, python-3.x, error-handling
# EAFP
try:
f = open(path)
except OSError:
pass
else:
with f:
data = f.read()
The difference is one calls path.exists first.
However, EAFP is better. The LBYL code has a race condition, if the file doesn't exist when path.exists() is called and is made before open(path) then we will need to handle an OSError.
The bug free version of LBYL is just EAFP with more code:
if path.exists():
try:
f = open(path)
except OSError:
pass
else:
with f:
data = f.read()
Now lets look at your code:
# LBYL
try:
yield tracer
except Exception as e: # noqa
if not on_error or not on_error(e, tracer):
tracer.final.log_error(message=f"Unhandled <{type(e).__name__}> has occurred: <{str(e) or 'N/A'}>")
raise
finally:
current_logger.reset(token)
# EAFP
try:
yield tracer
except Exception as e: # noqa
try:
on_error(e, tracer)
except TypeError | DoesNotApply:
tracer.final.log_error(message=f"Unhandled <{type(e).__name__}> has occurred: <{str(e) or 'N/A'}>")
raise
finally:
current_logger.reset(token)
Your EAFP is just LBYL but with more code.
So isn't a good use of EAFP. | {
"domain": "codereview.stackexchange",
"id": 45166,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, error-handling",
"url": null
} |
python, json
Title: parsing json file with potential corrupted record and sorting by id to output first n lines - cleaner logic
Question: messy json file is parsed and should output the N highest
record IDs & scores by score in descending order, highest score first.
the code works but i wonder if there is better readability, help me refactor it.
The function takes 2 args - the data file path and num of scores to return:
python myprogram.py highest score_recs.data 25
The input data file has a record per line. Each line has the following structure:
<score>: <json string>
If the line has a score that would make it part of the highest scores,
then the remainder of the line must be parsable as JSON, and
there must be an id key at the top level of this JSON doc.
An example data file could look like this:
10622876: {"umbrella": 99180, "name": "24490249af01e145437f2f64d5ddb9c04463c033", "value": 12354, "payload": "........", "date_stamp": 58874, "time": 615416, "id": "3c867674494e4a7aac9247a9d9a2179c"}
13214012: {"umbrella": 924902, "name": "70dd4d9494d1cd0362e123ce90f4053726b29e97", "value": 976852, "payload": "........", "date_stamp": 3255, "time": 156309, "id": "085a11e1b82b441184f4a193a3c9a13c"}
11446512: {"umbrella": 727371, "name": "8e21427b2350023079835361dce03cdea95a2983", "value": 70801, "payload": "........", "date_stamp": 1730, "time": 496866, "id": "84a0ccfec7d1475b8bfcae1945aea8f0"}
11025835: === THIS IS NOT JSON and should error
11269569: {"umbrella": 902167, "name": "e4898b9bf79831cf36811917a797ef0fcf3af636", "value": 593180, "payload": "........", "date_stamp": 58736, "time": 1014495, "id": "7ec85fe3aa3c4dd599e23111e7abf5c1"}
11027069: {"umbrella": 990975, "name": "8aa306fb59e275a7e39debb1d5113ff411df22ad", "value": 67842, "payload": "........", "date_stamp": 60161, "time": 225413, "id": "f812d487de244023a6a713e496a8427d"}
initially json file is not sorted by scores.
steps: | {
"domain": "codereview.stackexchange",
"id": 45167,
"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, json",
"url": null
} |
python, json
initially json file is not sorted by scores.
steps:
the bad json error is thrown only if there is bad record within the first minimum n unsorted lines,i.e. in the original json
otherwise, even if there is bad record but not within the first n unsorted lines i can keep all the records and parse it
sort it by scores in desc order, then keep the first n
output a list of dicts, each dict has 2 fields - score,id
For example, if run with an N of 3 and 4th entry is bad json, it still works and produce:
python myprogram highest score_recs.data 3
[
{
"score": 13214012,
"id": "085a11e1b82b441184f4a193a3c9a13c"
},
{
"score": 11446512,
"id": "84a0ccfec7d1475b8bfcae1945aea8f0"
},
{
"score": 11269569,
"id": "7ec85fe3aa3c4dd599e23111e7abf5c1"
}
]
But when run with an N that includes that line, it would error:
$ python myprogram highest score_recs.data 10
invalid json format No JSON object could be decoded
THIS IS NOT JSON | {
"domain": "codereview.stackexchange",
"id": 45167,
"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, json",
"url": null
} |
python, json
The scores are unique across the data
set * Scores can repeat, but you should only count the id of the last line processed
as the “winning” id. if score is not present it should give format error.
scores.data:
10622876: {"umbrella": 99180, "name": "24490249af01e145437f2f64d5ddb9c04463c033", "value": 12354, "payload": "........", "date_stamp": 58874, "time": 615416, "id": "3c867674494e4a7aac9247a9d9a2179c"}
13214012: {"umbrella": 924902, "name": "70dd4d9494d1cd0362e123ce90f4053726b29e97", "value": 976852, "payload": "........", "date_stamp": 3255, "time": 156309, "id": "085a11e1b82b441184f4a193a3c9a13c"}
11446512: {"umbrella": 727371, "name": "8e21427b2350023079835361dce03cdea95a2983", "value": 70801, "payload": "........", "date_stamp": 1730, "time": 496866, "id": "84a0ccfec7d1475b8bfcae1945aea8f0"}
11025835: === THIS IS NOT JSON and should error if this line is part of the result set, but is ok if it not ==
11269569: {"umbrella": 902167, "name": "e4898b9bf79831cf36811917a797ef0fcf3af636", "value": 593180, "payload": "........", "date_stamp": 58736, "time": 1014495, "id": "7ec85fe3aa3c4dd599e23111e7abf5c1"}
11027069: {"umbrella": 990975, "name": "8aa306fb59e275a7e39debb1d5113ff411df22ad", "value": 67842, "payload": "........", "date_stamp": 60161, "time": 225413, "id": "f812d487de244023a6a713e496a8427d"}
the python code:
import json
import sys
def main(filename, n):
res = []
main = dict()
cnt = 1
with open(filename, "r") as f:
for line in f:
id, content = line.split(":", 1)
try:
id = int(id)
except ValueError:
raise "Format error - no id" | {
"domain": "codereview.stackexchange",
"id": 45167,
"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, json",
"url": null
} |
python, json
if "IS NOT JSON" in content:
print("found bad json - check if we can continue")
if cnt <= n:
# here this means the original unsorted json file has bad json within the first needed n lines - so we need to throw error as per the condition
raise "ERROR: THIS IS NOT JSON"
else:
print("ah no, its good")
else:
try: # need try here cuz when json.loads() sees bad json - it will throw jsondecode error, that i need to catch
newd = json.loads(content)
main[id] = newd
cnt += 1
except:
print(
"keep pushing! that bad json is after the minimum n we need - so we need to record all jsons then sort then get the first n"
)
main = [[k, v] for k, v in main.items()]
main = sorted(main, reverse=True, key=lambda x: x[0])
#get the first sorted n items, create a dict [score][id]
main = dict(main[:n])
for k, v in main.items():
score = k
id = v["id"]
newd = dict()
newd["score"] = score
newd["id"] = id
res.append(newd)
return res
arg_list = (sys.argv)
filenamepath = str(arg_list[1])
num_lines = int(arg_list[2])
main(filenamepath, num_lines)
Answer: name your module
$ python myprogram.py ...
Yeah, that's not a name.
Maybe high_score_report.py ?
name your function
def main...
This is a terrific name for "first function that will execute".
But its body is entirely too long --
it contains all of your business logic.
If you retain the name main, then this function should
pretty much immediately delegate to better named code
whose name describes the logic.
don't rename
def main(filename, n):
res = []
main = dict() | {
"domain": "codereview.stackexchange",
"id": 45167,
"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, json",
"url": null
} |
python, json
main = dict()
Uggh! First main is a module-level function, then
we shadow that with a local variable.
No. Don't do that.
Pick a new name.
It doesn't matter to the machine,
but it does matter to the maintenance engineer
who is reading this code months down the road.
Especially if the engineer has a phone
conversation
about the code.
Similarly, further down in your code,
prefer an identifier of id_ rather than shadowing the builtin
id.
crack argv
arg_list = (sys.argv)
The extra ( ) parens are weird and distracting.
Please format with
black
to remove such artifacts.
Also, renaming the familiar sys.argv doesn't seem to help humans much.
use an if __name__ guard
arg_list = (sys.argv)
filenamepath = str(arg_list[1])
num_lines = int(arg_list[2])
main(filenamepath, num_lines)
This will run when other modules, such as your
unit tests,
import this module.
Use a guard to prevent such side effects.
Also this is too long, and not just because the str() is redundant.
Rewrite with slice + tuple unpack:
def main(filename, n):
...
if __name__ == "__main__":`
filenamepath, num_lines = sys.argv[1:]
main(filenamepath, int(num_lines))
Or better, add type annotation and let
typer
worry about cracking argv:
from pathlib import Path
import typer
def main(filename: Path, n: int):
...
if __name__ == "__main__":`
typer.run(main)
do one thing well
Each function should have a
single responsibility.
Here, you appear to be doing several things:
Identify well-formed lines that start with integer + colon.
Identify "bad JSON" lines, distinguishing between "late bad" and fatal "early bad".
Report on just the top-N entries. | {
"domain": "codereview.stackexchange",
"id": 45167,
"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, json",
"url": null
} |
python, json
In a bash script we might organize this as a multi-step pipeline
using the | pipe character.
In python it is often convenient to chain generators together.
So we might have:
from operator import itemgetter
...
def get_scored_content(self):
with open(self.filename) as f:
for line in f:
score, content = line.split(":", 1)
yield int(score), content
def get_json_ids(self):
for i, (score, content) in enumerate(self.get_scored_content()):
if i < self.n:
d = json.loads(content)
else:
try:
d = json.loads(content)
except json.decoder.JSONDecodeError:
continue
yield score, d["id"]
def get_top_entries(self):
return sorted(self.get_json_ids(), reverse=True, key=itemgetter(0))[:self.n]
Now a simple comprehension can easily turn
those N entries into the desired list of dicts.
Note the use of the common
itemgetter idiom.
use accurate identifiers
You wrote id when representing a score.
I renamed it in the above code.
display results
The OP code evaluates main for side effects
and discards its dict result.
You probably wanted to send the result
to stdout or to a file.
This module appears to achieve many of its design goals.
It has accumulated some technical debt and
would benefit from a bit of refactoring.
I would be reluctant to delegate maintenance tasks
on this codebase in its current form. | {
"domain": "codereview.stackexchange",
"id": 45167,
"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, json",
"url": null
} |
python, python-3.x, verilog, system-verilog
Title: ROM memory in SystemVerilog and cocotb
Question: The Verilog module describes a ROM memory. An initialization file is needed for the INIT_FILE parameter.
Below are Makefile, gtkwave.tcl to launch gtkwave, launch_tb.py (please use it to start simulation) and rom_tb.py as well as rom.sv.
Refer also to the cocotb home page.
rom.sv
module rom #
(
parameter integer DATA_WIDTH = 8,
parameter integer ADDR_WIDTH = 8,
parameter string INIT_FILE = ""
)
(
input logic clk_i,
input logic [ADDR_WIDTH - 1 : 0] addr_i,
output logic [ADDR_WIDTH - 1 : 0] data_o
);
localparam integer MEM_DEPTH = 2 ** ADDR_WIDTH;
logic [ADDR_WIDTH - 1 : 0] data;
logic [ADDR_WIDTH - 1 : 0] rom_mem [0 : MEM_DEPTH - 1];
initial
begin
if (INIT_FILE != "")
begin
$display("loading rom");
$readmemh(INIT_FILE, rom_mem);
end
else
begin
$error("init file is needed");
end
end
always_ff @ (posedge clk_i)
begin
data <= rom_mem[addr_i];
end
always_comb
begin
data_o = data;
end
initial begin
$dumpfile("dump.vcd");
$dumpvars(1, rom);
end
endmodule
Makefile
SIM?=icarus
TOPLEVEL_LANG?=verilog
WAVES?=0
COCOTB_HDL_TIMEUNIT=1ns
COCOTB_HDL_TIMEPRECISION=1ns
SRC_DIR=../../rtl
DUT=rom
TOPLEVEL=$(DUT)
MODULE=$(DUT)_tb
VERILOG_SOURCES+=$(SRC_DIR)/$(DUT).sv
DATA_WIDTH?=8
ADDR_WIDTH?=3
INIT_FILE?=$(shell pwd)/rom_init.txt
COMPILE_ARGS+=-P$(TOPLEVEL).DATA_WIDTH=$(DATA_WIDTH)
COMPILE_ARGS+=-P$(TOPLEVEL).ADDR_WIDTH=$(ADDR_WIDTH)
COMPILE_ARGS+=-P$(TOPLEVEL).INIT_FILE=$(INIT_FILE)
ifeq ($(WAVES), 1)
VERILOG_SOURCES+=iverilog_dump.v
COMPILE_ARGS+=-s iverilog_dump
else
GFLAGS=-S gtkwave.tcl
endif
include $(shell cocotb-config --makefiles)/Makefile.sim
all:
echo $(COMPILE_ARGS)
gtkwave $(GFLAGS) *.vcd 2>/dev/null || $(GTKWAVE_OSX) $(GFLAGS) *.vcd 2>/dev/null | {
"domain": "codereview.stackexchange",
"id": 45168,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, verilog, system-verilog",
"url": null
} |
python, python-3.x, verilog, system-verilog
iverilog_dump.v:
echo 'module iverilog_dump();' > $@
echo 'initial begin' >> $@
echo ' $$dumpfile("$(TOPLEVEL).fst");' >> $@
echo ' $$dumpvars(0, $(TOPLEVEL));' >> $@
echo 'end' >> $@
echo 'endmodule' >> $@
clean::
rm -rf *.vcd
rom_tb.py
#!/usr/bin/python
import random
import cocotb
from cocotb.clock import Clock
from cocotb.triggers import RisingEdge
class Rom_tb(object):
def __init__(self, dut):
self.dut = dut
cocotb.start_soon(Clock(self.dut.clk_i, 10, units="ns").start())
async def read_addr(self, addr):
self.dut.addr_i.value = addr
await RisingEdge(self.dut.clk_i)
await RisingEdge(self.dut.clk_i)
return self.dut.data_o.value
async def read_rand_addr(self, max_range):
rand_addr = random.randint(0, max_range)
cocotb.log.info(f"Random address: {rand_addr} Data: {await self.read_addr(rand_addr)}")
#todo: compare with file content
async def reading_whole_mem(self, max_range):
for addr in range(0, max_range):
cocotb.log.info(f"Address: {addr} Data: {await self.read_addr(addr)}")
@cocotb.test()
async def main(dut):
highest_addr = 8
max_rand_val = 7
cocotb.log.info("Start of simulation")
tb = Rom_tb(dut)
await tb.reading_whole_mem(highest_addr)
await tb.read_rand_addr(max_rand_val)
await tb.read_rand_addr(max_rand_val)
cocotb.log.info("End of simulation")
if __name__ == "__main__":
sys.exit(main())
gtkwave.tcl
set nfacs [ gtkwave::getNumFacs ]
set all_facs [list]
for {set i 0} {$i < $nfacs } {incr i} {
set facname [ gtkwave::getFacName $i ]
lappend all_facs "$facname"
}
set num_added [ gtkwave::addSignalsFromList $all_facs ]
puts "num signals added: $num_added"
# zoom full
gtkwave::/Time/Zoom/Zoom_Full
# Print
set dumpname [ gtkwave::getDumpFileName ]
gtkwave::/File/Print_To_File PDF {Letter (8.5" x 11")} Minimal $dumpname.pdf | {
"domain": "codereview.stackexchange",
"id": 45168,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, verilog, system-verilog",
"url": null
} |
python, python-3.x, verilog, system-verilog
launch_tb.py
#!/usr/bin/python
import subprocess
print("cleaning...")
subprocess.run(["make", "clean"])
print("launching the tb")
subprocess.run(["make"])
Answer: This review is limited to the SystemVerilog code (rom.sv).
You declared the DATA_WIDTH parameter, but your code does not use it. I assume you really want to use it for the declarations of the data and memory variables. You probably didn't notice since you assigned the WIDTH parameters to the same value (8).
Otherwise, the code is easy to understand, uses descriptive variable names and makes good use of parameters for constant values.
As far as the code layout goes, I prefer to make better use of vertical space by having the begin and end keywords "cuddled" on lines with other meaningful code, as you did with one of your initial blocks. I also prefer 4 singles spaces for indentation over 2.
module rom #
(
parameter integer DATA_WIDTH = 8,
parameter integer ADDR_WIDTH = 8,
parameter string INIT_FILE = ""
)
(
input logic clk_i,
input logic [ADDR_WIDTH - 1 : 0] addr_i,
output logic [DATA_WIDTH - 1 : 0] data_o
);
localparam integer MEM_DEPTH = 2 ** ADDR_WIDTH;
logic [DATA_WIDTH - 1 : 0] data;
logic [DATA_WIDTH - 1 : 0] rom_mem [0 : MEM_DEPTH - 1];
initial begin
if (INIT_FILE != "") begin
$display("loading rom");
$readmemh(INIT_FILE, rom_mem);
end else begin
$error("init file is needed");
end
end
always_ff @ (posedge clk_i) begin
data <= rom_mem[addr_i];
end
always_comb begin
data_o = data;
end
initial begin
$dumpfile("dump.vcd");
$dumpvars(1, rom);
end
endmodule | {
"domain": "codereview.stackexchange",
"id": 45168,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, verilog, system-verilog",
"url": null
} |
c, memory-management
Title: malloc() and free() implementation
Question: I'm looking for a code review of my custom memory allocation library (written for educational purposes), which includes malloc(), calloc(), realloc(), and free() functions.
Review Goals:
Does the code ensure that the pointers returned by *alloc() are properly aligned for all types, as required by C standards, to avoid potential undefined behavior?
Does any part of my code invokes undefined behavior?
General coding comments, style, etc.
Code:
liballoc.h:
#ifndef LIBALLOC_H
#define LIBALLOC_H
/**
* \brief The **malloc** function allocates space for an object whose size is specified by *size*
* and whose value is indeterminate.
* \param size - The size of the object to be allocated.
* \return The **malloc** function returns either a null pointer or a pointer to the allocated
* space. If the size of the space requested is zero, a null pointer is returned.
*/
void *malloc(size_t size);
/**
* \brief The **calloc** function allocates space for an array of *nmemb* objects, each of whose size
* is *size*. The space is initialized to all bits zero.
* \param nmemb - The number of objects.
* \param size - The size of each object.
* \return The **calloc** function returns either a null pointer or a pointer to the allocated space.
* If the size of the space requested is zero, a null pointer is returned.
*/
void *calloc(size_t nmemb, size_t size); | {
"domain": "codereview.stackexchange",
"id": 45169,
"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",
"url": null
} |
c, memory-management
/**
* \brief The **realloc** function deallocates the old object pointed to by *ptr* and returns a pointer to
* a new object that has the size specified by *size*. The contents of the new object shall be
* the same as that of the old object prior to deallocation, upto the lesser of the new and
* old sizes. Any bytes in the new object beyond the size of the old object have indeterminate
* values.
*
* If *ptr* is a null pointer,the **realloc** function behaves like the **malloc** function for the specified *size*.
* Otherwise, if *ptr* does not match a pointer earlier returned by a memory management function, or if the
* space has been deallocated by a call to the **free** or **realloc** function, the behavior is undefined.
* If *size* is nonzero and memory for the new object is not allocated, the old object is not deallocated.
* If *size* is zero and memory for the new object is not allocated, the old object is not deallocated,
* and its value shall be unchanged.
*
* \param ptr - A pointer to the object to be reallocated.
* \param size - The new size.
* \return The **realloc** function returns a pointer to the new object, or a null pointer if the new object
* if the new object has not been allocated.
*
*/
void *realloc(void *ptr, size_t size);
/**
* \brief The **free** function causes the space pointed to by *ptr* to be deallocated, that is, made
* unavailable for further allocation. If *ptr* is a null pointer, no action occurs. Otherwise,
* if the argument does not match a pointer earlier returned by a memory management function,
* or if the space has been deallocated by a call to **free**, the behaviour is undefined.
* \param ptr - A pointer to the object to be deallocated.
* \return The **free** function returns no value.
*/
void free(void *ptr); | {
"domain": "codereview.stackexchange",
"id": 45169,
"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",
"url": null
} |
c, memory-management
#endif /* LIBALLOC_H */
liballoc.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
#define _DEFAULT_SOURCE
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdalign.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include "liballoc.h"
#define MALLOC_LOCK() (pthread_mutex_lock (&global_malloc_lock))
#define MALLOC_UNLOCK() (pthread_mutex_unlock (&global_malloc_lock))
#define CHUNK_SIZE(chunk) ((chunk)->size)
#define NEXT_CHUNK(chunk) ((chunk)->next)
#define IS_CHUNK_FREE(chunk) ((chunk)->is_free)
#define MARK_CHUNK_FREE(chunk) ((chunk)->is_free = true)
#define MARK_CHUNK_NONFREE(chunk) ((chunk)->is_free = false)
#define SET_CHUNK_SIZE(chunk, size) ((chunk)->size = (size))
#define SET_NEXT_CHUNK(chunk, val) ((chunk)->next = (val))
#define SBRK_FAILED ((void *) -1)
/* The C Standard states that the pointer returned if the allocation succeeds is
* suitably aligned so that it may be assigned to a pointer to any type of object
* with a fundamental alignment requirement.
*/
typedef struct header {
_Alignas (max_align_t) struct header *next;
size_t size;
bool is_free;
} header_t;
static header_t *head, *tail;
static pthread_mutex_t global_malloc_lock;
static header_t *get_free_block(size_t size)
{
/* Ascertain if there's a free block that can accommodate requested size. */
for (header_t * curr = head; curr; curr = NEXT_CHUNK(curr)) {
if (IS_CHUNK_FREE(curr) && CHUNK_SIZE(curr) >= size) {
return curr;
}
}
return NULL;
} | {
"domain": "codereview.stackexchange",
"id": 45169,
"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",
"url": null
} |
c, memory-management
void *malloc(size_t size)
{
/* The C Standard states that if the size of the space requested is zero,
* the behavior is implementation-defined: either a null pointer is returned
* to indicate an error, or the behavior is as if the size were some non zero
* value, except that the returned pointer shall not be used to access an object.
* We shall opt for the former.
*/
if (!size || size > SIZE_MAX - sizeof (header_t)) { /* Prevent overflow. */
return NULL;
}
MALLOC_LOCK();
header_t *header = get_free_block(size);
if (header) {
/* We have an apt free block. */
MARK_CHUNK_NONFREE(header);
MALLOC_UNLOCK();
return header + 1;
}
/* The size requested needs to be a multiple of alignof (max_align_t). */
size_t const padding = size % alignof (max_align_t);
if (padding) {
size += alignof (max_align_t) - padding;
}
intptr_t const total_size = (intptr_t) (sizeof (header_t) + size);
void *const chunk = sbrk(total_size);
if (chunk == SBRK_FAILED) {
MALLOC_UNLOCK();
return NULL;
}
header = chunk;
SET_CHUNK_SIZE(header, size);
MARK_CHUNK_NONFREE(header);
SET_NEXT_CHUNK(header, NULL);
if (!head) {
head = header;
}
if (tail) {
SET_NEXT_CHUNK(tail, header);
}
tail = header;
MALLOC_UNLOCK();
return header + 1;
}
void *calloc(size_t nmemb, size_t size)
{
if (!nmemb || !size) {
return NULL;
}
if (size < SIZE_MAX / nmemb) { /* Allocation too big. */
return NULL;
}
size *= nmemb;
void *const chunk = malloc(size);
if (!chunk) {
return NULL;
}
return memset(chunk, 0X00, size);
}
void *realloc(void *ptr, size_t size)
{
if (!ptr || !size) {
return malloc(size);
}
const header_t *const header = (header_t *) ptr - 1;
if (CHUNK_SIZE(header) >= size) {
return ptr;
} | {
"domain": "codereview.stackexchange",
"id": 45169,
"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",
"url": null
} |
c, memory-management
if (CHUNK_SIZE(header) >= size) {
return ptr;
}
void *const ret = malloc(size);
if (ret) {
/* Relocate the contents to the new chunkier chunk and
* free the old chunk.
*/
memcpy(ret, ptr, CHUNK_SIZE(header));
free(ptr);
}
return ret;
}
void free(void *ptr)
{
if (!ptr) {
return;
}
MALLOC_LOCK();
header_t *const header = (header_t *) ptr - 1;
/* Get a pointer to the current program break address.
*/
const void *const prog_brk = sbrk(0);
/* Ascertain whether the block to be freed is the last one in the
* list. If so, shrink the size of the heap and release the memory
* to the OS. Else, keep the block but mark it as free for use.
*/
if ((char *) ptr + CHUNK_SIZE(header) == prog_brk) {
if (head == tail) {
head = tail = NULL;
} else {
for (header_t * tmp = head; tmp; tmp = NEXT_CHUNK(tmp)) {
SET_NEXT_CHUNK(tmp, NULL);
tail = tmp;
}
}
/* sbrk() with a negative argument decrements the program break,
* which releases memory the memory back to the OS.
*/
sbrk((intptr_t) (0 - sizeof (header_t) - CHUNK_SIZE(header)));
/* This lock does not ensure thread-safety, for sbrk() itself
* is not thread-safe.
*/
MALLOC_UNLOCK();
return;
}
MARK_CHUNK_FREE(header);
MALLOC_UNLOCK();
}
makefile:
CFLAGS := -s
CFLAGS += -std=c2x
CFLAGS += -no-pie
#CFLAGS += -g3
#CFLAGS += -ggdb
CFLAGS += -Wall
CFLAGS += -Wextra
CFLAGS += -Warray-bounds
CFLAGS += -Wconversion
CFLAGS += -Wmissing-braces
CFLAGS += -Wno-parentheses
CFLAGS += -Wno-format-truncation
CFLAGS += -Wpedantic
CFLAGS += -Wstrict-prototypes
CFLAGS += -Wwrite-strings
CFLAGS += -Winline
CFLAGS += -O2 | {
"domain": "codereview.stackexchange",
"id": 45169,
"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",
"url": null
} |
c, memory-management
NAME := liballoc_$(shell uname -m)-$(shell uname -s)
LIBDIR := bin
SLIB := $(LIBDIR)/$(NAME).a
DLIB := $(LIBDIR)/$(NAME).so
SRCS := $(wildcard src/*.c)
OBJS := $(patsubst src/%.c, obj/%.o, $(SRCS))
all: $(SLIB) $(DLIB)
$(SLIB): $(OBJS)
$(AR) $(ARFLAGS) $@ $^
$(DLIB): $(OBJS)
$(CC) $(CFLAGS) -fPIC -shared $(SRCS) -o $@
obj/%.o: src/%.c
$(CC) $(CFLAGS) -c $< -o $@
clean:
$(RM) -rf $(OBJS)
fclean:
$(RM) $(SLIB) $(DLIB)
.PHONY: fclean clean all
.DELETE_ON_ERROR:
Answer: Documentation:
Be more definite in your descriptions. Does the null pointer returned on requesting zero bytes indicate a failure?
In that case, shorter and unambiguous: "Returns a pointer to the allocated space or a null pointer on failure. Requesting zero bytes always fails."
In the other case, consider this: "Returns a pointer to the allocated space or a null pointer. Requesting zero bytes always succeeds with a null pointer."
Admittedly, that only really gets important when we get to realloc, but it should be consistent throughout:
"If *size* is zero and memory for the new object is not allocated, the old object is not deallocated, and its value shall be unchanged."
What? Can we allocate zero bytes? Can/Will that result in a null pointer? Will that indicate success, failure, or Schrödinger?
Also, can shrinking fail? Will it ever free memory?
As the documentation should stand alone, I have ignored the implementation to this point.
Tests
Are very much missing.
No wonder the next section has big items.
Implementation bug:
You are off by the padding in your implementation of malloc(). size <= SIZE_MAX - sizeof(header_t) still allows size + padding > SIZE_MAX - sizeof(header_t), causing you to pass 0 to sbrk() and assume it got SIZE_MAX + 1 bytes, though the function just returned the current value.
Did you try out calloc?
Your second check goes in the wrong direction.
Implementation: | {
"domain": "codereview.stackexchange",
"id": 45169,
"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",
"url": null
} |
c, memory-management
Did you try out calloc?
Your second check goes in the wrong direction.
Implementation:
Using macros for the locking allows easy removal of same, so can be justified.
It allows for easy adoption of the same algorithm for single-threaded and low-contention multi-threaded use.
The rest of those macros, used for operations on chunks, just obscure the code though. Best to get rid of the lot.
Point of fact, I gave up digging into free and thus overlooked another bug Toby Speight found.
Consider mmap for private anonymous pages (and mremap for realloc) instead of brk for additional memory. It's the modern approach for good reason, namely playing nicely with ASLR, and still working if there is something in the way of a straight expansion.
Admittedly, as it works with page-size granularity, it makes invest ing into splitting and coalescing blocks that much more urgent.
If you free the last chunk requested from the OS you haven't yet returned, you return it. But all the free chunks next to it will be kept...
Consider a uniform limit on the line length, preferably equal to the customary 80.
Vertical scrolling is bad enough for comprehension, but horizontal scrolling is orders of magnitude worse.
The makefile already conforms, the implementation file is wrapped just above, but the header file is wrapped significantly later... | {
"domain": "codereview.stackexchange",
"id": 45169,
"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",
"url": null
} |
c, wordle
Title: Wordle50 - A Command-Line Word Game
Question: "Wordle50" is a command-line-based adaptation of the popular Wordle daily word game. In this word-guessing game, players aim to decipher a randomly selected word with lengths varying from 5 to 8 characters, drawn from a predefined word list (text files). They are granted one extra guess compared to the length of the target word.
The program provides feedback using color-coded responses - green for correctly placed letters, yellow for correctly identified but misplaced letters, and red for entirely incorrect letters (the original game uses grey for entirely incorrect letters). Players continue their attempts until they accurately reveal the word or exhaust their permitted tries.
Review Goals:
General coding comments, style, potential undefined behavior, et cetera.
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
/* Each of our text files contains 1000 words. */
#define LIST_SIZE 1000
#define FNAME_SIZE 6
#define PROMPT_SIZE 128
#define MAX_WORD_LENGTH 8
#define MIN_WORD_LENGTH 5
#define EXACT 2 /* Right letter; right place. */
#define CLOSE 1 /* Right letter; wrong place. */
#define WRONG 0 /* Wrong letter. */
/* ANSI color codes for boxed in letters.*/
#define GREEN "\e[38;2;255;255;255;1m\e[48;2;106;170;100;1m"
#define YELLOW "\e[38;2;255;255;255;1m\e[48;2;201;180;88;1m"
#define RED "\e[38;2;255;255;255;1m\e[48;2;220;20;60;1m"
#define RESET "\e[0;39m"
static char *get_guess(size_t wlen)
{
char *guess = NULL;
size_t glen = 0;
ssize_t rc = 0;
char prompt[PROMPT_SIZE];
snprintf(prompt, PROMPT_SIZE, "Input a %zu-letter word: ", wlen);
do {
fputs(prompt, stdout);
rc = getline(&guess, &glen, stdin);
if (rc == -1) {
break;
}
guess[strcspn(guess, "\n")] = '\0';
} while (strlen(guess) != wlen); | {
"domain": "codereview.stackexchange",
"id": 45170,
"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, wordle",
"url": null
} |
c, wordle
guess[strcspn(guess, "\n")] = '\0';
} while (strlen(guess) != wlen);
return guess;
}
static bool guess_exists(const char *restrict guess, size_t lsize, size_t wlen, const char list[lsize][wlen])
{
for (size_t i = 0; i < lsize ; ++i) {
if (!strcasecmp(guess, list[i])) {
return true;
}
}
return false;
}
static size_t sum_array(size_t size, const size_t arr[size])
{
size_t sum = 0;
for (size_t i = 0; i < size; ++i) {
sum += arr[i];
}
return sum;
}
static size_t calculate_word_score(const char *restrict guess, size_t *restrict status,
const char *restrict choice)
{
size_t i;
for (i = 0; guess[i]; ++i) {
for (size_t j = 0; choice[j]; ++j) {
if (choice[j] == guess[i]) {
if (i == j) {
status[i] = EXACT;
} else if (status[i] != EXACT) {
status[i] = CLOSE;
}
}
}
}
return sum_array(i, status);
}
static void print_word(const char *restrict guess, size_t wlen,
const size_t *restrict status)
{
for (size_t i = 0; i < wlen; ++i) {
switch (status[i]) {
case EXACT:
printf(GREEN "%c" RESET, guess[i]);
break;
case CLOSE:
printf(YELLOW "%c" RESET, guess[i]);
break;
default:
printf(RED "%c" RESET, guess[i]);
break;
}
}
putchar('\n');
}
static inline bool validate_wlen(size_t wlen)
{
return wlen >= MIN_WORD_LENGTH && wlen <= MAX_WORD_LENGTH;
}
static bool run_game(size_t lsize, size_t wlen, const char options[lsize][wlen + 1], const char *restrict choice)
{
/* Allow one more guess than the length of the word. */
const size_t guesses = wlen + 1;
bool won = false; | {
"domain": "codereview.stackexchange",
"id": 45170,
"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, wordle",
"url": null
} |
c, wordle
printf(GREEN "This is WORDLE50" RESET "\n"
"You have %zu tries to guess the %zu-letter word I'm thinking of\n",
guesses, wlen);
for (size_t i = 0; i < guesses; ++i) {
char *guess = get_guess(wlen);
/* Check if guess is in the list. */
while (!guess_exists(guess, LIST_SIZE, wlen + 1, options)) {
puts("The word is not in list.");
free(guess);
guess = get_guess(wlen);
}
/* Array to hold guess status. */
size_t status[wlen];
/* Set all elements of status array initially to 0, aka WRONG. */
for (size_t i = 0; i < wlen; ++i) {
status[i] = 0;
}
size_t score = calculate_word_score(guess, status, choice);
printf("Guess %zu: ", i + 1);
print_word(guess, wlen, status);
free(guess);
/* If they guessed it exactly right, set terminate loop. */
if (score == EXACT * wlen) {
won = true;
break;
}
}
return won;
}
int main(int argc, char **argv)
{
if (argc != 2 || !validate_wlen(strtol(argv[1], NULL, 10))) {
fprintf(stderr, "Usage: %s <k> (5-8)\n", argv[0]);
return EXIT_FAILURE;
}
/* Open correct file, each file has exactly LIST_SIZE words. */
const size_t wlen = (size_t) strtol(argv[1], NULL, 10);
char wl_filename[FNAME_SIZE];
snprintf(wl_filename, FNAME_SIZE, "%zu.txt", wlen);
FILE *const wlist = fopen(wl_filename, "r");
if (!wlist) {
perror("fopen()");
return EXIT_FAILURE;
}
/* Load word file into an array of size LIST_SIZE. */
char options[LIST_SIZE][wlen + 1];
for (size_t i = 0; i < LIST_SIZE; ++i) {
fscanf(wlist, "%s", options[i]);
}
/* Pseudorandomly select a word for this game. */
srand(time(NULL));
const char *const choice = options[rand() % LIST_SIZE]; | {
"domain": "codereview.stackexchange",
"id": 45170,
"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, wordle",
"url": null
} |
c, wordle
run_game(LIST_SIZE, wlen, options, choice) ? puts("You won!") : printf("The target word was: %s\n", choice);
fclose(wlist);
return EXIT_SUCCESS;
}
To build the game:
Clone this repository: Wordle50
cd into the repository.
Run:
make wordle50
Answer: Lack of comments
At least <"Wordle50" is a command-line-based adaptation of ... the target word> deserves to be a code comment, perhaps as part of a command line option "-help".
Longer functions deserve a line or two describing the function goal.
Non-standard code
\e --> \033
getline(), strcasecmp(), ssize_t are not part of the C standard as of C17.
Data validation
I'd expect get_guess() to validate characters read, perhaps to letters.
Correct file?
fscanf(wlist, "%s", options[i]); stands on shaky ground as 1) return value not checked. 2) string size read may exceed options[i] size 3) if file longer than expected, no notice given.
I'd expect the number of words to be driven by the file and not a program constant here.
Consider a command line option to select the files' directory.
More informative prompt
When while (strlen(guess) != wlen) is true, consider a prompt to inform user of the invalidity of input.
Better random initialization
srand(time(NULL)); initializes to the same state if called in the same second as time_t usually has second resolution. Consider xor'ing in other to differentiate if code called multiple times in the same second - which may happen in automated usage.
// srand(time(NULL))
unsigned r = (unsigned) (time(NULL) ^ getpid_or_the_like());
srand(r); | {
"domain": "codereview.stackexchange",
"id": 45170,
"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, wordle",
"url": null
} |
c, wordle
For testing purposes, consider a command line option to override and assign r.
Close when done
fclose(wlist); deserves to be right after the for (size_t i = 0; i < LIST_SIZE; ++i) loop. No need to leave open while running the game.
Avoid magic numbers
As is, code has to update LIST_SIZE and a comment should a value other than 1000 get used.
// From
/* Each of our text files contains 1000 words. */
// To
/* Each of our text files contains LIST_SIZE words. */
Auto format
Code looks manually formatted ( I could be wrong on this). Better to auto-format. Manually formatting is not productive.
IMO, the code width used is too great.
Define more locally
// size_t i;
// for (i = 0; guess[i]; ++i) {
for (size_t i = 0; guess[i]; ++i) {
// ssize_t rc = 0;
// ...
// rc = getline(&guess, &glen, stdin);
ssize_t rc = getline(&guess, &glen, stdin);
Pedantic: No NULL check
Code that calls get_guess() never checks for NULL. Perhaps exit code in get_guess() should allocation fail.
Pedantic: Check argc
argv[0] == NULL is possible.
// NULL?
fprintf(stderr, "Usage: %s <k> (5-8)\n", argv[0]);
Pedantic: Look for out of range input before changing due to type
validate_wlen(size_t wlen) --> validate_wlen(long wlen) as that is the type strtol() returns.
Minor: Unneeded restrict
Even if guess and status overlap, it is not a concern here as data is only read.
// static void print_word(const char *restrict guess, size_t wlen,
// const size_t *restrict status)
static void print_word(const char *guess, size_t wlen, const size_t *status)
With the restrict, code may optimize a tad better, but I do not see its value here.
Minor: Unnecessary dependence on Variable Length Array (VLA) support
VLA support is optional in C11 onward.
char options[LIST_SIZE][wlen + 1]; requires VLA support. Consider
char options[LIST_SIZE][MAX_WORD_LENGTH + 1];
... and size_t status[wlen]; --> size_t status[MAX_WORD_LENGTH + 1]; | {
"domain": "codereview.stackexchange",
"id": 45170,
"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, wordle",
"url": null
} |
beginner, c, array, linked-list
Title: Linked list and array list performance comparison in C
Question: After watching Stroustrup's presentation on performance comparison between vectors and linked lists (https://youtu.be/YQs6IC-vgmo?si=9r5wXqnwkmN29xqn), I've decided it would be a good problem to get a hang of C. To that end, I've profiled how long gthe removal of all elements from the lists by sampling random indices takes. It's a toy problem, and I did not want to go for a doubly linked list immediately, just PoC implementation using fixed data types in nodes and a single linked list. I'm aware the implementations can be optimized, but first I wanted to make sure I'm not doing any terrible practices.
What I'm looking for is mostly design review, specifically:
Is this a proper way to design multiple implementations of a single interface?
removed
If there are obvious bugs or "it works, but please don't do it that way" things, please point them out.
Thank you to anyone who takes the time to check this out. A side note, the tester.c and tester.h were taken from https://codeahoy.com/learn/cprogramming/ch46/ so I will not be including them for review (but a big thanks to the authors, it's a really cool tool!).
profile_list.c
#include "lists/list.h"
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <stdio.h>
#define N_ELEMS 100000
#define TO_REMOVE 100000
void test_list(List list)
{
clock_t start = clock();
for (int i = 0; i < TO_REMOVE; i++)
{
usize next_index = rand() % List_length(list);
List_success res = List_remove_index(list, next_index);
assert(res != List_ERROR);
}
clock_t end = clock();
printf("Remove time: %ld\n", end - start);
}
int main(int argc, char const *argv[])
{
srand(time(NULL));
List list = List_init();
for (int i = 0; i < N_ELEMS; i++)
{
List_append(list, i);
}
test_list(list);
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, linked-list",
"url": null
} |
beginner, c, array, linked-list
lists/list.h
#ifndef C4E61219_04C6_41E9_87A7_649125E1083C
#define C4E61219_04C6_41E9_87A7_649125E1083C
#include <stddef.h>
#include <stdint.h>
typedef int32_t i32;
typedef size_t usize;
typedef struct List *List;
typedef enum
{
List_ERROR,
List_OK
} List_success;
typedef struct List_result
{
List_success success;
i32 data;
} List_result;
List List_init(void);
void List_delete(List *list);
void List_append(List list, i32 data);
List_success List_insert(List list, i32 data, usize position);
List_success List_remove_val(List list, i32 val);
List_success List_remove_index(List list, usize position);
List_result List_get(List list, usize position);
void List_print(List list);
usize List_length(List list);
#endif /* C4E61219_04C6_41E9_87A7_649125E1083C */
lists/linked_list.c
#include "list.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
typedef struct Node *Node;
Node make_node(i32 data, Node next);
void delete_node(Node *node);
struct List
{
Node head;
usize size;
};
struct Node
{
i32 data;
Node next;
};
Node make_node(i32 data, Node next)
{
Node node = malloc(sizeof(Node));
if (node == NULL)
{
fprintf(stderr, "Failed to allocate memory for node!\n");
exit(EXIT_FAILURE);
}
node->data = data;
node->next = next;
return node;
}
void delete_node(Node *node)
{
free(*node);
*node = NULL;
}
List List_init(void)
{
List list = malloc(sizeof(List));
if (list == NULL)
{
fprintf(stderr, "Failed to allocate memory for list!\n");
exit(EXIT_FAILURE);
}
list->head = NULL;
list->size = 0;
return list;
}
void List_delete(List *list_pointer)
{
List list = *list_pointer;
while (list->head != NULL)
{
Node current_node = list->head;
list->head = current_node->next;
delete_node(¤t_node);
}
free(list);
*list_pointer = NULL;
} | {
"domain": "codereview.stackexchange",
"id": 45171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, linked-list",
"url": null
} |
beginner, c, array, linked-list
void List_append(List list, i32 data)
{
Node node = make_node(data, NULL);
list->size += 1;
if (list->head == NULL)
{
list->head = node;
return;
}
Node current_node = list->head;
while (current_node->next != NULL)
{
current_node = current_node->next;
}
current_node->next = node;
}
List_success List_insert(List list, i32 data, usize index)
{
if (index >= list->size || index < 0)
{
return List_ERROR;
}
list->size += 1;
Node node = make_node(data, NULL);
Node current_node = list->head;
if (index == 0)
{
node->next = current_node;
list->head = node;
return List_OK;
}
while (index > 1) /*Stop at the element just before the position!*/
{
current_node = current_node->next;
index -= 1;
}
node->next = current_node->next;
current_node->next = node;
return List_OK;
}
List_success List_remove_val(List list, i32 val)
{
if (val == list->head->data)
{
Node to_delete = list->head;
list->head = list->head->next;
delete_node(&to_delete);
list->size -= 1;
return List_OK;
}
for (Node curr = list->head; curr->next != NULL; curr = curr->next)
{
if (curr->next->data == val)
{
Node to_delete = curr->next;
curr->next = curr->next->next;
delete_node(&to_delete);
list->size -= 1;
return List_OK;
}
}
return List_ERROR;
}
List_success List_remove_index(List list, usize index)
{
if (index >= list->size || index < 0)
{
return List_ERROR;
}
list->size -= 1;
if (index == 0)
{
Node to_delete = list->head;
list->head = list->head->next;
delete_node(&to_delete);
return List_OK;
} | {
"domain": "codereview.stackexchange",
"id": 45171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, linked-list",
"url": null
} |
beginner, c, array, linked-list
Node current_node = list->head;
while (index > 1)
{
index -= 1;
current_node = current_node->next;
}
Node to_delete = current_node->next;
current_node->next = to_delete->next;
delete_node(&to_delete);
return List_OK;
}
List_result List_get(List list, usize index)
{
List_result res;
if (index >= list->size || index < 0)
{
res.success = List_ERROR;
}
else
{
res.success = List_OK;
Node current_node = list->head;
while (index > 0)
{
index -= 1;
current_node = current_node->next;
}
res.data = current_node->data;
}
return res;
}
void List_print(List list)
{
printf("[");
Node curr_node = list->head;
while (curr_node != NULL)
{
printf("%d, ", curr_node->data);
curr_node = curr_node->next;
}
printf("]\n");
}
usize List_length(List list)
{
return list->size;
}
lists/array_list.c
#include "list.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct List
{
i32 *elements;
usize size;
usize capacity;
};
List List_init(void)
{
List list = malloc(sizeof(List));
if (list == NULL)
{
fprintf(stderr, "Failed to allocate memory for list!\n");
exit(EXIT_FAILURE);
}
list->elements = NULL;
list->size = 0;
list->capacity = 0;
return list;
}
void List_delete(List *list)
{
free((*list)->elements);
(*list)->elements = NULL;
free(*list);
*list = NULL;
}
static inline usize _closest_power_of_2(usize val)
{
usize p = 1;
while (p < val)
{
p = p << 1;
}
return p;
}
void _resize_if_needed(List list, usize newsize)
{
if (newsize == 0)
{
free(list->elements);
list->elements = NULL;
list->capacity = 0;
return;
}
usize blocksize = _closest_power_of_2(newsize);
usize new_capacity = blocksize * sizeof(i32); | {
"domain": "codereview.stackexchange",
"id": 45171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, linked-list",
"url": null
} |
beginner, c, array, linked-list
if (new_capacity == list->capacity)
{
return;
}
if (list->elements == NULL)
{
list->elements = malloc(new_capacity);
if (list->elements == NULL)
{
fprintf(stderr, "Failed to allocate memory for list elements of %zu!\n", new_capacity);
exit(EXIT_FAILURE);
}
list->capacity = new_capacity;
}
else
{
void *tmp = realloc(list->elements, new_capacity);
if (tmp != NULL)
{
list->elements = tmp;
}
else
{
fprintf(stderr, "Failed to allocate memory for list elements of %zu!\n", new_capacity);
exit(EXIT_FAILURE);
}
}
}
void List_append(List list, i32 data)
{
_resize_if_needed(list, list->size + 1);
list->elements[list->size] = data;
list->size += 1;
}
List_success List_insert(List list, i32 data, usize position)
{
if (position < 0 || position >= list->size)
{
return List_ERROR;
}
_resize_if_needed(list, list->size + 1);
for (usize i = list->size; i > position; i--)
{
list->elements[i] = list->elements[i - 1];
}
list->elements[position] = data;
list->size += 1;
return List_OK;
}
List_success List_remove_val(List list, i32 val)
{
for (usize i = 0; i < list->size; i++)
{
if (list->elements[i] == val)
{
List_remove_index(list, i);
return List_OK;
}
}
return List_ERROR;
}
List_success List_remove_index(List list, usize position)
{
if (position < 0 || position >= list->size)
{
return List_ERROR;
}
for (usize i = position; i < list->size - 1; i++)
{
list->elements[i] = list->elements[i + 1];
}
_resize_if_needed(list, list->size - 1);
list->size -= 1;
return List_OK;
} | {
"domain": "codereview.stackexchange",
"id": 45171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, linked-list",
"url": null
} |
beginner, c, array, linked-list
_resize_if_needed(list, list->size - 1);
list->size -= 1;
return List_OK;
}
List_result List_get(List list, usize position)
{
List_result res = {0};
if (position < 0 || position >= list->size)
{
res.success = List_ERROR;
}
else
{
res.data = list->elements[position];
res.success = List_OK;
}
return res;
}
void List_print(List list)
{
printf("[");
for (int i = 0; i < list->size; i++)
{
printf("%d, ", list->elements[i]);
}
printf("]\n");
}
usize List_length(List list)
{
return list->size;
}
test/test_list.c
/*
Includes required for tester.h to work.
*/
#include <stdio.h>
#include <setjmp.h>
#include <signal.h>
#include <unistd.h>
#include "../lists/list.h"
#include "tester.h"
int main(int argc, char const *argv[])
{
List list = List_init();
List_success res;
usize currsize;
/* Test initialize empty list */
TEST_ASSERT(List_length(list) == 0);
List_append(list, 5);
List_append(list, 15);
List_append(list, 200);
/* Test List_append increased List_length */
TEST_ASSERT(List_length(list) == 3);
/* Test List_get zeroth index */
TEST_ASSERT(List_get(list, 0).data == 5);
/* Test List_get non-zero index */
TEST_ASSERT(List_get(list, 1).data == 15);
/* Test List_get non-existent index */
TEST_ASSERT(List_get(list, 15).success == List_ERROR);
/* Test List_insert on the zeroth position */
res = List_insert(list, -1, 0);
TEST_ASSERT(res == List_OK && List_get(list, 0).data == -1);
/* Test List_insert on non-zero position */
res = List_insert(list, -256, 2);
TEST_ASSERT(res == List_OK && List_get(list, 2).data == -256);
/* Test List_insert on non-existing position */
res = List_insert(list, 800, 19);
TEST_ASSERT(res == List_ERROR); | {
"domain": "codereview.stackexchange",
"id": 45171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, linked-list",
"url": null
} |
beginner, c, array, linked-list
/* Test remove value at zeroth position */
currsize = List_length(list);
res = List_remove_val(list, -1);
TEST_ASSERT(res == List_OK && List_length(list) == currsize - 1);
/* Test remove value at non-zeroth position */
currsize = List_length(list);
res = List_remove_val(list, 15);
TEST_ASSERT(res == List_OK && List_length(list) == currsize - 1);
/* Test remove trying to remove non-existent value */
currsize = List_length(list);
res = List_remove_val(list, 15);
TEST_ASSERT(res == List_ERROR && List_length(list) == currsize);
/* Test remove some index */
currsize = List_length(list);
res = List_remove_index(list, 1);
TEST_ASSERT(res == List_OK && List_length(list) == currsize - 1);
/* Test remove zeroth index */
currsize = List_length(list);
res = List_remove_index(list, 0);
TEST_ASSERT(res == List_OK && List_length(list) == currsize - 1);
/* Test remove non-existent index */
currsize = List_length(list);
res = List_remove_index(list, 19);
TEST_ASSERT(res == List_ERROR && List_length(list) == currsize);
/* Test delete list */
List_delete(&list);
TEST_ASSERT(list == NULL);
return 0;
}
Makefile
CC=gcc
CFLAGS=-g3 -Wall
all:
test: test_linked_list.out test_array_list.out
./test_linked_list.out
./test_array_list.out
@echo OK!
test_linked_list.out: test/test_list.o test/tester.o lists/linked_list.o
$(CC) $(CFLAGS) -o $@ $^
test_array_list.out: test/test_list.o test/tester.o lists/array_list.o
$(CC) $(CFLAGS) -o $@ $^
test/test_list.o: test/tester.h lists/list.h
perftest: profile_array_list profile_linked_list
@echo LinkedList:
./profile_linked_list
@echo ArrayList:
./profile_array_list
profile_array_list.out: profile_list.o lists/array_list.o
$(CC) $(CFLAGS) -o $@ $^
profile_linked_list.out: profile_list.o lists/linked_list.o
$(CC) $(CFLAGS) -o $@ $^
tester.o: test/tester.h | {
"domain": "codereview.stackexchange",
"id": 45171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, linked-list",
"url": null
} |
beginner, c, array, linked-list
tester.o: test/tester.h
linked_list.o: lists/list.h
array_list.o: lists/list.h
clean:
rm -f *.o test/*.o lists/*.o *.out
Edits:
Removed question 2) since it is not suited for this community
Answer: Most of the code looks good, apart from the misleading typedef that harold's answer addresses. In this review, I'll be assuming that we fix that problem.
I just have a handful of minor observations; no very serious problems.
The main program
It might be worth adding assert(TO_REMOVE <= N_ELEMS) at the start of the function to fail early rather than hitting a divide-by-zero if we give it bad input.
We could convert clock_t values to human units (e.g. by dividing by (double)CLOCKS_PER_SEC for seconds). But that's not important for this case, where we're more interested in the ratio of the two implementations.
rand() % List_length(list) doesn't give a perfectly uniform probability distribution. That's not important here, but thought I should mention it.
srand(time(NULL)); will give us a different random sequence depending on when we run the program. Usually, that's a good thing, but when we're comparing two implementations, it's arguably fairer if we give both implementations exactly the same workload. So I'd seed with a fixed value (or just omit this, which has the effect of srand(1)).
We don't use any command-line arguments, so could use the simpler signature int main(void).
The main() function is magical in that we're allowed to reach the end of it without returning a value, and that's treated as success. So we can remove the return statement. If we choose to keep it regardless, we could make it clearer by using the macro EXIT_SUCCESS instead of plain 0. | {
"domain": "codereview.stackexchange",
"id": 45171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, linked-list",
"url": null
} |
beginner, c, array, linked-list
Common definitions
I'm really not a fan of the typedefs of standard library types. Code would be clearer if it directly used the names we all know.
What would be valuable would be a name such as list_value_t to identify the type contained by the list, so that could be easily changed without affecting anything else. (Warning: identifiers ending in _t are reserved by POSIX, so this naming might not be appropriate in a program that uses any POSIX headers).
The linked list
When allocating memory, it's generally a good practice to use the size of the target rather than its type - like this:
Node *node = malloc(sizeof *node); | {
"domain": "codereview.stackexchange",
"id": 45171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, linked-list",
"url": null
} |
beginner, c, array, linked-list
Though it makes little difference here, it can make reading code easier when the assignment is a long way from the declaration, because we don't need to go back and find the declaration of node to check that the allocation is the correct size. And we can change the type more easily, with the allocation remaining correct.
It's good to see that the return value is tested before use. Normally, I'd say that exiting the program from a function like this is too drastic - we should instead inform the caller (who might need to take other actions, or may be able to mitigate the memory shortage). But for this simple use, it's probably acceptable.
When checking pointers for nullness, it's a matter of taste whether we explicitly compare against NULL or use the conversion of pointer to boolean that does that for us. I find the implicit version cleaner, but some do believe that the explicit conversion reinforces the type involved. I do appreciate consistency, and you're absolutely fine there!
We have ++ operator for adding 1 to a value. Although += 1 isn't wrong, it's more idiomatic to write ++list->size rather than list->size += 1. Similarly, I'd write --list->size when we remove a value.
In a real library implementation, where failed memory allocation doesn't immediately abort the program, we'd need to be a bit more careful about exactly when we modify the size - only when the action definitely happens, and not in the error path.
There's a few places where we need to special-case the "head" element for different behaviour. It's possible to avoid this by embedding a Node within the List structure. This "dummy head" node doesn't represent a value, but it can allow us uniform access regardless of position. You should be able to find reading material online to support this design. | {
"domain": "codereview.stackexchange",
"id": 45171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, linked-list",
"url": null
} |
beginner, c, array, linked-list
List_remove_val() doesn't have any documentation. I had to read the implementation to discover that it removes only the first matching value, or returns error if no value matches. This is something that you should communicate clearly to users (which may well include Future You!). Other functions are generally obvious from their names and signatures.
As an alternative to List_result for List_get, consider passing a pointer to a location to copy the value to:
List_success List_get(const List *list, usize index, i32 *value) | {
"domain": "codereview.stackexchange",
"id": 45171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, linked-list",
"url": null
} |
beginner, c, array, linked-list
(notice the use of const to declare that this function doesn't modify the list)
Consider adding a FILE* argument to List_print so that we can print to any stream (e.g. for writing to files or to stderr).
The array
When deleting the array, this assignment is pointless:
(*list)->elements = NULL;
Since the very next thing we do is to free(*list), that's effectively a dead write: no valid code can access that value subsequently.
Some of the functions have names that are reserved identifiers: in particular, all the names beginning with underscore are reserved for use by the implementation and should not be defined in user programs.
The _closest_power_of_2() function isn't guaranteed to terminate for half the possible arguments. If val is greater than SIZE_MAX/2, then we'll never reach a power of two that's greater than val (p becomes zero when unsigned << overflows). We could change it so that it returns one less than a power of two, by adding 1 at each step (though the name becomes a misnomer then, and should be changed). Or we could count how many times we can shift val rightwards before it becomes zero.
We don't need separate code branches in _resize_if_needed() - realloc(NULL, n) is specified to be equivalent to malloc(n). This function should be declared static, as it's not needed outside of its translation unit.
Instead of this loop:
for (usize i = list->size; i > position; i--)
{
list->elements[i] = list->elements[i - 1];
}
we can use the standard library function:
// untested - may contain off-by-one errors!
memmove(list->elements + i + 1, list->elements + i,
(list->size - position) * sizeof *list->elements); | {
"domain": "codereview.stackexchange",
"id": 45171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, linked-list",
"url": null
} |
beginner, c, array, linked-list
We should use memmove() when removing elements too. This may well be faster than the explicit loop (but a good compiler will be able to convert that to memmove() when optimising).
test_list
No review of this, because most of it depends on TEST_ASSERT() which is not present.
Makefile
We need to be compiling with optimisations enabled, if our benchmarks are to be meaningful. I'd recommend some additional warnings, too:
CFLAGS += -O3
CFLAGS += -Wextra
CFLAGS += -Wwrite-strings
CFLAGS += -Warray-bounds
CFLAGS += -Wmissing-braces
CFLAGS += -Wconversion
CFLAGS += -Wstrict-prototypes
CFLAGS += -fanalyzer
Consider adding a target to run the tests under Valgrind, to help identify memory leaks, use-after-free and similar issues.
The clean target could use $(RM) rather than writing out rm -f - and that may help it work on non-POSIX platforms, too.
Add the standard pseudo-targets:
.DELETE_ON_ERROR:
.PHONY: clean all test perftest | {
"domain": "codereview.stackexchange",
"id": 45171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, array, linked-list",
"url": null
} |
c++, c++14, fixed-point
Title: Fixed Point Type
Question: I am implementing a fixed point type, which mostly is used to be able store numbers as multiples of some base (power of 2). Apart from that, the type should be able to replace double/float values without the need of modifying some code. In its current implementation only basic arithmetic operations are possible but it should not be hard to extend the type.
I stripped away a lot of code which repeats other code - e.g. in the following only operator< is defined; all other comparison operators are defined in the same way.
The implementation trusts a lot that the compiler optimizes most of the code - e.g. instead of shift operations I wrote multiplications.
Things I want from this type:
Header only
Modulo arithmetic for all operations
No undefined behaviour possible when this type is used (given that it is not abused)
Should be hard to use this type wrong
Operations are implemented efficient
no implicit conversion from fixed to built-in types
Radix point can be "outside" of the range of underlying bits - e.g. fixed<8,10>, which has range -2^17 to 2^17-1, with an ulp of 2^10 is possible.
For points 1, 2, 4 and 7 I am quite sure I succeeded, for the other points I am nut sure.
Target Version
C++14 Since this libarary must also be usable for CUDA and in the rest of the codebase there are problems with C++17 and Cuda.
Things I don't like currently
I want most binary functions (operator+, etc...) to be compatible with two fixed objects, as well with one fixed object and one built-in arithmetic type - e.g. fixed + fixed, fixed + int, int + fixed. This currently leads to a lot of code duplication which I would like to get rid of.
Unit Tests
I wrote a lot of unit tests too, which I can always post if wanted. The unit tests use code from other parts of my projects too, thus I would have to rewrite them to a large extent in order to be able to post them here
#ifndef FIXED_HPP
#define FIXED_HPP | {
"domain": "codereview.stackexchange",
"id": 45172,
"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++14, fixed-point",
"url": null
} |
c++, c++14, fixed-point
#ifndef FIXED_HPP
#define FIXED_HPP
/**
* This is an implementation of a fixed point type
* Usage: fixed<TOTAL,SHIFT,SIGN> value
* TOTAL integer, number of total bits of underlying type, must be 8,16,32 or 64
* SHIFT integer, defines how much the radix point is shifted to the right. Can be negative.
* SIGN enum class signed_e, default=signed_e:signed, defines whether the type is signed or not.
* T (experimental) underlying type, default = determined by TOTAL
*
* Implemented operations:
* all casts to other basic types
* +, -, ~, !, >>, <<, as well as the operators +=, -=, ...
* ++ and -- operators are only defined when the number one can be represented
*
* Notes:
* In Debug mode, when a fixed object is created using a value, it is checked whether the value is in the proper range.
* All (subsequent) calculations are done using 2-complements unsigned integers, and thus, wrap around.
*/
#include <cassert>
#include <cmath>
#include <cstdint>
#include <limits>
#include <ostream>
#include <type_traits> | {
"domain": "codereview.stackexchange",
"id": 45172,
"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++14, fixed-point",
"url": null
} |
c++, c++14, fixed-point
namespace detail { namespace fixed {
static inline constexpr double pow2_worker( double res, int n ) {
if ( n<0 ) {
return pow2_worker( res/2., n+1 );
} else if ( n>0 ) {
return pow2_worker( res*2., n-1 );
} else {
return res;
}
}
} }
static inline constexpr double pow2( int n ) {
return detail::fixed::pow2_worker( 1, n );
}
template<typename OUT,typename IN> static inline constexpr OUT safe_numeric_cast( IN in ) {
// taken from stackoverflow.com/questions/25857843
if ( std::isnan(in) ) {
return 0;
}
int exp;
std::frexp( in, &exp );
if( std::isfinite(in) && exp<= 63 ) {
return static_cast<int64_t>( in );
} else {
return std::signbit( in ) ? std::numeric_limits<int64_t>::min() : std::numeric_limits<int64_t>::max();
}
}
template<typename T>
static inline constexpr T rightshift( T value, int8_t shift ) {
static_assert( ((-4)>>1) == -2, "This library assumes sign-extending right shift" );
assert( sizeof(value)*8 >= (shift>0?shift:-shift) );
if ( shift>0 ) {
return value >> shift;
} else if ( shift<0 ) {
return value << -shift;
} else {
return value;
}
}
enum class signed_e {
signed_t, unsigned_t
};
template <int TOTAL, int SHIFT, signed_e SIGN, typename T> class fixed;
template<typename Number=long long> inline constexpr
void inrange( Number n, int TOTAL, int SHIFT, signed_e S ) noexcept {
auto I = TOTAL + SHIFT;
assert( ((void)"(Out of range) Given number not representable in target format",
S==signed_e::signed_t ?
n >= -pow2( I-1 ) && n <= pow2( I-1 ) - pow2( SHIFT ) :
n >= 0 && n <= pow2( I ) - pow2( SHIFT )
) );
}
namespace detail { namespace fixed {
struct NoScale {}; | {
"domain": "codereview.stackexchange",
"id": 45172,
"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++14, fixed-point",
"url": null
} |
c++, c++14, fixed-point
namespace detail { namespace fixed {
struct NoScale {};
template <int T,signed_e S> struct type_from_size { // unspecialized type, compilation fails if this is chosen
};
template <> struct type_from_size<8,signed_e::signed_t> {
using value_type = uint8_t;
};
template <> struct type_from_size<8,signed_e::unsigned_t> {
using value_type = uint8_t;
};
template <> struct type_from_size<16,signed_e::signed_t> {
using value_type = uint16_t;
};
// etc...
} }
template<int TOTAL, int SHIFT=TOTAL/2, signed_e SIGN=signed_e::signed_t, typename T = typename detail::fixed::type_from_size<TOTAL,SIGN>::value_type>
class fixed {
public:
/// member variables
using base_type = T;
using compare_type = typename std::conditional< SIGN==signed_e::signed_t, typename std::make_signed<base_type>::type, base_type >::type;
base_type data_;
static_assert( -1 == ~0, "This library assumes 2-complement integers" );
/// constructors
fixed() noexcept = default;
fixed( const fixed & ) noexcept = default;
fixed& operator=( const fixed & ) noexcept = default;
template <class Number> inline constexpr
fixed( Number n, typename std::enable_if<std::is_arithmetic<Number>::value>::type* = nullptr ) noexcept :
data_( safe_numeric_cast<base_type>(n * pow2(-SHIFT)) ) {
inrange( n );
}
inline constexpr
fixed( base_type n, const detail::fixed::NoScale & ) noexcept : data_(n) {
}
inline constexpr static
fixed from_base( base_type n ) noexcept {
return fixed( n, detail::fixed::NoScale() );
}
/// helper functions
public:
template<typename Number> inline constexpr
void inrange( Number n ) const noexcept {
::inrange<Number>( n, TOTAL, SHIFT, SIGN );
} | {
"domain": "codereview.stackexchange",
"id": 45172,
"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++14, fixed-point",
"url": null
} |
c++, c++14, fixed-point
/// comparison operators
inline constexpr
bool operator<( fixed rhs ) const noexcept {
return static_cast<compare_type>( data_ ) < static_cast<compare_type>( rhs.data_ );
}
// etc...
/// unary operators
inline constexpr
bool operator!() const noexcept {
return !data_;
}
// etc...
inline constexpr
fixed & operator++() noexcept {
static_assert( SHIFT<=0 && -SHIFT<=TOTAL, "++ operator not possible" );
data_ += pow2( -SHIFT );
return *this;
}
inline constexpr
const fixed operator++( int ) noexcept {
static_assert( SHIFT<=0 && -SHIFT<=TOTAL, "++ operator not possible" );
fixed tmp(*this);
data_ += pow2( -SHIFT );
return tmp;
}
//etc...
public: // basic math operators
inline constexpr
fixed& operator+=( fixed n ) noexcept {
data_ += n.data_;
return *this;
}
inline constexpr
fixed& operator-=( fixed n ) noexcept {
data_ -= n.data_;
return *this;
}
public:
/// binary math operators
inline constexpr
fixed& operator&=( fixed n ) noexcept {
data_ &= n.data_;
return *this;
}
//etc...
/// conversion to basic types
template<typename OUT, typename std::enable_if_t<std::is_integral<OUT>::value,bool> = false >
inline constexpr explicit
operator OUT () const noexcept {
return rightshift( static_cast<OUT>(data_), -SHIFT );
}
template<typename OUT, typename std::enable_if_t<std::is_floating_point<OUT>::value,bool> = false >
inline constexpr explicit
operator OUT () const noexcept {
return static_cast<OUT>( data_ ) * static_cast<OUT>( pow2(SHIFT) );
}
inline constexpr
base_type raw() const noexcept {
return data_;
}
public:
inline constexpr
void swap( fixed &rhs ) noexcept {
using std::swap;
swap( data_, rhs.data_ );
}
}; | {
"domain": "codereview.stackexchange",
"id": 45172,
"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++14, fixed-point",
"url": null
} |
c++, c++14, fixed-point
};
template <int T, int SH, signed_e SI>
std::ostream &operator<<( std::ostream &os, fixed<T,SH,SI> f ) {
os << static_cast<double>( f );
return os;
}
// basic math operators
template <int T, int SH, signed_e SI> inline constexpr
fixed<T,SH,SI> operator+( fixed<T,SH,SI> lhs, fixed<T,SH,SI> rhs ) noexcept {
lhs += rhs;
return lhs;
}
template <int T, int SH, signed_e SI, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> inline constexpr
fixed<T,SH,SI> operator+( fixed<T,SH,SI> lhs, Number rhs ) noexcept {
lhs += fixed<T,SH,SI>( rhs );
return lhs;
}
template <int T, int SH, signed_e SI, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> inline constexpr
fixed<T,SH,SI> operator+( Number lhs, fixed<T,SH,SI> rhs ) noexcept {
fixed<T,SH,SI> tmp(lhs);
tmp += rhs;
return tmp;
}
//etc...
// shift operators
template <int T, int SH, signed_e SI, class Integer, class = typename std::enable_if<std::is_integral<Integer>::value>::type> inline constexpr
fixed<T,SH,SI> operator<<( fixed<T,SH,SI> lhs, Integer rhs ) noexcept {
lhs <<= rhs;
return lhs;
}
template <int T, int SH, signed_e SI, class Integer, class = typename std::enable_if<std::is_integral<Integer>::value>::type> inline constexpr
fixed<T,SH,SI> operator>>( fixed<T,SH,SI> lhs, Integer rhs ) noexcept {
lhs >>= rhs;
return lhs;
}
// comparison operators
template <int T, int SH, signed_e SI, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> inline constexpr
bool operator<( fixed<T,SH,SI> lhs, Number rhs ) noexcept {
return lhs < fixed<T,SH,SI>( rhs );
}
template <int T, int SH, signed_e SI, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> inline constexpr
bool operator<( Number lhs, fixed<T,SH,SI> rhs ) noexcept {
return fixed<T,SH,SI>(lhs) < rhs;
} | {
"domain": "codereview.stackexchange",
"id": 45172,
"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++14, fixed-point",
"url": null
} |
c++, c++14, fixed-point
namespace std {
/// specialization of std::numeric_limits
template<int TOTAL,int SHIFT,signed_e SIGNED> struct numeric_limits<::fixed<TOTAL,SHIFT,SIGNED>> {
static constexpr bool is_specialized = true;
static constexpr double lowest() noexcept { return SIGNED==signed_e::signed_t ? -pow2( TOTAL + SHIFT - 1 ) : 0; }
static constexpr double max() noexcept { return SIGNED==signed_e::signed_t ? pow2( TOTAL + SHIFT - 1 ) - pow2( SHIFT ) : pow2( TOTAL + SHIFT ) - pow2( SHIFT ); }
// etc.
};
}
int main() {
fixed<16,-8> x = -10;
x+=-2;
auto r = x<-5;
auto y = x + 100;
return (int)x;
}
#endif //FIXED_HPP
Credits
This type is a heavily modified fixed point type written by Evan Teran.
Answer:
I want most binary functions (operator+, etc...) to be compatible with two fixed objects, as well with one fixed object and one built-in arithmetic type - e.g. fixed + fixed, fixed + int, int + fixed. This currently leads to a lot of code duplication which I would like to get rid of. | {
"domain": "codereview.stackexchange",
"id": 45172,
"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++14, fixed-point",
"url": null
} |
c++, c++14, fixed-point
In my implementation (which is Decimal, not power-of-two, and has different design requirements for many of your points), I decided to provide operator+ between identical types only. It would be confusing to have the result be a type that differs from either of the arguments and could lead to use of more distinct types than intended. On the other hand, operator+= does allow mixed types, as the result is implicitly the type of the left-hand operand, and it gives a compile-time error if the right-hand operand is larger in either size to the left of the decimal or size to the right of the decimal.
As for code duplication, I rely on operator= (only) to do the heavy lifting of implicitly widening the type. The addition and subtraction operators call that to condition the right-hand argument.
As for built-in integer type as one argument: are you doing size match checking? If you have, for example a 32-bit int with 5 implied fractional bits, then adding a regular 32-bit value will be too large to the left of the binary point. In my library, I disallow this, but constexpr constructors let me easily mark the regular int with a size that's smaller than the int. E.g. d1 += decimal<3,0>(n); tells it that n has (at most) three decimal digits (recall my library is decimal based) rather than 9 or 10 that would fit in a regular int. Thus, is passes the width checking and automatically widens to the declared type of d1 which is, say, 5 digits to the left and 4 to the right of the decimal point and represented in a 32-bit value.
Doing the underlying work as unsigned integers will be less efficient (less ability to optimize the inlined functions) as using signed values.
Why are your functions static inline instead of just inline? That is not normal. | {
"domain": "codereview.stackexchange",
"id": 45172,
"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++14, fixed-point",
"url": null
} |
c++, c++14, fixed-point
Why are your functions static inline instead of just inline? That is not normal.
You have namespaces nested as detail::fixed rather than the other way around? Also odd. Hmm, I see fixed is a class template that is not inside a namespace at all! You should put everything inside a namespace to prevent clashes.
template<typename OUT,typename IN> static inline constexpr OUT safe_numeric_cast( IN in ) {
It's hard to read with the template prefix and following declaration on one line like that. And again, it's quite odd to see inline static. Try:
template<typename OUT,typename IN>
constexpr OUT safe_numeric_cast ( IN in )
{
Furthermore, the use of IN and OUT may conflict with other libraries. I've seen those defined as macros that are used to mark parameters as with languages such as Ada or COM/CORBA marshalling.
The inline is not needed here to allow use inside a header. A template is not a function, just like how a cookie-cutter is not a cookie. There is no code there; and the instantiation of the template, which is a function, understands being instantiated in multiple translation units. Note that inline is no longer a hint used to ask to compiler to inline the function — the compiler decides for itself what to inline or not. It is only used to allow definitions to appear in headers so that multiple copies are merged. On the other hand, static means that the instantiated function will not be shared among different translation units, which is the exact opposite in meaning. And why would you want to do that? | {
"domain": "codereview.stackexchange",
"id": 45172,
"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++14, fixed-point",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Title: An Updated recursive_reduce_string Template Function Implementation in C++
Question: This is a follow-up question for A recursive_reduce Template Function with Unwrap Level Implementation in C++ and A recursive_reduce_string Template Function Implementation in C++. Considering the issue mentioned in G. Sliepen's answer, some modifications are made here:
It is not generic enough. Even if you only wanted it to be limited to strings, consider that std::string is just a type alias for std::basic_string<char>. What about std::wstring, std::u8string, std::pmr::string, std::string_view, C strings and all other kinds of strings?
The name implies it is similar to std::reduce(), however it doesn't support a custom reduction operator, doesn't support an initial element, and doesn't support parallelism.
In this post, the updated recursive_reduce_string template function not only support various type of string (std::string, std::wstring, std::u8string, std::pmr::string) but also support custom reduction operator, initial element and parallelism.
The experimental implementation | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
recursive_reduce_string template function implementation
// recursive_reduce_string template function
template<std::size_t base_level, class T>
constexpr auto recursive_reduce_string(const T& input)
{
if (input.empty())
{
throw std::runtime_error("input is empty!");
}
if constexpr (recursive_depth<T>() == base_level)
{
return input;
}
else if constexpr (recursive_depth<T>() == base_level + 1)
{
auto output = input[0];
for(int i = 1; i < std::ranges::size(input); ++i)
{
output+=input[i];
}
return output;
}
else
{
auto result = recursive_reduce_string<base_level>(
UL::recursive_transform<recursive_depth<T>() - 2>(
input,
[](auto&& element){ return recursive_reduce_string<base_level>(element); })
);
return result;
}
}
// recursive_reduce_string template function (with execution policy)
template<std::size_t base_level, class ExPo, class T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_reduce_string(ExPo execution_policy, const T& input)
{
if (input.empty())
{
throw std::runtime_error("input is empty!");
}
if constexpr (recursive_depth<T>() == base_level)
{
return input;
}
else if constexpr (recursive_depth<T>() == base_level + 1)
{
auto output = input[0];
for(int i = 1; i < std::ranges::size(input); ++i)
{
output+=input[i];
}
return output;
}
else
{
auto result = recursive_reduce_string<base_level>(
execution_policy,
UL::recursive_transform<recursive_depth<T>() - 2>(
execution_policy,
input,
[&](auto&& element){ return recursive_reduce_string<base_level>(execution_policy, element); })
);
return result;
}
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_string template function with initial value
template<std::size_t base_level, class T, class TI>
requires (is_summable<recursive_unwrap_type_t<recursive_depth<T>() - base_level, T>, TI>)
constexpr auto recursive_reduce_string(const T& input, const TI init)
{
if (input.empty())
{
throw std::runtime_error("input is empty!");
}
if constexpr (recursive_depth<T>() == base_level)
{
return input;
}
else if constexpr (recursive_depth<T>() == base_level + 1)
{
auto output = init;
for(auto&& element : input)
{
output+=element;
}
return output;
}
else
{
auto result = recursive_reduce_string<base_level>(
UL::recursive_transform<recursive_depth<T>() - 2>(
input,
[&](auto&& element){ return recursive_reduce_string<base_level>(element); }),
init
);
return result;
}
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_string template function with execution policy and initial value
template<std::size_t base_level, class ExPo, class T, class TI>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
is_summable<recursive_unwrap_type_t<recursive_depth<T>() - base_level, T>, TI>)
constexpr auto recursive_reduce_string(ExPo execution_policy, const T& input, const TI init)
{
if (input.empty())
{
throw std::runtime_error("input is empty!");
}
if constexpr (recursive_depth<T>() == base_level)
{
return input;
}
else if constexpr (recursive_depth<T>() == base_level + 1)
{
auto output = init;
for(auto&& element : input)
{
output+=element;
}
return output;
}
else
{
auto result = recursive_reduce_string<base_level>(
execution_policy,
UL::recursive_transform<recursive_depth<T>() - 2>(
execution_policy,
input,
[&](auto&& element){ return recursive_reduce_string<base_level>(execution_policy, element); }),
init
);
return result;
}
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_string template function with initial value and specified operation
template<std::size_t base_level, class T, class TI, class BinaryOp>
requires ( std::regular_invocable<
BinaryOp,
recursive_unwrap_type_t<recursive_depth<T>() - base_level, T>,
recursive_unwrap_type_t<recursive_depth<T>() - base_level, T>>)
constexpr auto recursive_reduce_string(const T& input, const TI init, BinaryOp binary_op)
{
if (input.empty())
{
throw std::runtime_error("input is empty!");
}
if constexpr (recursive_depth<T>() == base_level)
{
return input;
}
else if constexpr (recursive_depth<T>() == base_level + 1)
{
auto output = init;
for(auto&& element : input)
{
output = std::invoke(binary_op, output, element);
}
return output;
}
else
{
auto result = recursive_reduce_string<base_level>(
UL::recursive_transform<recursive_depth<T>() - 2>(
input,
[&](auto&& element){ return recursive_reduce_string<base_level>(element); }),
init,
binary_op
);
return result;
}
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_string template function with execution policy, initial value and specified operation
template<std::size_t base_level, class ExPo, class T, class TI, class BinaryOp>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
std::regular_invocable<
BinaryOp,
recursive_unwrap_type_t<recursive_depth<T>() - base_level, T>,
recursive_unwrap_type_t<recursive_depth<T>() - base_level, T>>)
constexpr auto recursive_reduce_string(ExPo execution_policy, const T& input, const TI init, BinaryOp binary_op)
{
if (input.empty())
{
throw std::runtime_error("input is empty!");
}
if constexpr (recursive_depth<T>() == base_level)
{
return input;
}
else if constexpr (recursive_depth<T>() == base_level + 1)
{
auto output = init;
for(auto&& element : input)
{
output = std::invoke(binary_op, output, element);
}
return output;
}
else
{
auto result = recursive_reduce_string<base_level>(
execution_policy,
UL::recursive_transform<recursive_depth<T>() - 2>(
execution_policy,
input,
[&](auto&& element){ return recursive_reduce_string<base_level>(execution_policy, element); }
),
init,
binary_op
);
return result;
}
}
Full Testing Code
The full testing code:
#include <algorithm>
#include <array>
#include <chrono>
#include <concepts>
#include <deque>
#include <execution>
#include <experimental/array>
#include <iostream>
#include <queue>
#include <ranges>
#include <string>
#include <vector>
// is_reservable concept
template<class T>
concept is_reservable = requires(T input)
{
input.reserve(1);
};
// is_sized concept, https://codereview.stackexchange.com/a/283581/231235
template<class T>
concept is_sized = requires(T x)
{
std::size(x);
}; | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<class T1, class T2>
concept is_summable = requires(T1 x1, T2 x2) { x1 + x2; };
// has_arithmetic_operations concept
template<class T>
concept has_arithmetic_operations = requires(T input)
{
std::plus<>{}(input, input);
std::minus<>{}(input, input);
std::multiplies<>{}(input, input);
std::divides<>{}(input, input);
};
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return std::size_t{0};
}
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + std::size_t{1};
}
// recursive_variadic_invoke_result_t implementation
template<std::size_t, typename, typename, typename...>
struct recursive_variadic_invoke_result { };
template<typename F, class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...>
{
using type = Container1<std::invoke_result_t<F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>>;
};
template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...>
{
using type = Container1<
typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...
>::type>;
}; | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<std::size_t unwrap_level, typename F, typename T1, typename... Ts>
using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type;
// recursive_array_invoke_result implementation
template<std::size_t, typename, typename, typename...>
struct recursive_array_invoke_result { };
template< typename F,
template<class, std::size_t> class Container,
typename T,
std::size_t N>
struct recursive_array_invoke_result<1, F, Container<T, N>>
{
using type = Container<
std::invoke_result_t<F, std::ranges::range_value_t<Container<T, N>>>,
N>;
};
template< std::size_t unwrap_level,
typename F,
template<class, std::size_t> class Container,
typename T,
std::size_t N>
requires ( std::ranges::input_range<Container<T, N>> &&
requires { typename recursive_array_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges
struct recursive_array_invoke_result<unwrap_level, F, Container<T, N>>
{
using type = Container<
typename recursive_array_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container<T, N>>
>::type, N>;
};
template< std::size_t unwrap_level,
typename F,
template<class, std::size_t> class Container,
typename T,
std::size_t N>
using recursive_array_invoke_result_t = typename recursive_array_invoke_result<unwrap_level, F, Container<T, N>>::type;
// recursive_unwrap_type_t struct implementation, https://codereview.stackexchange.com/q/284610/231235
template<std::size_t, typename, typename...>
struct recursive_unwrap_type { }; | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_unwrap_type<1, Container1<Ts1...>, Ts...>
{
using type = std::ranges::range_value_t<Container1<Ts1...>>;
};
template<std::size_t unwrap_level, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_unwrap_type<unwrap_level, Container1<Ts1...>, Ts...>
{
using type = typename recursive_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container1<Ts1...>>
>::type;
};
template<std::size_t unwrap_level, typename T1, typename... Ts>
using recursive_unwrap_type_t = typename recursive_unwrap_type<unwrap_level, T1, Ts...>::type;
// recursive_array_unwrap_type struct implementation, https://stackoverflow.com/a/76347485/6667035
template<std::size_t, typename>
struct recursive_array_unwrap_type { };
template<template<class, std::size_t> class Container,
typename T,
std::size_t N>
struct recursive_array_unwrap_type<1, Container<T, N>>
{
using type = std::ranges::range_value_t<Container<T, N>>;
}; | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<std::size_t unwrap_level, template<class, std::size_t> class Container,
typename T,
std::size_t N>
requires ( std::ranges::input_range<Container<T, N>> &&
requires { typename recursive_array_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges
struct recursive_array_unwrap_type<unwrap_level, Container<T, N>>
{
using type = typename recursive_array_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container<T, N>>
>::type;
};
template<std::size_t unwrap_level, class Container>
using recursive_array_unwrap_type_t = typename recursive_array_unwrap_type<unwrap_level, Container>::type;
// https://codereview.stackexchange.com/a/253039/231235
template<template<class...> class Container = std::vector, std::size_t dim, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<Container, dim - 1, T>(input, times));
}
}
namespace UL // unwrap_level
{
template< std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>)
constexpr auto make_view(const Container& input, const F& f) noexcept
{
return std::ranges::transform_view(
input,
[&f](const auto&& element) constexpr { return recursive_transform(element, f ); } );
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
/* Override make_view to catch dangling references. A borrowed range is
* safe from dangling..
*/
template <std::ranges::input_range T>
requires (!std::ranges::borrowed_range<T>)
constexpr std::ranges::dangling make_view(T&&) noexcept
{
return std::ranges::dangling();
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// clone_empty_container template function implementation
template< std::size_t unwrap_level = 1,
std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>)
constexpr auto clone_empty_container(const Container& input, const F& f) noexcept
{
const auto view = make_view(input, f);
recursive_variadic_invoke_result<unwrap_level, F, Container> output(std::span{input});
return output;
}
// recursive_transform template function implementation (the version with unwrap_level template parameter)
template< std::size_t unwrap_level = 1,
class T,
std::copy_constructible F,
class Proj = std::identity>
requires (unwrap_level <= recursive_depth<T>()&& // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235
std::ranges::view<T>&&
std::is_object_v<F>)
constexpr auto recursive_transform(const T& input, const F& f, Proj proj = {} )
{
if constexpr (unwrap_level > 0)
{
auto output = clone_empty_container(input, f);
if constexpr (is_reservable<decltype(output)>&&
is_sized<decltype(input)>)
{
output.reserve(input.size());
std::ranges::transform(
input,
std::ranges::begin(output),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); },
proj
);
}
else
{
std::ranges::transform(
input,
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }, | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
proj
);
}
return output;
}
else if constexpr(std::regular_invocable<F, T>)
{
return std::invoke(f, std::invoke(proj, input));
}
else
{
static_assert(!std::regular_invocable<F, T>, "Uninvocable?");
}
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
/* This overload of recursive_transform is to support std::array
*/
template< std::size_t unwrap_level = 1,
template<class, std::size_t> class Container,
typename T,
std::size_t N,
typename F >
requires (std::ranges::input_range<Container<T, N>>)
constexpr auto recursive_transform(const Container<T, N>& input, const F& f)
{
recursive_array_invoke_result_t<unwrap_level, F, Container, T, N> output{};
if constexpr (unwrap_level > 1)
{
std::ranges::transform(
input,
std::ranges::begin(output),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
}
else
{
std::ranges::transform(
input,
std::ranges::begin(output),
f
);
}
return output;
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_transform function implementation (the version with unwrap_level, without using view)
template<std::size_t unwrap_level = 1, class T, class F>
requires (unwrap_level <= recursive_depth<T>()&& // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235
!std::ranges::view<T>)
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_variadic_invoke_result_t<unwrap_level, F, T> output{};
std::ranges::transform(
input, // passing a range to std::ranges::transform()
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return std::invoke(f, input); // use std::invoke()
}
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_transform implementation (the version with unwrap_level, with execution policy)
template<std::size_t unwrap_level = 1, class ExPo, class T, std::copy_constructible F>
requires (unwrap_level <= recursive_depth<T>() && // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235
std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_variadic_invoke_result_t<unwrap_level, F, T> output{};
output.resize(input.size());
std::mutex mutex;
std::transform(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[&](auto&& element)
{
std::lock_guard lock(mutex);
return recursive_transform<unwrap_level - 1>(execution_policy, element, f);
});
return output;
}
else
{
return std::invoke(f, input);
}
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_transform implementation (binary case, the version with unwrap_level)
template<std::size_t unwrap_level = 1, class ExPo, std::ranges::input_range R1, std::ranges::input_range R2, std::copy_constructible F>
constexpr auto recursive_transform(ExPo execution_policy, const R1& input1, const R2& input2, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_variadic_invoke_result_t<unwrap_level, F, R1> output{};
output.resize(input1.size());
std::mutex mutex;
std::transform(execution_policy, std::ranges::cbegin(input1), std::ranges::cend(input1), std::ranges::cbegin(input2), std::ranges::begin(output),
[&](auto&& element1, auto&& element2)
{
std::lock_guard lock(mutex);
return recursive_transform<unwrap_level - 1>(execution_policy, element1, element2, f);
});
return output;
}
else
{
return std::invoke(f, input1, input2);
}
}
}
// recursive_reduce_string template function
template<std::size_t base_level, class T>
constexpr auto recursive_reduce_string(const T& input)
{
if (input.empty())
{
throw std::runtime_error("input is empty!");
}
if constexpr (recursive_depth<T>() == base_level)
{
return input;
}
else if constexpr (recursive_depth<T>() == base_level + 1)
{
auto output = input[0];
for(int i = 1; i < std::ranges::size(input); ++i)
{
output+=input[i];
}
return output;
}
else
{
auto result = recursive_reduce_string<base_level>(
UL::recursive_transform<recursive_depth<T>() - 2>(
input,
[](auto&& element){ return recursive_reduce_string<base_level>(element); })
);
return result;
}
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_string template function (with execution policy)
template<std::size_t base_level, class ExPo, class T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_reduce_string(ExPo execution_policy, const T& input)
{
if (input.empty())
{
throw std::runtime_error("input is empty!");
}
if constexpr (recursive_depth<T>() == base_level)
{
return input;
}
else if constexpr (recursive_depth<T>() == base_level + 1)
{
auto output = input[0];
for(int i = 1; i < std::ranges::size(input); ++i)
{
output+=input[i];
}
return output;
}
else
{
auto result = recursive_reduce_string<base_level>(
execution_policy,
UL::recursive_transform<recursive_depth<T>() - 2>(
execution_policy,
input,
[&](auto&& element){ return recursive_reduce_string<base_level>(execution_policy, element); })
);
return result;
}
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_string template function with initial value
template<std::size_t base_level, class T, class TI>
requires (is_summable<recursive_unwrap_type_t<recursive_depth<T>() - base_level, T>, TI>)
constexpr auto recursive_reduce_string(const T& input, const TI init)
{
if (input.empty())
{
throw std::runtime_error("input is empty!");
}
if constexpr (recursive_depth<T>() == base_level)
{
return input;
}
else if constexpr (recursive_depth<T>() == base_level + 1)
{
auto output = init;
for(auto&& element : input)
{
output+=element;
}
return output;
}
else
{
auto result = recursive_reduce_string<base_level>(
UL::recursive_transform<recursive_depth<T>() - 2>(
input,
[&](auto&& element){ return recursive_reduce_string<base_level>(element); }),
init
);
return result;
}
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_string template function with execution policy and initial value
template<std::size_t base_level, class ExPo, class T, class TI>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
is_summable<recursive_unwrap_type_t<recursive_depth<T>() - base_level, T>, TI>)
constexpr auto recursive_reduce_string(ExPo execution_policy, const T& input, const TI init)
{
if (input.empty())
{
throw std::runtime_error("input is empty!");
}
if constexpr (recursive_depth<T>() == base_level)
{
return input;
}
else if constexpr (recursive_depth<T>() == base_level + 1)
{
auto output = init;
for(auto&& element : input)
{
output+=element;
}
return output;
}
else
{
auto result = recursive_reduce_string<base_level>(
execution_policy,
UL::recursive_transform<recursive_depth<T>() - 2>(
execution_policy,
input,
[&](auto&& element){ return recursive_reduce_string<base_level>(execution_policy, element); }),
init
);
return result;
}
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_string template function with initial value and specified operation
template<std::size_t base_level, class T, class TI, class BinaryOp>
requires ( std::regular_invocable<
BinaryOp,
recursive_unwrap_type_t<recursive_depth<T>() - base_level, T>,
recursive_unwrap_type_t<recursive_depth<T>() - base_level, T>>)
constexpr auto recursive_reduce_string(const T& input, const TI init, BinaryOp binary_op)
{
if (input.empty())
{
throw std::runtime_error("input is empty!");
}
if constexpr (recursive_depth<T>() == base_level)
{
return input;
}
else if constexpr (recursive_depth<T>() == base_level + 1)
{
auto output = init;
for(auto&& element : input)
{
output = std::invoke(binary_op, output, element);
}
return output;
}
else
{
auto result = recursive_reduce_string<base_level>(
UL::recursive_transform<recursive_depth<T>() - 2>(
input,
[&](auto&& element){ return recursive_reduce_string<base_level>(element); }),
init,
binary_op
);
return result;
}
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_string template function with execution policy, initial value and specified operation
template<std::size_t base_level, class ExPo, class T, class TI, class BinaryOp>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
std::regular_invocable<
BinaryOp,
recursive_unwrap_type_t<recursive_depth<T>() - base_level, T>,
recursive_unwrap_type_t<recursive_depth<T>() - base_level, T>>)
constexpr auto recursive_reduce_string(ExPo execution_policy, const T& input, const TI init, BinaryOp binary_op)
{
if (input.empty())
{
throw std::runtime_error("input is empty!");
}
if constexpr (recursive_depth<T>() == base_level)
{
return input;
}
else if constexpr (recursive_depth<T>() == base_level + 1)
{
auto output = init;
for(auto&& element : input)
{
output = std::invoke(binary_op, output, element);
}
return output;
}
else
{
auto result = recursive_reduce_string<base_level>(
execution_policy,
UL::recursive_transform<recursive_depth<T>() - 2>(
execution_policy,
input,
[&](auto&& element){ return recursive_reduce_string<base_level>(execution_policy, element); }
),
init,
binary_op
);
return result;
}
}
template<class T>
requires (std::ranges::input_range<T>)
constexpr auto recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << "\n";
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto&& x)
{
std::cout << std::string(level, ' ') << x << "\n";
return x;
}
);
return output;
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<class T>
requires (std::ranges::input_range<T> &&
std::ranges::input_range<std::ranges::range_value_t<T>>)
constexpr T recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << "\n";
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto&& element)
{
return recursive_print(element, level + 1);
}
);
return output;
}
void recursive_reduce_string_tests()
{
std::cout << "recursive_reduce_string function test with std::vector<std::string>:\n";
std::vector<std::string> word_vector1 = {"foo", "bar", "baz", "quux"};
std::cout << recursive_reduce_string<1>(word_vector1) << '\n';
std::cout << "recursive_reduce_string function test with std::vector<std::vector<std::string>>:\n";
std::vector<std::vector<std::string>> word_vector2 = {word_vector1, word_vector1, word_vector1};
std::cout << recursive_reduce_string<1>(word_vector2) << "\n\n";
std::cout << "recursive_reduce_string function test with std::array<std::string, 3>:\n";
std::array<std::string, 3> word_array1 = {"foo", "bar", "baz"};
std::cout << recursive_reduce_string<1>(word_array1) << '\n';
std::cout << "recursive_reduce_string function test with std::array<std::array<std::string, 3>, 3>:\n";
std::array<decltype(word_array1), 3> word_array2 = {word_array1, word_array1, word_array1};
std::cout << recursive_reduce_string<1>(word_array2) << "\n\n";
std::cout << "recursive_reduce_string function test with execution policy, std::vector<std::string>:\n";
std::cout << recursive_reduce_string<1>(std::execution::seq, word_vector1) << '\n';
std::cout << "recursive_reduce_string function test with execution policy, std::vector<std::vector<std::string>>:\n";
std::cout << recursive_reduce_string<1>(std::execution::seq, word_vector2) << "\n\n"; | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "recursive_reduce_string function test with initial value, std::vector<std::string>:\n";
std::string s1{ "_" };
std::cout << recursive_reduce_string<1>(word_vector1, s1) << '\n';
std::cout << "recursive_reduce_string function test with initial value, std::vector<std::vector<std::string>>:\n";
std::cout << recursive_reduce_string<1>(word_vector2, s1) << "\n\n";
std::cout << "recursive_reduce_string function test with execution policy, initial value, std::vector<std::string>:\n";
std::cout << recursive_reduce_string<1>(std::execution::seq, word_vector1, s1) << '\n';
std::cout << "recursive_reduce_string function test with execution policy, initial value, std::vector<std::vector<std::string>>:\n";
std::cout << recursive_reduce_string<1>(std::execution::seq, word_vector2, s1) << "\n\n";
std::cout << "recursive_reduce_string function test with initial value, specified operation, std::vector<std::string>:\n";
std::cout << recursive_reduce_string<1>(
word_vector1,
s1,
[](std::string x, std::string y) { return x + " " + y; }) << "\n\n";
std::cout << "recursive_reduce_string function test with execution policy, initial value, specified operation, std::vector<std::string>:\n";
std::cout << recursive_reduce_string<1>(
std::execution::seq,
word_vector1,
s1,
[](std::string x, std::string y) { return x + " " + y; }) << "\n\n";
std::cout << "recursive_reduce_string function test with std::deque<std::string>:\n";
std::deque<std::string> word_deque1 = {"1", "2", "3", "4"};
std::cout << recursive_reduce_string<1>(word_deque1) << '\n';
std::cout << "recursive_reduce_string function test with std::deque<std::deque<std::string>>:\n";
std::deque<std::deque<std::string>> word_deque2 = {word_deque1, word_deque1, word_deque1};
std::cout << recursive_reduce_string<1>(word_deque2) << "\n\n"; | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "recursive_reduce_string function test with std::vector<std::wstring>:\n";
std::vector<std::wstring> wstring_vector1{};
for(int i = 0; i < 4; ++i)
{
wstring_vector1.push_back(std::to_wstring(i));
}
std::wcout << recursive_reduce_string<1>(wstring_vector1) << '\n';
std::cout << "recursive_reduce_string function test with std::vector<std::vector<std::wstring>>:\n";
std::vector<decltype(wstring_vector1)> wstring_vector2{};
for(int i = 0; i < 4; ++i)
{
wstring_vector2.push_back(wstring_vector1);
}
std::wcout << recursive_reduce_string<1>(wstring_vector2) << "\n\n";
std::cout << "recursive_reduce_string function test with std::array<std::wstring, 4>:\n";
auto wstring_array1 = std::experimental::make_array(
std::to_wstring(1),
std::to_wstring(2),
std::to_wstring(3),
std::to_wstring(4)
);
std::wcout << recursive_reduce_string<1>(wstring_array1) << '\n';
std::cout << "recursive_reduce_string function test with std::array<std::array<std::wstring, 4>, 4>:\n";
auto wstring_array2 = std::experimental::make_array(
wstring_array1,
wstring_array1,
wstring_array1,
wstring_array1
);
std::wcout << recursive_reduce_string<1>(wstring_array2) << "\n\n";
std::cout << "recursive_reduce_string function test with std::deque<std::wstring>:\n";
std::deque<std::wstring> wstring_deque1{};
for(int i = 0; i < 4; ++i)
{
wstring_deque1.push_back(std::to_wstring(i));
}
std::wcout << recursive_reduce_string<1>(wstring_vector1) << '\n'; | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "recursive_reduce_string function test with std::deque<std::deque<std::wstring>>:\n";
std::deque<decltype(wstring_deque1)> wstring_deque2{};
for(int i = 0; i < 4; ++i)
{
wstring_deque2.push_back(wstring_deque1);
}
std::wcout << recursive_reduce_string<1>(wstring_deque2) << "\n\n";
std::cout << "recursive_reduce_string function test with std::vector<std::u8string>:\n";
std::vector<std::u8string> u8string_vector1{};
for(int i = 0; i < 4; ++i)
{
u8string_vector1.push_back(u8"\u20AC2.00");
}
std::cout << reinterpret_cast<const char*>(recursive_reduce_string<1>(u8string_vector1).c_str()) << '\n';
std::cout << "recursive_reduce_string function test with std::vector<std::vector<std::u8string>>:\n";
std::vector<std::vector<std::u8string>> u8string_vector2 = {u8string_vector1, u8string_vector1, u8string_vector1};
std::cout << reinterpret_cast<const char*>(recursive_reduce_string<1>(u8string_vector2).c_str()) << "\n\n";
std::cout << "recursive_reduce_string function test with std::vector<std::pmr::string>:\n";
std::pmr::string pmr_string1 = "123";
std::vector<std::pmr::string> pmr_string_vector1 = {pmr_string1, pmr_string1, pmr_string1};
std::cout << recursive_reduce_string<1>(pmr_string_vector1) << "\n\n";
return;
}
int main()
{
auto start = std::chrono::system_clock::now();
recursive_reduce_string_tests();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n';
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
The output of the test code above:
recursive_reduce_string function test with std::vector<std::string>:
foobarbazquux
recursive_reduce_string function test with std::vector<std::vector<std::string>>:
foobarbazquuxfoobarbazquuxfoobarbazquux
recursive_reduce_string function test with std::array<std::string, 3>:
foobarbaz
recursive_reduce_string function test with std::array<std::array<std::string, 3>, 3>:
foobarbazfoobarbazfoobarbaz
recursive_reduce_string function test with execution policy, std::vector<std::string>:
foobarbazquux
recursive_reduce_string function test with execution policy, std::vector<std::vector<std::string>>:
foobarbazquuxfoobarbazquuxfoobarbazquux
recursive_reduce_string function test with initial value, std::vector<std::string>:
_foobarbazquux
recursive_reduce_string function test with initial value, std::vector<std::vector<std::string>>:
_foobarbazquuxfoobarbazquuxfoobarbazquux
recursive_reduce_string function test with execution policy, initial value, std::vector<std::string>:
_foobarbazquux
recursive_reduce_string function test with execution policy, initial value, std::vector<std::vector<std::string>>:
_foobarbazquuxfoobarbazquuxfoobarbazquux
recursive_reduce_string function test with initial value, specified operation, std::vector<std::string>:
_ foo bar baz quux
recursive_reduce_string function test with execution policy, initial value, specified operation, std::vector<std::string>:
_ foo bar baz quux
recursive_reduce_string function test with std::deque<std::string>:
1234
recursive_reduce_string function test with std::deque<std::deque<std::string>>:
123412341234
recursive_reduce_string function test with std::vector<std::wstring>:
0123
recursive_reduce_string function test with std::vector<std::vector<std::wstring>>:
0123012301230123
recursive_reduce_string function test with std::array<std::wstring, 4>:
1234
recursive_reduce_string function test with std::array<std::array<std::wstring, 4>, 4>:
1234123412341234 | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
recursive_reduce_string function test with std::deque<std::wstring>:
0123
recursive_reduce_string function test with std::deque<std::deque<std::wstring>>:
0123012301230123
recursive_reduce_string function test with std::vector<std::u8string>:
€2.00€2.00€2.00€2.00
recursive_reduce_string function test with std::vector<std::vector<std::u8string>>:
€2.00€2.00€2.00€2.00€2.00€2.00€2.00€2.00€2.00€2.00€2.00€2.00
recursive_reduce_string function test with std::vector<std::pmr::string>:
123123123
Computation finished at Thu Oct 26 08:44:11 2023
elapsed time: 0.00210049
Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
A recursive_reduce Template Function with Unwrap Level Implementation in C++ and
A recursive_reduce_string Template Function Implementation in C++
What changes has been made in the code since last question?
Another approach of recursive_reduce_string template function implementation is proposed in this post.
Why a new review is being asked for?
Please review the revised recursive_reduce_string template function implementation and all suggestions are welcome.
Answer: It can reduce more than just strings
Your code is now very generic. In fact, there is nothing in the code referring to strings of any kind. For example, you can sum a vector of integers with it:
std::vector<int> int_vector = {1, 2, 3, 4, 5};
std::cout << recursive_reduce_string<0>(int_vector) << '\n';
So you basically reimplemented your own recursive_reduce() with unwrap level, except instead of saying how many levels to unwrap, now the template parameter says how many levels to leave wrapped.
You should either rename this new function such that it doesn't mention strings anymore, and makes it clear that the parameter is how many levels to leave unwrapped, or alternatively, consider merging this into recursive_reduce(), and maybe use negative values of the template parameter to get the new behavior? | {
"domain": "codereview.stackexchange",
"id": 45173,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
javascript, assembly
Title: The core of the assembler (the part of the assembler that actually converts mnemonics to opcodes) is hard to follow due to many if-branchings
Question: For my Bachelor thesis, I made a PicoBlaze Assembler and Emulator in JavaScript. I've discussed it on many Internet forums, and quite a few people have complained that the core of my assembler is hard-to-follow due to lots of if-branchings. So, what are some other ways of making the core of the assembler? Do the cores of good assemblers somehow use polymorphism to avoid that problem?
"use strict";
function formatAsByte(n) {
n = Math.round(n);
if (n < 0 || n > 255) {
alert("Some part of the assembler tried to format the number " + n +
" as a byte, which makes no sense.");
return "ff";
}
let ret = n.toString(16);
while (ret.length < 2)
ret = "0" + ret;
return ret;
}
function formatAsInstruction(n) {
n = Math.round(n);
if (n < 0 || n >= 1 << 18) {
alert("Some part of the assembler tried to format the number " + n +
" as an instruction, which makes no sense.");
return "ff";
}
let ret = n.toString(16);
while (ret.length < 5)
ret = "0" + ret;
return ret;
}
function formatAs4bits(n) {
n = Math.round(n);
if (n < 0 || n >= 1 << 4) {
alert("Some part of the assembler tried to format the number " + n +
" as a single hexadecimal digit, which makes no sense.");
return "f";
}
let ret = n.toString(16);
while (ret.length < 1)
ret = "0" + ret;
return ret;
}
function isDirective(str) {
if (typeof str !== "string") {
alert(
'Internal compiler error: The first argument of the "isDirective" function is not a string!');
return false;
}
for (const directive of preprocessor)
if (RegExp("^" + directive + "$", "i").test(str))
return true;
if (/:$/.test(str))
return true;
return false;
} | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
function assemble(parsed, context) {
machineCode = [];
for (let i = 0; i < 4096; i++)
machineCode.push({hex : "00000", line : 0});
let address = 0;
for (const node of parsed.children) {
const check_if_the_only_argument_is_register = () => {
// Let's reduce the code repetition a bit by using lambda functions...
if (node.children.length !== 1) {
alert("Line #" + node.lineNumber + ': The AST node "' + node.text +
'" should have exactly 1 child node!');
return;
}
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a valid register name!');
return;
}
};
const check_if_there_are_three_child_nodes_and_the_second_one_is_comma = () => {
if (node.children.length !== 3) {
alert(
"Line #" + node.lineNumber + ': The AST node "' + node.text +
'" should have exactly three child nodes (a comma is also a child node).');
return; // This line causes this bug:
// https://github.com/FlatAssembler/PicoBlaze_Simulator_in_JS/issues/18
}
if (node.children[1].text !== ",") {
alert("Line #" + node.lineNumber + ': Expected a comma instead of "' +
node.children[1].text + '"!');
return;
}
};
if (/^address$/i.test(node.text))
address =
node.children[0].interpretAsArithmeticExpression(context.constants);
else if (/^load$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
// TODO: "bennyboy" from "atheistforums.org" thinks that
// doing this check (whether an argument is a register) again and again
// slows down the assembler significantly, it would be good to | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
// slows down the assembler significantly, it would be good to
// investigate whether that is true:
// https://atheistforums.org/thread-61911-post-2112572.html#pid2112572
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "0";
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
// If we are moving a constant to a register.
machineCode[address].hex += "1";
else
machineCode[address].hex += "0";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
else
machineCode[address].hex +=
node.children[2].getRegisterNumber(context.namedRegisters) + "0";
address++;
} else if (/^star$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "1";
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
// If we are moving a constant to a register.
machineCode[address].hex += "7";
else
machineCode[address].hex += "6";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none") | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
else
machineCode[address].hex +=
node.children[2].getRegisterNumber(context.namedRegisters) + "0";
address++;
} else if (/^store$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "2";
if (node.children[2].text === "()")
machineCode[address].hex += "e";
else
machineCode[address].hex += "f";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].text === "()") {
if (node.children[2].children.length !== 1) {
alert("Line #" + node.lineNumber +
": The node '()' should have exactly one child!");
return;
}
if (node.children[2].children[0].getRegisterNumber(
context.namedRegisters) === "none") {
alert("Line #" + node.lineNumber + ': "' +
node.children[2].children[0].text + '" is not a register!');
return;
}
machineCode[address].hex +=
node.children[2].children[0].getRegisterNumber(
context.namedRegisters) +
"0";
} else
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
address++;
} else if (/^fetch$/i.test(node.text)) { | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
context.constants));
address++;
} else if (/^fetch$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "0";
if (node.children[2].text === "()")
machineCode[address].hex += "a";
else
machineCode[address].hex += "b";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].text === "()") {
if (node.children[2].children.length !== 1) {
alert("Line #" + node.lineNumber +
": The node '()' should have exactly one child!");
return;
}
if (node.children[2].children[0].getRegisterNumber(
context.namedRegisters) === "none") {
alert("Line #" + node.lineNumber + ': "' +
node.children[2].children[0].text + '" is not a register!');
return;
}
machineCode[address].hex +=
node.children[2].children[0].getRegisterNumber(
context.namedRegisters) +
"0";
} else
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
address++;
} else if (/^input$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber; | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "0";
if (node.children[2].text === "()")
machineCode[address].hex += "8";
else
machineCode[address].hex += "9";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].text === "()") {
if (node.children[2].children.length !== 1) {
alert("Line #" + node.lineNumber +
": The node '()' should have exactly one child!");
return;
}
if (node.children[2].children[0].getRegisterNumber(
context.namedRegisters) === "none") {
alert("Line #" + node.lineNumber + ': "' +
node.children[2].children[0].text + '" is not a register!');
return;
}
machineCode[address].hex +=
node.children[2].children[0].getRegisterNumber(
context.namedRegisters) +
"0";
} else
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
address++;
} else if (/^output$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "2";
if (node.children[2].text === "()")
machineCode[address].hex += "c";
else
machineCode[address].hex += "d";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].text === "()") {
if (node.children[2].children.length !== 1) { | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
if (node.children[2].text === "()") {
if (node.children[2].children.length !== 1) {
alert("Line #" + node.lineNumber +
": The node '()' should have exactly one child!");
return;
}
if (node.children[2].children[0].getRegisterNumber(
context.namedRegisters) === "none") {
alert("Line #" + node.lineNumber + ': "' +
node.children[2].children[0].text + '" is not a register!');
return;
}
machineCode[address].hex +=
node.children[2].children[0].getRegisterNumber(
context.namedRegisters) +
"0";
} else
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
address++;
} else if (/^outputk$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
machineCode[address].line = node.lineNumber;
machineCode[address].hex =
"2b" +
formatAsByte(node.children[0].interpretAsArithmeticExpression(
context.constants)) +
formatAs4bits(node.children[2].interpretAsArithmeticExpression(
context.constants));
address++;
} else if (/^regbank$/i.test(node.text)) {
if (node.children.length !== 1) {
alert("Line #" + node.lineNumber + ': The AST node "' + node.text +
'" should have exactly one (1) child!');
return;
}
machineCode[address].line = node.lineNumber;
if (node.children[0].text === "a" || node.children[0].text === "A")
machineCode[address].hex = "37000";
else if (node.children[0].text === "b" || node.children[0].text === "B")
machineCode[address].hex = "37001";
else {
alert("Line #" + node.lineNumber +
": Expected 'A' or 'B' instead of '" + node.children[0].text +
"'!"); | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
": Expected 'A' or 'B' instead of '" + node.children[0].text +
"'!");
return;
}
address++;
} else if (/^hwbuild$/i.test(node.text)) {
if (node.children.length !== 1) {
alert("Line #" + node.lineNumber + ': The AST node "' + node.text +
'" should have exactly one (1) child!');
return;
}
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex =
"14" + node.children[0].getRegisterNumber(context.namedRegisters) +
"80";
address++;
} else if (/^inst$/i.test(node.text)) {
if (node.children.length !== 1) {
alert("Line #" + node.lineNumber + ': The AST node "' + node.text +
'" should have exactly one (1) child!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = formatAsInstruction(
node.children[0].interpretAsArithmeticExpression(context.constants));
address++;
} else if (/^jump$/i.test(node.text)) {
machineCode[address].line = node.lineNumber;
if (node.children.length === 1) {
if (node.children[0].getLabelAddress(context.labels,
context.constants) === "none") {
alert("Line #" + node.lineNumber + ": Label '" +
node.children[0].text + "' is not declared!");
return;
}
machineCode[address].hex =
"22" +
node.children[0].getLabelAddress(context.labels, context.constants);
} else {
if (node.children.length !== 3) {
alert(
"Line #" + node.lineNumber + ": The '" + node.text + | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.