text
stringlengths
1
2.12k
source
dict
python, google-bigquery, google-cloud-platform I have no idea why you're calling str(table), given that table should already be a str. In the interest of naming consistency, consider calling it just bucket rather than bucket_name. nit: Running $ black -S *.py on this wouldn't hurt, to tidy up the spacing a bit. meaningful identifier Thank you for this helpful comment, I appreciate it. if not status: # if status is empty, the insert job is successful and tables should be extracted to Cloud Storage I imagine Google's docs refer to the return value as a status. Here, it might be more helpful to name it errors, and then there would be no need for that comment. Let's talk about the missing else: clause. If there are errors, wouldn't you like for a logger to report the details? multiprocessing a way to run in parallel the data transfer for all 3 tables? import multiprocessing ... tables = [f"table_{i}" for i in range(1, 4)] with multiprocessing.Pool() as pool: pool.map(move_data, tables) Consider using one of the variant mappers, such as imap_unordered(), which grant greater latitude to the scheduler by relaxing the ordering constraints. This code achieves its design goals. I would be willing to delegate or accept maintenance tasks on it.
{ "domain": "codereview.stackexchange", "id": 45529, "lm_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, google-bigquery, google-cloud-platform", "url": null }
python, performance, memory-optimization Title: Optimized Python Solution for Determining if an Array Contains All Possibilities Question: Problem: You have been tasked with writing a method named is_all_possibilities (or IsAllPossibilities, as per your preference) that accepts an integer array and returns True if the array contains all possibilities (i.e., all integers from 0 to the length of the array - 1), otherwise returns False. My Solution: def is_all_possibilities(arr): if len(arr) == 0: return False n = len(arr) - 1 i = 0 for x in sorted(arr): if x != i: return False i += 1 return True Could you review and optimize the following Python code used to determine if an integer array contains all possibilities from 0 to the length of the array - 1? The current implementation iterates through the array and checks if each element matches the expected sequence. We're seeking a more efficient solution. Answer: As you've seen in many of the other solutions, it's pretty feasible to re-frame your original implementation as a generator, and this increases legibility. Add unit tests. I disregard your memory tag and focus on run-time performance. Importantly, there is no one algorithm that will be the best choice for all inputs; the nature of the inputs will significantly change which method is best-suited. For example, for inputs that have out-of-range values, this simple implementation will perform well as it's suited to early-terminate: def r_enum(arr: list[int]) -> bool: arr.sort() return all( i == x for i, x in enumerate(arr) ) (However, your use of sorted - whereas it takes a small performance hit when compared to in-place sorting - is preferable as it reduces side-effects.) This is equivalent to the marginally faster but more impenetrable all( itertools.starmap(operator.eq, enumerate(arr)) )
{ "domain": "codereview.stackexchange", "id": 45530, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, memory-optimization", "url": null }
python, performance, memory-optimization The above functional approach may be your best choice as an all-around efficient implementation. To summarise the input-kind effect over all of the methods we've seen so far: import itertools import math import operator from collections import Counter from timeit import timeit from typing import Callable, Any import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from matplotlib.axes import Axes from numpy.random import default_rng def op(arr): if len(arr) == 0: return False n = len(arr) - 1 i = 0 for x in sorted(arr): if x != i: return False i += 1 return True def jh_a(arr: list[int]) -> bool: arr.sort() return ( len(set(arr)) == len(arr) and arr[0] == 0 and arr[-1] == len(arr) - 1 and all(isinstance(x, int) for x in arr) ) def jh_c(arr: list[int]) -> bool: n = len(arr) expected_sum = n * (n - 1) / 2 return ( math.prod(filter(lambda x: x > 0, arr)) == factorial(n - 1) and sum(arr) == expected_sum and min(arr) == 0 and max(arr) == len(arr) - 1 and all(isinstance(x, int) for x in arr) ) def factorial(n: int) -> int: return math.prod(range(1, n + 1)) def jh_d(arr: list[int]) -> bool: arr.sort() return all(arr[i] == i for i in range(len(arr))) def jh_e(arr: list[int]) -> bool: arr.sort() return all(isinstance(arr[i], int) and arr[i] == i for i in range(len(arr))) def r_enum(arr: list[int]) -> bool: arr.sort() return all( i == x for i, x in enumerate(arr) ) def r_functional(arr: list[int]) -> bool: arr.sort() return all( itertools.starmap(operator.eq, enumerate(arr)) ) def harith_a(arr: list[int]) -> bool: if len(arr) == 0: return False for i, x in enumerate(sorted(arr)): if x != i: return False return True
{ "domain": "codereview.stackexchange", "id": 45530, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, memory-optimization", "url": null }
python, performance, memory-optimization for i, x in enumerate(sorted(arr)): if x != i: return False return True def harith_b(arr: list[int]) -> bool: return False if len(arr) == 0 else sorted(arr) == list(range(len(arr))) def harith_c(arr: list[int]) -> bool: return 0 if len(arr) == 0 else Counter(arr) == Counter(range(len(arr))) def ahall_a(arr: list[int]) -> bool: return False if len(arr) == 0 else set(arr) == set(range(len(arr))) def ahall_b(arr: list[int]) -> bool: return bool(arr) and set(arr) == set(range(len(arr))) def ahall_c(arr: list[int]) -> bool: return set(arr) == set(range(len(arr) or 1)) def sudix_b(arr: list[int]) -> bool: bit_arr = np.zeros(len(arr),dtype=bool) for x in arr: if x<0 or x>= len(arr): return False if bit_arr[x] == True: return False bit_arr[x] = True return True METHODS = ( op, jh_a, # jh_b, # fails for [0 0 3 3] jh_c, jh_d, jh_e, harith_a, harith_b, harith_c, r_enum, r_functional, ahall_a, ahall_b, ahall_c, sudix_b, ) def test() -> None: examples = ( # (), # arguably appropriate here, but OP coded the opposite (0,), (1, 0, 2), (2, 1, 0), (0, 1, 2, 3, 4), ) counterexamples = ( (1,), (2, 1), (1, 2, 3), (0, 0, 3, 3), # This disqualifies jh_b (-1, 0, 1, 2), ) for method in METHODS: for example in examples: assert method(list(example)), f'{method.__name__} failed example' for example in counterexamples: assert not method(list(example)), f'{method.__name__} failed counterexample' def benchmark() -> None: rand = default_rng(seed=0) def make_shuffle(n: int) -> np.ndarray: series = np.arange(n) rand.shuffle(series) return series
{ "domain": "codereview.stackexchange", "id": 45530, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, memory-optimization", "url": null }
python, performance, memory-optimization rows = [] kinds = ( ('repeated_0', lambda n: np.full(shape=n, fill_value=0)), ('repeated_hi', lambda n: np.full(shape=n, fill_value=n + 1)), ('sorted', lambda n: np.arange(n)), ('shuffled', make_shuffle), ) for kind, make_input in kinds: sizes = (10**np.linspace(0, 4, num=6)).astype(int) def run_all( rep: int, n: int, inputs: np.ndarray, methods: tuple[Callable, ...], ) -> list[dict[str, Any]]: result = [] for method in methods: inputs_list = inputs.tolist() def run() -> bool: return method(inputs_list) result.append({ 'n': n, 'kind': kind, 'method': method.__name__, 'rep': rep, 'dur': timeit(stmt=run, number=1), }) return result prune_rows = run_all(rep=0, n=sizes[-1], inputs=make_input(sizes[-1]), methods=METHODS) prune_rows.sort(key=lambda row: row['dur']) pruned_methods = [ next( method for method in METHODS if method.__name__ == row['method'] ) for row in prune_rows[:len(prune_rows)//2][::-1] ] for n in sizes: inputs = make_input(n) for rep in range(5): rows.extend(run_all(rep=rep, n=n, inputs=inputs, methods=pruned_methods)) df = pd.DataFrame.from_dict(rows) df = df.groupby(['n', 'kind', 'method'])['dur'].min() fig, axes = plt.subplots(nrows=2, ncols=2) fig.suptitle(f'{len(METHODS)//2} fastest methods, four input kinds') axes = [ax for row in axes for ax in row]
{ "domain": "codereview.stackexchange", "id": 45530, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, memory-optimization", "url": null }
python, performance, memory-optimization for kind, ax in zip(df.index.unique('kind'), axes): ax: Axes ax.set_xscale('log') ax.set_yscale('log') ax.set_title(kind) sns.lineplot( ax=ax, data=df[(slice(None), kind, slice(None))].reset_index(), x='n', y='dur', hue='method', ) plt.show() if __name__ == '__main__': test() benchmark()
{ "domain": "codereview.stackexchange", "id": 45530, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, memory-optimization", "url": null }
c, aes Title: AES implementation in C Question: I've implemented AES encryption in C to get more familiar with the language and to understand how encryption works better. I understand this code is unsuitable for actual cryptographic use and I'd like feedback which focuses more on code style/quality than security related things. aes.h #include <stdint.h> #include <stddef.h> /* Define constants and sbox */ #define Nb 4 #define Nk(keysize) ((int)(keysize / 32)) #define Nr(keysize) ((int)(Nk(keysize) + 6)) /* State and key types */ typedef uint8_t** State; typedef uint8_t* Key; /* My additional methods */ void encrypt(char* plain, char* key); void decrypt(char* cipher, char* key); State* toState(uint8_t* input); uint8_t** fromState(State* state); void freeState(State* state); void stringToBytes(char* str, uint8_t* bytes); /* AES main methods */ uint8_t** Cipher(uint8_t* input, uint8_t* keySchedule, size_t keySize); uint8_t** InvCipher(uint8_t* input, uint8_t* w, size_t keySize); /* AES sub-methods */ void _SubBytes(State* state, const uint8_t* box); void SubBytes(State* state); void InvSubBytes(State* state); void _ShiftRows(State* state, int multiplier); void ShiftRows(State* state); void InvShiftRows(State* state); void MixColumns(State* state); void InvMixColumns(State* state); void AddRoundKey(State* state, uint8_t* roundKey); void KeyExpansion(uint8_t* key, uint8_t* keySchedule, size_t keySize); /* AES sub-sub-methods and round constant array */ uint8_t* SubWord(uint8_t* a); uint8_t* RotWord(uint8_t* a); uint8_t* Rcon(int a); /* AES helper methods */ uint8_t* xorWords(uint8_t* a, uint8_t* b); uint8_t* copyWord(uint8_t* start); uint8_t* getWord(uint8_t* w, int i); uint8_t galoisMultiply(uint8_t a, uint8_t b); const.c /* The S-box and it's inverse. */ #include <stdint.h>
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes const uint8_t sbox[] = {0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16};
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes const uint8_t isbox[] = {0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d};
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes aes.c #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <stddef.h> #include "aes.h" #include "const.c" int main(){ /* Examples of encryption */ printf("ENCRYPTION:\n"); encrypt("3243f6a8885a308d313198a2e0370734", "2b7e151628aed2a6abf7158809cf4f3c"); /* Appendix B example */ encrypt("00112233445566778899aabbccddeeff", "000102030405060708090a0b0c0d0e0f"); /* Appendix C 128-bit example */ encrypt("00112233445566778899aabbccddeeff", "000102030405060708090a0b0c0d0e0f1011121314151617"); /* Appendix C 192-bit example */ encrypt("00112233445566778899aabbccddeeff", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); /* Appendix C 256-bit example */ /* Inverse of the above */ printf("DECRYPTION:\n"); decrypt("3925841d02dc09fbdc118597196a0b32", "2b7e151628aed2a6abf7158809cf4f3c"); decrypt("69c4e0d86a7b0430d8cdb78070b4c55a", "000102030405060708090a0b0c0d0e0f"); decrypt("dda97ca4864cdfe06eaf70a0ec0d7191", "000102030405060708090a0b0c0d0e0f1011121314151617"); decrypt("8ea2b7ca516745bfeafc49904b496089", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); return 0; }
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes void AES_main(char* text, char* keyStr, int encrypting){ /* Takes a 128-bit hexadecimal string plaintext and 128-, 192- or 256- bit hexadecimal string key and applies AES encryption or decryption. */ uint8_t *keySchedule, **output; int i; /* Convert input string to state */ uint8_t* input = malloc(sizeof(uint8_t) * 16); stringToBytes(text, input); /* Convert key string to bytes */ size_t keyBytes = (sizeof(uint8_t)*strlen(keyStr))/2; Key key = malloc(keyBytes); stringToBytes(keyStr, key); /* Convert number of bytes to bits */ size_t keySize = keyBytes * 8; /* Create array for key schedule */ keySchedule = calloc(4 * Nb * (Nr(keySize) + 1), sizeof(uint8_t)); /* Expand key */ KeyExpansion(key, keySchedule, keySize); /* Run cipher */ if(encrypting){ output = Cipher(input, keySchedule, keySize); } else{ output = InvCipher(input, keySchedule, keySize); } /* Display result */ for(i = 0; i < 16; i++){ printf("%02x", (*output)[i]); } printf("\n"); /* Free memory */ free(input); free(key); free(keySchedule); free(*output); free(output); } void encrypt(char* plaintext, char* keyStr){ AES_main(plaintext, keyStr, 1); } void decrypt(char* ciphertext, char* keyStr){ AES_main(ciphertext, keyStr, 0); }
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes void decrypt(char* ciphertext, char* keyStr){ AES_main(ciphertext, keyStr, 0); } /* AES main methods */ void KeyExpansion(uint8_t* key, uint8_t* w, size_t keySize){ /* Takes a 128-, 192- or 256-bit key and applies the key expansion algorithm to produce a key schedule. */ int i, j; uint8_t *wi, *wk, *temp, *rconval; /* Copy the key into the first Nk words of the schedule */ for(i = 0; i < Nk(keySize); i++){ for(j = 0; j < Nb; j++){ w[4*i+j] = key[4*i+j]; } } i = Nk(keySize); /* Generate Nb * (Nr + 1) additional words for the schedule */ while(i < Nb * (Nr(keySize) + 1)){ /* Copy the previous word */ temp = copyWord(getWord(w, i-1)); if(i % Nk(keySize) == 0){ /* If i is divisble by Nk, rotate and substitute the word and then xor with Rcon[i/Nk] */ rconval = Rcon(i/Nk(keySize)); xorWords(SubWord(RotWord(temp)), rconval); free(rconval); } else if(Nk(keySize) > 6 && i % Nk(keySize) == 4){ /* If Nk > 6 and i mod Nk is 4 then just substitute */ memcpy(temp, SubWord(temp), 4); } /* Get pointers for the current word and the (i-Nk)th word */ wi = getWord(w, i); wk = getWord(w, i - Nk(keySize)); /* wi = temp xor wk */ memcpy(wi, xorWords(temp, wk), 4); free(temp); i++; } } uint8_t** Cipher(uint8_t* input, uint8_t* w, size_t keySize){ /* AES Cipher method - Takes a 128 bit array of bytes and the key schedule and applies the cipher algorithm, returning a pointer to an array of output. */ int i; uint8_t** output; State* state = toState(input);
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes /* Cipher method */ AddRoundKey(state, getWord(w, 0)); for(i = 1; i < Nr(keySize); i++){ SubBytes(state); ShiftRows(state); MixColumns(state); AddRoundKey(state, getWord(w, i*Nb)); } SubBytes(state); ShiftRows(state); AddRoundKey(state, getWord(w, Nr(keySize)*Nb)); output = fromState(state); freeState(state); return output; } uint8_t** InvCipher(uint8_t* input, uint8_t* w, size_t keySize){ /* AES InvCipher method - Takes 128 bits of cipher text and the key schedule and applies the inverse cipher, returning a pointer to an array of plaintext bytes. */ int i; uint8_t** output; State* state = toState(input); /* Inverse cipher method */ AddRoundKey(state, getWord(w, Nr(keySize) * Nb)); for(i = Nr(keySize) - 1; i >= 1; i--){ InvShiftRows(state); InvSubBytes(state); AddRoundKey(state, getWord(w, i*Nb)); InvMixColumns(state); } InvShiftRows(state); InvSubBytes(state); AddRoundKey(state, getWord(w, 0)); output = fromState(state); freeState(state); return output; }
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes output = fromState(state); freeState(state); return output; } /* State to/from and helper methods */ State* toState(uint8_t* input){ /* Takes an array of bytes and returns a pointer to a State. */ int i, j; /* Malloc state pointer and state. The state pointer is returned because it is more useful than the state itself */ State* stateptr = malloc(sizeof(State)); *stateptr = malloc(4 * sizeof(uint8_t*)); State state = *stateptr; for(i = 0; i < 4; i++){ state[i] = malloc(Nb * sizeof(uint8_t)); } /* Fill state */ for(i = 0; i < 4; i++){ for(j = 0; j < Nb; j++){ /* Set value in state array to current byte j and i are swapped because the input is transposed */ state[j][i] = *input; /* Increment pointer */ input++; } } return stateptr; } uint8_t** fromState(State* state){ /* Takes a State and returns a pointer to an array of bytes. */ int i, j; /* Malloc outputptr and output */ uint8_t** outputptr = malloc(sizeof(uint8_t*)); *outputptr = malloc(sizeof(uint8_t) * 16); uint8_t* output = *outputptr; /* Fill output */ for(i = 0; i < 4; i++){ for(j = 0; j < Nb; j++){ /* Set the output to it's array item, transposing the state */ *output = (*state)[j][i]; /* Increment the pointer */ output++; } } return outputptr; } void freeState(State* state){ /* Free the memory used by each row, the state itself and the pointer to the state. */ int i; for(i = 0; i < 4; i++){ free((*state)[i]); } free(*state); free(state); }
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes void stringToBytes(char* str, uint8_t* bytes){ /* Converts a hexadecimal string of bytes into an array of uint8_t. */ int i; for(i = 0; i < strlen(str) - 1; i += 2){ /* Allocate space for pair of nibbles */ char* pair = malloc(2 * sizeof(char)); /* Copy current and next character to pair */ memcpy(pair, &str[i], 2); /* Use strtol to convert string to long, which is implicitly converted to a uint8_t. This is stored in index i/2 as there are half as many bytes as hex characters */ bytes[i/2] = strtol(pair, NULL, 16); free(pair); } } /* AES sub-methods */ void _SubBytes(State* state, const uint8_t* box){ /* Generalised SubBytes method which takes the S-box to use as an argument. */ int i, j; for(i = 0; i < 4; i++){ for(j = 0; j < Nb; j++){ /* Get the new value from the S-box */ uint8_t new = box[(*state)[i][j]]; (*state)[i][j] = new; } } } void SubBytes(State* state){ _SubBytes(state, sbox); } void InvSubBytes(State* state){ _SubBytes(state, isbox); } void _ShiftRows(State* state, int multiplier){ /* Generalised ShiftRows method which takes a multiplier which affects the shift direction. */ int i, j; for(i = 0; i < 4; i++){ /* The row number is the number of shifts to do */ uint8_t temp[4]; for(j = 0; j < Nb; j++){ /* The multiplier determines whether to do a left or right shift */ temp[((j + Nb) + (multiplier * i)) % Nb] = (*state)[i][j]; } /* Copy temp array to state array */ memcpy((*state)[i], temp, 4); } } void ShiftRows(State* state){ _ShiftRows(state, -1); } void InvShiftRows(State* state){ _ShiftRows(state, 1); }
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes void InvShiftRows(State* state){ _ShiftRows(state, 1); } uint8_t galoisMultiply(uint8_t a, uint8_t b){ /* Multiplies two bytes in the 2^8 Galois field. Implementation based on description from https://en.wikipedia.org/wiki/Finite_field_arithmetic#Rijndael's_(AES)_finite_field */ uint8_t p = 0; int i; int carry; for(i = 0; i < 8; i++){ if((b & 1) == 1){ p ^= a; } b >>= 1; carry = a & 0x80; a <<= 1; if(carry == 0x80){ a ^= 0x1b; } } return p; } void MixColumns(State* state){ /* Applies the MixColumns method to the state. See Section 5.1.3 of the standard for explanation. */ int c, r; for(c = 0; c < Nb; c++){ uint8_t temp[4]; temp[0] = galoisMultiply((*state)[0][c], 2) ^ galoisMultiply((*state)[1][c], 3) ^ (*state)[2][c] ^ (*state)[3][c]; temp[1] = (*state)[0][c] ^ galoisMultiply((*state)[1][c], 2) ^ galoisMultiply((*state)[2][c], 3) ^ (*state)[3][c]; temp[2] = (*state)[0][c] ^ (*state)[1][c] ^ galoisMultiply((*state)[2][c], 2) ^ galoisMultiply((*state)[3][c], 3); temp[3] = galoisMultiply((*state)[0][c], 3) ^ (*state)[1][c] ^ (*state)[2][c] ^ galoisMultiply((*state)[3][c], 2); /* Copy temp array to state */ for(r = 0; r < 4; r++){ (*state)[r][c] = temp[r]; } } }
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes void InvMixColumns(State* state){ /* Applies InvMixColumns to the state. See Section 5.3.3 of the standard for explanation. */ int c, r; for(c = 0; c < Nb; c++){ uint8_t temp[4]; temp[0] = galoisMultiply((*state)[0][c], 14) ^ galoisMultiply((*state)[1][c], 11) ^ galoisMultiply((*state)[2][c], 13) ^ galoisMultiply((*state)[3][c], 9); temp[1] = galoisMultiply((*state)[0][c], 9) ^ galoisMultiply((*state)[1][c], 14) ^ galoisMultiply((*state)[2][c], 11) ^ galoisMultiply((*state)[3][c], 13); temp[2] = galoisMultiply((*state)[0][c], 13) ^ galoisMultiply((*state)[1][c], 9) ^ galoisMultiply((*state)[2][c], 14) ^ galoisMultiply((*state)[3][c], 11); temp[3] = galoisMultiply((*state)[0][c], 11) ^ galoisMultiply((*state)[1][c], 13) ^ galoisMultiply((*state)[2][c], 9) ^ galoisMultiply((*state)[3][c], 14); /* Copy temp array to state */ for(r = 0; r < 4; r++){ (*state)[r][c] = temp[r]; } } } void AddRoundKey(State* state, uint8_t* roundKey){ /* Takes a pointer to the start of a round key and XORs it with the columns of the state. */ int c, r; for(c = 0; c < Nb; c++){ for(r = 0; r < 4; r++){ /* XOR each column with the round key */ (*state)[r][c] ^= *roundKey; roundKey++; } } } /* AES sub-sub-methods */ uint8_t* SubWord(uint8_t* a){ /* Substitute bytes in a word using the sbox. */ int i; uint8_t* init = a; for(i = 0; i < 4; i++){ *a = sbox[*a]; a++; } return init; } uint8_t* RotWord(uint8_t* a){ /* Rotate word then copy to pointer. */ uint8_t rot[] = {a[1], a[2], a[3], a[0]}; memcpy(a, rot, 4); return a; }
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes uint8_t* Rcon(int a){ /* Calculates the round constant and returns it in an array. This implementation is adapted from https://github.com/secworks/aes/blob/6fb0aef25df082d68da9f75e2a682441b5f9ff8e/src/model/python/rcon.py#L180 */ uint8_t rcon = 0x8d; int i; for(i = 0; i < a; i++){ rcon = ((rcon << 1) ^ (0x11b & - (rcon >> 7))); } /* The round constant array is always of the form [rcon, 0, 0, 0] */ uint8_t* word = calloc(4, sizeof(uint8_t)); word[0] = rcon; return word; } /* Word helper methods */ uint8_t* xorWords(uint8_t* a, uint8_t* b){ /* Takes the two pointers to the start of 4 byte words and XORs the words, overwriting the first. Returns a pointer to the first byte of the first word. */ int i; uint8_t* init = a; for(i = 0; i < 4; i++, a++, b++){ *a ^= *b; } return init; } uint8_t* copyWord(uint8_t* start){ /* Returns a pointer to a copy of a word. */ int i; uint8_t* word = malloc(sizeof(uint8_t) * 4); for(i = 0; i < 4; i++, start++){ word[i] = *start; } return word; } uint8_t* getWord(uint8_t* w, int i){ /* Takes a word number (w[i] in spec) and returns a pointer to the first of it's 4 bytes. */ return &w[4*i]; }
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes Answer: There's a lot of stuff in the header file that looks like implementation detail, which could be private to aes.c. The header should just have the public types and functions that are intended to be called from outside. Don't #include *.c files - compile them separately, and link the resulting object files. The non-public functions should be declared with static linkage, so they don't pollute the namespace of other translation units. Return value from malloc() must not be dereferenced, unless it's confirmed not to be null. Similarly, don't assume strtol() is always successful - check before using the result. I get quite a lot of compiler and Valgrind warnings - definitely worth addressing these: gcc-11 -std=c17 -fPIC -gdwarf-4 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Wstrict-prototypes -fanalyzer -Wconversion 275946.c -o 275946 275946.c:68:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes] 68 | int main(){ | ^~~~ 275946.c: In function ‘main’: 275946.c:71:13: warning: passing argument 1 of ‘encrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 71 | encrypt("3243f6a8885a308d313198a2e0370734", "2b7e151628aed2a6abf7158809cf4f3c"); /* Appendix B example */ | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:14:20: note: expected ‘char *’ but argument is of type ‘const char *’ 14 | void encrypt(char* plain, char* key); | ~~~~~~^~~~~ 275946.c:71:49: warning: passing argument 2 of ‘encrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 71 | encrypt("3243f6a8885a308d313198a2e0370734", "2b7e151628aed2a6abf7158809cf4f3c"); /* Appendix B example */ | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:14:33: note: expected ‘char *’ but argument is of type ‘const char *’ 14 | void encrypt(char* plain, char* key);
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes 14 | void encrypt(char* plain, char* key); | ~~~~~~^~~ 275946.c:72:13: warning: passing argument 1 of ‘encrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 72 | encrypt("00112233445566778899aabbccddeeff", "000102030405060708090a0b0c0d0e0f"); /* Appendix C 128-bit example */ | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:14:20: note: expected ‘char *’ but argument is of type ‘const char *’ 14 | void encrypt(char* plain, char* key); | ~~~~~~^~~~~ 275946.c:72:49: warning: passing argument 2 of ‘encrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 72 | encrypt("00112233445566778899aabbccddeeff", "000102030405060708090a0b0c0d0e0f"); /* Appendix C 128-bit example */ | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:14:33: note: expected ‘char *’ but argument is of type ‘const char *’ 14 | void encrypt(char* plain, char* key); | ~~~~~~^~~ 275946.c:73:13: warning: passing argument 1 of ‘encrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 73 | encrypt("00112233445566778899aabbccddeeff", "000102030405060708090a0b0c0d0e0f1011121314151617"); /* Appendix C 192-bit example */ | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:14:20: note: expected ‘char *’ but argument is of type ‘const char *’ 14 | void encrypt(char* plain, char* key); | ~~~~~~^~~~~ 275946.c:73:49: warning: passing argument 2 of ‘encrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 73 | encrypt("00112233445566778899aabbccddeeff", "000102030405060708090a0b0c0d0e0f1011121314151617"); /* Appendix C 192-bit example */ | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes 275946.c:14:33: note: expected ‘char *’ but argument is of type ‘const char *’ 14 | void encrypt(char* plain, char* key); | ~~~~~~^~~ 275946.c:74:13: warning: passing argument 1 of ‘encrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 74 | encrypt("00112233445566778899aabbccddeeff", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); /* Appendix C 256-bit example */ | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:14:20: note: expected ‘char *’ but argument is of type ‘const char *’ 14 | void encrypt(char* plain, char* key); | ~~~~~~^~~~~ 275946.c:74:49: warning: passing argument 2 of ‘encrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 74 | encrypt("00112233445566778899aabbccddeeff", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); /* Appendix C 256-bit example */ | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:14:33: note: expected ‘char *’ but argument is of type ‘const char *’ 14 | void encrypt(char* plain, char* key); | ~~~~~~^~~ 275946.c:77:13: warning: passing argument 1 of ‘decrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 77 | decrypt("3925841d02dc09fbdc118597196a0b32", "2b7e151628aed2a6abf7158809cf4f3c"); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:15:20: note: expected ‘char *’ but argument is of type ‘const char *’ 15 | void decrypt(char* cipher, char* key); | ~~~~~~^~~~~~ 275946.c:77:49: warning: passing argument 2 of ‘decrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 77 | decrypt("3925841d02dc09fbdc118597196a0b32", "2b7e151628aed2a6abf7158809cf4f3c");
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes 77 | decrypt("3925841d02dc09fbdc118597196a0b32", "2b7e151628aed2a6abf7158809cf4f3c"); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:15:34: note: expected ‘char *’ but argument is of type ‘const char *’ 15 | void decrypt(char* cipher, char* key); | ~~~~~~^~~ 275946.c:78:13: warning: passing argument 1 of ‘decrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 78 | decrypt("69c4e0d86a7b0430d8cdb78070b4c55a", "000102030405060708090a0b0c0d0e0f"); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:15:20: note: expected ‘char *’ but argument is of type ‘const char *’ 15 | void decrypt(char* cipher, char* key); | ~~~~~~^~~~~~ 275946.c:78:49: warning: passing argument 2 of ‘decrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 78 | decrypt("69c4e0d86a7b0430d8cdb78070b4c55a", "000102030405060708090a0b0c0d0e0f"); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:15:34: note: expected ‘char *’ but argument is of type ‘const char *’ 15 | void decrypt(char* cipher, char* key); | ~~~~~~^~~ 275946.c:79:13: warning: passing argument 1 of ‘decrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 79 | decrypt("dda97ca4864cdfe06eaf70a0ec0d7191", "000102030405060708090a0b0c0d0e0f1011121314151617"); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:15:20: note: expected ‘char *’ but argument is of type ‘const char *’ 15 | void decrypt(char* cipher, char* key); | ~~~~~~^~~~~~ 275946.c:79:49: warning: passing argument 2 of ‘decrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 79 | decrypt("dda97ca4864cdfe06eaf70a0ec0d7191", "000102030405060708090a0b0c0d0e0f1011121314151617");
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:15:34: note: expected ‘char *’ but argument is of type ‘const char *’ 15 | void decrypt(char* cipher, char* key); | ~~~~~~^~~ 275946.c:80:13: warning: passing argument 1 of ‘decrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 80 | decrypt("8ea2b7ca516745bfeafc49904b496089", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:15:20: note: expected ‘char *’ but argument is of type ‘const char *’ 15 | void decrypt(char* cipher, char* key); | ~~~~~~^~~~~~ 275946.c:80:49: warning: passing argument 2 of ‘decrypt’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 80 | decrypt("8ea2b7ca516745bfeafc49904b496089", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275946.c:15:34: note: expected ‘char *’ but argument is of type ‘const char *’ 15 | void decrypt(char* cipher, char* key); | ~~~~~~^~~ 275946.c: In function ‘AES_main’: 275946.c:102:33: warning: conversion to ‘size_t’ {aka ‘long unsigned int’} from ‘int’ may change the sign of the result [-Wsign-conversion] 102 | keySchedule = calloc(4 * Nb * (Nr(keySize) + 1), sizeof(uint8_t)); | ~~~~~~~^~~~~~~~~~~~~~~~~~~ 275946.c: In function ‘stringToBytes’: 275946.c:301:18: warning: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare] 301 | for(i = 0; i < strlen(str) - 1; i += 2){ | ^
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes 301 | for(i = 0; i < strlen(str) - 1; i += 2){ | ^ 275946.c:310:22: warning: conversion from ‘long int’ to ‘uint8_t’ {aka ‘unsigned char’} may change value [-Wconversion] 310 | bytes[i/2] = strtol(pair, NULL, 16); | ^~~~~~ In function ‘toState’: 275946.c:240:15: warning: dereference of possibly-NULL ‘stateptr’ [CWE-690] [-Wanalyzer-possible-null-dereference] 240 | *stateptr = malloc(4 * sizeof(uint8_t*)); | ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ‘toState’: events 1-2 | | 239 | State* stateptr = malloc(sizeof(State)); | | ^~~~~~~~~~~~~~~~~~~~~ | | | | | (1) this call could return NULL | 240 | *stateptr = malloc(4 * sizeof(uint8_t*)); | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (2) ‘stateptr’ could be NULL: unchecked value from (1) | In function ‘fromState’: 275946.c:267:16: warning: dereference of possibly-NULL ‘outputptr’ [CWE-690] [-Wanalyzer-possible-null-dereference] 267 | *outputptr = malloc(sizeof(uint8_t) * 16); | ~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ‘fromState’: events 1-2 | | 266 | uint8_t** outputptr = malloc(sizeof(uint8_t*)); | | ^~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (1) this call could return NULL | 267 | *outputptr = malloc(sizeof(uint8_t) * 16); | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (2) ‘outputptr’ could be NULL: unchecked value from (1) | 275946.c:274:21: warning: dereference of possibly-NULL ‘output’ [CWE-690] [-Wanalyzer-possible-null-dereference] 274 | *output = (*state)[j][i]; | ~~~~~~~~^~~~~~~~~~~~~~~~
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes 274 | *output = (*state)[j][i]; | ~~~~~~~~^~~~~~~~~~~~~~~~ ‘fromState’: events 1-3 | | 267 | *outputptr = malloc(sizeof(uint8_t) * 16); | | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (1) this call could return NULL |...... | 270 | for(i = 0; i < 4; i++){ | | ~~~~~ | | | | | (2) following ‘true’ branch (when ‘i <= 3’)... | 271 | for(j = 0; j < Nb; j++){ | | ~~~~~ | | | | | (3) ...to here | ‘fromState’: events 4-6 | | 271 | for(j = 0; j < Nb; j++){ | | ^ | | | | | (4) following ‘true’ branch (when ‘j <= 3’)... |...... | 274 | *output = (*state)[j][i]; | | ~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | | | (5) ...to here | | (6) ‘output’ could be NULL: unchecked value from (1) | In function ‘stringToBytes’: 275946.c:305:9: warning: dereference of possibly-NULL ‘pair’ [CWE-690] [-Wanalyzer-possible-null-dereference] 305 | memcpy(pair, &str[i], 2); | ^~~~~~~~~~~~~~~~~~~~~~~~ ‘stringToBytes’: events 1-4 | | 301 | for(i = 0; i < strlen(str) - 1; i += 2){ | | ~~^~~~~~~~~~~~~~~~~ | | | | | (1) following ‘true’ branch... | 302 | /* Allocate space for pair of nibbles */ | 303 | char* pair = malloc(2 * sizeof(char)); | | ~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (2) ...to here | | (3) this call could return NULL
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes | | (3) this call could return NULL | 304 | /* Copy current and next character to pair */ | 305 | memcpy(pair, &str[i], 2); | | ~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (4) ‘pair’ could be NULL: unchecked value from (3) | In function ‘_ShiftRows’: 275946.c:355:9: warning: dereference of possibly-NULL ‘*_13 + _15’ [CWE-690] [-Wanalyzer-possible-null-dereference] 355 | memcpy((*state)[i], temp, 4); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ ‘InvCipher’: events 1-2 | | 200 | uint8_t** InvCipher(uint8_t* input, uint8_t* w, size_t keySize){ | | ^~~~~~~~~ | | | | | (1) entry to ‘InvCipher’ |...... | 208 | State* state = toState(input); | | ~~~~~~~~~~~~~~ | | | | | (2) calling ‘toState’ from ‘InvCipher’ | +--> ‘toState’: events 3-16 | | 230 | State* toState(uint8_t* input){ | | ^~~~~~~ | | | | | (3) entry to ‘toState’ |...... | 242 | for(i = 0; i < 4; i++){ | | ~~~~~ | | | | | (4) following ‘true’ branch (when ‘i <= 3’)... | | (7) following ‘true’ branch (when ‘i <= 3’)... | | (9) following ‘true’ branch (when ‘i <= 3’)... | | (11) following ‘true’ branch (when ‘i <= 3’)... | | (13) following ‘false’ branch (when ‘i > 3’)... | 243 | state[i] = malloc(Nb * sizeof(uint8_t)); | | ~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | |
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes | | | | | | | (6) this call could return NULL | | (5) ...to here | | (8) ...to here | | (10) ...to here | | (12) ...to here |...... | 246 | for(i = 0; i < 4; i++){ | | ~~~~~ ~~~~~ | | | | | | | (15) following ‘true’ branch (when ‘i <= 3’)... | | (14) ...to here | 247 | for(j = 0; j < Nb; j++){ | | ~~~~~ | | | | | (16) ...to here | ‘toState’: events 17-18 | | 247 | for(j = 0; j < Nb; j++){ | | ^ | | | | | (17) following ‘true’ branch (when ‘j <= 3’)... |...... | 251 | state[j][i] = *input; | | ~ | | | | | (18) ...to here | ‘toState’: events 19-20 | | 246 | for(i = 0; i < 4; i++){ | | ~~~ | | | | | (20) ...to here | 247 | for(j = 0; j < Nb; j++){ | | ^ | | | | | (19) following ‘false’ branch (when ‘j > 3’)... | <------+ | ‘InvCipher’: events 21-22 | | 208 | State* state = toState(input); | | ^~~~~~~~~~~~~~ | | |
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes | | ^~~~~~~~~~~~~~ | | | | | (21) returning to ‘InvCipher’ from ‘toState’ |...... | 211 | AddRoundKey(state, getWord(w, Nr(keySize) * Nb)); | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (22) calling ‘AddRoundKey’ from ‘InvCipher’ | +--> ‘AddRoundKey’: event 23 | | 427 | void AddRoundKey(State* state, uint8_t* roundKey){ | | ^~~~~~~~~~~ | | | | | (23) entry to ‘AddRoundKey’ | ‘AddRoundKey’: events 24-29 | | 433 | for(c = 0; c < Nb; c++){ | | ^ ~~~ | | | | | | | (29) ...to here | | (24) following ‘true’ branch (when ‘c <= 3’)... | 434 | for(r = 0; r < 4; r++){ | | ~~~~~ ~~~~~ | | | | | | | (26) following ‘true’ branch (when ‘r <= 3’)... | | | (28) following ‘false’ branch (when ‘r > 3’)... | | (25) ...to here | 435 | /* XOR each column with the round key */ | 436 | (*state)[r][c] ^= *roundKey; | | ~~~~~~~~ | | | | | (27) ...to here | <------+ | ‘InvCipher’: events 30-33 | | 211 | AddRoundKey(state, getWord(w, Nr(keySize) * Nb)); | | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (30) possible return of NULL to ‘InvCipher’ from ‘AddRoundKey’ | 212 | for(i = Nr(keySize) - 1; i >= 1; i--){
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes | 212 | for(i = Nr(keySize) - 1; i >= 1; i--){ | | ~~~~~~ | | | | | (31) following ‘true’ branch (when ‘i > 0’)... | 213 | InvShiftRows(state); | | ~~~~~~~~~~~~~~~~~~~ | | | | | (32) ...to here | | (33) calling ‘InvShiftRows’ from ‘InvCipher’ | +--> ‘InvShiftRows’: events 34-35 | | 363 | void InvShiftRows(State* state){ | | ^~~~~~~~~~~~ | | | | | (34) entry to ‘InvShiftRows’ | 364 | _ShiftRows(state, 1); | | ~~~~~~~~~~~~~~~~~~~~ | | | | | (35) calling ‘_ShiftRows’ from ‘InvShiftRows’ | +--> ‘_ShiftRows’: events 36-38 | | 341 | void _ShiftRows(State* state, int multiplier){ | | ^~~~~~~~~~ | | | | | (36) entry to ‘_ShiftRows’ |...... | 347 | for(i = 0; i < 4; i++){ | | ~~~~~ | | | | | (37) following ‘true’ branch (when ‘i <= 3’)... |...... | 350 | for(j = 0; j < Nb; j++){ | | ~~~~~ | | | | | (38) ...to here | ‘_ShiftRows’: events 39-41 | | 350 | for(j = 0; j < Nb; j++){ | | ^ | | | | | (39) following ‘true’ branch (when ‘j <= 3’)...
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes | | (39) following ‘true’ branch (when ‘j <= 3’)... | 351 | /* The multiplier determines whether to do a left or right shift */ | 352 | temp[((j + Nb) + (multiplier * i)) % Nb] = (*state)[i][j]; | | ~~~~~~~~ | | | | | (40) ...to here |...... | 355 | memcpy((*state)[i], temp, 4); | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (41) ‘*_13 + _15’ could be NULL: unchecked value from (6) | In function ‘Rcon’: 275946.c:479:13: warning: dereference of possibly-NULL ‘word’ [CWE-690] [-Wanalyzer-possible-null-dereference] 479 | word[0] = rcon; | ~~~~~~~~^~~~~~ ‘Rcon’: events 1-2 | | 478 | uint8_t* word = calloc(4, sizeof(uint8_t)); | | ^~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (1) this call could return NULL | 479 | word[0] = rcon; | | ~~~~~~~~~~~~~~ | | | | | (2) ‘word’ could be NULL: unchecked value from (1) | In function ‘copyWord’: 275946.c:505:17: warning: dereference of possibly-NULL ‘word’ [CWE-690] [-Wanalyzer-possible-null-dereference] 505 | word[i] = *start; | ~~~~~~~~^~~~~~~~ ‘copyWord’: events 1-4 | | 503 | uint8_t* word = malloc(sizeof(uint8_t) * 4); | | ^~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (1) this call could return NULL | 504 | for(i = 0; i < 4; i++, start++){
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes | 504 | for(i = 0; i < 4; i++, start++){ | | ~~~~~ | | | | | (2) following ‘true’ branch (when ‘i <= 3’)... | 505 | word[i] = *start; | | ~~~~~~~~~~~~~~~~ | | | | | | | (4) ‘word + (sizetype)i’ could be NULL: unchecked value from (1) | | (3) ...to here |
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes valgrind --leak-check=full ./275946 ==401323== Memcheck, a memory error detector ==401323== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==401323== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info ==401323== Command: ./275946 ==401323== ENCRYPTION: ==401323== Invalid read of size 1 ==401323== at 0x48B2055: ____strtol_l_internal (strtol_l.c:432) ==401323== by 0x109A6E: stringToBytes (275946.c:310) ==401323== by 0x1092CD: AES_main (275946.c:94) ==401323== by 0x109437: encrypt (275946.c:125) ==401323== by 0x1091D4: main (275946.c:71) ==401323== Address 0x4a514d2 is 0 bytes after a block of size 2 alloc'd ==401323== at 0x483F7B5: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==401323== by 0x109A3D: stringToBytes (275946.c:303) ==401323== by 0x1092CD: AES_main (275946.c:94) ==401323== by 0x109437: encrypt (275946.c:125) ==401323== by 0x1091D4: main (275946.c:71) ==401323== ==401323== Invalid read of size 1 ==401323== at 0x48B2055: ____strtol_l_internal (strtol_l.c:432) ==401323== by 0x109A6E: stringToBytes (275946.c:310) ==401323== by 0x109303: AES_main (275946.c:98) ==401323== by 0x109437: encrypt (275946.c:125) ==401323== by 0x1091D4: main (275946.c:71) ==401323== Address 0x4a51a22 is 0 bytes after a block of size 2 alloc'd ==401323== at 0x483F7B5: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==401323== by 0x109A3D: stringToBytes (275946.c:303) ==401323== by 0x109303: AES_main (275946.c:98) ==401323== by 0x109437: encrypt (275946.c:125) ==401323== by 0x1091D4: main (275946.c:71) ==401323== 3925841d02dc09fbdc118597196a0b32 69c4e0d86a7b0430d8cdb78070b4c55a dda97ca4864cdfe06eaf70a0ec0d7191 8ea2b7ca516745bfeafc49904b496089 DECRYPTION: ==401323== Invalid read of size 1 ==401323== at 0x48B2055: ____strtol_l_internal (strtol_l.c:432) ==401323== by 0x109A6E: stringToBytes (275946.c:310)
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes ==401323== by 0x109A6E: stringToBytes (275946.c:310) ==401323== by 0x1092CD: AES_main (275946.c:94) ==401323== by 0x109462: decrypt (275946.c:129) ==401323== by 0x109247: main (275946.c:77) ==401323== Address 0x4a597e2 is 0 bytes after a block of size 2 alloc'd ==401323== at 0x483F7B5: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==401323== by 0x109A3D: stringToBytes (275946.c:303) ==401323== by 0x1092CD: AES_main (275946.c:94) ==401323== by 0x109462: decrypt (275946.c:129) ==401323== by 0x109247: main (275946.c:77) ==401323== ==401323== Invalid read of size 1 ==401323== at 0x48B2055: ____strtol_l_internal (strtol_l.c:432) ==401323== by 0x109A6E: stringToBytes (275946.c:310) ==401323== by 0x109303: AES_main (275946.c:98) ==401323== by 0x109462: decrypt (275946.c:129) ==401323== by 0x109247: main (275946.c:77) ==401323== Address 0x4a59d32 is 0 bytes after a block of size 2 alloc'd ==401323== at 0x483F7B5: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==401323== by 0x109A3D: stringToBytes (275946.c:303) ==401323== by 0x109303: AES_main (275946.c:98) ==401323== by 0x109462: decrypt (275946.c:129) ==401323== by 0x109247: main (275946.c:77) ==401323== 3243f6a8885a308d313198a2e0370734 00112233445566778899aabbccddeeff 00112233445566778899aabbccddeeff 00112233445566778899aabbccddeeff ==401323== ==401323== HEAP SUMMARY: ==401323== in use at exit: 0 bytes in 0 blocks ==401323== total heap usage: 819 allocs, 819 frees, 5,880 bytes allocated ==401323== ==401323== All heap blocks were freed -- no leaks are possible ==401323== ==401323== For lists of detected and suppressed errors, rerun with: -s ==401323== ERROR SUMMARY: 304 errors from 4 contexts (suppressed: 0 from 0)
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c, aes I recommend working through these issues, and posting revised code as a follow-up question.
{ "domain": "codereview.stackexchange", "id": 45531, "lm_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, aes", "url": null }
c++, multithreading Title: C++ inline minimalist thread pool Question: This is a "minimal thread pool" I came up with to compare with a colleague's approach using Rust's Rayon's par_bridge() to automatically parallelize looping over an indexed container (a vector in his case). This is basically a std::for_each with std::execution::unsequenced_policy (in this case), but you have access to the guts of the pool (you can decide on chunk size, number of threads, .. waiting for executors in C++26). bool process_one(string filePath); // can be a lambda passed as argument too void loopFilesVect(vector<string>& filesVect, int packSize, int nbThreads) { int nTh = nbThreads; uint32_t N = filesVect.size()/* #items */, c = N/packSize /* #packs */; mutex mtx; vector< unique_ptr<std::latch> > sigs; // unique_ptr for automatic deletion of latches
{ "domain": "codereview.stackexchange", "id": 45532, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading", "url": null }
c++, multithreading int k = 0; atomic_uint32_t success = 0; auto process_chunk = [&](const uint32_t start, const uint32_t end) { cerr<<std::format(" Worker {} : {} to {}\n", start/packSize, start,end-1); for(unsigned int i = start; i < end; ++i) { if(process_one(filesVect[i])) success++; else cerr<<" error processing "<<filesVect[i]<<"\n"; } { scoped_lock<mutex> g{ mtx }; sigs[k++]->count_down(); } cout<<std::format(" Worker {} done\n", start/packSize); }; std::vector<std::future<void>> workers; // std::async() -> future #define submitPack(start,end) { sigs.emplace_back(new std::latch{1}); \ workers.push_back( std::async(std::launch::async, process_chunk, start, end )); } cout<<std::format(" Processing {} file{}..", N, N==1?"":"s"); { if(nTh>c) nTh = c; auto it = sigs.cbegin(); int n = 0; for(n = 0; n < nTh; n++) // use up allowed task count submitPack( n*packSize, std::min((n+1)*packSize,N) ); (*it)->wait(); it++; // wait for 1st task to finish, so we can start a new one without exceeding nTh n = nTh/* n*packSize already processed */; c-- /* now last pack makes n*packSize > c*packSize */; while(n*packSize < N) { // do nothing if all packs already submitted submitPack( n*packSize, n==c ? N/*last one*/ : (n+1)*packSize ); if( n==c ) break; // previous line just submitted last pack (*it)->wait(); it++; // wait for oldest task to finish } sigs.back()->wait(); // wait for the last pack to be processed } cout<<std::format("Done ({} successfully processed)\n", success.load()); } loopFilesVect(vFiles, thread::hardware_concurrency()/2, 200);
{ "domain": "codereview.stackexchange", "id": 45532, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading", "url": null }
c++, multithreading loopFilesVect(vFiles, thread::hardware_concurrency()/2, 200); Performance was similar to Rust's, which was satisfying (given the power of Rayon). It uses the lightest synchronization object available (a latch{1}), and it's all in front of you : you can make this as sophisticated as you want (from adding atomic counters for statistics like nProcessed, nFailed, .. to using an elaborate synch mechanism beyond scoped_lock - but then maybe you need a Pro-thread pool). Do you see anything wrong/improvable with this implementation ?
{ "domain": "codereview.stackexchange", "id": 45532, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading", "url": null }
c++, multithreading Answer: Code style This code is terrible to read; the formatting is inconsistent, sometimes there are multiple statements per line, sometimes not. There are comments in the middle of lines, making it easy to miss things. I recommend you use an automatic code formatter to reformat your code. Also avoid unnecessary abbreviations and one-letter variables. Exceptions are only things that are very commonly used, like i for a loop variable. However, you have N, n, k and c, and it's very hard to tell what those are from just their name alone. This function does too many things You claim "this is a minimal thread pool", but it's not. It's a function that only works on a vector of strings, and calls process_one() on each of them in parallel. What if you have something that is not a vector of strings? What if you want to call some other function than process_one()? I would try to create something that's just a generic thread pool, without hardcoding what kind of container to work on or what function to call on each of the elements. That will result in much more reusable code. Avoid macros submitPack() does not need to be a macro, just make it a lambda. Use std::size_t for sizes, counts and indices You are mixing int, unsigned int and uint32_t. Be consistent, and prefer to use std::size_t for sizes, counts and indices. It's more complicated than necessary There's a mutex, latches and futures. You shouldn't need all three. Furthermore, you are starting a new thread for each chunk, which has some unnecessary overhead. I would just start nTh tasks that each pick chunks themselves until all chunks have been processed. Something like: auto process_chunks = [&]() { while (true) { std::size_t start; std::size_t end; { std::lock_guard lock(mtx); if (k > c) return; start = k * packSize; end = std::min(start + packSize, N); k++; }
{ "domain": "codereview.stackexchange", "id": 45532, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading", "url": null }
c++, multithreading end = std::min(start + packSize, N); k++; } for (std::size_t i = start; i < end; ++i) process_one(filesVect[i]); } }
{ "domain": "codereview.stackexchange", "id": 45532, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading", "url": null }
c++, multithreading std::vector<std::jthread> workers; workers.reserve(n); for (std::size_t n = 0; n < nTh; ++n) { workers.emplace_back(process_chunks); } // Wait for all work to finish: workers.clear(); I've used std::jthread here for simplicity, but you can do the same with std::async(). And instead of using a mutex, you could even use a std::atomic<std::size_t> to track the next chunk to process. loopFilesVect() is called with parameters in the wrong order When you call loopFilesVect() at the end of your code, you passed the number of threads and the chunk size in the wrong order. This is a common problem when passing two parameters of the same type; the compiler cannot tell that there is a problem here. You can avoid this in several ways. Maybe the simplest is to not have a parameter for the number of threads, but just the chunk size, and always use up to std::thread::hardware_concurrency() threads. Another way is to define a struct that contains the parameters, so you can use designated initializers: struct thread_pool_parameters { std::size_t packSize; std::size_t nbThreads; }; void loopFilesVect(vector<string>& filesVect, thread_pool_parameters parameters) { … } loopFilesVect(vFiles, {.packSize = 200, .nbThreads = std::thread::hardware_concurrency() / 2});
{ "domain": "codereview.stackexchange", "id": 45532, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading", "url": null }
php, laravel, eloquent Title: Sanitize URL string for Insertion Upon DB table via Eloquent model Question: In my case I am saving a URL into my database via Eloquent Model: namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; class PageLink extends Model { use HasFactory; protected $table='links'; public function setUrlAttribute(string $url):void { $saneUrl = trim($url); $saneUrl = filter_var($url, FILTER_SANITIZE_URL); $saneUrl = preg_replace("/javascript:.*/","",$saneUrl); $saneUrl = htmlspecialchars($url); $saneUrl = Str::of($url)->stripTags()->toString(); /** * Regex was found into https://stackoverflow.com/a/36564776 * The idea is to extract the url from attack vectors such as: * * "http://example.com\"/> <IMG SRC= onmouseover=\"alert('xxs')\"/> * * This allows me to make the entry safe */ preg_match_all('/https?\:\/\/[^\" ]+/i', $saneUrl, $match); if(is_array($match[0]) && isset($match[0][0])){ $saneUrl=$match[0][0]; }elseif (is_string($match[0])){ $saneUrl=$match[0]; }else { $saneUrl=""; } $this->attributes['url']=$saneUrl; } } And in my blade view it is rendered as: <a href="{{$link->url}}">{{$link->url}}</a> But also will be provided via AJAX API as well (that is under development). Therefore I want to sanitize my input upon a valid URL. I do not validate it here because my controller does this for me: use Illuminate\Contracts\Validation\Validator; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; Route::post("/url",function(Request $request){ $validator = Validator::create($request->all(),[ 'url'=>"required|url" ],[ 'url'=>"Δεν δώσατε έναν έγγυρο σύνδεσμο" ]);
{ "domain": "codereview.stackexchange", "id": 45533, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, laravel, eloquent", "url": null }
php, laravel, eloquent if($validator->fails()){ return new JsonResponse(['msg'=>$validator->error()],400); } $link = new Link(); $link->url = $request->get('url'); try{ $link->save(); }catch(\Exception $e){ report($e); return new JsonResponse(["msg"=>"Link fails to be saved"],500); } return new JsonResponse($link,201); }); And here is a unit test for the model: namespace Tests\Feature\Unit\Model; use App\Models\Link; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; class UserPageLinkTest extends TestCase { use RefreshDatabase; public static function urlProvider(): array { return [ ['http://example.com<script>alert("XSS");</script>'], ["http://example.com\" onfocus=\"alert(\"Hello\")\""], ["https://example.com\' onfocus='alert('Hello')'"], ["<script>alert(\"XSS\")</script>"], ["http://example.com\"/> <IMG SRC= onmouseover=\"alert('xxs')\"/>"], ["javascript:alert(String.fromCharCode(88,83,83))"] ]; } /** * @dataProvider urlProvider */ public function testUrlSanitizedFromXss($input): void { $model = new Link(); $model->url = $input; $saneUrl = $model->url; $this->assertNotEquals($saneUrl,$input); } } The idea behind the code is to make a minimal/lightweight CMS that manages some fixed pages. But in my case could I omit any other filter and just use regex and still be safe from XSS attacks in the input??? Answer: The biggest problem here is that you are going overboard with precautions. Security is important, but it must be logical.
{ "domain": "codereview.stackexchange", "id": 45533, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, laravel, eloquent", "url": null }
php, laravel, eloquent What $saneUrl = preg_replace("/javascript:.*/","",$saneUrl); is for? Given below you will only allow https:// schema and therefore javascript:// won't make it in anyway? What $saneUrl = htmlspecialchars($url); is for? Given you would apply this sanitization with {{$link->url}} anyway What $saneUrl = Str::of($url)->stripTags()->toString(); is for? What HTML tags you expect to remain after applying htmlspecialchars? ;-) Another problem is that you are trying to use deliberately wrong URLs. Even trying to "extract the URL from attack vectors" WHY? I am genuinely puzzled. A generally accepted approach is to validate the data, and abort processing if validation fails. When you get an URL like this http://example.com\"/> <IMG SRC= onmouseover=\"alert('xxs')\"/>, it shouldn't be processed at all. Return a 422 error or whatever and call it a day. In your place I would do it like this: public function setUrlAttribute(string $url):void { $url = trim($url); $invalidUrl = !filter_var($url, FILTER_VALIDATE_URL); $invalidScheme = !preg_match('~^http~', $url); if ($invalidUrl || $invalidScheme) { throw WhateverLaravelThrowsInSuchCase("Invalid url"); } $this->attributes['url']=$url; } That's all.
{ "domain": "codereview.stackexchange", "id": 45533, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, laravel, eloquent", "url": null }
python, simulation Title: Friendly probability puzzle solved with simulation Question: A friend posed to me a question to see if I could solve it. He says I solved it appropriately. I was hoping someone here could give me a review of the program I wrote to answer it. I figured it would be a good exercise in trying to do things as well as possible and try to follow conventions. The problem Aaron and Alexander are going to have a duel. Apparently, Alexander insulted Aaron and so Aaron has demanded a duel with pistols. The ground rules for the duel are that they will exchange single shots until someone is hit and thus the duel will end with the winner having been the first to hit the opponent. Both Aaron and Alexander have experience with duels and have tracked the frequency of their hits in past duels. freq Alexander hits = 0.6, freq Aaron hits = 0.5. Using these frequencies as probabilities A. What is the probability that Aaron will win the duel if he shoots first? B. What is the probability that Aaron will win the duel if he shoots second? After some digging and research, the problem can be solved treating the duel as an infinite geometric series and the result is A. 0.625 and B. 0.25. I'll save solving it that way in my code for another day. Instead, I solved it by simulating 10,000 duels using their hit probabilities. I know creating a class for a simple problem, but I figured it was a good exercise. Let me know what you think. My code import numpy as np class Contestant: """Creates a contestant for a duel. Attributes: ---------- name: string Name of the contestant hit_prob: NumPy array of float Array containing the contestant's probability of a hit and probability of a miss hit_arr: NumPy array of int Array containing the two possible outcomes of a shot, 1 = hit, 0 = miss. shot_arr: NumPy array of int Array containing 100 predicted shots based on the hit_prob array
{ "domain": "codereview.stackexchange", "id": 45534, "lm_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, simulation", "url": null }
python, simulation Methods: ------- simulate_shots Creates an array of predicted shot results for the shooter """ def __init__(self, name, hit_prob): """Initialize a contestant name, hit probability array, hit array, and an empty shot array.""" self.name = name self.hit_prob = hit_prob self.hit_arr = np.array([1, 0]) self.shot_arr = np.empty(100, dtype='int') def simulate_shots(self, num_selection): """Class method to simulate a series of shots based on the contestant's hit probability. Parameters: ---------- num_selection: int The number of shots to simulate. Returns: numpy.ndarray: Array of the simulated shots.""" # create an array of index numbers to select from hit_indices = np.random.choice(len(self.hit_arr), size=num_selection, p=self.hit_prob) # select those indices from the hit arrays self.shot_arr = self.hit_arr[hit_indices] def duel(first_shooter, second_shooter, volley): """Function to simulate a duel between the two contestants. Parameters: ---------- first_shooter: Contestant Contestant that shoots first second_shooter: Contestant Contestant that shoots second volley: int The current round of the duel. Returns: str: Name of the winner. """ if first_shooter.shot_arr[volley]: return first_shooter.name else: if second_shooter.shot_arr[volley]: return second_shooter.name volley += 1 return duel(first_shooter, second_shooter, volley) # the number of duels to simulate number_of_duels = 10000 # probability arrays for the contestants contestant_1 = Contestant('Aaron', np.array([0.5, 0.5])) contestant_2 = Contestant('Alexander', np.array([0.6, 0.4])) # the lists of wins cont_1_shoots_first = [] cont_2_shoots_first = [] for duels in range(number_of_duels):
{ "domain": "codereview.stackexchange", "id": 45534, "lm_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, simulation", "url": null }
python, simulation for duels in range(number_of_duels): # simulate an array of shots for both contestants contestant_1.simulate_shots(100) contestant_2.simulate_shots(100) # volley until there's a winner and append the winners name to the list cont_1_shoots_first.append(duel(contestant_1, contestant_2, 0)) cont_2_shoots_first.append(duel(contestant_2, contestant_1, 0)) # calculate probabilities print(f"If {contestant_1.name} shoots first, the probability he wins is " f"{cont_1_shoots_first.count(contestant_1.name)/number_of_duels}.") print(f"If {contestant_1.name} shoots second, the probability he wins is " f"{cont_2_shoots_first.count(contestant_1.name)/number_of_duels}.") Edit: "dual" to "duel" Answer: Overall, it looks excellent: Good partitioning of code into class and functions Good layout and flow of the code Good naming of class, functions and variables Lint check (pylint) shows no major issues Great usage of docstrings/comments, especially on function inputs and return values Your question text correctly uses the word "duel", and you even use it a couple times in the code comments. I think you really meant to use "duel" everywhere else in your code, instead of the word "dual". For example: """Creates a contestant for a dual. You should mention the word "pistols" somewhere in your code comments, as you do in the question text. Note: The question was changed after I posted this Answer. The original question used dual instead of duel in several places. For the dual function, it would be helpful to mention in the comments that the function is called recursively. Also explicitly mention the ending condition for the recursion. In the dual function, consider using an if/elif/else: if first_shooter.shot_arr[volley]: return first_shooter.name elif second_shooter.shot_arr[volley]: return second_shooter.name else: volley += 1 return duel(first_shooter, second_shooter, volley)
{ "domain": "codereview.stackexchange", "id": 45534, "lm_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, simulation", "url": null }
python, simulation Firstly, it is a little more compact. Secondly, it makes it clear that one of three things will be returned. I know creating a class for a simple problem, but I figured it was a good exercise. I think what you are trying to say there is that you think it is overkill to use OOP here. Since you've already put in the work, it could allow for easier expansion of your code to add more features.
{ "domain": "codereview.stackexchange", "id": 45534, "lm_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, simulation", "url": null }
rust Title: Rust - idiomatic file search Question: I'm learning Rust. Could you share some tips for improving this code so it's more idiomatic and functional? I would prefer to stick to the standary library, and avoid unnecessary sorting or memory allocations. fn first_file_in_dir(dir_path: &Path, extension: &str) -> Result<PathBuf, io::Error> { let mut matching_path = None; for entry in fs::read_dir(dir_path)? { let entry = entry?; if !entry.file_type()?.is_file() { continue; } let path = entry.path(); if !path.extension().is_some_and(|x| x == extension) { continue; } if let Some(ref mut matching_path) = matching_path { if path < *matching_path { *matching_path = path; } } else { matching_path = Some(path); } } if let Some(matching_path) = matching_path { Ok(matching_path) } else { Err(io::Error::new(io::ErrorKind::NotFound, format!("No *.{} file in {}", extension, dir_path.to_string_lossy()))) } } The function returns the first file with a given extension inside a directory. Because the order of items from fs::read_dir() is platform dependent, it iterates over all files and picks the top one by name. Any I/O errors are propagated to the caller. Thanks!
{ "domain": "codereview.stackexchange", "id": 45535, "lm_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 }
rust Answer: The code already looks fairly good. Some possible improvements: Use cargo fmt ... to format the code according to recommended style guidelines. Use clippy ... to lint your code. I recommend the additional options -- -W clippy::pedantic -W clippy::nursery -W clippy::unwrap_used. Use built-in functions You use Option::is_some_and(). You may as well use Option::ok_or_else(). Subjective opinion Matching Some(ref mut) is okay, but I prefer to match against &mut option instead. Suggested: fn first_file_in_dir(dir_path: &Path, extension: &str) -> Result<PathBuf, io::Error> { let mut matching_path = None; for entry in fs::read_dir(dir_path)? { let entry = entry?; if !entry.file_type()?.is_file() { continue; } let path = entry.path(); if !path.extension().is_some_and(|x| x == extension) { continue; } if let Some(matching_path) = &mut matching_path { if path < *matching_path { *matching_path = path; } } else { matching_path = Some(path); } } matching_path.ok_or_else(|| { io::Error::new( io::ErrorKind::NotFound, format!("No *.{} file in {}", extension, dir_path.to_string_lossy()), ) }) }
{ "domain": "codereview.stackexchange", "id": 45535, "lm_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 }
rust Alternative implementation If you don't mind ignoring erroneous entries, you can even write the method as one expression: pub fn first_file_in_dir(dir_path: &Path, extension: &str) -> Result<PathBuf, io::Error> { fs::read_dir(dir_path)? .filter_map(|result| { result.ok().and_then(|entry| { entry.file_type().ok().and_then(|file_type| { if file_type.is_file() && entry.path().extension().is_some_and(|x| x == extension) { Some(entry.path()) } else { None } }) }) }) .reduce(|lhs, rhs| if lhs < rhs { lhs } else { rhs }) .ok_or_else(|| { io::Error::new( io::ErrorKind::NotFound, format!("No *.{} file in {}", extension, dir_path.to_string_lossy()), ) }) }
{ "domain": "codereview.stackexchange", "id": 45535, "lm_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 }
php Title: Justify Text on Image GD PHP Question: we are trying to justify a long text into a image and we need to justify it. We have solved the problem with this function, but it's too heavy and takes a long time to process the text justification. Any faster solution in order to justify a text? $image = ImageCreateFromJPEG( "sample.jpg" ); $color = imagecolorallocate($image, 0, 0, 0); $font = 'arial.ttf'; $text1 = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum'; $a = imagettftextjustified($image, 20, 0, 50, 50, $color, $font,$text1, 500, $minspacing=3,$linespacing=1); header('Content-type: image/jpeg'); imagejpeg($image,NULL,100);
{ "domain": "codereview.stackexchange", "id": 45536, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php", "url": null }
php function imagettftextjustified(&$image, $size, $angle, $left, $top, $color, $font, $text, $max_width, $minspacing=3,$linespacing=1) { $wordwidth = array(); $linewidth = array(); $linewordcount = array(); $largest_line_height = 0; $lineno=0; $words=explode(" ",$text); $wln=0; $linewidth[$lineno]=0; $linewordcount[$lineno]=0; foreach ($words as $word) { $dimensions = imagettfbbox($size, $angle, $font, $word); $line_width = $dimensions[2] - $dimensions[0]; $line_height = $dimensions[1] - $dimensions[7]; if ($line_height>$largest_line_height) $largest_line_height=$line_height; if (($linewidth[$lineno]+$line_width+$minspacing)>$max_width) { $lineno++; $linewidth[$lineno]=0; $linewordcount[$lineno]=0; $wln=0; } $linewidth[$lineno]+=$line_width+$minspacing; $wordwidth[$lineno][$wln]=$line_width; $wordtext[$lineno][$wln]=$word; $linewordcount[$lineno]++; $wln++; } for ($ln=0;$ln<=$lineno;$ln++) { $slack=$max_width-$linewidth[$ln]; if (($linewordcount[$ln]>1)&&($ln!=$lineno)) $spacing=($slack/($linewordcount[$ln]-1)); else $spacing=$minspacing; $x=0; for ($w=0;$w<$linewordcount[$ln];$w++) { imagettftext($image, $size, $angle, $left + intval($x), $top + $largest_line_height + ($largest_line_height * $ln * $linespacing), $color, $font, $wordtext[$ln][$w]); $x+=$wordwidth[$ln][$w]+$spacing+$minspacing; } } return true; }
{ "domain": "codereview.stackexchange", "id": 45536, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php", "url": null }
php Answer: This submission is about performance, yet it contains no timing measurements. Your summary complaint seems to be: For N words we have N calls to bbox() and to render text(), which will take a Long Time. Ok. Let's see how we could make fewer calls. Absent timing measurements I'm going to assume that both calls have approximately equal cost. I'm going to assume there's some call overhead, so that imagettftext( ... , "hello world", ... ) runs quicker than imagettftext( ... , "hello", ... ) imagettftext( ... , "world", ... ) OP approach extract helper foreach ($words as $word) { ... } for ($ln = 0; $ln <= $lineno; $ln++) { ... for ($w = 0; $w < $linewordcount[$ln]; $w++)
{ "domain": "codereview.stackexchange", "id": 45536, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php", "url": null }
php Please break out the foreach code as a helper, and that first for as another helper function. Each function will have a single responsibility. composite a line at a time That nested for executes, IDK, more than ten times per line? And yet you already know from bbox() which words will appear on the line. Glue some of them together, at least in the case where $spacing is "small" or is equal to $minspacing. Pick one or two break locations, and send 1/2 the words or 1/3 of the words into text() rendering at a time. Downside is slightly different word spacing within the line, even though you still justify to avoid ragged right. LaTeX approach Use a professional solution that achieves high quality typesetting results. Ask LaTeX to render several lines of text as a .PNG bitmap, and composite that into your final graphic image. letter metrics approach We don't exactly have to call bbox() at all, not in this program. Write a program that calls bbox() for 26 upper + lower letters, plus a few punctuation marks and whatever other characters appear in your input corpus. Remember the widths, and write them out to a JSON database. When compositing text, start by reading in that JSON file. Author a helper function that given a word or phrase will use the recorded widths to estimate what bbox() would say. It won't get kerning 100% right, but it will be close enough, as it will know that "l" is skinnier than "m". You might even feed the entire text to the helper, and let it make line break decisions.
{ "domain": "codereview.stackexchange", "id": 45536, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php", "url": null }
c++, recursion, template, concurrency, c++20 Title: Order guaranteed recursive_transform template function implementation with execution policy in C++ Question: This is a follow-up question for A recursive_transform Template Function with Execution Policy, A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++, A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++ and A recursive_depth function for calculating depth of nested types implementation in C++. Considering that the previous std::for_each version recursive_transform doesn’t ensure deterministic behavior, the individual results could be emplaced into the output container in an arbitrary order because of the multiple factors. Therefore, another version recursive_transform template function which is order guaranteed and unwrap_level controlled has been proposed in this post. Referencing the latest call signature of std::ranges::transform, the concept std::copy_constructible is used on the input function parameter. Also, the similar way is used here. The experimental implementation Order guaranteed recursive_transform template function implementation: // recursive_invoke_result_t implementation template<std::size_t, typename, typename> struct recursive_invoke_result { }; template<typename T, typename F> struct recursive_invoke_result<0, F, T> { using type = std::invoke_result_t<F, T>; }; template<std::size_t unwrap_level, typename F, template<typename...> typename Container, typename... Ts> requires (std::ranges::input_range<Container<Ts...>> && requires { typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type; }) struct recursive_invoke_result<unwrap_level, F, Container<Ts...>> { using type = Container<typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type>; };
{ "domain": "codereview.stackexchange", "id": 45537, "lm_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, concurrency, c++20", "url": null }
c++, recursion, template, concurrency, c++20 template<std::size_t unwrap_level, typename F, typename T> using recursive_invoke_result_t = typename recursive_invoke_result<unwrap_level, F, T>::type; // 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>; }; 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;
{ "domain": "codereview.stackexchange", "id": 45537, "lm_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, concurrency, c++20", "url": null }
c++, recursion, template, concurrency, c++20 template<typename OutputIt, std::copy_constructible NAryOperation, typename InputIt, typename... InputIts> constexpr OutputIt transform(OutputIt d_first, NAryOperation op, InputIt first, InputIt last, InputIts... rest) { while (first != last) { *d_first++ = op(*first++, (*rest++)...); } return d_first; } // recursive_transform for the multiple parameters cases (the version with unwrap_level) template<std::size_t unwrap_level = 1, class F, class Arg1, class... Args> requires(unwrap_level <= recursive_depth<Arg1>()) constexpr auto recursive_transform(const F& f, const Arg1& arg1, const Args&... args) { if constexpr (unwrap_level > 0) { recursive_variadic_invoke_result_t<unwrap_level, F, Arg1, Args...> output{}; transform( std::inserter(output, std::ranges::end(output)), [&f](auto&& element1, auto&&... elements) { return recursive_transform<unwrap_level - 1>(f, element1, elements...); }, std::ranges::cbegin(arg1), std::ranges::cend(arg1), std::ranges::cbegin(args)... ); return output; } else if constexpr(std::regular_invocable<F, Arg1, Args...>) { return std::invoke(f, arg1, args...); } else { static_assert(!std::regular_invocable<F, Arg1, Args...>, "Uninvocable?"); } }
{ "domain": "codereview.stackexchange", "id": 45537, "lm_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, concurrency, c++20", "url": null }
c++, recursion, template, concurrency, c++20 // recursive_transform implementation (the version with unwrap_level, with execution policy) template<std::size_t unwrap_level = 1, class ExPo, class T, class F> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>&& (unwrap_level <= recursive_depth<T>())) constexpr auto recursive_transform(ExPo execution_policy, const F& f, const T& input) { if constexpr (unwrap_level > 0) { recursive_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, f, element); }); return output; } else if constexpr(std::regular_invocable<F, T>) { return std::invoke(f, input); } else { static_assert(!std::regular_invocable<F, T>, "Uninvocable?"); } } Full Testing Code The full testing code: // Order guaranteed recursive_transform template function implementation with execution policy in C++ #include <algorithm> #include <cassert> #include <concepts> #include <execution> #include <functional> #include <iostream> #include <iterator> #include <ranges> #include <string> #include <vector> // recursive_depth function implementation template<typename T> constexpr std::size_t recursive_depth() { return 0; } template<std::ranges::input_range Range> constexpr std::size_t recursive_depth() { return recursive_depth<std::ranges::range_value_t<Range>>() + 1; } // recursive_invoke_result_t implementation template<std::size_t, typename, typename> struct recursive_invoke_result { }; template<typename T, typename F> struct recursive_invoke_result<0, F, T> { using type = std::invoke_result_t<F, T>; };
{ "domain": "codereview.stackexchange", "id": 45537, "lm_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, concurrency, c++20", "url": null }
c++, recursion, template, concurrency, c++20 template<std::size_t unwrap_level, typename F, template<typename...> typename Container, typename... Ts> requires (std::ranges::input_range<Container<Ts...>> && requires { typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type; }) struct recursive_invoke_result<unwrap_level, F, Container<Ts...>> { using type = Container<typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type>; }; template<std::size_t unwrap_level, typename F, typename T> using recursive_invoke_result_t = typename recursive_invoke_result<unwrap_level, F, T>::type; // 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": 45537, "lm_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, concurrency, c++20", "url": null }
c++, recursion, template, concurrency, c++20 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; template<typename OutputIt, std::copy_constructible NAryOperation, typename InputIt, typename... InputIts> constexpr OutputIt transform(OutputIt d_first, NAryOperation op, InputIt first, InputIt last, InputIts... rest) { while (first != last) { *d_first++ = op(*first++, (*rest++)...); } return d_first; } // recursive_transform for the multiple parameters cases (the version with unwrap_level) template<std::size_t unwrap_level = 1, class F, class Arg1, class... Args> requires(unwrap_level <= recursive_depth<Arg1>()) constexpr auto recursive_transform(const F& f, const Arg1& arg1, const Args&... args) { if constexpr (unwrap_level > 0) { recursive_variadic_invoke_result_t<unwrap_level, F, Arg1, Args...> output{}; transform( std::inserter(output, std::ranges::end(output)), [&f](auto&& element1, auto&&... elements) { return recursive_transform<unwrap_level - 1>(f, element1, elements...); }, std::ranges::cbegin(arg1), std::ranges::cend(arg1), std::ranges::cbegin(args)... ); return output; } else if constexpr(std::regular_invocable<F, Arg1, Args...>) { return std::invoke(f, arg1, args...); } else { static_assert(!std::regular_invocable<F, Arg1, Args...>, "Uninvocable?"); } }
{ "domain": "codereview.stackexchange", "id": 45537, "lm_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, concurrency, c++20", "url": null }
c++, recursion, template, concurrency, c++20 // recursive_transform implementation (the version with unwrap_level, with execution policy) template<std::size_t unwrap_level = 1, class ExPo, class T, class F> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>&& (unwrap_level <= recursive_depth<T>())) constexpr auto recursive_transform(ExPo execution_policy, const F& f, const T& input) { if constexpr (unwrap_level > 0) { recursive_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, f, element); }); return output; } else if constexpr(std::regular_invocable<F, T>) { return std::invoke(f, input); } else { static_assert(!std::regular_invocable<F, T>, "Uninvocable?"); } } template<std::size_t dim, class T> constexpr auto n_dim_vector_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_vector_generator<dim - 1>(input, times); std::vector<decltype(element)> output(times, element); return output; } } void recursiveTransformTest(); int main() { recursiveTransformTest(); return 0; } void recursiveTransformTest() { for (std::size_t N = 1; N < 10; N++) { std::size_t N1 = N, N2 = N, N3 = N; auto test_vector = n_dim_vector_generator<3>(0, 10);
{ "domain": "codereview.stackexchange", "id": 45537, "lm_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, concurrency, c++20", "url": null }
c++, recursion, template, concurrency, c++20 for (std::size_t z = 1; z <= N3; z++) { for (std::size_t y = 1; y <= N2; y++) { for (std::size_t x = 1; x <= N1; x++) { test_vector.at(z - 1).at(y - 1).at(x - 1) = x * 100 + y * 10 + z; } } } auto expected = recursive_transform<3>([](auto&& element) {return element + 1; }, test_vector); auto actual = recursive_transform<3>(std::execution::par, [](auto&& element) {return element + 1; }, test_vector); std::cout << "N = " << N << ": " << std::to_string(actual == expected) << '\n'; } } The output of the testing code above: N = 1: 1 N = 2: 1 N = 3: 1 N = 4: 1 N = 5: 1 N = 6: 1 N = 7: 1 N = 8: 1 N = 9: 1 A Godbolt link is here. All suggestions are welcome. The summary information: Which question it is a follow-up to? A recursive_transform Template Function with Execution Policy, A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++, A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++ and A recursive_depth function for calculating depth of nested types implementation in C++ What changes has been made in the code since last question? I am attempting to propose another version recursive_transform template function implementation with the following criteria: Order guaranteed in parallel mode (set by execution policy parameter) unwrap_level template parameter controlled Trying to use std::copy_constructible concept Why a new review is being asked for? If there is any possible improvement, please let me know.
{ "domain": "codereview.stackexchange", "id": 45537, "lm_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, concurrency, c++20", "url": null }
c++, recursion, template, concurrency, c++20 Why a new review is being asked for? If there is any possible improvement, please let me know. Answer: The mutexes inhibit parallel execution You use a mutex at each recursion level. This inhibits parallel execution of std::transform(). This defeats the purpose of having an execution_policy parameter. Also, it does nothing to preserve the order. The order preservation comes solely from std::transform() itself. Why is the version without execution policy different? The version of recursive_transform() that doesn't take an execution policy parameter looks very different from the one that does. I would expect it to look mostly the same, the only difference being the presence of execution_policy. One version using std::inserter() and the other creating a new container object and calling resize() on it will likely mean that some container types will only work with one version, others only with the other version. Ideally, they both work on the same set of container types, so they can be used interchangeably. Add a constraint on the invocable In previous reviews we discussed how to properly constrain the type of invocable passed to your recursive algorithms. That can be done here as well. The use of static_assert() is less desirable, as it will only trigger in the deepest recursion level, causing a long and hard to read error message. And the custom message "Uninvocable?" is not very helpful either. At the very least, don't ask a one-word question, but instead state the exact problem clearly, for example by writing something like: static_assert(…, "The function passed to recursive_transform() cannot be invoked" "with the element types at the given recursion level.");
{ "domain": "codereview.stackexchange", "id": 45537, "lm_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, concurrency, c++20", "url": null }
c++, serialization, constrained-templates, c++23 Title: Function templates for serializing/deserializing POD types Question: Are the two function templates below well-formed for serializing/deserializing POD types? Will they work for all the different types that satisfy the constraint pod? Here (live): #include <type_traits> #include <ostream> #include <istream> #include <fstream> #include <print> #include <stdfloat> template <class T> concept pod = std::is_standard_layout_v<T> && std::is_trivial_v<T>; template <pod T> [[ nodiscard ]] bool put_pod( std::ostream& os, const T& value ) { const auto good { os.write( reinterpret_cast<const char*>( &value ), sizeof( value ) ).good( ) }; return good; } template <pod T> [[ nodiscard ]] bool get_pod( std::istream& is, T& value ) { T temp_value; const auto good { is.read( reinterpret_cast<char*>( &temp_value ), sizeof( temp_value ) ).good( ) }; if ( good ) value = temp_value; return good; } int main( ) { { std::ofstream ofs { "data.bin", std::ios::binary | std::ios::app }; if ( !ofs.is_open( ) ) return 1; const std::float32_t value { 7.00035f32 }; const auto good { put_pod( ofs, value ) }; if ( !good ) return 1; std::println( "{}", value ); } std::println( "-----------------------------" ); { std::ifstream ifs { "data.bin", std::ios::binary }; if ( !ifs.is_open( ) ) return 1; while ( true ) { std::float32_t value; const auto good { get_pod( ifs, value ) }; if ( !good ) break; std::println( "{}", value ); } } } Also what other constraints should I use? For instance, std::default_initializable and std::destructible might be useful for get_pod since it both default constructs an instance of type T and then destructs it. However, I'm not sure if it's necessary in this case. Answer: This is not a good idea To answer your questions directly:
{ "domain": "codereview.stackexchange", "id": 45538, "lm_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++, serialization, constrained-templates, c++23", "url": null }
c++, serialization, constrained-templates, c++23 Answer: This is not a good idea To answer your questions directly: Are the two function templates below well-formed for serializing/deserializing POD types? Yes, they are “well-formed”. Will they work for all the different types that satisfy the constraint pod? No. The C++ standard guarantees that serializing and de-serializing data the way you are doing will only round-trip correctly when you run the exact same program. I want to stress that again: the EXACT same program. (And, probably only under the same conditions, though the standard has nothing to say about what those conditions might be.) That means:
{ "domain": "codereview.stackexchange", "id": 45538, "lm_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++, serialization, constrained-templates, c++23", "url": null }
c++, serialization, constrained-templates, c++23 This is not guaranteed to work across different hardware (x86 and ARM, for example). This is not even guaranteed to work if the hardware uses the same ISA (two systems running ARMv8, for example). This is not guaranteed to work on a single system using two different operating systems (if you dual boot on a single machine and try writing with Windows and reading with Linux, or use two different containers or VMs, for example). This is not guaranteed to work even on the same platform, if different compilers are used (GCC for the writer, Clang for the reader, for example). This is not guaranteed to work even on the same platform, with the same compiler, if different versions are used (GCC 12 and 13, for example). This is not even guaranteed to work on the same platform, with the same version of the same compiler, if different compiler flags are used. And this might blow your mind, but even if you take the exact same source code, compile it twice for the exact same platform, with the exact same compiler, with the exact same settings, the two executables are not guaranteed to be able to work together. As in, data serialized out of one might not be compatible as input for the other. It would be a truly evil compiler that did this deliberately; however… and this is the point I’m trying to hammer home… the standard does not promise that this WON’T happen. (And, it might happen accidentally, if some setting gets unknowingly flipped.)
{ "domain": "codereview.stackexchange", "id": 45538, "lm_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++, serialization, constrained-templates, c++23", "url": null }
c++, serialization, constrained-templates, c++23 And if all the above doesn’t scare you out of this idea, this next point should: IF there is something… anything… any incompatibility introduced by a difference in platform, compiler, settings, the phase of the moon, whatever… NOTHING will save you. There is no practical way to guarantee that any data serialized out can be de-serialized back in correctly. You will not be saved by the type system. You will not be saved by any clever programming; even the best-designed and -written types are vulnerable. You will not be given any warnings or errors or any indication of trouble. Your program will simply do something unexpected. THAT should terrify you. I would say the only conceivable use for such a serialization facility would be for backing up/restoring data for a single program, and probably even for a single program run. It might be useful if, say your program will be going to sleep: you can dump the contents of memory, go to sleep, then wake back up and restore the program state. Or if the program is doing one expensive task, but has to stop to do another: it can dump the data for the first task, do the second, then restore the state of the first task and continue. Maaaaaybe it might be useful to save program state, shut down the program, then restart it later and restore the state to where you left off… but that would be highly dangerous; you would need some way to determine that the state is still safe, and there probably is no foolproof way to do that. If you were thinking of using this serialization method to save files to be loaded on other machines, or even on the same machine by different programs, or even using this method to persist data for a single program long-term… dear god, no. Don’t. Serializing data to binary format, for very fast save/load times, is possible. But not like this. Not just carelessly barfing raw memory into a file. “POD” is a useless classification This is particularly true for this use case on two levels.
{ "domain": "codereview.stackexchange", "id": 45538, "lm_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++, serialization, constrained-templates, c++23", "url": null }
c++, serialization, constrained-templates, c++23 “POD” is a useless classification This is particularly true for this use case on two levels. First, let’s look at your concept: template <class T> concept pod = std::is_standard_layout_v<T> && std::is_trivial_v<T>;
{ "domain": "codereview.stackexchange", "id": 45538, "lm_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++, serialization, constrained-templates, c++23", "url": null }
c++, serialization, constrained-templates, c++23 The layout has literally no relevance to what you are trying to do. It doesn’t matter if a type is standard layout or not if all you’re interested in is whether you can bit-blast data into it. Consider the following class: class foo { public: int x; private: int y; }; This is not standard layout, but it is trivial. You could dump its memory representation and reload it, no problem. (Well, no problem aside from all the problems mentioned above. But let’s assume that’s a given.) All you care about is whether the type is trivial, and… and I’ll get to this later… specifically if it’s just trivially copyable. The second level of uselessness of “POD” is specific to what you’re doing. Just because a type is a “POD” type doesn’t mean it can be serialized in the way you are trying to do. Take std::string_view, for example. std::string_view is technically not trivial because it does not have a trivial default constructor, but that isn’t relevant here. It is trivially-copyable, and it is standard-layout (at least in both libstdc++ and libc++, and it may be mandated to be so but I can’t say for sure off the top of my head). However, serializing then de-serializing a std::string_view by merely copying its bits would be a terrible idea. This is why the answer to “Will they work for all the different types that satisfy the constraint pod?” is unequivocally “no”. There are many types that satisfy “POD” (or “standard layout”, or “trivially copyable”) that will not serialize/deserialize properly by merely bit-blasting their guts. So, basically: “POD” is unnecessarily strict for what you are doing; and “POD” is excessively loose for what you are doing.
{ "domain": "codereview.stackexchange", "id": 45538, "lm_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++, serialization, constrained-templates, c++23", "url": null }
c++, serialization, constrained-templates, c++23 Or even more basically: “POD” is wrong for what you are doing. But this isn’t really an issue with the “POD” classification specifically. NOTHING will work as a general concept for a single serialization strategy. Trying to blindly suck an entire category of types into a common serialization strategy is doomed to fail. The only thing that knows whether and how it is safe to serialize a type is the type itself. At the very least, types should be have to opt-in to whether they are okay with being serialized by having their guts copied (or by having their data members individually serialized, or by any method). Or, put another way, it is not so much that “POD” is wrong for what you are doing, as it is that what you are doing is wrong. Don’t use IOStreams’s .good() All of your error checking is done by using the .good() member function of input/output streams. That is not correct. The reason is that .good() doesn’t just check the stream’s error state; it also checks for EOF. But EOF is not an error. It is possible for a stream’s EOF bit to be set even for a successful read. Here is a simple example. Note that the read was successful, but .good() returned false. .good() has a very specific use case… and it’s not what you’re doing. The correct way to check for a read/write error is to use the stream’s bool conversion. Note that in the example above, the bool conversion correctly returns true for a successful read. It will ALWAYS return true for a successful read/write… and never return true if a read/write failed for any reason. Your get_pod() is needlessly complex So you want to confirm that the read was successful before actually changing value. That’s good. To do that, you use a temporary T as a buffer. That’s not so good. Because you do this, you introduce the pointless necessity that T has to be default constructible, even though you already have a T (value).
{ "domain": "codereview.stackexchange", "id": 45538, "lm_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++, serialization, constrained-templates, c++23", "url": null }
c++, serialization, constrained-templates, c++23 Consider instead that while you do need a temporary place to put the input so you can verify the read succeeded before touching value… that temporary place does not need to be a T. For example: template <pod T> [[nodiscard]] auto get_pod(std::istream& is, T& value) -> bool { alignas(T) char buffer[sizeof(T)];
{ "domain": "codereview.stackexchange", "id": 45538, "lm_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++, serialization, constrained-templates, c++23", "url": null }
c++, serialization, constrained-templates, c++23 if (is.read(buffer, sizeof(T))) { std::memcpy(&value, buffer, sizeof(T)); return true; } return false; } The alignas(T) is technically not necessary, but if the buffer has the same alignment as the value, then there is a better chance of being able to copy the memory in chunks, rather than byte-by-byte. Now that you no longer care whether the type is default constructible, you can loosen the constraints: template <typename T> requires std::is_trivially_copyable_v<T> [[nodiscard]] auto put_pod(std::ostream& os, T const& value) { return bool{os.write(reinterpret_cast<char const*>(&value), sizeof(T))}; } template <typename T> requires std::is_trivially_copyable_v<T> [[nodiscard]] auto get_pod(std::istream& is, T& value) { alignas(T) char buffer[sizeof(T)]; if (is.read(buffer, sizeof(T))) { std::memcpy(&value, buffer, sizeof(T)); return true; } return false; } But, again, this is not a good idea. A recommendation for a serialization API So you want a serialize arbitrary types. Fine, but you can’t just blindly assume that all types are serializable, or deserializable, or neither or both. And you can’t assume that all types will want to be serialized in the same way. What I would recommend is to make a single function overload set for serializing, and another for de-serialzing. For example: namespace whatevs { // Don't actually write these; just illustrating the API. [[nodiscard]] auto serialize(std::ostream& o, T const& t) -> std::ostream&; [[nodiscard]] auto deserialize(std::istream& o, T& t) -> std::istream&; } // namespace whatevs Then create overloads for the basic types: namespace whatevs { [[nodiscard]] auto serialize(std::ostream& o, int t) -> std::ostream& { // whatever logic to serialize an int } [[nodiscard]] auto deserialize(std::istream& o, int& t) -> std::istream& { // whatever logic to deserialize an int }
{ "domain": "codereview.stackexchange", "id": 45538, "lm_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++, serialization, constrained-templates, c++23", "url": null }
c++, serialization, constrained-templates, c++23 // Repeat for all built-in types. // // Note that you don't *literally* need to write the functions above for // every built-in type. There are ways to avoid duplicating work. // // You can also add types like std::string. } // namespace whatevs Now anyone who wants their type to be serializable can simply define this function for their type: namespace indi { struct my_type { int x; double y; }; } // namespace indi [[nodiscard]] auto whatevs::serialize(std::ostream& o, indi::my_type const& t) -> std::ostream& { whatevs::serialize(o, t.x); whatevs::serialize(o, t.y); return o; } [[nodiscard]] auto whatevs::deserialize(std::istream& o, indi::my_type& t) -> std::istream& { // Or use temporaries to hold the data, and don't touch t // unless all reads succeed. whatevs::deserialize(i, t.x); whatevs::deserialize(i, t.y); return i; } There are ways you can make this easier and more ergonomic (you might want to make the actual (de)serialize function a neibloid, for example), but that’s the gist. Now you’re probably thinking that it sucks that you can’t auto-generate the obvious default serialize/deserialize function. It does, but that capability is coming. It might look like this: namespace whatevs { template <typename T> requires requires { T::default_serializable; } [[nodiscard]] auto serialize(std::ostream& o, T const& t) -> std::ostream& { template for (constexpr auto member : std::meta::nonstatic_data_members_of(^T)) { if (not serialize(o, t.[:member:])) break; } return o; } } // namespace whatevs And you’d opt into it like this: namespace indi { struct my_type { static constexpr auto default_serializable = true; int x; double y; }; } // namespace indi Something like that, basically. But that’s the future… possibly as early as C++26. For now, you’ll have to hand-roll the serialize/de-serialize functions.
{ "domain": "codereview.stackexchange", "id": 45538, "lm_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++, serialization, constrained-templates, c++23", "url": null }
android, kotlin, kotlin-compose Title: Compose Grid With Lists Question: I have created a Grid out of using the new concept of List in Kotlin. I'm open to any feed back to how this code could be improved. It functions as expected and I'm happy with the results. import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material3.Card import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.grid.ui.theme.DataSource import com.example.grid.ui.theme.DataSource.topics import com.example.grid.ui.theme.GridTheme import com.example.grid.ui.theme.Topic
{ "domain": "codereview.stackexchange", "id": 45539, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "android, kotlin, kotlin-compose", "url": null }
android, kotlin, kotlin-compose class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { GridTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { GridApp() } } } } } @Composable fun GridApp() { GridList(gridList = DataSource.topics, modifier = Modifier) } @Composable fun Topics(topic: Topic, modifier: Modifier = Modifier){ val number = topic.numbers.toString() Card{ Row { Image(painter = painterResource(topic.image), contentDescription = stringResource(topic.name), modifier .size(68.dp) .fillMaxHeight()) Column(modifier.width(120.dp)){Text(LocalContext.current.getString(topic.name), modifier = modifier .padding(horizontal = 16.dp) .padding(top = 16.dp) .padding(bottom = 8.dp), style = MaterialTheme.typography.bodyMedium) Row(modifier = Modifier, horizontalArrangement = Arrangement.End){ Icon(painterResource(R.drawable.ic_grain), contentDescription = "few dots", Modifier .padding(start = 16.dp) .padding(end = 8.dp)) Text((number), modifier) } } } } } @Composable fun GridList(gridList: List<Topic>, modifier: Modifier = Modifier.padding(8.dp)){ LazyVerticalGrid(columns = GridCells.Fixed(2), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = modifier.padding(8.dp)) { items(topics) { topic -> Topics(topic = topic) } } }
{ "domain": "codereview.stackexchange", "id": 45539, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "android, kotlin, kotlin-compose", "url": null }
android, kotlin, kotlin-compose } } @Preview @Composable private fun showTopicGrid() { Topics(Topic(R.string.film, 321, R.drawable.film)) } Answer: Looks quite good already, I haven't found any serious issues. The are some minor improvements that I would suggest, though. Small bugs I'm not sure how your data source looks like, but you import com.example.grid.ui.theme.DataSource.topics and use it in GridList as parameter for the items builder. That doesn't seem right, since there is already an unused List<Topic> parameter for this composable. I would rename that parameter from gridList to topcis and remove the import statement. It is unclear to me what the modifier parameter of Topics should modify. The expectation of what such a modifier does would be to modify the entirety of that composable, to change its size, for example. You, however, just apply it to an Image, a Column and two different Texts. That doesn't seem right. I do not think there even should be a modifier parameter for Topics. GridList has a modifier parameter with the default Modifier.padding(8.dp). Modifier parameters always should have the default Modifier to harmonize the behaviour with other composables. Since you apply that padding later on anyways, correcting the default value won't have any undesired side effects. Minor improvements
{ "domain": "codereview.stackexchange", "id": 45539, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "android, kotlin, kotlin-compose", "url": null }
android, kotlin, kotlin-compose Minor improvements You sometimes use LocalContext.current.getString() and sometimes you use stringResource(). It should always be the latter. The string literal "few dots" should be replaced by a string resource. In Topics the Text composable that displays the topic name uses the padding modifier three times in a row which can be condensed to a single padding(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 8.dp). The same applies to the Icon a bit down below where the padding can be condensed to padding(start = 16.dp, end = 8.dp). Also in the Topics composable, the size of the Image is set to a square with size(68.dp) and then the height is changed to fillMaxHeight(). It would be a bit more clear to only set width(68.dp) (instead of size) because the height component won't matter anyways. To increase readbility, functions with multiple parameters should have each parameter on a seperate line. This applies to function declarations as well as function calls. The last parameter should always have a trailing comma (the same as the other parameters), even if it's optional for the last parameter. Multiline function calls should always use parameter names. The Text that displays the number is wrapped unnecessarily in parentheses. The composable showTopicGrid should start with a capital letter. There are some unused imports and some indentation issues that Android Studio can automatically correct for you if you press Ctrl+Alt+O and Ctrl+Alt+L respectively. There are a lot of superflous empty lines that can be removed.
{ "domain": "codereview.stackexchange", "id": 45539, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "android, kotlin, kotlin-compose", "url": null }
android, kotlin, kotlin-compose I have incorporated all these changes into your code. It now looks like this (I stripped the imports): class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { GridTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background, ) { GridApp() } } } } } @Composable fun GridApp() { GridList( topics = DataSource.topics, ) } @Composable fun Topics( topic: Topic, ) { val number = topic.numbers.toString() Card { Row { Image( painter = painterResource(topic.image), contentDescription = stringResource(topic.name), modifier = Modifier .width(68.dp) .fillMaxHeight(), ) Column( modifier = Modifier.width(120.dp), ) { Text( text = stringResource(topic.name), modifier = Modifier .padding(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 8.dp), style = MaterialTheme.typography.bodyMedium, )
{ "domain": "codereview.stackexchange", "id": 45539, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "android, kotlin, kotlin-compose", "url": null }
android, kotlin, kotlin-compose Row( modifier = Modifier, horizontalArrangement = Arrangement.End, ) { Icon( painter = painterResource(R.drawable.ic_grain), contentDescription = stringResource(R.string.ic_grain_description), modifier = Modifier .padding(start = 16.dp, end = 8.dp), ) Text( text = number, modifier = Modifier, ) } } } } } @Composable fun GridList( topics: List<Topic>, modifier: Modifier = Modifier, ) { LazyVerticalGrid( columns = GridCells.Fixed(2), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = modifier.padding(8.dp), ) { items(topics) { topic -> Topics(topic = topic) } } } @Preview @Composable private fun ShowTopicGrid() { Topics(Topic(R.string.film, 321, R.drawable.film)) } Final thoughts As your app grows in size you will have more and more data sources that need to be transformed into UI elements. This can get quite complex really fast. The canonical recommendation is to structure your app in different layers that handle the different aspects independent from each other.
{ "domain": "codereview.stackexchange", "id": 45539, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "android, kotlin, kotlin-compose", "url": null }
java, beginner Title: An API fetcher class - afraid of overengineering class Question: I'd like to ask you for a code review of this class. I'm quite new to Java and I'm afraid I have way overengineered this class. It's goal is only to fetch a specified data from given API, whose link is stored in config.properties. I would be grateful for both implementation details critique and design ones too. package org.example; import java.io.*; import java.net.*; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.Path; import java.util.Properties; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class APIDataFetcher { private static final Logger logger = LogManager.getLogger(APIDataFetcher.class); private static final Properties properties = new Properties(); static { try (InputStream inputStream = APIDataFetcher.class.getClassLoader().getResourceAsStream("config.properties")) { if (inputStream != null) { properties.load(inputStream); } else { logger.info("config.properties file not found in resources."); } } catch (IOException e) { logger.error("Error loading configuration file.", e); } } public static void saveData(String fileName, JsonNode jsonNode) { try { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); String jsonString = objectMapper.writeValueAsString(jsonNode); Path filePath = Paths.get(fileName); Files.write(filePath, jsonString.getBytes()); } catch (IOException e) { logger.error("Error occurred while writing JSON to file: " + fileName, e); } }
{ "domain": "codereview.stackexchange", "id": 45540, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner public static JsonNode getJSONString() { try { return parseJSON(fetchAllData()); } catch (IOException e) { logger.error("Error occurred while fetching or parsing data", e); return null; } catch (URISyntaxException e) { throw new RuntimeException(e); } } private static JsonNode parseJSON(String jsonString) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readTree(jsonString); } private static String fetchAllData() throws IOException, URISyntaxException { StringBuilder responseBuilder = new StringBuilder(); try (BufferedReader reader = getReader()) { String line; while ((line = reader.readLine()) != null) { responseBuilder.append(line); } } return responseBuilder.toString(); } private static BufferedReader getReader() throws URISyntaxException, IOException { String apiUrl = properties.getProperty("api.url"); URI uri = new URI(apiUrl); URL url = uri.toURL(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { logger.error("Could not connect to the data source. HTTP Status Code: " + responseCode); throw new RuntimeException("Could not connect to the data source. HTTP Status Code: " + responseCode); } return new BufferedReader(new InputStreamReader(connection.getInputStream())); } }
{ "domain": "codereview.stackexchange", "id": 45540, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner } Answer: simple things should be simple 1 StringBuilder responseBuilder = new StringBuilder(); 2 try (BufferedReader reader = getReader()) { 3 String line; 4 while ((line = reader.readLine()) != null) { 5 responseBuilder.append(line); 6 } 7 } 8 return responseBuilder.toString(); I don't understand why this isn't a one-liner: return getReader().lines().collect(Collectors.joining()); Less dramatically, parseJSON() also could be a one-liner. global vs local names Your method names are all very nice and self-explanatory; keep it up. Consider using brief names, maybe 2 characters or so, for local variables. Their meaning tends to be quite clear from context. Some java code can develop a Bond james = Bond() quality to it, which short names will soften a bit. coupling to config file Consider offering a signature of getReader(String apiUrl). And then a one-liner getReader() can call it with that property if you feel you need that. As stated it relies on sort of a hidden global variable, and it's not convenient for promotion to public re-use nor even for being called by unit tests. The getJSONString() signature is rather cryptic in the same way. It would benefit from taking an argument, to clarify what it's reading. javadoc Your method names are good, and for private methods that suffices. But your public methods would benefit from at least a one-sentence /** javadoc */ description of their single responsibility. Caller wants to know: "What's the contract? What can I rely on?"
{ "domain": "codereview.stackexchange", "id": 45540, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
c, generics, stack Title: Generic stack implementation Question: The provided code (a header-only library inspired by stb libraries] defines functions for creating a stack, pushing elements onto the stack, popping elements from the stack, peeking at the top element without removing it, checking if the stack is full or empty, getting the size of the stack, and destroying the stack. Note: The implementation does not support heterogeneous types. #ifndef STACK_H #define STACK_H /* To use, do this: * #define STACK_IMPLEMENTATION * before you include this file in *one* C file to create the implementation. * * i.e. it should look like: * #include ... * #include ... * * #define STACK_IMPLEMENTATION * #include "stack.h" * ... * * To make all the functions have internal linkage, i.e. be private to the * source file, do this: * #define IO_STATIC * before including "stack.h" * * i.e. it should look like: * #define STACK_IMPLEMENTATION * #define STACK_STATIC * #include "stack.h" * ... * * You can define STACK_MALLOC, STACK_REALLOC, and STACK_FREE to avoid using * malloc(), realloc(), and free(). */ #ifndef STACK_DEF #ifdef STACK_STATIC #define STACK_DEF static #else #define STACK_DEF extern #endif /* STACK_STATIC */ #endif /* STACK_DEF */ #if defined(__GNUC__) || defined(__clang__) #define ATTRIBUTE_NONNULL(...) __attribute__ ((nonnull (__VA_ARGS__))) #define ATTRIBUTE_WARN_UNUSED_RESULT __attribute__ ((warn_unused_result)) #else #define ATTRIBUTE_NONNULL(...) /* If only. */ #define ATTRIBUTE_WARN_UNUSED_RESULT /* If only. */ #endif /* defined(__GNUC__) || defined(__clang__) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdbool.h> typedef struct stack Stack;
{ "domain": "codereview.stackexchange", "id": 45541, "lm_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, generics, stack", "url": null }
c, generics, stack typedef struct stack Stack; /* * Creates a stack with `cap` elements of size `memb_size`. * * The stack can only store one type of elements. It does not support * heterogeneuous types. * * Returns a pointer to the stack on success, or NULL on failure to allocate * memory. */ STACK_DEF Stack *stack_create(size_t cap, unsigned int memb_size) ATTRIBUTE_WARN_UNUSED_RESULT; /* * Pushes an element to the top of the stack referenced by `s`. It automatically * resizes the stack if it is full. * * Whilst pushing an element, there's no need of a cast, as there is an implicit * conversion to and from a void *. * * On a memory allocation failure, it returns false. Else it returns true. */ STACK_DEF bool stack_push(Stack *s, const void *data) ATTRIBUTE_NONNULL(1, 2) ATTRIBUTE_WARN_UNUSED_RESULT; /* * Removes the topmost element of the stack referenced by `s` and returns it. * If the stack is empty, it returns NULL. * * The returned element should be casted to a pointer of the type that was * pushed on the stack, and then dereferenced. * * Note that casting to a pointer of the wrong type is Undefined Behavior, and * so is dereferencing to performing arithmetic on a void *. */ STACK_DEF void *stack_pop(Stack *s) ATTRIBUTE_NONNULL(1); /* * Returns a pointer to the topmost element of the stack referenced by `s` * without removing it. If the stack is empty, it returns NULL. */ STACK_DEF const void *stack_peek(const Stack *s) ATTRIBUTE_NONNULL(1); /* * Returns true if the capacity of the stack referenced by `s` is full, or false * elsewise. */ STACK_DEF bool stack_is_full(const Stack *s) ATTRIBUTE_NONNULL(1); /* * Returns true if the count of elements in the stack referenced by `s` is zero, * or false elsewise. */ STACK_DEF bool stack_is_empty(const Stack *s) ATTRIBUTE_NONNULL(1); /* * Returns the count of elements in the stack referenced by `s`. */ STACK_DEF size_t stack_size(const Stack *s) ATTRIBUTE_NONNULL(1);
{ "domain": "codereview.stackexchange", "id": 45541, "lm_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, generics, stack", "url": null }
c, generics, stack /* * Destroys and frees all memory associated with the stack referenced by `s`. */ STACK_DEF void stack_destroy(Stack *s) ATTRIBUTE_NONNULL(1); #endif /* STACK_H */ #ifdef STACK_IMPLEMENTATION #if defined(STACK_MALLOC) && defined(STACK_REALLOC) && defined(STACK_FREE) // Ok. #elif !defined(STACK_MALLOC) && !defined(STACK_REALLOC) && !defined(STACK_FREE) // Ok. #else #error "Must define all or none of STACK_MALLOC, STACK_REALLOC, and STACK_FREE." #endif #ifndef STACK_MALLOC #define STACK_MALLOC(sz) malloc(sz) #define STACK_REALLOC(p, sz) realloc(p, sz) #define STACK_FREE(p) free(p) #endif struct stack { void *data; size_t size; size_t cap; unsigned int memb_size; }; STACK_DEF bool stack_is_full(const Stack *s) { return s->size == s->cap; } STACK_DEF bool stack_is_empty(const Stack *s) { return !s->size; } STACK_DEF const void *stack_peek(const Stack *s) { if (stack_is_empty(s)) { return NULL; } return (char *) s->data + (s->size - 1) * s->memb_size; } STACK_DEF Stack *stack_create(size_t cap, unsigned int memb_size) { if (!cap || !memb_size) { return NULL; } Stack *const s = STACK_MALLOC(sizeof *s); if (s) { s->data = STACK_MALLOC(memb_size * cap); if (s->data) { s->cap = cap; s->size = 0; s->memb_size = memb_size; } else { free(s); return NULL; } } return s; } STACK_DEF bool stack_push(Stack *s, const void *data) { if (s->size >= s->cap) { s->cap *= 2; void *const tmp = STACK_REALLOC(s->data, s->cap * s->memb_size); if (!tmp) { return false; } s->data = tmp; } char *const target = (char *) s->data + (s->size * s->memb_size); memcpy(target, data, s->memb_size); return !!++s->size; }
{ "domain": "codereview.stackexchange", "id": 45541, "lm_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, generics, stack", "url": null }
c, generics, stack memcpy(target, data, s->memb_size); return !!++s->size; } STACK_DEF void *stack_pop(Stack *s) { if (stack_is_empty(s)) { return NULL; } --s->size; void *const top = (char *) s->data + (s->size * s->memb_size); return top; } STACK_DEF void stack_destroy(Stack *s) { STACK_FREE(s->data); STACK_FREE(s); } STACK_DEF size_t stack_size(const Stack *s) { return s->size; } #endif /* STACK_IMPLEMENTATION */ #ifdef TEST_MAIN #include <assert.h> int main(void) { /* We could support heterogenuous objects by using void pointers. */ Stack *stack = stack_create(100, sizeof (int)); assert(stack); for (int i = 0; i < 150; ++i) { assert(stack_push(stack, &i)); } assert(!stack_is_empty(stack)); assert(stack_size(stack) == 150); assert(*(int *) stack_peek(stack) == 149); assert(*(int *) stack_peek(stack) == 149); assert(*(int *) stack_peek(stack) == 149); for (int i = 149; i != -1; i--) { assert(*(int *) stack_peek(stack) == i); assert(*(int *) stack_pop(stack) == i); } stack_destroy(stack); return EXIT_SUCCESS; } #endif /* TEST_MAIN */ Are there any bugs or undefined/implementation-defined behavior in the code? How can it be modified to support heterogeneous types? General coding comments, style, et cetera. Answer: Advice I - unsigned int memb_size This is a counter. Therefore, I suggest using a data type that is tailored for counting: size_t memb_size;. Advice II - More verbose zero comparisons In stack_is_empty, you write: !s->size;. I suggest you write instead s->size == 0;. Advice III - stack_create In stack_create, you write: if (!cap || !memb_size) { return NULL; } Why not: if (cap == 0 || memb_size == 0) { return NULL; }
{ "domain": "codereview.stackexchange", "id": 45541, "lm_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, generics, stack", "url": null }
c, generics, stack Why not: if (cap == 0 || memb_size == 0) { return NULL; } Advice IV - Contract the stack when too small I suggest this: when the load factor of your stack drops below 25%, halve its capacity. This will optimize the memory usage of your stack while keeping the running time complexity of stack_pop as amortized \$\Theta(1)\$. This is a basic stuff from CLRS.
{ "domain": "codereview.stackexchange", "id": 45541, "lm_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, generics, stack", "url": null }
java, performance, algorithm, programming-challenge, time-limit-exceeded Title: Leetcode : First Missing Positive Question: I was trying out leetcode's first missing positive. As per the challenge's description: Given an unsorted integer array nums, return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space. My solution passes all tests, except last five i.e. where the nums array's size is \$10^5\$. When the array is of that size I get "Time Limit Exceeded". Here is my solution: (PS: class and methods naming are kept as given by leetcode) class Solution { public int firstMissingPositive(int[] nums) { int minIndex = 0; int integerCounter = 0; for (int i = minIndex; i < nums.length; i++) { if (i == 0) { integerCounter += 1; } if (nums[i] == integerCounter) { // swap int temp = nums[minIndex]; nums[minIndex] = nums[i]; nums[i] = temp; minIndex += 1; i = minIndex - 1; integerCounter++; } } return integerCounter > 0 ? integerCounter : -1; } } My Question How can I improve this algorithm to tackle super large (e.g. \$10^5\$) nums array without getting the "Time Limit Exceeded" and without having to completely modify the function? Graphical explanation of my solution using an example
{ "domain": "codereview.stackexchange", "id": 45542, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, algorithm, programming-challenge, time-limit-exceeded", "url": null }
java, performance, algorithm, programming-challenge, time-limit-exceeded Answer: One way to solve this within the given constraints is to use the input array to store which numbers have been seen. Negative numbers will never contribute to the answer, so we can iterate once to replace them with 0 (which will help with the next step). Let us use nums[i] to mark whether the integer i + 1 appears in nums. To prevent overwriting elements we might need later, if we need to indicate the existence of a value i + 1, we can make the element at index i negative. Then, we can recover the original value of an element by taking the absolute value (with Math.abs). The longest possible consecutive sequence of positive numbers would be the range [1, nums.length] (which can only occur when all elements are distinct), so we can ignore any elements outside that range. We make another pass over the array to mark the seen elements that could contribute to a consecutive sequence of positive numbers. When marking an element, if the value at the position is positive, we multiply it by -1 to make it negative. If it is 0, we set the value to a negative value such that its absolute value is outside the range of [1, nums.length] to ensure it is not considered part of the answer, e.g. -nums.length - 1. (Alternatively, we can set the value to the value seen on the current iteration multiplied by -1, as having the same number appear multiple times does not affect the answer.) Finally, we loop over the array once more, finding the longest prefix of negative numbers (which indicates the longest consecutive sequence of positive numbers we can make from numbers in the array starting from 1). Sample implementation: public int firstMissingPositive(int[] nums) { for (int i = 0; i < nums.length; i++) nums[i] = Math.max(nums[i], 0); for (int i = 0; i < nums.length; i++) { int actualVal = Math.abs(nums[i]); if (actualVal > 0 && actualVal <= nums.length) { if (nums[actualVal - 1] == 0) nums[actualVal - 1] = ~nums.length;
{ "domain": "codereview.stackexchange", "id": 45542, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, algorithm, programming-challenge, time-limit-exceeded", "url": null }
java, performance, algorithm, programming-challenge, time-limit-exceeded if (nums[actualVal - 1] == 0) nums[actualVal - 1] = ~nums.length; else if (nums[actualVal - 1] > 0) nums[actualVal - 1] *= -1; } } int i = 0; while (i < nums.length && nums[i] < 0) ++i; return i + 1; }
{ "domain": "codereview.stackexchange", "id": 45542, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, algorithm, programming-challenge, time-limit-exceeded", "url": null }
c++, time Title: Checking to see if the current time is close to 9PM Question: I want to check if the current time is "close" to 9pm UTC. I have the following code to a.) get "now" and convert it to UTC time and b.) get 9pm utc time. Based off when I run it, it looks like it's running. However, I usually use scripting languages, and this looks absolutely crazy to me. I don't necessarily want to shorten this in terms of LOC, but I just wanted to check I'm not violating some principle I don't even know about. #include <iostream> #include <ctime> int main() { // Get the current time in the machine's local time zone std::time_t currentTime = std::time(nullptr); // Get the time zone difference between local time and UTC (in seconds) std::tm* localTime = std::localtime(&currentTime); long localTimeZoneOffset = localTime->tm_gmtoff; // Adjust the current time to UTC std::time_t nowUtcTime = currentTime - localTimeZoneOffset; std::tm* utcLocalTime = std::localtime(&nowUtcTime); // construct 9pm std::tm utc9PM = *std::localtime(&nowUtcTime); // deep copy? utc9PM.tm_hour = 21; // 9pm utc utc9PM.tm_min = 0; utc9PM.tm_sec = 0; std::time_t ninePmUTC = std::mktime(&utc9PM); //ok std::cout << "now UTC in seconds since epoch: " << nowUtcTime << std::endl; std::cout << "9pm UTC in seconds sinc epoch: " << ninePmUTC << std::endl; std::cout << "now in utc calendar time: " << utcLocalTime->tm_hour << ":" << utcLocalTime->tm_min << ":" << utcLocalTime->tm_sec << std::endl; std::cout << "9pm utc in calendar time: " << utc9PM.tm_hour <<":" << utc9PM.tm_min <<":" << utc9PM.tm_sec << std::endl; } Answer: This is already in the Standard Library. Use std::chrono::utc_clock from <chrono>, and compute the duration: const auto now = std::chrono::utc_clock::now(); const auto time_of_day = now - std::chrono::floor<std::chrono::days>(now);
{ "domain": "codereview.stackexchange", "id": 45543, "lm_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++, time", "url": null }
c++, time An extremely crude example: #include <chrono> #include <cstdlib> #include <iostream> int main() { constexpr auto nine_pm = std::chrono::hours(21); const auto now = std::chrono::utc_clock::now(); const auto time_of_day = now - std::chrono::floor<std::chrono::days>(now); const auto in_minutes = std::chrono::duration_cast<std::chrono::minutes>(nine_pm - time_of_day) .count(); if (in_minutes >= 0) { std::cout << in_minutes/60 << ':' << in_minutes%60 << " until 21:00 UTC.\n"; } else { const auto minutes_after = -in_minutes; std::cout << minutes_after/60 << ':' << minutes_after%60 << " after 21:00 UTC.\n"; } return EXIT_SUCCESS; } Or if you stick with <ctime>, use gmtime() to get UTC. Also, list your headers in alphabetical order, or some other order that’s easy and logical. This will make it much easier to notice missing or duplicated headers.
{ "domain": "codereview.stackexchange", "id": 45543, "lm_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++, time", "url": null }
c++, algorithm, recursion, template, c++20 Title: A recursive_transform_reduce Template Function with Unwrap Level Implementation in C++ Question: This is a follow-up question for A recursive_transform_reduce Function for Various Type Arbitrary Nested Iterable Implementation in C++ and recursive_invocable and recursive_project_invocable Concept Implementation in C++. I am trying to implement another version recursive_transform_reduce function which takes unwrap_level as an input in this post. Moreover, the recursive_invocable concept is used here, also. The Usage Description Similar to std::transform_reduce, the purpose of recursive_transform_reduce template function is to apply a function (unary operation) to each element located in the specified unwrap level in the given range then reduce the results with a binary operation. There are four parameters in recursive_transform_reduce function (the version without execution policy) and the first and second parameters are necessary (The second one is to determine the output type). The experimental implementation recursive_transform_reduce Template Function // recursive_transform_reduce template function implementation template<std::size_t unwrap_level, class Input, class T, class UnaryOp = std::identity, class BinaryOp = std::plus<T>> requires(recursive_invocable<unwrap_level, UnaryOp, Input>) constexpr auto recursive_transform_reduce(const Input& input, T init = {}, const UnaryOp& unary_op = {}, const BinaryOp& binop = std::plus<T>()) { if constexpr (unwrap_level > 0) { return std::transform_reduce(std::ranges::begin(input), std::ranges::end(input), init, binop, [&](auto& element) { return recursive_transform_reduce<unwrap_level - 1>(element, init, unary_op, binop); }); } else { return std::invoke(binop, init, std::invoke(unary_op, input)); } }
{ "domain": "codereview.stackexchange", "id": 45544, "lm_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++, algorithm, recursion, template, c++20", "url": null }
c++, algorithm, recursion, template, c++20 // recursive_transform_reduce template function implementation with execution policy template<std::size_t unwrap_level, class ExecutionPolicy, class Input, class T, class UnaryOp = std::identity, class BinaryOp = std::plus<T>> requires(recursive_invocable<unwrap_level, UnaryOp, Input>&& std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>) constexpr auto recursive_transform_reduce(ExecutionPolicy execution_policy, const Input& input, T init = {}, const UnaryOp& unary_op = {}, const BinaryOp& binop = std::plus<T>()) { if constexpr (unwrap_level > 0) { return std::transform_reduce( execution_policy, std::ranges::begin(input), std::ranges::end(input), init, binop, [&](auto& element) { return recursive_transform_reduce<unwrap_level - 1>(execution_policy, element, init, unary_op, binop); }); } else { return std::invoke(binop, init, std::invoke(unary_op, input)); } } Full Testing Code The full testing code: // A recursive_transform_reduce Template Function with Unwrap Level Implementation in C++ #include <algorithm> #include <array> #include <cassert> #include <chrono> #include <concepts> #include <deque> #include <execution> #include <exception> //#include <experimental/ranges/algorithm> #include <experimental/array> #include <functional> #include <iostream> #include <iterator> #include <ranges> #include <string> #include <utility> #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); }; template<typename T> concept is_summable = requires(T x) { x + x; }; // recursive_unwrap_type_t struct implementation template<std::size_t, typename, typename...> struct recursive_unwrap_type { };
{ "domain": "codereview.stackexchange", "id": 45544, "lm_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++, algorithm, recursion, template, c++20", "url": null }
c++, algorithm, recursion, template, c++20 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_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>...>>; };
{ "domain": "codereview.stackexchange", "id": 45544, "lm_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++, algorithm, recursion, template, c++20", "url": null }
c++, algorithm, recursion, template, c++20 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>; }; 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>; };
{ "domain": "codereview.stackexchange", "id": 45544, "lm_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++, algorithm, recursion, template, c++20", "url": null }
c++, algorithm, recursion, template, c++20 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_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": 45544, "lm_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++, algorithm, recursion, template, c++20", "url": null }
c++, algorithm, recursion, template, c++20 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<std::size_t dim, class T, template<class...> class Container = std::vector> 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<dim - 1, T, Container>(input, times)); } } template<std::size_t dim, std::size_t times, class T> constexpr auto n_dim_array_generator(T input) { if constexpr (dim == 0) { return input; } else { std::array<decltype(n_dim_array_generator<dim - 1, times>(input)), times> output; for (size_t i = 0; i < times; i++) { output[i] = n_dim_array_generator<dim - 1, times>(input); } return output; } } // 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}; }
{ "domain": "codereview.stackexchange", "id": 45544, "lm_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++, algorithm, recursion, template, c++20", "url": null }
c++, algorithm, recursion, template, c++20 // recursive_depth function implementation with target type template<typename T_Base, typename T> constexpr std::size_t recursive_depth() { return std::size_t{0}; } template<typename T_Base, std::ranges::input_range Range> requires (!std::same_as<Range, T_Base>) constexpr std::size_t recursive_depth() { return recursive_depth<T_Base, std::ranges::range_value_t<Range>>() + std::size_t{1}; } // is_recursive_invocable template function implementation template<std::size_t unwrap_level, class F, class... T> requires(unwrap_level <= recursive_depth<T...>()) static constexpr bool is_recursive_invocable() { if constexpr (unwrap_level == 0) { return std::invocable<F, T...>; } else { return is_recursive_invocable< unwrap_level - 1, F, std::ranges::range_value_t<T>...>(); } } // recursive_invocable concept template<std::size_t unwrap_level, class F, class... T> concept recursive_invocable = is_recursive_invocable<unwrap_level, F, T...>(); // is_recursive_project_invocable template function implementation template<std::size_t unwrap_level, class Proj, class F, class... T> requires(unwrap_level <= recursive_depth<T...>() && recursive_invocable<unwrap_level, Proj, T...>) static constexpr bool is_recursive_project_invocable() { if constexpr (unwrap_level == 0) { return std::invocable<F, std::invoke_result_t<Proj, T...>>; } else { return is_recursive_project_invocable< unwrap_level - 1, Proj, F, std::ranges::range_value_t<T>...>(); } } // recursive_project_invocable concept template<class F, std::size_t unwrap_level, class Proj, class... T> concept recursive_projected_invocable = is_recursive_project_invocable<unwrap_level, Proj, F, T...>();
{ "domain": "codereview.stackexchange", "id": 45544, "lm_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++, algorithm, recursion, template, c++20", "url": null }
c++, algorithm, recursion, template, c++20 /* recursive_all_of template function implementation with unwrap level */ template<std::size_t unwrap_level, class T, class Proj = std::identity, recursive_projected_invocable<unwrap_level, Proj, T> UnaryPredicate> constexpr auto recursive_all_of(T&& value, UnaryPredicate&& p, Proj&& proj = {}) { if constexpr (unwrap_level > 0) { return std::ranges::all_of(value, [&](auto&& element) { return recursive_all_of<unwrap_level - 1>(element, p, proj); }); } else { return std::invoke(p, std::invoke(proj, value)); } } /* recursive_find template function implementation with unwrap level */ template<std::size_t unwrap_level, class R, class T, class Proj = std::identity> requires(recursive_invocable<unwrap_level, Proj, R>) constexpr auto recursive_find(R&& range, T&& target, Proj&& proj = {}) { if constexpr (unwrap_level > 0) { return std::ranges::find_if(range, [&](auto& element) { return recursive_find<unwrap_level - 1>(element, target, proj); }) != std::ranges::end(range); } else { return range == std::invoke(proj, target); } } template<std::size_t unwrap_level, class ExecutionPolicy, class R, class T, class Proj = std::identity> requires(recursive_invocable<unwrap_level, Proj, R>&& std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>) constexpr auto recursive_find(ExecutionPolicy execution_policy, R&& range, T&& target, Proj&& proj = {}) { if constexpr (unwrap_level > 0) { return std::find_if(execution_policy, std::ranges::begin(range), std::ranges::end(range), [&](auto& element) { return recursive_find<unwrap_level - 1>(execution_policy, element, target, proj); }) != std::ranges::end(range); } else { return range == std::invoke(proj, target); } }
{ "domain": "codereview.stackexchange", "id": 45544, "lm_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++, algorithm, recursion, template, c++20", "url": null }