text
stringlengths
1
2.12k
source
dict
strings, haskell Title: Generic splitting in Haskell Question: I am new to Haskell and took it upon myself to make a simple generic list-splitting (e.g. string-splitting) function: -- Helper for splitting: reduce into a list of lists, splitting on delimiters splitInner :: (Eq a) => [a] -> a -> [[a]] -> [[a]] splitInner c s (x:y) | s `elem` c = [] : (x:y) | otherwise = (s : x) : y splitInner c s [] | s `elem` c = [] | otherwise = [[s]] -- Split a list into a list of lists on a given set of delimiters split :: (Eq a) => [a] -> [a] -> [[a]] split delim = foldr (splitInner delim) [] -- Remove empty lists from a list of lists collapse :: (Eq a) => [[a]] -> [[a]] collapse = filter (/= []) -- Split a string on any span of whitespace within splitSpaces = collapse . split "\t\r\n " main = (print . splitSpaces) "\t \r\nhello world, this is code!\nFoo bar " -- prints ["hello", "world,", "this", "is", "code!", "Foo", "bar"] I'm aware that there's a split package that already implements functionality like this. However, I'm curious: is there any way I could have expressed this functionality better, or more concisely or clearly, still using just the standard library? Or, perhaps, does my code deviate from a typical Haskell solution in some other way? I'm much more used to imperative than functional programming and don't yet have the best sense on evaluating the 'readability' or clarity of code like this. I'd also like to point out the fact that I couldn't figure out a good way to clearly label the arguments to a function in its definition - the signature [a] -> [a] -> [[a]] certainly doesn't reveal which [a] is the delimiter, for example.
{ "domain": "codereview.stackexchange", "id": 43383, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, haskell", "url": null }
strings, haskell Answer: Regarding identification of function arguments; it's often enough to just name them well. For example it's clear that split's first arg is the delimiter because it's named. Sometimes that's not enough, and it doesn't work for arguments you're not binding, so deffer to a more formal style of comments, which in Haskell means Haddock. This will help with splitInner, but you should still rename those arguments! The behavior of split as written is kinda weird. Basically, a long chain of delimiters will behave differently (append a bunch of empty lists, or not) depending if they're at the beginning or end of the input. Do you want to have separate split and collapse functions? If you do then you should do something to normalize the behavior of split, but probably it's better to just fix split so you don't need collapse (which needed a better name anyway). split :: (Eq a) => [a] -> [a] -> [[a]] split deliminators = discard . foldr inner [[]] where discard xs(x : xs') = if null x then xs' else xs inner item acc@(current : closedChunks) | item `elem` deliminators = [] : (discard acc) | otherwise = (item : current) : closedChunks As for the most idiomatic Haskell way to do all this... You could read the source code for the pre-existing library, but that might not be what you need right now. The basic idea of what they're doing is they're acknowledging that there are a lot of different things people might mean by "I want a function to split a list.", so they've built a framework within which it's easy to build lots of "split" functions out of components. That's certainly idiomatic Haskell! but it usually isn't one's first strategy.
{ "domain": "codereview.stackexchange", "id": 43383, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, haskell", "url": null }
c, strings, array, formatting, integer Title: Integer array to string Question: This function creates takes an int * buffer and creates a neatly formatted string (useful for printing the contents of an array). Is the code easy to follow? Is it efficient? Am I allocating and freeing memory properly? Bonus question: is there an idiomatic way to do this in C, such as through a set of library routines? #include <stdlib.h> #include <stdio.h> #include <string.h> char *int_array_to_string(int *arr, size_t length) { char **strings = calloc(length, sizeof(char *)); int num_chars = 0; for (size_t i = 0; i < length; i++) { char *num_string = calloc(32, sizeof(char)); // 32 digits should fit any int sprintf(num_string, "%d", arr[i]); strings[i] = num_string; num_chars += strlen(num_string); } num_chars += 2 * (length - 1); // extra bytes for comma and space chars following the numbers (except for the last number) num_chars += 2; // bytes for curly braces at the beginning and end char *result = calloc(num_chars, sizeof(char)); size_t i = 0; result[i++] = '{'; for (size_t j = 0; j < length; j++) { char *str = strings[j]; for (size_t k = 0; k < strlen(str); k++) result[i++] = str[k]; free(str); result[i++] = ','; result[i++] = ' '; } free(strings); result[num_chars - 1] = '}'; return result; } Answer: result is not zero-terminated. You should allocate one byte more. To my taste, there are too many allocations. Compute the required size, and allocating once. You already allocate 32 bytes per array element, so char * result = malloc(length * 32 + whatever_extra_space_necessary); Now recall that sprintf returns an amount of bytes it actually printed, and remove a superfluous call to strlen: char * where = result; for (size_t i = 0; i < length; i++) { size_t printed = sprintf(where, "%d, ", arr[i]); where += printed; }
{ "domain": "codereview.stackexchange", "id": 43384, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, strings, array, formatting, integer", "url": null }
c, strings, array, formatting, integer Your code prints an unpleasant ", " after the last element of an array. If it is a conscious decision, it is all right; if it is not, consider printing the first element separately: print("%d", arr[0]); for (i = 1; ....) print(", %d", arr[i]);
{ "domain": "codereview.stackexchange", "id": 43384, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, strings, array, formatting, integer", "url": null }
javascript Title: A reduce method which aggregates common data in objects Question: I built a method using reduce of JS to aggregate together data from a DB in a better shape. What I'm wondering is, if that method can be simplified with a more modern approach or better written. Like using a different method instead of a reduce. The method takes the dbData which includes data in the following form: const dbData = [{ studyId: 'X', siteId: 'A', day: '2000-01-01', status: 'PENDING_CALLCENTER', current: 5, total: 17, }, { studyId: 'X', siteId: 'A', day: '2000-01-01', status: 'PENDING_SITE', current: 3, total: 9, }, { studyId: 'Y', siteId: 'B', day: '2000-01-01', status: 'PENDING_SITE', current: 3, total: 9, }, { studyId: 'Y', siteId: 'B', day: '2000-01-01', status: 'PENDING_CALLCENTER', current: 3, total: 9, }, ] The data contains two same fields/values as studyId and siteId and what I aggregate is the status, current, total to be included under the same Study and Site. The output of the above passing via the method: [ { "studyId": "X", "siteId": "A", "currents": { "PENDING_CALLCENTER": 5, "PENDING_SITE": 3 }, "totals": { "PENDING_CALLCENTER": 17, "PENDING_SITE": 9 } }, { "studyId": "Y", "siteId": "B", "currents": { "PENDING_SITE": 6, "PENDING_CALLCENTER": 3 }, "totals": { "PENDING_SITE": 18, "PENDING_CALLCENTER": 9 } } ]
{ "domain": "codereview.stackexchange", "id": 43385, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript So it is reduced to a different form where we have one object per studyId and siteId which includes the currents and totals of the status. The method dbData.reduce((acc, row) => { const { studyId, siteId, status, current, total } = row; const idx = acc.findIndex(x => studyId === x.studyId && siteId === x.siteId); const item = idx === -1 ? { studyId, siteId, currents: {}, totals: {} } : { ...acc[idx] }; item.currents[status] = item.currents[status] ? item.currents[status] + current : current; item.totals[status] = item.totals[status] ? item.totals[status] + total : total; if (idx === -1) { acc.push(item); } else { acc[idx] = item; } return acc; }, []); A working example const dbData = [{ studyId: 'X', siteId: 'A', day: '2000-01-01', status: 'PENDING_CALLCENTER', current: 5, total: 17, }, { studyId: 'X', siteId: 'A', day: '2000-01-01', status: 'PENDING_SITE', current: 3, total: 9, }, { studyId: 'Y', siteId: 'B', day: '2000-01-01', status: 'PENDING_SITE', current: 3, total: 9, }, { studyId: 'Y', siteId: 'B', day: '2000-01-01', status: 'PENDING_CALLCENTER', current: 3, total: 9, }, ]; const reduced = dbData.reduce((acc, row) => { const { studyId, siteId, status, current, total } = row; const idx = acc.findIndex(x => studyId === x.studyId && siteId === x.siteId); const item = idx === -1 ? { studyId, siteId, currents: {}, totals: {} } : { ...acc[idx] }; item.currents[status] = item.currents[status] ? item.currents[status] + current : current; item.totals[status] = item.totals[status] ? item.totals[status] + total : total; if (idx === -1) { acc.push(item); } else { acc[idx] = item; } return acc; }, []); console.log(reduced); Answer: A couple of things that can be simplified/refactored:
{ "domain": "codereview.stackexchange", "id": 43385, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript console.log(reduced); Answer: A couple of things that can be simplified/refactored: Conditionals can be reduced to improve code readability. No need to clone an object if it already exists. Instead, we can just update the currents and totals properties. const dbData = [{ studyId: 'X', siteId: 'A', day: '2000-01-01', status: 'PENDING_CALLCENTER', current: 5, total: 17, }, { studyId: 'X', siteId: 'A', day: '2000-01-01', status: 'PENDING_SITE', current: 3, total: 9, }, { studyId: 'Y', siteId: 'B', day: '2000-01-01', status: 'PENDING_SITE', current: 3, total: 9, }, { studyId: 'Y', siteId: 'B', day: '2000-01-01', status: 'PENDING_CALLCENTER', current: 3, total: 9, }, ]; const reduced = dbData.reduce((acc, row) => { const { studyId, siteId, status, current, total } = row; const idx = acc.findIndex(x => studyId === x.studyId && siteId === x.siteId); if (idx === -1) { const item = { studyId, siteId, currents: { [status]: current, }, totals: { [status]: total, }, }; acc.push(item); } else { acc[idx].currents[status] = (acc[idx].currents[status] || 0) + current; acc[idx].totals[status] = (acc[idx].totals[status] || 0) + total; } return acc; }, []); console.log(reduced);
{ "domain": "codereview.stackexchange", "id": 43385, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
python Title: Project Euler - Problem #1 - Multiples of 3 or 5 - Python Question: This is my solution for problem 1 of the projectEuler with python: import time start_time = time.time() #Time at the start of program execution def multiple_3_or_5(n): if n % 3 ==0 or n % 5 ==0: return True else: return False sum = 0 for i in range (1,1000): # print ("checking :" , i) if multiple_3_or_5(i): # print ("multiple is fine for", i) sum = sum + i # print ("Sum is =", sum) print (sum) end_time = time.time() #Time at the end of execution print ("Time of program execution:", (end_time - start_time)) #Time of program execution
{ "domain": "codereview.stackexchange", "id": 43386, "lm_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", "url": null }
python Answer: Put all of your code in functions. Including the code to represent Euler problem 1, along with the code to exercise that function. Implement automated tests for those functions. While implementing such code, express your expections for correctness in the form of automated tests. Ultimately, you'll want to learn how to use one of Python's testing frameworks, such as pytest. In the meantime, or in small-scale or informal situations, you can roll your own testing code, as illustrated below. Functions based on a simple boolean test can return directly. You can drop the if-else clauses from multiple_3_or_5() and just return the boolean result. The built-in sum function takes an iterable. Just add up the values of i for which multiple_3_or_5(i) returns true. Don't obsess over performance until you know you have a problem. This program is uninteresting from a performance perspective. Drop the extraneous timing code. And even if you disagree with my perspective, at least focus your measurements on the relevant code -- just the call of euler_1() function, rather than the execution of the entire program. def main(): TESTS = ( (10, 23), (1000, 233168), ) for limit, expected in TESTS: got = euler_1(limit) if got == expected: print('ok') else: print(limit, got, expected) def euler_1(limit = 1000): return sum(i for i in range (1, limit) if multiple_3_or_5(i)) def multiple_3_or_5(n): return n % 3 == 0 or n % 5 == 0 if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43386, "lm_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", "url": null }
c++, algorithm, security, cryptography, aes Title: Rijndael Cipher in C++ (128bit AES) Question: I am a hobbyist and do not work in the industry, but I do have an interest in programming an cryptography. I decided to have a go at writing a 128bit implementation of AES in C++. This is my first ever C++ program and I learn as I went. So I'm sure there are a lot of bad habits or things that are simply wrong. But it does give the correct results as described by FIPS 197 :) Appreciate any feedback that I can get. #include <iostream> #include <array> using namespace std; void printBlock(const array<array<int,4>,4>& block){ //Function to print a block to terminal for (size_t i = 0; i < 4; ++i){ printf("%.2x, %.2x, %.2x, %.2x\n", block[i][0], block[i][1], block[i][2], block[i][3]); } } void printRow(const array<int,4>& row){ //Function to print a row to terminal printf("%.2x, %.2x, %.2x, %.2x\n", row[0], row[1], row[2], row[3]); } void print_1d_State(const array<int,16>& e){ //Function to print a 1d version of the state to terminal printf("%.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x\n", e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8], e[9], e[10], e[11], e[12], e[13], e[14], e[15]); } void printKeySchedule(const array<array<int,16>,11>& keySchedual){ //Function to print keys for debugging for (size_t i=0; i<11; ++i){ print_1d_State(keySchedual[i]); } } array<array<int,4>,4> inputToState(const array<int,16>& input){ //Function turns a 128bit/ 16 element array and minipulates into a 4x4 matrix array<array<int,4>,4> state = {};
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes //Loop the input and assign to state for(size_t i=0; i<4; ++i){ for(size_t j=0; j<4; ++j){ state[i][j] = input[i+4*j]; } } return state; } array<int,16> stateToOutput(const array<array<int,4>,4>& state){ //Function takes a 128bit 4x4 block/ matrix and minipulates into a 1d array of words array<int,16> output = {}; //Loop the state and assign to output for(size_t i=0; i<4; ++i){ for(size_t j=0; j<4; ++j){ output[i+4*j] = state[i][j]; } } return output; } array<array<int,4>,4> keyToWords(const array<int,16>& roundKey){ //Function will take a rounds key and minipulate it into a 4x4 array //With each row being a word array<array<int,4>,4> wordBlock = {}; for (size_t i= 0; i < 4; ++i){ //Get words from key wordBlock[i] = {roundKey[4*i], roundKey[1+i*4], roundKey[2+i*4], roundKey[3+i*4]}; } return wordBlock; } array<array<int,4>,4> transposeState(const array<array<int,4>,4>& state){ //Function will transpose the state into a 4x4 matrix of words array<array<int,4>,4> tState = {}; for(size_t i = 0; i < 4; ++i){ for(size_t j = 0; j < 4; ++j){ tState[i][j] = state[j][i]; } } return tState; } int multiply_by_2(const int v){ /* Function to impliment multiplication by 2 of Galois Field GF(2^8). Shift bits left by 1, if high bit is 0 return the value. If the high bit is one XOR the value with 0x1B. (0x1B comes from the field representation) */ int s = v << 1; //Shift bits left by 1 //If high bit = 1 (0x80 = 10000000bin) if (v & 0x80){ s &= 0xff; //Bitwise AND (ff = 11111111bin) This effectivly takes first 8 bits s = s ^ 0x1b; } return s; } int multiply_by_3(int v){ /* Function to impliment multiplication by 3 of Galois Field GF(2^8). This is simply the XOR of multiply by 2, with the original value. */ return multiply_by_2(v) ^ v; }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes int lookupByte(int &byte){ //This method takes a byte, performs a lookup in the AES SBOX and returns the corresponding value int x = byte >> 4; //Shifts 4 bits right i.e. takes first 4 bits and discards the rest int y = byte & 0x0f; // 0x0f = 15 = 00001111(bin). Effectivly takes last 4 bits and dicards the rest
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes const int sbox[16][16] = {{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": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes return sbox[x][y]; } int invLookupByte(int &byte){ //This method takes a byte, performs a lookup in the inverse AES SBOX and returns the corresponding value int x = byte >> 4; //Shifts 4 bits right i.e. takes first 4 bits and discards the rest int y = byte & 0x0f; // 0x0f = 15 = 00001111(bin). Effectivly takes last 4 bits and dicards the rest
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes const int sboxinv[16][16] = {{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},
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes {0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26,0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d}};
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes return sboxinv[x][y]; } auto subBytes(const array<array<int,4>,4>& state){ //Function takes the current state and subs each byte using sbox look up //the sboxLookup variable indicates the use of sbox or sboxInv i.e. forward or reverse lookup. array<array<int,4>,4> result = {}; int byte; for (size_t i=0; i<4; ++i){ for (size_t j=0; j<4; ++j){ byte = state[i][j]; result[i][j] = lookupByte(byte); } } return result; } auto unSubBytes(const array<array<int,4>,4>& state){ //Function takes the current states and subs each byte using sbox look up //the sboxLookup variable indicates the use of sbox or sboxInv i.e. forward or reverse lookup. array<array<int,4>,4> result = {}; int byte; for (size_t i=0; i<4; ++i){ for (size_t j=0; j<4; ++j){ byte = state[i][j]; result[i][j] = invLookupByte(byte); } } return result; } array<int,4> shiftRow(const array<int,4>& row, const int shift){ //Recursive function to shft a row left by given value array<int,4> result = {}; result = row; if(shift){ //Shift by 1 int temp = result[0]; for (size_t i=0; i<3; ++i){ result[i] = result[i+1]; } result[3] = temp; //reduce shift and perform again result = shiftRow(result, shift -1); } else{ return result; } } auto shiftRows(const array<array<int,4>,4>& state){ //Function to shift rows of the state left by the value of their index array<array<int,4>,4> result = {}; for (size_t i = 0; i < 4; i++){ result[i] = shiftRow(state[i], i); } return result; } array<int,4> unShiftRow(const array<int,4>& row, const int shift){ //Recursive function to shift a row right by given value array<int,4> result = {}; result = row; if(shift){ //Shift by 1 int temp = result[3];
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes if(shift){ //Shift by 1 int temp = result[3]; for (int i=3; i>0; --i){ result[i] = result[i-1]; } result[0] = temp; //reduce shift and perform again result = unShiftRow(result, shift -1); } else{ return result; } } auto unShiftRows(const array<array<int,4>,4>& state){ //Function to shift rows of the state right by the value of their index array<array<int,4>,4> result = {}; for (size_t i = 0; i < 4; i++){ result[i] = unShiftRow(state[i], i); } return result; } auto mixColumn(const array<int,4>& stateColumn){ //Function takes a column of the state and 'mixes' it according to the matrix multiplication defined in FIPS 197 array<int,4> result = {}; result[0] = multiply_by_2(stateColumn[0]) ^ multiply_by_3(stateColumn[1]) ^ stateColumn[2] ^ stateColumn[3]; result[1] = multiply_by_2(stateColumn[1]) ^ multiply_by_3(stateColumn[2]) ^ stateColumn[3] ^ stateColumn[0]; result[2] = multiply_by_2(stateColumn[2]) ^ multiply_by_3(stateColumn[3]) ^ stateColumn[0] ^ stateColumn[1]; result[3] = multiply_by_2(stateColumn[3]) ^ multiply_by_3(stateColumn[0]) ^ stateColumn[1] ^ stateColumn[2]; return result; } auto mixColumns(const array<array<int,4>,4>& state){ //Function takes the current states and applies the 'mixColumn' function column by column array<array<int,4>,4> result = {}; array<int,4> column = {}; //Grab the columns and mix for(size_t i = 0; i < 4; ++i){ for(size_t j = 0; j < 4; ++j){ column[j] = state[j][i]; } column = mixColumn(column); //Transpose the columns back into rows for(size_t j = 0; j < 4; ++j){ result[j][i] = column[j]; } }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes return result; } auto unMixColumns(const array<array<int,4>,4>& state){ //Function performs the inverse of the mixColumns function by using the 'cheat' method of //applying mixColumns 3 times array<array<int,4>,4> result = {}; result = mixColumns(state); result = mixColumns(result); result = mixColumns(result); return result; } array<int,4> xorWords(const array<int,4>& wordA, const array<int,4>& wordB){ //Function takes 2 words, XORs each element and returns the result array<int,4> result = {}; for (size_t i = 0; i < 4; i++){ result[i] = wordA[i] ^ wordB[i]; } return result; } array<int,4> subWord(const array<int,4>& word){ //Function takes the a word, performs an sbox lookup on each element and returns the result array<int,4> result = {}; int byte; for (size_t i=0; i<4; ++i){ byte = word[i]; result[i] = lookupByte(byte); } return result; } array<int,4> rotWord(const array<int,4>& word){ //Function takes the a word, performs a rightward cyclic shift and returns the result array<int,4> result = {}; result = shiftRow(word, 1); return result; } auto addRoundKey(const array<array<int,4>,4>& state, const array<int,16>& roundKey){ //Function takes 2 4x4 matricies, xors the corresponding columns and returns the result array<array<int,4>,4> result = {}; array<array<int,4>,4> stateWords = {}; array<array<int,4>,4> keyWords = {}; //Convert state and key into rows of words stateWords = transposeState(state); keyWords = keyToWords(roundKey); //Loop columns of the state and xor with the corresponding key column for (size_t i = 0; i < 4; ++i){ result[i] = xorWords(stateWords[i], keyWords[i]); } //Transpose words back into columns when returning return transposeState(result); }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes //Transpose words back into columns when returning return transposeState(result); } array<array<int,16>,11> generateKeys(const array<int,16>& key){ //Function performs the key expansion algorithm to expand a single 128 bit key into //10 round keys know as the keySchedule. Note this is coded specifically for 128bit keys and //will NOT work for other AES varients array<array<int,16>,11> keySchedule = {}; array<array<int,4>,4> roundKey = {}; array<array<int,4>,4> pRoundKey = {}; array<int,16> temp = {}; const array<array<int,4>,10> RCON = {{{0x01, 0x00, 0x00, 0x00}, {0x02, 0x00, 0x00, 0x00}, {0x04, 0x00, 0x00, 0x00}, {0x08, 0x00, 0x00, 0x00}, {0x10, 0x00, 0x00, 0x00}, {0x20, 0x00, 0x00, 0x00}, {0x40, 0x00, 0x00, 0x00}, {0x80, 0x00, 0x00, 0x00}, {0x1b, 0x00, 0x00, 0x00}, {0x36, 0x00, 0x00, 0x00}}}; keySchedule[0] = key; //Extract the words from the key and arrange into a block for (size_t i=0; i<4; ++i){ pRoundKey[i] = {key[4*i], key[4*i+1], key[4*i+2], key[4*i+3]}; } //Loop rounds for (size_t i=0; i<10; ++i){ //Rotate last word of PRK roundKey[0] = rotWord(pRoundKey[3]); //SubBytes of last word in PRK roundKey[0] = subWord(roundKey[0]); //XOR : first word PRK, current RK state, rcon(round) roundKey[0] = xorWords(xorWords(pRoundKey[0], roundKey[0]), RCON[i]); //XOR the other words in sequential order for (size_t j=1; j<4; ++j){ roundKey[j] = xorWords(roundKey[j-1], pRoundKey[j]); }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes //Arrange block back into 1d key for (size_t r=0; r<4; ++r){ for (size_t c=0; c<4; ++c){ temp[4*r+c] = roundKey[r][c]; } } //Add new round key to key schedule keySchedule[i+1] = temp; //Set new PRK pRoundKey = roundKey; } return keySchedule; } array<array<int,4>,4> encryptBlock(const array<array<int,4>,4>& block, const array<array<int,16>,11> keySchedual){ //Function will take a plain text 128bit block, perform the Rijndael algorithm with a //128bit key and return the cipher text vesion of the block array<array<int,4>,4> state = block; //First round //AddRoundKey state = addRoundKey(state, keySchedual[0]); //9 main rounds for (size_t i=1; i<10; ++i){ //SubBytes state = subBytes(state); //ShiftRows state = shiftRows(state); //MixColumns state = mixColumns(state); //AddRoundKey state = addRoundKey(state, keySchedual[i]); } //Final round //SubBytes state = subBytes(state); //ShiftRows state = shiftRows(state); //AddRoundKey state = addRoundKey(state, keySchedual[10]); return state; } array<array<int,4>,4> decryptBlock(const array<array<int,4>,4>& block, const array<array<int,16>,11> keySchedual){ //Function will take a cipher text 128bit block, perform the inverse Rijndael algorithm with a //128bit key and return the plain text vesion of the block array<array<int,4>,4> state = {}; state = block;
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes state = block; //Undo final round //undo AddRoundKey state = addRoundKey(state, keySchedual[10]); //undo ShiftRows state = unShiftRows(state); //undo SubBytes state = unSubBytes(state); //Undo 9 main rounds for (size_t i=9; i>0; --i){ //Undo addRoundKey state = addRoundKey(state, keySchedual[i]); //Undo mixColumns state = unMixColumns(state); //Undo shiftRows state = unShiftRows(state); //Undo SubBytes state = unSubBytes(state); } //undo first round //Undo AddRoundKey state = addRoundKey(state, keySchedual[0]); return state; } int main(){ /* Example values given in FIPS 197 Input = 32 43 f6 a8 88 5a 30 8d 31 31 98 a2 e0 37 07 34 Cipher Key = 2b 7e 15 16 28 ae d2 a6 ab f7 15 88 09 cf 4f 3c */ array<int,16> input = {0x32,0x43,0xf6,0xa8,0x88,0x5a,0x30,0x8d, 0x31,0x31,0x98,0xa2,0xe0,0x37,0x07,0x34};; array<int,16> key = {0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6, 0xab,0xf7,0x15,0x88, 0x09,0xcf,0x4f,0x3c}; array<array<int,16>,11> keySchedual = {}; array<array<int,4>,4> pTextBlock = {}; array<array<int,4>,4> cTextBlock = {}; array<int,16> output = {}; //Generate keys keySchedual = generateKeys(key); //Perform encryption cout << "INITIAL INPUT:\n"; print_1d_State(input); pTextBlock = inputToState(input); cTextBlock = encryptBlock(pTextBlock, keySchedual); cout << "CIPHER TEXT:\n"; output = stateToOutput(cTextBlock); print_1d_State(output); //Perform decryption pTextBlock = decryptBlock(cTextBlock, keySchedual); cout << "DECRYPTED OUTPUT:\n"; output = stateToOutput(pTextBlock); print_1d_State(output); }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes } Answer: Overall, this is an excellent first attempt. It’s good enough that I would accept it as okay even in a project I was in charge of. It’s not perfect, of course—nothing really is, and there’s always room to improve even experts’ code—but it is solid, and most of the areas of improvement are things that are nontrivial… things I wouldn’t even expect from an experienced C++ programmer. There is one small bug—technically two, but it’s the exact same bug duplicated in two places—but it’s a doozy. I’m surprised the code even compiles. Certainly I would have expected it to throw up a few warnings, even if warnings are not enabled (but they always should be!). I’ll get into a line-by-line review of the code, but before I do, I want to cover a few issues that are endemic. Since they come up over and over again, there’s no point mentioning them repeatedly, so I’ll just get them out of the way. Types There are no types in the code. For example, for a block, you just use array<int, 16> (or array<array<int, 4>, 4>, depending on the context). C++ is a strongly-typed language. In fact, it is probably the most strongly-typed language you’ll ever use. It’s all about the types. If you get the types right, everything else Just Works. It’s hard to appreciate just how magical it gets when the types are perfect: You’ll find that writing code is almost effortless, and everything just works perfectly, automatically. You’ll find that you can’t make mistakes; they’re all caught immediately, and the fix is also immediately obvious. For example, let’s consider your main() function. There are ~30 lines of code there to set up a cipher, encrypt a block, print it, decrypt it, and print it again. But… that’s just four “things” to do… so, why couldn’t it be done in ~4 lines? auto main() -> int { auto key = aes_128_key{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; auto cipher = aes_128{key};
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes auto input = aes_128_block{0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34}; std::cout << "INITIAL INPUT:\n" << input; auto output = cipher.encrypt(input); std::cout << "CIPHER TEXT:\n" << output; output = cipher.decrypt(output); std::cout << "DECRYPTED OUTPUT:\n" << output; } I mean, do you need any more than that? The key expansion could be computed in the constructor for the aes_128 class; it doesn’t need to be done separately. And with a dedicated block type, you don’t need to transform flat 16-element arrays into 4×4 arrays, or have a separate print function; the block type would know how to do all that itself. And everything could be checked rigorously to detect errors: if you mistakenly provide only 120 bits to the key—you accidentally forgot an octet—that could be detected immediately at compile time (whereas an array would simply silently replace the missing 8 bytes with zero). And that’s just the tip of the iceberg. With a dedicated type, you could add more convenience functionality. For example, let’s say you want to encrypt an entire file. That could be as easy as: auto file = std::ifstream{"file.dat", std::ios_base::binary}; auto out = std::ofstream{"file.enc", std::ios_base::binary}; cipher.encrypt(file, out);
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes cipher.encrypt(file, out); The moral here is that when coding in C++, you should look for the “things” and the “operations”… and every “thing” should be an object with a meaningful type, and every “operation” should be a function. With AES, the “things” are things like “key”, “block”, and so on. The “operations” are “encrypt” and “decrypt”, but there are also lower-level operations like “shift rows” and “mix columns”. You’ve done an excellent job of picking out the operations… but you’re missing out on a lot of the power of C++ by not also extracting the “things”. Unsigned numbers Throughout your code, you use signed integers—int—for all values. Normally that would exactly the right thing to do. Normally you should always use signed integers—I often see newbies using unsigned integers for things they figure can never be negative… but that’s misguided. There are only two situations where you should use unsigned integers: When you are bit-twiddling. When you are using modular arithmetic. So, normally, using int would be exactly the right thing to do. However… This just happens to be a rare case where using unsigned integers is proper: You are doing bit-twiddling. For example, the final step in each round is XORing the round key and the current state. More importantly, you are using modular arithmetic. Modular arithmetic (and/or elliptic curves) is one of the key mathematical tricks that makes encryption cheap to do, and expensive to undo.
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes So, this is a very rare situation where I have to reverse my usual rule, and say you shouldn’t use signed integers, you should use unsigned integers. Now, this kinda connects to the note about types above. If you had used specific types throughout, then there would only be one or two places where you’d have to edit the code to switch from signed int to unsigned int. For example, if you had a block type, there would be maybe one or two lines in that type where you would have to make the switch… and then everywhere that used the block type would be automatically fixed. But because you used ad hoc types like array<int, 16>, you’d have to make the fix all over the place. Testing It’s good that you checked that your code actually works! You’d be surprised, and probably horrified, at how often I see beginners write code, then submit it for review, and they haven’t even checked that it works—sometimes they haven’t even checked that it compiles. However, one of the best practices you can learn as a programmer—and not just a C++ programmer—is testing. A good C++ developer always tests their code; in fact, I’d say that anyone who doesn’t test their code is simply not a good C++ developer. I actually recommend writing the tests before you start writing the actual code; this can be a great way to make sure your interface is good, and it can help you get a better understanding of what you need, and what you don’t. You should choose a testing framework, then learn it, love it, live it. Personally, I swear by Boost.Test, but that’s not for the faint of heart; it can be a nightmare to set up, but once it’s up and going, it’s wonderful. A much simpler, but still excellent option is Catch2. I’ll use Catch2 to illustrate the idea of testing here.
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes Now, AES has a “proper” testing procedure specified by NIST—the Advanced Encryption Standard Algorithm Validation System (AESAVS). This procedure is mega complex, with 3 different test categories, and 7 different encryption modes. For now, let’s just focus on the easiest: the known answer test (KAT), in electronic code book (ECB) mode. You can get a copy of the KAT test vectors from the Internet Archive. If you download the KAT zip file and extract it, you’ll see 144 files. The ones we want are the ones that start with ECB, with 128 in them (for the 128-bit key size). That narrows the list to 8 files:
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes ECBGFSbox128e.txt ECBKeySbox128e.txt ECBVarKey128e.txt ECBVarTxt128e.txt ECBGFSbox128d.txt ECBKeySbox128d.txt ECBVarKey128d.txt ECBVarTxt128d.txt The ECB is the mode, then the test type, then 128 for the key size, then e or d for encryption or decryption. The four test types are: GFSbox. This sets the key to zero, to focus on testing the substitution box in the rounds. KeySbox. This sets the text to zero, to focus on testing the key expansion. VarKey for variable key. Basically, set the key and the text to zero, and then set one bit at a time in the key. VarText for variable text. Basically, set the key and the text to zero, and then set one bit at a time in the text. So let’s pick the GFSbox type, and open up ECBGFSbox128e.txt, and this is what we see: [ENCRYPT] COUNT = 0 KEY = 00000000000000000000000000000000 PLAINTEXT = f34481ec3cc627bacd5dc3fb08f273e6 CIPHERTEXT = 0336763e966d92595a567cc9ce537f5e COUNT = 1 KEY = 00000000000000000000000000000000 PLAINTEXT = 9798c4640bad75c7c3227db910174e72 CIPHERTEXT = a9a1631bf4996954ebc093957b234589 COUNT = 2 KEY = 00000000000000000000000000000000 PLAINTEXT = 96ab5c2ff612d9dfaae8c31f30c42168 CIPHERTEXT = ff4f8391a6a40ca5b25d23bedd44a597 COUNT = 3 KEY = 00000000000000000000000000000000 PLAINTEXT = 6a118a874519e64e9963798a503f1d35 CIPHERTEXT = dc43be40be0e53712f7e2bf5ca707209 COUNT = 4 KEY = 00000000000000000000000000000000 PLAINTEXT = cb9fceec81286ca3e989bd979b0cb284 CIPHERTEXT = 92beedab1895a94faa69b632e5cc47ce COUNT = 5 KEY = 00000000000000000000000000000000 PLAINTEXT = b26aeb1874e47ca8358ff22378f09144 CIPHERTEXT = 459264f4798f6a78bacb89c15ed3d601 COUNT = 6 KEY = 00000000000000000000000000000000 PLAINTEXT = 58c8e00b2631686d54eab84b91f0aca1 CIPHERTEXT = 08a4e2efec8a8e3312ca7460b9040bbf
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes In theory, you’re supposed to write a whole testing suite that reads this file (and the others), parses it, and then automatically generates the tests. But, let’s just do it the simple way for now. There are 7 tests in that file, each with a key of zero, a different input (PLAINTEXT), and the expected output (CIPHERTEXT). Let’s just copy out the inputs and outputs: TEST_CASE("ECBGFSbox128e") { auto const data = GENERATE(table<aes_128_block, aes_128_block>>({ {{0xf3, 0x44, 0x81, 0xec, 0x3c, 0xc6, 0x27, 0xba, 0xcd, 0x5d, 0xc3, 0xfb, 0x08, 0xf2, 0x73, 0xe6}, {0x03, 0x36, 0x76, 0x3e, 0x96, 0x6d, 0x92, 0x59, 0x5a, 0x56, 0x7c, 0xc9, 0xce, 0x53, 0x7f, 0x5e}}, {{0x97, 0x98, 0xc4, 0x64, 0x0b, 0xad, 0x75, 0xc7, 0xc3, 0x22, 0x7d, 0xb9, 0x10, 0x17, 0x4e, 0x72}, {0xa9, 0xa1, 0x63, 0x1b, 0xf4, 0x99, 0x69, 0x54, 0xeb, 0xc0, 0x93, 0x95, 0x7b, 0x23, 0x45, 0x89}}, // ... and so on ... })); auto key = aes_128_key{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto cipher = aes_128{key}; auto input = std::get<0>(data); auto output = std::get<1>(data); REQUIRE(cipher.encrypt(input) == output); }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes REQUIRE(cipher.encrypt(input) == output); } That will generate 7 tests, that each use a zero key to encrypt the given input, then checks if it equals the expected output. If the encryption algorithm is correct, those 7 tests will all pass. (Note that I think this technically not the correct way to do the AESAVS ECB tests. Doing it this way will recreate the cipher for each of the 7 tests. I think the proper way is to make the cipher only once and reuse it. But, whatever.) If you do basically the same thing for the other three test types, and also do decryption tests as well, you will end up with dozens of tests. If your algorithm passes all of those, then you can be pretty damn confident it’s okay. And if you want to get crazy, you can also try writing tests for the other, chained and counter modes. And if you want get really crazy, you can try implementing the multi-block and Monte Carlo tests. If you go that far, you’ve basically passed the AESAVS, and could submit your implementation for certification. But let’s not get crazy here. Generally, when you are implementing an algorithm that transforms one thing into another, you will want to write a test that basically looks like: TEST_CASE("algorithm test") { auto const data = GENERATE(table<input_type, output_type>>({ {input_1, expected_1}, {input_2, expected_2}, {input_3, expected_3}, // ... and so on ... })); REQUIRE(algorithm(std::get<0>(data)) == std::get<1>(data)); }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes REQUIRE(algorithm(std::get<0>(data)) == std::get<1>(data)); } The whole AESAVS dance was just about getting those input and expected values. I took the liberty of setting up a Godbolt that shows the test in action. I had to make some small fixes to get it to compile (which I’ll mention in the code review), but as you can see, all the tests pass. This is how you properly test an algorithm. Doing it this way makes the tests automated, and does the checking in code—you don’t need to eyeball output to make sure it’s good. In practice, you should implement the tests first, which means they will (and should!) all fail at first, and then you start implementing the algorithm to start making tests pass. This should be your standard development cycle: run tests, write code to fix failures, repeat. Code review #include <iostream> #include <array> You are missing quite a few includes that you need. For example, you use printf(), but don’t include <cstdio>; you use size_t, but don’t include anything that defines that (there are several options). using namespace std;
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes Never, never do this. It’s not worth all the potential problems, which can be both subtle and infuriating. It’s just a few more characters to write the std:: wherever needed, and it helps identify when you are using standard library types, versus when you are using your own types or other library’s types. Note that if you’re actually using your own types, you’ll be using a lot fewer std:: types anyway. void printBlock(const array<array<int,4>,4>& block){ //Function to print a block to terminal for (size_t i = 0; i < 4; ++i){ printf("%.2x, %.2x, %.2x, %.2x\n", block[i][0], block[i][1], block[i][2], block[i][3]); } } void printRow(const array<int,4>& row){ //Function to print a row to terminal printf("%.2x, %.2x, %.2x, %.2x\n", row[0], row[1], row[2], row[3]); } void print_1d_State(const array<int,16>& e){ //Function to print a 1d version of the state to terminal printf("%.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x\n", e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8], e[9], e[10], e[11], e[12], e[13], e[14], e[15]); } void printKeySchedule(const array<array<int,16>,11>& keySchedual){ //Function to print keys for debugging for (size_t i=0; i<11; ++i){ print_1d_State(keySchedual[i]); } }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes As I mentioned in the preamble, if you write proper types, you can give those types their own stream inserters, and you won’t need these functions. You could just do std::cout << ___. However, let’s assume we need these functions. In that case, you shouldn’t use the C library functions; you should use IOstreams. Ideally you should take the stream as a parameter, too, so you can print to any stream. For maximum efficiency, you should probably write to a buffer, and then stream the whole buffer. For example (with hacky and untested code): template <typename CharT, typename Traits> auto print_1d_state(std::basic_ostream<CharT, Traits>& out, std::array<int, 16> const& state) { constexpr auto digits = std::array{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; auto buffer = std::array<char, 64>{}; auto p = buffer.data(); for (auto byte : state) { *p++ = digits[(static_cast<unsigned int>(byte) & 0xF0u) >> 4]; *p++ = digits[static_cast<unsigned int>(byte) & 0xFu]; *p++ = ','; *p++ = ' '; } p -= 2; *p++ = '\n'; *p++ = '\0'; out << buffer.data(); } // usage: // print_1d_state(std::cout, state); But again, this would be better as an inserter for an actual state type. array<array<int,4>,4> inputToState(const array<int,16>& input){ //Function turns a 128bit/ 16 element array and minipulates into a 4x4 matrix array<array<int,4>,4> state = {}; //Loop the input and assign to state for(size_t i=0; i<4; ++i){ for(size_t j=0; j<4; ++j){ state[i][j] = input[i+4*j]; } } return state; } array<int,16> stateToOutput(const array<array<int,4>,4>& state){ //Function takes a 128bit 4x4 block/ matrix and minipulates into a 1d array of words array<int,16> output = {};
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes //Loop the state and assign to output for(size_t i=0; i<4; ++i){ for(size_t j=0; j<4; ++j){ output[i+4*j] = state[i][j]; } } return output; } The only reason these two functions are necessary is because you are using raw arrays, and need to convert a flat array to a square “matrix”. But suppose you had an actual state type instead. And suppose it looked like this: class state { std::array<std::byte, 16> _bytes; public: // ... [snip] ... constexpr auto at(std::size_t n) const { return _bytes[n]; } constexpr auto at(std::size_t i, std::size_t j) const { return _bytes[i + (4 * j)]; } // ... [snip] ... }; You see? You don’t need two different types to have the best of both worlds, and there’s no need to convert back and forth. Want to treat the state as a flat array of 16 octets? Use .at(0) to .at(15). Want to treat the state as a 4×4 matrix? Use .at(0, 0) to .at(3, 3). (Note that in a future version of C++, you will be allowed to use commas in subscripts. So you will one day be able to write s[0] for a 1D flat view, and s[0, 0] for a 2D matrix view.) array<array<int,4>,4> keyToWords(const array<int,16>& roundKey){ //Function will take a rounds key and minipulate it into a 4x4 array //With each row being a word array<array<int,4>,4> wordBlock = {}; for (size_t i= 0; i < 4; ++i){ //Get words from key wordBlock[i] = {roundKey[4*i], roundKey[1+i*4], roundKey[2+i*4], roundKey[3+i*4]}; } return wordBlock; } This is another transformation function that would be unnecessary with a custom state type. The next few functions are fine. int lookupByte(int &byte){ //This method takes a byte, performs a lookup in the AES SBOX and returns the corresponding value int x = byte >> 4; //Shifts 4 bits right i.e. takes first 4 bits and discards the rest int y = byte & 0x0f; // 0x0f = 15 = 00001111(bin). Effectivly takes last 4 bits and dicards the rest
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes const int sbox[16][16] = {{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": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes return sbox[x][y]; }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes Now, I mentioned at the top that you should be using unsigned types, but there is another issue with using int: AES is a byte-wise algorithm (where bytes are 8 bits). Basically everywhere you have int, you should have unsigned char or std::byte. Normally that doesn’t matter much, because if arguments are going to be passed in registers, they’ll be basically expanded to int size regardless. However, it does have some costs, and some that are quite significant. For example, if all your operands are int sized, then you’ll fit a lot fewer of them at a time when doing vectorized operations… and vectorization could speed things up a lot, so you really want as much as that to happen as possible. But even here there is a huge cost. That substitution box is 256 elements. If those elements were bytes, it would be 256 bytes. But you’ve used ints. Given that ints are often 2, 4, and sometimes even 8 bytes, this array will actually be 512, 1024, or 2048 bytes. An array of 256 bytes would have a much better chance of being able to fit in cache memory, and stay there, than a 1 kiB array. And if your substitution box is being bumped in and out of cache every round… your encryption will be slow. The solution is to use bytes. And in fact, you should use bytes everywhere, rather than ints. This will not only allow more stuff to fit in cache during encryption/decryption, it will also allow for more vectorization. Now, the question is whether to use unsigned char… which is the old school way of writing “byte”… or std::byte. The latter is more explicit, and safer… but… std::byte still has still a lot of missing functionality, and using it can be a little clunky. I’ll show you what code looks like with both so you can decide: // With unsigned char: constexpr auto lookupByte(unsigned char b) { constexpr auto sbox = std::array<unsigned char, 256>{ 0x63u, 0x7cu, 0x77u, 0x7bu, 0xf2u, 0x6bu, 0x6fu, 0xc5u, 0x30u, 0x01u, 0x67u, 0x2bu, 0xfeu, 0xd7u, 0xabu, 0x76u,
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes 0x30u, 0x01u, 0x67u, 0x2bu, 0xfeu, 0xd7u, 0xabu, 0x76u, // ... 0x8cu, 0xa1u, 0x89u, 0x0du, 0xbfu, 0xe6u, 0x42u, 0x68u, 0x41u, 0x99u, 0x2du, 0x0fu, 0xb0u, 0x54u, 0xbbu, 0x16u };
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes return sbox[b]; } // With std::byte: constexpr auto lookupByte(std::byte b) { // Unfortunately, there are no byte literals (though there should be!), // and (unsigned) integer literals won't implicitly convert (because they // might overflow - this is a good thing), so we need to *EXPLICITLY* // convert every value to byte. // // We could do std::byte{0x??} for every single value… but we can save // some typing and some space if we use an alias for std::byte. using x = std::byte; constexpr auto sbox = std::array<std::byte, 256>{ x{0x63u}, x{0x7cu}, x{0x77u}, x{0x7bu}, x{0xf2u}, x{0x6bu}, x{0x6fu}, x{0xc5u}, x{0x30u}, x{0x01u}, x{0x67u}, x{0x2bu}, x{0xfeu}, x{0xd7u}, x{0xabu}, x{0x76u}, // ... x{0x8cu}, x{0xa1u}, x{0x89u}, x{0x0du}, x{0xbfu}, x{0xe6u}, x{0x42u}, x{0x68u}, x{0x41u}, x{0x99u}, x{0x2du}, x{0x0fu}, x{0xb0u}, x{0x54u}, x{0xbbu}, x{0x16u} }; // And, std::byte doesn’t automatically convert to a number (which is // another good thing), so we need to manually do that. return sbox[std::to_integer<unsigned int>(b)]; // or, in C++23: // return sbox[std::to_underlying(b)]; } std::byte is wordier because you need to be more explicit, which is really a good thing, but it can be aggravating. Whether you use unsigned int or std::byte, what you really should do is use an alias. Here’s how: First, you should start with having everything in your own namespace. For me, I’d use namespace indi, and then I’d probably put all the encryption stuff in a encryption namespace. For you, I’ll assume namespace wire::encryption. Once you have a namespace, you’d just make an alias for byte: namespace wire::encryption { using byte = unsigned char; // or std::byte } // namespace wire::encryption
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes using byte = unsigned char; // or std::byte } // namespace wire::encryption And then you’d use byte everywhere, instead of int. I’d also add a couple of convenience features. I would add a user-defined literal for bytes, and a conversion function to numbers: namespace wire::encryption { using byte = unsigned char; // or std::byte consteval auto operator""_b(unsigned long long int value) { if (value > 0xFFu) throw std::out_of_range{"byte value out of range"}; return static_cast<byte>(value); } constexpr auto to_number(byte b) noexcept { return static_cast<unsigned char>(b); } } // namespace wire::encryption The UDL allows you to do: constexpr auto sbox = std::array{ 0x63_b, 0x7c_b, 0x77_b, 0x7b_b, 0xf2_b, 0x6b_b, 0x6f_b, 0xc5_b, 0x30_b, 0x01_b, 0x67_b, 0x2b_b, 0xfe_b, 0xd7_b, 0xab_b, 0x76_b, // ... 0x8c_b, 0xa1_b, 0x89_b, 0x0d_b, 0xbf_b, 0xe6_b, 0x42_b, 0x68_b, 0x41_b, 0x99_b, 0x2d_b, 0x0f_b, 0xb0_b, 0x54_b, 0xbb_b, 0x16_b }; And the conversion helper allows you to do: return sbox[to_number(b)]; And everything will work whether you use unsigned char or std::byte. Anywho, going back to the function in question: int lookupByte(int &byte){ //This method takes a byte, performs a lookup in the AES SBOX and returns the corresponding value int x = byte >> 4; //Shifts 4 bits right i.e. takes first 4 bits and discards the rest int y = byte & 0x0f; // 0x0f = 15 = 00001111(bin). Effectivly takes last 4 bits and dicards the rest
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes const int sbox[16][16] = {{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": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes return sbox[x][y]; } First, I don’t see the point of taking the argument by reference. I assume that’s a typo. Making the s-box a 2D array and then using bit-twiddling to extract the two nibbles from the byte seems a bit pointless. Why not make the s-box a 1D array, and just use the byte value directly? I would also make the function constexpr, and I would consider making it noexcept. Making it noexcept is a bit tricky, because a byte may not be 8-bits. If bytes are 8-bits, then the function cannot fail: all possible 8-bit values are covered in the s-box. However… if a byte is greater than 8 bits, then it is possible to have a value outside the range of 0–255… which means the function could fail. What you could do is use a conditional noexcept specifier, and only make it noexcept if a byte is 8 bits: constexpr auto lookupByte(byte b) noexcept(std::numeric_limits<unsigned char>::digits == 8) { // ... } There’s one more thing I’d suggest. When filling out a big block of numbers like this, it is easy to screw up and add too many or too few values. If you specify the array size, and add too many values, the compiler will catch it, which is cool. But if you add too few values, the compiler won’t complain… it will just add zeroes at the end. To avoid this problem, I would recommend letting the compiler deduce the number of values, and then double check that the count is correct: constexpr auto sbox = std::array{ 0x63_b, 0x7c_b, 0x77_b, 0x7b_b, 0xf2_b, 0x6b_b, 0x6f_b, 0xc5_b, 0x30_b, 0x01_b, 0x67_b, 0x2b_b, 0xfe_b, 0xd7_b, 0xab_b, 0x76_b, // ... 0x8c_b, 0xa1_b, 0x89_b, 0x0d_b, 0xbf_b, 0xe6_b, 0x42_b, 0x68_b, 0x41_b, 0x99_b, 0x2d_b, 0x0f_b, 0xb0_b, 0x54_b, 0xbb_b, 0x16_b }; static_assert(sbox.size() == 256);
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes static_assert(sbox.size() == 256); The inverse function is essentially the same, so let’s skip to the actual substitution function: auto subBytes(const array<array<int,4>,4>& state){ //Function takes the current state and subs each byte using sbox look up //the sboxLookup variable indicates the use of sbox or sboxInv i.e. forward or reverse lookup. array<array<int,4>,4> result = {}; int byte; for (size_t i=0; i<4; ++i){ for (size_t j=0; j<4; ++j){ byte = state[i][j]; result[i][j] = lookupByte(byte); } } return result; } Generally, writing naked for loops in modern C++ is frowned upon. Instead, you should use algorithms. Let’s assume the state is a flat array<int, 16> instead of a 2D array. In that case, this function could be: constexpr auto subBytes(std::array<int, 16> state) { std::ranges::transform(state, state.begin(), lookupByte); return state; } Obviously, things are more complicated with a 2D array… but that’s really a hint that you shouldn’t be using 2D arrays. On to the row shift: array<int,4> shiftRow(const array<int,4>& row, const int shift){ //Recursive function to shft a row left by given value array<int,4> result = {}; result = row; if(shift){ //Shift by 1 int temp = result[0]; for (size_t i=0; i<3; ++i){ result[i] = result[i+1]; } result[3] = temp; //reduce shift and perform again result = shiftRow(result, shift -1); } else{ return result; } } This is a place where using an algorithm would really help, for a couple of reasons. First, the simplicity. Check it out: constexpr auto shiftRow(array<int, 4> row, int const shift) noexcept { std::ranges::rotate(row, row.begin() + shift); return row; }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes return row; } Second, and more importantly… you have a serious bug. In fact, I’m surprised your code even compiles. Surely it must give some warnings, at least. The problem is that if shift is not zero… what does the function return? Answer: it returns nothing; it just falls off the end and boom, undefined behaviour. (In practice, it looks like you may be getting lucky, in that the UB is just that the last return value that was left in the return slot gets returned again… which happens to make things work.) The fix is simple. Instead of the last few lines being: else{ return result; } They should just be: return result; (This is basically what I had to do to get the Godbolt tests to compile.) But again, the smart thing to do is just use the built-in algorithm. It’s simpler, it’s already rigorously tested, and it just works. The same applies to the next function: auto shiftRows(const array<array<int,4>,4>& state){ //Function to shift rows of the state left by the value of their index array<array<int,4>,4> result = {}; for (size_t i = 0; i < 4; i++){ result[i] = shiftRow(state[i], i); } return result; } This could be: constexpr auto shiftRows(std::array<std::array<byte, 4>, 4> state) { std::ranges::transform(state, state.begin(), shiftRow); return state; }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes return state; } Note that I take the argument by value, not by const&, because we’re making a copy anyway. You could also take it by const& as you do, then copy it into result, again, as you do; that’s fine, nothing wrong with that at all. The un-shift functions are basically identical, so I’ll skip ’em. auto mixColumn(const array<int,4>& stateColumn){ //Function takes a column of the state and 'mixes' it according to the matrix multiplication defined in FIPS 197 array<int,4> result = {}; result[0] = multiply_by_2(stateColumn[0]) ^ multiply_by_3(stateColumn[1]) ^ stateColumn[2] ^ stateColumn[3]; result[1] = multiply_by_2(stateColumn[1]) ^ multiply_by_3(stateColumn[2]) ^ stateColumn[3] ^ stateColumn[0]; result[2] = multiply_by_2(stateColumn[2]) ^ multiply_by_3(stateColumn[3]) ^ stateColumn[0] ^ stateColumn[1]; result[3] = multiply_by_2(stateColumn[3]) ^ multiply_by_3(stateColumn[0]) ^ stateColumn[1] ^ stateColumn[2]; return result; } This is fine, but it could be simplified. There’s no need to create the result array, and then later fill it in—you could do it all in one step—but realistically, that unnecessary step will be optimized away by any modern compiler. Still, you could just as easily write: constexpr auto mixColumn(std::array<byte, 4> const& stateColumn) { return std::array<byte, 4>{ multiply_by_2(stateColumn[0]) ^ multiply_by_3(stateColumn[1]) ^ stateColumn[2] ^ stateColumn[3], multiply_by_2(stateColumn[1]) ^ multiply_by_3(stateColumn[2]) ^ stateColumn[3] ^ stateColumn[0], multiply_by_2(stateColumn[2]) ^ multiply_by_3(stateColumn[3]) ^ stateColumn[0] ^ stateColumn[1], multiply_by_2(stateColumn[3]) ^ multiply_by_3(stateColumn[0]) ^ stateColumn[1] ^ stateColumn[2] }; }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes The next function could also be simplified quite a bit: auto mixColumns(const array<array<int,4>,4>& state){ //Function takes the current states and applies the 'mixColumn' function column by column array<array<int,4>,4> result = {}; array<int,4> column = {}; //Grab the columns and mix for(size_t i = 0; i < 4; ++i){ for(size_t j = 0; j < 4; ++j){ column[j] = state[j][i]; } column = mixColumn(column); //Transpose the columns back into rows for(size_t j = 0; j < 4; ++j){ result[j][i] = column[j]; } } return result; } You see the two inner loops? They do the same thing, in the same order, using column as an intermediate to bridge between them. You could simplify that to: constexpr auto mixColumns(std::array<std::array<byte, 4>, 4> const& state) { auto result = std::array<std::array<byte, 4>, 4>{}; for(auto i = 0; i < 4; ++i) { for(int j = 0; j < 4; ++j) result[j][i] = mixColumn(state[j][i]); } return result; } Let’s skip unMixColums(). array<int,4> xorWords(const array<int,4>& wordA, const array<int,4>& wordB){ //Function takes 2 words, XORs each element and returns the result array<int,4> result = {}; for (size_t i = 0; i < 4; i++){ result[i] = wordA[i] ^ wordB[i]; } return result; } Another function that could be massively simplified and made safer with standard algorithms: auto xorWords(std::array<byte, 4> const& wordA, std::array<byte, 4> const& wordB) { auto result = std::array<byte, 4>{}; std::ranges::transform(wordA, wordB, result.begin(), std::bit_xor<>{}); return result; }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes std::ranges::transform(wordA, wordB, result.begin(), std::bit_xor<>{}); return result; } I’ll skip the next few functions because it’s mostly more of the same. array<array<int,16>,11> generateKeys(const array<int,16>& key){ //Function performs the key expansion algorithm to expand a single 128 bit key into //10 round keys know as the keySchedule. Note this is coded specifically for 128bit keys and //will NOT work for other AES varients array<array<int,16>,11> keySchedule = {}; array<array<int,4>,4> roundKey = {}; array<array<int,4>,4> pRoundKey = {}; array<int,16> temp = {}; const array<array<int,4>,10> RCON = {{{0x01, 0x00, 0x00, 0x00}, {0x02, 0x00, 0x00, 0x00}, {0x04, 0x00, 0x00, 0x00}, {0x08, 0x00, 0x00, 0x00}, {0x10, 0x00, 0x00, 0x00}, {0x20, 0x00, 0x00, 0x00}, {0x40, 0x00, 0x00, 0x00}, {0x80, 0x00, 0x00, 0x00}, {0x1b, 0x00, 0x00, 0x00}, {0x36, 0x00, 0x00, 0x00}}}; keySchedule[0] = key; //Extract the words from the key and arrange into a block for (size_t i=0; i<4; ++i){ pRoundKey[i] = {key[4*i], key[4*i+1], key[4*i+2], key[4*i+3]}; }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes //Loop rounds for (size_t i=0; i<10; ++i){ //Rotate last word of PRK roundKey[0] = rotWord(pRoundKey[3]); //SubBytes of last word in PRK roundKey[0] = subWord(roundKey[0]); //XOR : first word PRK, current RK state, rcon(round) roundKey[0] = xorWords(xorWords(pRoundKey[0], roundKey[0]), RCON[i]); //XOR the other words in sequential order for (size_t j=1; j<4; ++j){ roundKey[j] = xorWords(roundKey[j-1], pRoundKey[j]); } //Arrange block back into 1d key for (size_t r=0; r<4; ++r){ for (size_t c=0; c<4; ++c){ temp[4*r+c] = roundKey[r][c]; } } //Add new round key to key schedule keySchedule[i+1] = temp; //Set new PRK pRoundKey = roundKey; } return keySchedule; }
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes //Set new PRK pRoundKey = roundKey; } return keySchedule; } I note that you list all or most of the functions’ variables at the top of the function. That is an archaic practice going back to the primordial days of C—nowadays, even C programmers don’t do that anymore. Declaring all the variables at the top creates both confusion, and the possibility of bugs when values get jiggered with in surprising places. For example, I think that you intend for pRoundKey to be carried over from loop iteration to loop iteration, while roundKey exists only within the loop. (Giving variables such similar names is also asking for trouble.) Instead, declare variables right where they’re needed. The name RCON is a dangerous idea. In C++, identifiers in ALL_CAPS (also known as SCREAMING_SNAKE_CASE), are traditionally reserved for the preprocessor. If you use such an identifier, you risk having it stomped on by someone’s macro. Summary Aside from that one bug (which, again, I’m really surprised the compiler didn’t choke on, or at least warn about), the implementation obviously works; you checked it yourself and saw that it gives the correct result, and I ran a small battery of tests, and it worked. The biggest problems with the code are: a lack of custom types; and not using standard algorithms, and instead rolling your own loops all over the place.
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes Making proper types can make the code both much simpler, and much safer, because your custom types can implement any useful operations, and prevent any undesired ones. Getting the types right is the secret to good C++ code; otherwise, you’re just writing jazzed-up C. One noteworthy issue with the code that is related to not using custom types is the fact that you spend a lot of time converting back and forth between flat 16 element arrays to 4×4 2D arrays. Indeed, close to half the implementation is just converting back and forth, which is both a fantastic waste of time, and a lot of unnecessary code. Even if you’re not going to use custom types, it would probably make more sense to just use flat arrays throughout—never 2D arrays—and wherever it would be more convenient to view the flat array as a 4×4 matrix, use something like the proposed mdspan, or just a simple function to convert a 2D (i, j) pair to a flat index, like so: template <std::size_t M, std::size_t N> constexpr auto to_index(std::size_t i, std::size_t j) { // An optional check, if you want: if constexpr (not NDEBUG) { if (i >= M or j >= N) throw std::out_of_range{"coordinate out of range"}; } return i * M + j; } //////////////////////////////////////// // Usage: auto block = std::array<byte, 16>{}; // A 1D view of the block: for (auto i = 0; i != 16; ++i) std::cout << block[i] << " "; // A 2D view of the block: for (auto i = 0; i != 4; ++i) { for (auto j = 0; j != 4; ++j) std::cout << block[to_index<4, 4>(i, j)] << " "; std::cout << "\n"; } 2D arrays are almost never worth the hassle. But especially here, where you’re just jumping back and forth between a flat view and a 2D view. Removing the need to do that will massively simplify your code. As for standard algorithms, they are superior to hand-rolled loops in at least three ways:
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes Hand-rolled loops are too easy to fuck up. That actually happened in this code. (Well, technically, the fuck-up wasn’t in a loop, but rather a recursive function… but loops and recursive functions are basically interchangeable, so, yeah.) They are pretty much self documenting. When you see a naked for loop, you have literally no idea what it’s really doing until you sit down and reason through the code. But a standard algorithm? rotate() is pretty self-explanatory. transform(something, operation) is also pretty clear. And so on. They are rigorously tested, and optimized. You might be able to write a safer and/or faster version… but almost certainly not in the general case. Plus, they offer intriguing possibilities for acceleration… not so much today (though, maybe!), but definitely in the future. I can’t think of any place where you might benefit from it offhand, but imagine you were doing an operation of 4 bytes like so: // Naked loop version (bad) for (auto i = 0; i != 4; ++i) b[i] = some_op(b[i]); // Algorithm version std::transform(b.begin(), b.end(), b.begin(), some_op); Now, if it’s possible, a good compiler will probably be smart enough to unroll that loop and vectorize the operation, so that some_op() will be done to all 4 bytes in a single operation… at least a 4× speedup. (And the same would happen for the algorithm.) But why rely on the compiler’s good graces? Why not specify that you want the whole operation vectorized? std::transform(std::execution::unseq, b.begin(), b.end(), b.begin(), some_op);
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes The difference is between silently praying that the compiler will vectorize the operation, and explicily asking the compiler to do that, while also documenting for readers of the code that you know it is safe and desirable for vectorization to happen here. I wouldn’t bother doing this today, especially since the constrained algorithms don’t support execution policies yet. But it is a possibility for the future. Once you have everything written using standard algorithms, adding the execution policy later is trivial. Another issue with your code is the interface. It’s not particularly user-friendly. You should consider how a user would want to do AES encryption/decryption. They’d want to set up an encrypter/decrypter with a key, then just blast bytes into it, getting encrypted bytes out. Something like this: auto const key = aes_128_key{/* write key here, or load it from a file or whatever */}; auto encrypter = aes_128{key}; // key expansion happens here auto const input = /* ... */; // the input could be a byte array or vector, // or an input stream from a file, or // whatever. auto output = /* ... */; // the output could be a vector we back-insert // into, or an output stream to a file, or // whatever. encrypter(std::ranges::begin(input), std::ranges::end(input), std::ranges::begin(output)); // or: // encryper(input, std::ranges::begin(output)); // Internally, the encrypter reads 128 bits at a time, padding if necessary.
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes // Internally, the encrypter reads 128 bits at a time, padding if necessary. That’s what a good interface looks like: Easy to use, hard to misuse. Finally, look into testing, with a proper testing framework. NIST specifies a complete testing program for AES implementations… but you don’t need to go that far (unless you want to!). For an algorithm that just transforms data from one form to another—which would include encryption and decryption—all you really need is a set of pairs of input and expected output. Then it’s just: TEST_CASE("algorithm test") { auto const data = GENERATE(table<input_type, output_type>>({ {input_1, expected_1}, {input_2, expected_2}, {input_3, expected_3}, // ... and so on ... })); REQUIRE(algorithm(std::get<0>(data)) == std::get<1>(data)); } Sure you can do more testing if your algorithm has interesting or special cases, or particular usage patterns—for example, you could do one set of tests with input that is exactly the size of a block, and another set with input that is smaller (to make sure that padding works), and other set with input that is larger (with various chaining strategies). But this is the basic pattern you’ll be using. One last thing I would suggest, and that is parameterizing your implementation. AES comes in 3 flavours, after all, and the 3 flavours are more or less identical. It is possible to make a single implementation that can do AES 128, AES 192, and AES 256. You could make the actual version a template parameter, so that, using the interface I suggested above: // To change to AES 192 or 256, simply change the template parameter (and // write/load a different sized key, of course). auto const key = aes<128>::key{/* key here, or load it from wherever */}; auto encrypter = aes{key}; // deduces aes<128>, from the key auto const input = /* ... */; auto output = /* ... */; encrypter(std::ranges::begin(input), std::ranges::end(input), std::ranges::begin(output));
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
c++, algorithm, security, cryptography, aes encrypter(std::ranges::begin(input), std::ranges::end(input), std::ranges::begin(output)); With some simple constraints (the key size/template parameter can only be 128, 192, or 256), and a few simple specialized traits (like, for example, see how to parameterize the number of rounds below), this should be pretty easy to make a single implementation for all versions of AES (or, indeed, for all versions of Rijndael, if you want to get crazy). template <std::size_t KeySize> requires (KeySize == 128) or (KeySize == 192) or (KeySize == 256) consteval auto _number_of_rounds() noexcept { if constexpr (KeySize == 128) return 10uz; if constexpr (KeySize == 192) return 12uz; if constexpr (KeySize == 256) return 14uz; } template <std::size_t KeySize> inline constexpr auto number_of_rounds = _number_of_rounds<KeySize>(); // Usage: std::cout << number_of_rounds<128>; // prints 10 That’s it!
{ "domain": "codereview.stackexchange", "id": 43387, "lm_label": 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, security, cryptography, aes", "url": null }
python, fibonacci-sequence Title: Calculate the sum of even Fibonacci numbers Question: This is my solution for problem 2 of Project Euler using Python: a, b = 1, 1 total = 0 while a <= 4000000: if a % 2 == 0: total += a a, b = b, a+b # the real formula for Fibonacci sequence print (total) I put the codes in the function IsEven: def IsEven(n): if n % 2 == 0: return True else: return False Answer: Modularity We have the printing and the constraints (the constant 4000000) mixed in with the logic of the code. If we create a function, we can unit-test it, and we can time its execution (both of which will be useful to you if you attempt other Project Euler challenges). Perhaps something like def sum_even_fibonacci(limit) '''Return the sum of all even Fibonacci numbers not greater than LIMIT ''' a, b = 1, 1 total = 0 while a <= limit: if a % 2 == 0: total += a a, b = b, a+b return total Simplify The function that's unused is very long winded. Any time we write if condition: return True; else: return False, we could simply write return condition. I.e. def IsEven(n): return n % 2 == 0 Algorithm Instead of generating all the Fibonacci numbers, use your mathematical knowledge to generate just the even ones. Can you work out a formula for their sum?
{ "domain": "codereview.stackexchange", "id": 43388, "lm_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, fibonacci-sequence", "url": null }
c++, interview-questions, change-making-problem Title: Vending machine change function Question: Write a function that takes an amount of money M, a price P and returns the change given in the smallest number of coins. The following coins are available: 1c, 5c, 10c, 25c, 50c, and $1. Time: 20min. I'm looking for all sorts of reviews considering the time limit and environment. Here's my code: #include <iostream> #include <vector> std::vector<int> getChange(double M, double P) { /* 1c, 5c, 10c, 25c, 50c, and $1 getChange(3.14, 1.99) should return [0,1,1,0,0,1] getChange(4, 3.14) should return [1,0,1,1,1,0] getChange(0.45, 0.34) should return [1,0,1,0,0,0] */ int denominations[] = {1, 5, 10, 25, 50, 100}; std::vector<int> r(sizeof denominations / sizeof denominations[0]); // I had a floating-point problem here by computing cents = (M-P)*100; // it took me a few minutes to figure it out int cents = (int)(M*100) - (int)(P*100); for(int i = sizeof denominations / sizeof denominations[0] - 1; i >= 0; --i){ r[i] = cents / denominations[i]; cents = cents % denominations[i]; } return r; } int main() { auto change = getChange(5, 0.99); for(auto i : change){ std::cout << i << ", "; } std::cout << std::endl; return 0; } Answer: You still have a floating point problem If you change your line to this input: auto change = getChange(0.04, 0.03); you will get the following output: 2, 0, 0, 0, 0, 0, As you can see, it answers with 2 pennies instead of one. The problem is with the line that you "fixed": // I had a floating-point problem here by computing cents = (M-P)*100; // it took me a few minutes to figure it out int cents = (int)(M*100) - (int)(P*100);
{ "domain": "codereview.stackexchange", "id": 43389, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, interview-questions, change-making-problem", "url": null }
c++, interview-questions, change-making-problem You did notice a problem with your floating point conversion but you came to the conclusion that it was the subtraction that was the problem. The actual problem is that a floating point value of something like 0.03 can sometimes be slightly above or slightly below the actual value of 0.03. In this case, it is slightly below. When you convert this value to cents by using (int)(P*100), you end up converting something like 2.999999 to 2 instead of 3. One way to avoid this problem is to round instead of truncate. So you can change your line to this to fix the problem: int cents = (int) (100*(M-P) + 0.5);
{ "domain": "codereview.stackexchange", "id": 43389, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, interview-questions, change-making-problem", "url": null }
c++, object-oriented, snake-game Title: Snake game as console app in c++ Question: I made a snake game as console aplication. It was my first real little project I did all alone. I tried using best practices I learned but I've got lost few times so I suppose there will be some bad practices and bugs. I would like if someone has time to review my code and tell me what I did wrong so I can improve. I did everything in file, I hope its not a problem for reader. #include<iostream> #include<array> #include <vector> #include <chrono> #include <conio.h> #include <thread> #include <random> using namespace std::chrono_literals; // for ms // map dimensions constexpr int mapHeight{ 15 }; constexpr int mapWidth{ 30 }; void gameOver(); // foward declaration instead moving whole definition to the top enum class Objects { wall, snake, fruit, empty, }; using mapType = std::array<std::array<Objects, mapWidth>, mapHeight>; //filling map with walls and empty space for beginning void fillMap(mapType& map) { for (int i{ 0 }; i < mapHeight; ++i) { for (int j{ 0 }; j < mapWidth; ++j) { if (i == 0 || i == mapHeight - 1 || j == 0 || j == mapWidth - 1) map[i][j] = Objects::wall; else map[i][j] = Objects::empty; } } } //printing map as it modifies through the game void printMap(const mapType& map) { for (int i{ 0 }; i < mapHeight; ++i) { for (int j{ 0 }; j < mapWidth; ++j) { switch (map[i][j]) { case Objects::wall: std::cout << "#"; break; case Objects::snake: std::cout << "o"; break; case Objects::fruit: std::cout << "F"; break; default: std::cout << " "; } } std::cout << "\n"; } } class Fruit { private: static int getRandomInt(int a, int b); static bool m_isSpawned; public:
{ "domain": "codereview.stackexchange", "id": 43390, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, snake-game", "url": null }
c++, object-oriented, snake-game static void spawn(mapType& map); static bool isSpawned(); static void spawnedFalse(); static void spawnedTrue(); }; bool Fruit::m_isSpawned = true; // true because game starts with spawned fruit int Fruit::getRandomInt(int a, int b) { static std::random_device randDev; static std::mt19937 twister(randDev()); static std::uniform_int_distribution<int> dist; dist.param(std::uniform_int_distribution<int>::param_type(a, b)); return dist(twister); } void Fruit::spawn(mapType& map) { //spawning anywhere empty while (true) { int y{ getRandomInt(1, mapHeight - 2) }; int x{ getRandomInt(1,mapWidth - 2) }; if (map[y][x] == Objects::empty) { map[y][x] = Objects::fruit; return; } } } bool Fruit::isSpawned() { return m_isSpawned; } void Fruit::spawnedFalse() { m_isSpawned = false; } void Fruit::spawnedTrue() { m_isSpawned = true; } class Snake { public: enum class Direction { up, right, down, left, }; private: struct Coordinates { int x; int y; }; std::vector<Coordinates> m_snakesBody{}; Coordinates m_frontPosition{}; int m_startLength{ 3 }; Direction m_direction{Direction::right}; static int m_score; public: Snake(mapType& map); //begining snakes position void move(mapType& map); // controls snakes movement void takeDirectionsByUserInput(); // enables user to control snake directions using WSAD keys void eraseTail(mapType& map); //erases last 'o' on the snake as the snake moves //adds 'o' on in direction where snake is going, so it can move ahead void addHeadToRight( mapType& map); void addHeadToDown( mapType& map); void addHeadToLeft( mapType& map); void addHeadToUp( mapType& map);
{ "domain": "codereview.stackexchange", "id": 43390, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, snake-game", "url": null }
c++, object-oriented, snake-game void eat(mapType& map); // increases score and tells us snake has eaten static int getScore(); }; int Snake::m_score = 0; Snake::Snake (mapType& map) { // /2 so snake appears in the middle int y{ mapHeight / 2 }; int x{ mapWidth / 2 - 1 }; //setting snake in the starting position by changing middle Object::empty into Object::snake for (int i{ 0 }; i < m_startLength; ++i) { map[y][x] = Objects::snake; Coordinates coo{ x,y }; m_snakesBody.push_back(coo); ++x; } m_frontPosition.x = x - 1; m_frontPosition.y = y; } void Snake::eraseTail(mapType& map) { //accesing x and y of first element in vector (back of the snake) int backX{ m_snakesBody.front().x }; int backY{ m_snakesBody.front().y }; //removing last part of snake so we can move ahead map[backY][backX] = Objects::empty; m_snakesBody.erase(m_snakesBody.begin()); } void Snake::addHeadToRight( mapType& map) { //checking if snake is moving into its body or wall, game over if it does //x+1 because snake is going right if (map[m_frontPosition.y][m_frontPosition.x + 1] == Objects::snake || map[m_frontPosition.y][m_frontPosition.x + 1] == Objects::wall) { gameOver(); }
{ "domain": "codereview.stackexchange", "id": 43390, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, snake-game", "url": null }
c++, object-oriented, snake-game if (map[m_frontPosition.y][m_frontPosition.x + 1] == Objects::fruit) eat(map); //if snakes next field is fruit, eat it //making one place in the right snake body if theres no colision map[m_frontPosition.y][m_frontPosition.x + 1] = Objects::snake; //pushing back new fornt in the vector as the snake goes forward int newFrontX{ m_frontPosition.x + 1 }; int newFrontY{ m_frontPosition.y }; Coordinates newFront = { newFrontX, newFrontY }; m_snakesBody.push_back(newFront); //increasing on x axis as we move right m_frontPosition.x += 1; } void Snake::addHeadToDown(mapType& map) { //checking if snake is moving into its body or wall, game over if it does if (map[m_frontPosition.y + 1][m_frontPosition.x] == Objects::snake || map[m_frontPosition.y + 1][m_frontPosition.x] == Objects::wall) { gameOver(); } if (map[m_frontPosition.y + 1][m_frontPosition.x] == Objects::fruit) eat(map); //making one place down snake body if theres no colision map[m_frontPosition.y + 1][m_frontPosition.x] = Objects::snake; //pushing back new fornt in the vector int newFrontX{ m_frontPosition.x }; int newFrontY{ m_frontPosition.y + 1 }; Coordinates newFront = { newFrontX, newFrontY }; m_snakesBody.push_back(newFront); //increasing on y axis as we move down m_frontPosition.y += 1; } void Snake::addHeadToLeft(mapType& map) { //checking if snake is moving into its body or wall, game over if it does if (map[m_frontPosition.y][m_frontPosition.x - 1] == Objects::snake || map[m_frontPosition.y][m_frontPosition.x - 1] == Objects::wall) { gameOver(); } if (map[m_frontPosition.y][m_frontPosition.x - 1] == Objects::fruit) eat(map); //making one place in the left snake body if theres no colision map[m_frontPosition.y][m_frontPosition.x - 1] = Objects::snake; //pushing back new fornt in the vector int newFrontX{ m_frontPosition.x - 1 };
{ "domain": "codereview.stackexchange", "id": 43390, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, snake-game", "url": null }
c++, object-oriented, snake-game //pushing back new fornt in the vector int newFrontX{ m_frontPosition.x - 1 }; int newFrontY{ m_frontPosition.y }; Coordinates newFront = { newFrontX, newFrontY }; m_snakesBody.push_back(newFront); //reducing on x axis as we move left m_frontPosition.x -= 1; } void Snake::addHeadToUp(mapType& map) { //checking if snake is moving into its body or wall, game over if it does if (map[m_frontPosition.y - 1][m_frontPosition.x] == Objects::snake || map[m_frontPosition.y - 1][m_frontPosition.x] == Objects::wall) { gameOver(); } if (map[m_frontPosition.y - 1][m_frontPosition.x] == Objects::fruit) eat(map); //making one place up snake body if theres no colision map[m_frontPosition.y - 1][m_frontPosition.x] = Objects::snake; //pushing back new fornt in the vector int newFrontX{ m_frontPosition.x }; int newFrontY{ m_frontPosition.y - 1 }; Coordinates newFront = { newFrontX, newFrontY }; m_snakesBody.push_back(newFront); //reducing y axis as we move up m_frontPosition.y -= 1; } void Snake::move(mapType& map) { switch (m_direction) { case Direction::right: { // changing snakes position on the map as it moves to the right addHeadToRight(map); //snake grows in tail if it ate (so we are not erasing it if there isn't fruit spawned what means snake ate) if((Fruit::isSpawned())){ eraseTail(map); }
{ "domain": "codereview.stackexchange", "id": 43390, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, snake-game", "url": null }
c++, object-oriented, snake-game break; } case Direction::down: { // changing snakes position on the map as it moves down addHeadToDown(map); //snake grows in tail if it ate (so we are not erasing it if there isn't fruit spawned what means snake ate) if ((Fruit::isSpawned())) { eraseTail(map); } break; } case Direction::left: { // changing snakes position on the map as it moves to the left addHeadToLeft(map); //snake grows in tail if it ate (so we are not erasing it if there isn't fruit spawned what means snake ate) if ((Fruit::isSpawned())) { eraseTail(map); } break; } case Direction::up: { // changing snakes position on the map as it moves up addHeadToUp(map); //snake grows in tail if it ate (so we are not erasing it if there isn't fruit spawned what means snake ate) if ((Fruit::isSpawned())) { eraseTail(map); } break; } } } void Snake::takeDirectionsByUserInput() { //ifs forbid going in opposite direction (turning down while going up etc) switch (_getch()) { case 'w': if (m_direction != Direction::down) { m_direction = Direction::up; } break; case 'd': if (m_direction != Direction::left) { m_direction = Direction::right; } break; case 's': if (m_direction != Direction::up) { m_direction = Direction::down; } break; case 'a': if (m_direction != Direction::right) { m_direction = Direction::left; } break; } }
{ "domain": "codereview.stackexchange", "id": 43390, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, snake-game", "url": null }
c++, object-oriented, snake-game void Snake::eat(mapType& map) { ++m_score; Fruit::spawnedFalse(); } int Snake::getScore() { return m_score; } void set_cursor(int x = 0, int y = 0) { HANDLE handle; COORD coordinates; handle = GetStdHandle(STD_OUTPUT_HANDLE); coordinates.X = x; coordinates.Y = y; SetConsoleCursorPosition(handle, coordinates); } void gameOver() { std::cout << "You lose, you scored " << Snake::getScore(); std::exit(0); } void playGame(mapType& map, Snake& snake) { Fruit::spawn(map); printMap(map); system("pause"); // waits for user input so it doesn't start automatically while (true) { set_cursor(); // cursor goes back and 0,0 and we overwrite old map with old map (used instead system("cls") for less flashing printMap(map); std::cout << Snake::getScore(); std::this_thread::sleep_for(150ms); // pauses program for 150 ms if (_kbhit()) { // true if user hit key snake.takeDirectionsByUserInput(); snake.move(map); } else { snake.move(map); } if (!(Fruit::isSpawned())) { Fruit::spawn(map); Fruit::spawnedTrue(); } } } int main() { mapType map{}; fillMap(map); Snake snake(map); playGame(map, snake); return 0; } Answer: Your code is good. The items I'm going to flag are minor or because I'm an old school developer and not fully comfortable with all this modern C++ shiz. :)
{ "domain": "codereview.stackexchange", "id": 43390, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, snake-game", "url": null }
c++, object-oriented, snake-game It appears that all your code is in one file. Its OK for this but what if you wanted to reuse the Fruit class. Personally I would split out your classes into separate h/cpp files to improve reuse and increase clarity. It will help you in the future if you have a comment describing the overall purpose of the class, I know in this case its very trivial, but its a good habit to get into. Personally I don't think there are enough comments through out the code. Comments are a really easy way of explaining what the code is supposed to do and unlike documents they are stored with the code and are more likely to get updated . I don't like code that isn't in braces{} like map[i][j] I have been burnt to many times in the past by someone adding a second line to the if statement. Its stupid but it happens under pressure. The formatting in the Snake::move() function is confusing. I would have defined a game class and had the constructor run the code that is in main (also contains playGame) You have hardcoded the control keys and the characters that represent the map, snake and fruit. If you had them as variables, you could allow the user to change the keys or support accessibility. Rather than Fruit::spawnedTrue() why not have Fruit::setSpawned(const bool flag) {m_isSpawned = flag;} If you added a constructor to the structs, a) it would make sure the PODs were initialised safely and b) it would make the code a bit shorter and cleaner. I'm going to say it again, your code is good, I would be happy if I wrote code like this. Everything listed above is trivial, ignore it if you want, you will still have good code.
{ "domain": "codereview.stackexchange", "id": 43390, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, snake-game", "url": null }
python, programming-challenge, primes, factors Title: Calculate the first largest factor of 600851475143 Question: ٍProblem description: The prime factors of 13195 are 5, 7, 13 and 29. Largest prime factor 13195 is 29. What is the largest prime factor of the number 600851475143 ? Prime Factor: any of the prime numbers that can be multiplied to give the original number. Example: Find the prime factors of 100: 100 ÷ 2 = 50; save 2 50 ÷ 2 = 25; save 2 25 ÷ 2 = 12.5, not evenly so divide by next highest number, 3 25 ÷ 3 = 8.333, not evenly so divide by next highest number, 4 But, 4 is a multiple of 2 so it has already been checked, so divide by next highest number, 5 25 ÷ 5 = 5; save 5 5 ÷ 5 = 1; save 5 List the resulting prime factors as a sequence of multiples, 2 x 2 x 5 x 5 or as factors with exponents, 2^2 x 5^2. My Solution This is my solution for problem 3 of Project Euler using Python: def FLPF(n): '''Find Largest Prime Factor ''' PrimeFactor = 1 i = 2 while i <= n / i: if n % i == 0: PrimeFactor = i n /= i else: i += 1 if PrimeFactor < n: PrimeFactor = int(n) return PrimeFactor Answer: Couple of points:
{ "domain": "codereview.stackexchange", "id": 43391, "lm_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, programming-challenge, primes, factors", "url": null }
python, programming-challenge, primes, factors if PrimeFactor < n: PrimeFactor = int(n) return PrimeFactor Answer: Couple of points: Use integer division, the double slash //. This has an update partner //= too so n //= i works as expected, and the result is always an integer. Multiplication is cleaner and perhaps a little clearer for your loop test, while i*i <= n:. As coded, the final value of n should be the largest prime factor of the passed parameter anyway - you don't actually need to keep PrimeFactor at all. It's good to make your function names and parameters reasonably descriptive. Python styles vary but you will often see underscore-separated phrases like def find_largest_prime_factor(target):. Of course this isn't so important for a small test routine for your own temporary use. You could perhaps speed things up in a couple of ways: by testing for factors of 2 first and then incrementing through the odd numbers, and by keeping a limit based on a square root which is only refreshed when a factor is found. Again not very important in this case. def find_largest_prime_factor(target): remnant = target fac = 2 while fac * fac <= remnant: if remnant % fac == 0: remnant //= fac else: fac += 1 return remnant
{ "domain": "codereview.stackexchange", "id": 43391, "lm_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, programming-challenge, primes, factors", "url": null }
c#, asp.net-mvc, asp.net-web-api Title: ASP.NET Web API for currency Question: On the basis of the daily exchange rate data of the CB (https://ww.cbr-xml-daily.ru/daily_json.js) it is necessary to create a Web-service using ASP.Net Core, which implements 2 API methods: GET /currencies - should return the list of currencies with the possibility of pagination GET /currency/ - must return the exchange rate for the transferred currency identifier I want to know what mistakes I have. What should I fix and how? Class (and interface) who parsing website (Register as transient): public interface ICurrentCurrency { Task<IEnumerable<Valute>> GetCurrencies(); } public class CurrentCurrency : ICurrentCurrency { public async Task<IEnumerable<Valute>> GetCurrencies() { HttpClientHandler handler = new HttpClientHandler(); IWebProxy proxy = WebRequest.GetSystemWebProxy(); proxy.Credentials = CredentialCache.DefaultCredentials; handler.Proxy = proxy; var client = new HttpClient(handler); var content = await client.GetAsync("https://www.cbr-xml-daily.ru/daily_json.js"); string json = await content.Content.ReadAsStringAsync(); var obj = JObject.Parse(json)["Valute"].ToString(); return JsonConvert.DeserializeObject<Dictionary<string, Valute>>(obj).Select(x => x.Value); } } In Main (.NET 6 syntax): var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddTransient<ICurrentCurrency, CurrentCurrency>(); var app = builder.Build(); app.UseHttpsRedirection(); app.MapControllers(); app.UseRouting(); app.Run(); Model: public class Valute { [JsonProperty("ID")] public string Id { get; set; } public string Name { get; set; } public string CharCode { get; set; } public string NumCode { get; set; } public int Nominal { get; set; } public decimal Value { get; set; } public decimal Previous { get; set; } }
{ "domain": "codereview.stackexchange", "id": 43392, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, asp.net-mvc, asp.net-web-api", "url": null }
c#, asp.net-mvc, asp.net-web-api Class for pagination: public class CurrencyPageParameters { public const int MaxPageSize = 5; public int PageNumber { get; set; } = 1; public int _pageSize; public int PageSize { get => _pageSize; set => _pageSize = (value > MaxPageSize) ? MaxPageSize : value; } } And controller: [ApiController] [Route("[action]")] public class CbrCurrencyController : ControllerBase { private ICurrentCurrency _currency; public CbrCurrencyController(ICurrentCurrency currency) { _currency = currency; } [HttpGet] [ActionName("currency")] public async Task<Valute> GetCurrency(string id) { var item = (await _currency.GetCurrencies()).FirstOrDefault(x => x.Id == id); return item; } [HttpGet] [ActionName("currencies")] public async Task<IEnumerable<Valute>> Currencies([FromQuery] CurrencyPageParameters @params) { var data = (await _currency.GetCurrencies()).Skip((@params.PageNumber - 1) * @params.PageSize).Take(@params.PageSize); return data; } } Answer: GetCurrencies I would suggest to create a named/typed HttpClient with the proxy handler to make it reusable In this SO topic you can read more about the solution serviceCollection .AddHttpClient("currencyClient") .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() { IWebProxy proxy = WebRequest.GetSystemWebProxy(); proxy.Credentials = CredentialCache.DefaultCredentials; Proxy = httpProxy }); I would also recommend to set the base url of the HttpClient rather than passing the whole url all the time serviceCollection .AddHttpClient("currencyClient"), c => { c.BaseAddress = new Uri("https://www.cbr-xml-daily.ru/"); }) .ConfigurePrimaryHttpMessageHandler(...); After these modifications your method could be simplified like this:
{ "domain": "codereview.stackexchange", "id": 43392, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, asp.net-mvc, asp.net-web-api", "url": null }
c#, asp.net-mvc, asp.net-web-api After these modifications your method could be simplified like this: public async Task<IEnumerable<Valute>> GetCurrencies() { var client = httpClientFactory.CreateClient(currencyClient); var content = await client.GetAsync("daily_json.js"); ... } I would also suggest to consider to use the ReadFromJsonAsync extension method of the HttpContent class to perform the deserialization It might make sense to introduce some caching here to reduce the network traffic and the overall response time CbrCurrencyController You can mark your _currency private field as readonly GetCurrency Inside the FirstOrDefault you might want to perform case insensitive string comparison .FirstOrDefault(x => string.Equals(x.Id, id, StringComparison.OrdinalIgnoreCase)) I would also suggest to return with 404 if the provided id does not have a corresponding currency In this case you have to use ActionResult class public async Task<ActionResult<Valute>> GetCurrency(string id) { var currencies = await _currency.GetCurrencies(); Valute item = currencies.FirstOrDefault(x => string.Equals(x.Id, id, StringComparison.OrdinalIgnoreCase)); return item ?? NotFound(); } Currencies I would suggest to perform some preliminary checks on your input model Like the PageNumber and PageSize fields are greater than 1 I would also recommend to check whether you are not over-paging (skipping more items than it is available) Just to make it clear the Skip and the Take will not break in case of over-paging the result will be an empty collection, but it does not make too much sense to perform such request
{ "domain": "codereview.stackexchange", "id": 43392, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, asp.net-mvc, asp.net-web-api", "url": null }
java, generics, cache Title: Correct usage of Java Generics for a simple cache holding objects of any particular type that contain an identifier of any particular type Question: The Stack Overflow question, I'm trying to create an inMemory database using Collections and generics, presents some code that attempts to use Java Generics for an in-memory cache of objects of any particular type that contain an identifier of any particular type. I revamped that code in to the following code. My code here seems to be working well enough, as seen in some tests below. Let's ignore the questionable wisdom of writing one’s own cache when many good implementations exist. This code is simply an exercise in trying to master some of the subtleties of Java Generics. My question is: Have I used Generics properly here? In particular, I do not yet understand where and how to use phrasing such as ? extends T. I am not asking about the lack of sophistication in the cache API. What I am asking is: Given the limited functionality shown in the current API, are Generics handled correctly and wisely? First piece of code, the interface for items going into the cache. One cache might hold objects whose identifier is text (String) while another cache might hold objects whose identifier is an integer (Integer), and a third cache for objects whose identifier is a UUID (UUID). public interface HasId < U > { U getId ( ); } Secondly, an example class (record, actually) for objects we might want to store in our cache. public record User( String username , String name , String surname ) implements HasId < String > { @Override public String getId ( ) { return this.username; } } And the cache implementation itself. Should public class Cache < T extends HasId , U > have a type hanging off the HasId, like this public class Cache < T extends HasId< U > , U >? import java.util.*; public class Cache < T extends HasId , U > { List < T > entities = new ArrayList <>();
{ "domain": "codereview.stackexchange", "id": 43393, "lm_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, generics, cache", "url": null }
java, generics, cache public class Cache < T extends HasId , U > { List < T > entities = new ArrayList <>(); public long size ( ) { return this.entities.size(); } public boolean keep ( T entity ) { return entities.add( entity ); } public boolean drop ( T entity ) { return entities.remove( entity ); } public Optional < T > find ( U id ) { for ( T entity : entities ) { if ( entity.getId().equals( id ) ) { return Optional.of( entity ); } } return Optional.empty(); } List < T > all ( ) { ArrayList < T > list = new ArrayList <>( this.entities ); return List.copyOf( list ); } List < T > allSorted ( Comparator < T > comparator ) { ArrayList < T > list = new ArrayList <>( this.entities ); list.sort( comparator ); return List.copyOf( list ); // Usually best to return an unmodifiable list. } } Here are some JUnit 5 Jupiter tests that all pass. @Test void addingBobShowsSizeOfOne ( ) { User bob = new User( "bob_barker" , "Bob" , "Barker" ); Cache < User, String > cache = new Cache <>(); cache.keep( bob ); assertEquals( 1 , cache.size() ); } @Test void addingAliceAndBobShowsSizeOfTwo ( ) { User alice = new User( "alice_n" , "Alice" , "Nelson" ); User bob = new User( "bob_b" , "Bob" , "Barker" ); Cache < User, String > cache = new Cache <>(); cache.keep( alice ); cache.keep( bob ); assertEquals( 2 , cache.size() ); } @Test void getAliceAfterAdding ( ) { User alice = new User( "alice_n" , "Alice" , "Nelson" ); Cache < User, String > cache = new Cache <>(); cache.keep( alice ); assertEquals( alice , cache.find( alice.username() ).get() ); }
{ "domain": "codereview.stackexchange", "id": 43393, "lm_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, generics, cache", "url": null }
java, generics, cache @Test void getAliceAndBobAfterAdding ( ) { User alice = new User( "alice_n" , "Alice" , "Nelson" ); User bob = new User( "bob_b" , "Bob" , "Barker" ); Cache < User, String > cache = new Cache <>(); cache.keep( alice ); cache.keep( bob ); Set < User > users = Set.of( alice , bob ); assertEquals( users , Set.copyOf( cache.all() ) ); } @Test void bobBarkerSortsBeforeAliceNelsonWhenComparingLastName () { User alice = new User( "alice_n" , "Alice" , "Nelson" ); User bob = new User( "bob_b" , "Bob" , "Barker" ); User bogus = new User( "bogus" , "Bogus" , "AAA" ); Cache < User, String > cache = new Cache <>(); cache.keep( alice ); cache.keep( bob ); List<User> expected = List.of(bob , alice ); Comparator<User> c = Comparator.comparing( User::surname ) ; assertEquals( expected , cache.allSorted( c ) ); } Answer: Yes, you do need to declare Cache as class Cache <T extends HasId<U>, U> otherwise this code compiles: Cache<User,Integer> c = new Cache<>(); c.keep(new User("a", "b", "c")); c.find(1); As find is comparing Integers and Strings it can never find anything. With the more explicit declaration the code above gives the error: java: type argument User is not within bounds of type-variable T
{ "domain": "codereview.stackexchange", "id": 43393, "lm_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, generics, cache", "url": null }
c#, performance Title: Recursively search directories and their subdirectories for images and videos, except system or locked folders Question: Search directories and their subdirectories for images and videos, except: Windows system folders, locked folders, and folders selected by me. For example, as a developer I have dozens of Visual Studio folders with folders named bin and debug in them. The goal was to write the program in a smart way. That's why I work with a List(of IO.FileInfo), which contains the files to be copied; and a List(of String), which contains the folder names that should not be searched. There is another List(of String); this one contains the allowed file extensions. The function calls itself again, so there is a List(Of IO.DirectoryInfo) that contains the folders that are already known. I also work with folder attributes so that the program doesn't try to search locked folders. That would throw an UnauthorizedAccessException and crash the program. By the way: Sorting the two lists “allowedExtensions” and “iDontWant” was for me only for clarity when debugging. Is there anything to improve here? StringNaturalSortComparer.cs using System.Collections.Generic; namespace Backup { public class StringNaturalSortComparer : IComparer<string> { [System.Runtime.InteropServices.DllImport("shlwapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] private static extern int StrCmpLogicalW(string psz1, string psz2); public int Compare(string x, string y) { return StrCmpLogicalW(x, y); } } } FormMain.cs using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Windows.Forms;
{ "domain": "codereview.stackexchange", "id": 43394, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance", "url": null }
c#, performance namespace Backup { public partial class FormMain : Form { private readonly List<System.IO.FileInfo> ListOfFilesToBeCopied = new List<System.IO.FileInfo>(); private readonly List<System.IO.DirectoryInfo> IAlreadyKnow = new List<System.IO.DirectoryInfo>(); public FormMain() { InitializeComponent(); } private readonly System.Globalization.CultureInfo Deu = new System.Globalization.CultureInfo("de-DE"); private void FormMain_Load(object sender, EventArgs e) { } private void ButtonStart_Click(object sender, EventArgs e) { IAlreadyKnow.Clear(); ListOfFilesToBeCopied.Clear(); SearchDirectories(new System.IO.DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))); long totalSizeInBytes = 0L; foreach (System.IO.FileInfo fi in ListOfFilesToBeCopied) { totalSizeInBytes += fi.Length; } Debug.WriteLine(""); Debug.WriteLine($"{ListOfFilesToBeCopied.Count} Files."); Debug.WriteLine($"{Math.Round((double)totalSizeInBytes / 1024.0, 0).ToString(Deu)} KB"); Debug.WriteLine($"{Math.Round((double)totalSizeInBytes / Math.Pow(1024.0, 2), 1).ToString(Deu)} MB"); Debug.WriteLine($"{Math.Round((double)totalSizeInBytes / Math.Pow(1024.0, 3), 1).ToString(Deu)} GB"); } private void SearchDirectories(System.IO.DirectoryInfo source) { List<string> allowedExtensions = new List<string> { ".jpg", ".jpeg", ".bmp", ".png", ".webp" }; if (CheckBoxV.Checked) { allowedExtensions.AddRange(new string[] { ".avi", ".mp4" }); } allowedExtensions = allowedExtensions.OrderBy(o => o, new StringNaturalSortComparer()).ToList();
{ "domain": "codereview.stackexchange", "id": 43394, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance", "url": null }
c#, performance List<string> iDontWant = new List<string> { ".config", ".dotnet", ".FreeYouTubeToMP3Converter", ".nuget", ".QtWebEngineProcess", ".templateengine", ".thumbnails", ".vscode", "3D Objects", "ansel", "Anwendungsdaten", "AppData", "Contacts", "Cookies", "Druckumgebung", "Eigene Dateien", "Favorites", "Links", "Lokale Einstellungen", "Netzwerkumgebung", "OneDrive", "Recent", "Saved Games", "Searches", "SendTo", "source", "Startmenü", "Vorlagen", "InventoryApp", ".picasaoriginals", ".vs", "v16", "bin", "Release", "My Project", "obj", "Debug", "TempPE", "packages", "lib", "Benutzerdefinierte Office-Vorlagen", "Custom Office Templates", "OneNote_RecycleBin", "config", "Logs", "TraceLogFiles" }; iDontWant = iDontWant.OrderBy(o => o, new StringNaturalSortComparer()).ToList(); // Check for folders that are in the source folder and view their files. int _9238 = (int)(System.IO.FileAttributes.Hidden | System.IO.FileAttributes.ReparsePoint | System.IO.FileAttributes.NotContentIndexed | System.IO.FileAttributes.System | System.IO.FileAttributes.Directory); foreach (System.IO.DirectoryInfo subdirectory in source.GetDirectories()) { // If that's a folder I don't want, or that's a system folder, move on to the next one! if (iDontWant.Contains(subdirectory.Name) || (int)subdirectory.Attributes == _9238 || IAlreadyKnow.Contains(subdirectory)) { continue; }
{ "domain": "codereview.stackexchange", "id": 43394, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance", "url": null }
c#, performance // Unfortunately, there are many system folders that are locked for programmes. I cannot know all of them, especially their foreign names. Therefore, in addition to the “iDontWant” list, there is this try-catch block. try { foreach (System.IO.FileInfo fi in subdirectory.GetFiles()) { if (allowedExtensions.Contains(fi.Extension.ToLower(Deu)) && !ListOfFilesToBeCopied.Contains(fi)) { ListOfFilesToBeCopied.Add(fi); } } IAlreadyKnow.Add(subdirectory); SearchDirectories(subdirectory); } catch (System.UnauthorizedAccessException ex) { Debug.WriteLine(ex.Message); } } } } } Answer: Let us first target the comment Why do you recreate and sort the iDontWant collection every time when someone calls the SearchDirectories method? – Peter Csala yesterday and let us only check about recreation of the List<string> iDontWant: on my Win10-PC the C:\Windows folder contains 142654 folders althougth in your app you only search inside the Environment.SpecialFolder.UserProfile folder on my Win10-PC this folder contains 16169 subfolders. Because you search through each subfolder which isn't contained in the iDontWant list I would assume you will search through 10000 folders which means the said list will be created 10000 times. This leads to the allowedExtensions which in best case only contains 5 items, but there just isn't a good reason to recreate that list either each time the method is called. You state as answer to the comment So far, there is no reason for me to declare this list global. I don't need it anywhere else.
{ "domain": "codereview.stackexchange", "id": 43394, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance", "url": null }
c#, performance So far, there is no reason for me to declare this list global. I don't need it anywhere else. which is a valid point, but how about using an overloaded method like so private void SearchDirectories(System.IO.DirectoryInfo source, List<string> allowedExtensions, List<string> excludedFolderNames) { int _9238 = (int)(System.IO.FileAttributes.Hidden | System.IO.FileAttributes.ReparsePoint | System.IO.FileAttributes.NotContentIndexed | System.IO.FileAttributes.System | System.IO.FileAttributes.Directory); foreach (System.IO.DirectoryInfo subdirectory in source.GetDirectories()) { // If that's a folder I don't want, or that's a system folder, move on to the next one! if (excludedFolderNames.Contains(subdirectory.Name) || (int)subdirectory.Attributes == _9238 || IAlreadyKnow.Contains(subdirectory)) { continue; } // Unfortunately, there are many system folders that are locked for programmes. I cannot know all of them, especially their foreign names. Therefore, in addition to the “iDontWant” list, there is this try-catch block. try { foreach (System.IO.FileInfo fi in subdirectory.GetFiles()) { if (allowedExtensions.Contains(fi.Extension.ToLower(Deu)) && !ListOfFilesToBeCopied.Contains(fi)) { ListOfFilesToBeCopied.Add(fi); } } IAlreadyKnow.Add(subdirectory); SearchDirectories(subdirectory, allowedExtensions, excludedFolderNames); } catch (System.UnauthorizedAccessException ex) { Console.WriteLine(ex.Message); } } }
{ "domain": "codereview.stackexchange", "id": 43394, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance", "url": null }
c#, performance which you would call like private void SearchDirectories(System.IO.DirectoryInfo source) { List<string> allowedExtensions = new List<string> { ".jpg", ".jpeg", ".bmp", ".png", ".webp" }; if (CheckBoxV.Checked) { allowedExtensions.AddRange(new string[] { ".avi", ".mp4" }); } allowedExtensions = allowedExtensions.OrderBy(o => o, new StringNaturalSortComparer()).ToList(); List<string> iDontWant = new List<string> { ".config", ".dotnet", ".FreeYouTubeToMP3Converter", ".nuget", ".QtWebEngineProcess", ".templateengine", ".thumbnails", ".vscode", "3D Objects", "ansel", "Anwendungsdaten", "AppData", "Contacts", "Cookies", "Druckumgebung", "Eigene Dateien", "Favorites", "Links", "Lokale Einstellungen", "Netzwerkumgebung", "OneDrive", "Recent", "Saved Games", "Searches", "SendTo", "source", "Startmenü", "Vorlagen", "InventoryApp", ".picasaoriginals", ".vs", "v16", "bin", "Release", "My Project", "obj", "Debug", "TempPE", "packages", "lib", "Benutzerdefinierte Office-Vorlagen", "Custom Office Templates", "OneNote_RecycleBin", "config", "Logs", "TraceLogFiles" }; iDontWant = iDontWant.OrderBy(o => o, new StringNaturalSortComparer()).ToList(); SearchDirectories(source, allowedExtensions, iDontWant); } But wait, in the current state of your code, we can do better.... the code in question can never reach the same folder twice which means that you don't need to know which subfolder had been processed. In the same way the code won't reach the same file twice. This means you can get rid of IAlreadyKnow and the call to ListOfFilesToBeCopied.Contains(fi). we should pass the FileAttributes as well because there is no need to create them always. We don't need them to be converted to an int either. by extracting the check for valid files and folders to separate methods the whole code gets easier to read. instead of using GetFiles() and GetDirectories() we could use EnumerateFiles and EnumerateDirectories.
{ "domain": "codereview.stackexchange", "id": 43394, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance", "url": null }
c#, performance we could take advantage of List<T>.AddRange() In addition, you should extract the searching code to a separate class to separate UI and logic. Summing up would look like so private bool IsValidDirectory(System.IO.DirectoryInfo subdirectory, System.IO.FileAttributes attribute, List<string> excludedFolderNames) { return !excludedFolderNames.Contains(subdirectory.Name) && subdirectory.Attributes != attribute; } private bool IsValidFile(System.IO.FileInfo file, List<string> allowedExtensions) { return allowedExtensions.Contains(file.Extension.ToLower(Deu)); } private void SearchDirectories(System.IO.DirectoryInfo source, List<string> allowedExtensions, System.IO.FileAttributes allowedAttributes, List<string> excludedFolderNames) { foreach (System.IO.DirectoryInfo subdirectory in source.EnumerateDirectories() .Where(d => IsValidDirectory(d, allowedAttributes, excludedFolderNames))) { // Unfortunately, there are many system folders that are locked for programmes. I cannot know all of them, especially their foreign names. Therefore, in addition to the “iDontWant” list, there is this try-catch block. try { ListOfFilesToBeCopied.AddRange(subdirectory.EnumerateFiles().Where(f => IsValidFile(f, allowedExtensions))); SearchDirectories(subdirectory, allowedExtensions, allowedAttributes, excludedFolderNames); } catch (System.UnauthorizedAccessException ex) { Console.WriteLine(ex.Message); } } }
{ "domain": "codereview.stackexchange", "id": 43394, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance", "url": null }
c#, performance And would be called like System.IO.FileAttributes allowedAttributes = (System.IO.FileAttributes.Hidden | System.IO.FileAttributes.ReparsePoint | System.IO.FileAttributes.NotContentIndexed | System.IO.FileAttributes.System | System.IO.FileAttributes.Directory); SearchDirectories(new System.IO.DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)), allowedExtensions, allowedAttributes, iDontWant);
{ "domain": "codereview.stackexchange", "id": 43394, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance", "url": null }
strings, rust, formatting Title: Rust program to print citations in Chicago author-date style Question: I have written a Rust program that lets you input a citation's metadata in a Bibtex-like format and generates a bibliography entry formatted in Markdown that conforms (more or less) to the Chicago Author-Date style described here. Currently, it supports citations for Books, JournalArticles, and NewspaperArticles with any number (>0) of authors. One of my goals was to write the code in a way that makes it easy to add a new resource type, say AcademicThesis, by creating a struct AcademicThesis containing the necessary fields and adding impl AcademicThesis { citation(&self) -> String { ... }} that generates the citation. A secondary goal was to make it expandable to other citation styles, but of course this would require first renaming the citation() method to something more specific. My motivation for writing this program is that almost all of the coding I do involves numerical schemes like this, and I almost never work with strings at all, but it seems like strings have a lot to teach us about how the Rust language works. The following are non-features that I decided against implementing until I have a firmer grasp of the Rust language: Page ranges such as (455, 468) are rendered naively as 455–468 instead of 455–68 Generates citations only, not a full bibliography (e.g. with line breaks, alphabetization, hanging indents...) I would appreciate a general code review. Here is the program: const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; pub struct Date { year: u16, month: usize, day: u16 } impl Date { // Return a string such as "May 23" representing the date fn to_month_day(&self) -> String { format!( "{} {}", MONTHS[self.month], self.day ) } } pub struct Name { first: String, last: String }
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
strings, rust, formatting pub struct Name { first: String, last: String } /// Convert a vector of author names into a string listing them in Chicago style fn list_authors(authors: &Vec<Name>) -> String { match authors.len() { 0 => panic!("No author given!"), 1 => format!("{}, {}", authors.first().unwrap().last, authors.first().unwrap().first), 2 => format!( "{}, {} and {} {}", authors.first().unwrap().last, authors.first().unwrap().first, authors.last().unwrap().first, authors.last().unwrap().last, ), _ => { let mut s = format!( "{}, {}, ", authors.first().unwrap().last, authors.first().unwrap().first ); for i in 1..authors.len()-1 { s.push_str(&format!( "{} {}, ", authors[i].first, authors[i].last )) }; s.push_str(&format!( "and {} {}", authors.last().unwrap().first, authors.last().unwrap().last )); s } } } /// Convert "str" to "[str](https://str)", which renders as a link in markdown fn link_to_clickable(url: &String) -> String { return format!("[{}](https://{})", url, url); } pub struct JournalArticle { authors: Vec<Name>, year: u16, title: String, journal: String, volume: u16, issue: u16, pages: (u16, u16), url: String } impl JournalArticle{ /// Generate a citation in Chicago style fn citation(&self) -> String { let author_string = list_authors(&self.authors);
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
strings, rust, formatting return format!( "{}. {}. &ldquo;{}.&rdquo; *{}* {} ({}): {}&ndash;{}. {}.", author_string, self.year, self.title, self.journal, self.volume, self.issue, self.pages.0, self.pages.1, link_to_clickable(&self.url) ); } } pub struct NewspaperArticle { authors: Vec<Name>, date: Date, title: String, newspaper: String, url: String } impl NewspaperArticle { /// Generate a citation in Chicago style fn citation(&self) -> String { let author_string = list_authors(&self.authors); let date_string = self.date.to_month_day(); return format!( "{}. {}. &ldquo;{}.&rdquo; *{},* {}. {}.", author_string, self.date.year, self.title, self.newspaper, date_string, link_to_clickable(&self.url) ); } } pub struct Book { authors: Vec<Name>, year: u16, title: String, publisher: String, location: String } impl Book { /// Generate a citation in Chicago style fn citation(&self) -> String { let author_string = list_authors(&self.authors); return format!( "{}. {}. *{}.* {}: {}.", author_string, self.year, self.title, self.location, self.publisher, ); } } fn main() { // Journal article with one author let source = JournalArticle{ authors: Vec::<Name>::from([Name{ first: String::from("Aaron"), last: String::from("Bodoh&ndash;Creed") }]), year: 2020, title: String::from("Optimizing for Distributional Goals in School Choice Problems"), journal: String::from("Management Science"), volume: 66, issue: 8, pages: (3657, 3676), url: String::from("doi.org/10.1287/mnsc.2019.3376") };
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
strings, rust, formatting println!("{}\n", source.citation()); // Journal article with two authors let source = JournalArticle{ authors: Vec::<Name>::from([Name{ first: String::from("Paul"), last: String::from("Milgrom") }, Name{ first: String::from("John"), last: String::from("Roberts") }]), year: 1990, title: String::from("The Economics of Modern Manufacturing: Technology, Strategy, and Organization"), journal: String::from("The American Economic Review"), volume: 80, issue: 3, pages: (511, 528), url: String::from("jstor.org/stable/2006681") }; println!("{}\n", source.citation()); // Journal article with three authors let source = JournalArticle{ authors: Vec::<Name>::from([Name{ first: String::from("Chandra"), last: String::from("Chekuri") }, Name{ first: String::from("Jan"), last: String::from("Vondrák") }, Name{ first: String::from("Rico"), last: String::from("Zenklusen") }]), year: 2014, title: String::from("Submodular Function Maximization via the Multilinear Relaxation and Contention Resolution Schemes"), journal: String::from("SIAM Journal on Computing"), volume: 43, issue: 6, pages: (3657, 3676), url: String::from("doi.org/10.1137/110839655") }; println!("{}\n", source.citation());
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
strings, rust, formatting println!("{}\n", source.citation()); // Newspaper article let source = NewspaperArticle{ authors: Vec::<Name>::from([Name{ first: String::from("Kathy Johnson"), // Middle names can be treated as an extension of first names last: String::from("Bowles") }]), date: Date{day: 24, month: 5, year: 2022}, title: String::from("Campus Landscapes: So Much More Than Marketing"), newspaper: String::from("Inside Higher Ed"), url: String::from("insidehighered.com/blogs/just-explain-it-me/campus-landscapes-so-much-more-marketing") }; println!("{}\n", source.citation()); // Book let source = Book{ authors: Vec::<Name>::from([Name{ first: String::from("Thomas"), last: String::from("Cormen") }, Name{ first: String::from("Charles"), last: String::from("Leiserson") }, Name{ first: String::from("Ronald"), last: String::from("Rivest") }]), year: 1996, title: String::from("Introduction to Algorithms"), publisher: String::from("The MIT Press"), location: String::from("Cambridge, Massachusetts") }; println!("{}\n", source.citation()); } It outputs Bodoh&ndash;Creed, Aaron. 2020. &ldquo;Optimizing for Distributional Goals in School Choice Problems.&rdquo; *Management Science* 66 (8): 3657&ndash;3676. [doi.org/10.1287/mnsc.2019.3376](https://doi.org/10.1287/mnsc.2019.3376). Milgrom, Paul and John Roberts. 1990. &ldquo;The Economics of Modern Manufacturing: Technology, Strategy, and Organization.&rdquo; *The American Economic Review* 80 (3): 511&ndash;528. [jstor.org/stable/2006681](https://jstor.org/stable/2006681).
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
strings, rust, formatting Chekuri, Chandra, Jan Vondrák, and Rico Zenklusen. 2014. &ldquo;Submodular Function Maximization via the Multilinear Relaxation and Contention Resolution Schemes.&rdquo; *SIAM Journal on Computing* 43 (6): 3657&ndash;3676. [doi.org/10.1137/110839655](https://doi.org/10.1137/110839655). Bowles, Kathy Johnson. 2022. &ldquo;Campus Landscapes: So Much More Than Marketing.&rdquo; *Inside Higher Ed,* June 24. [insidehighered.com/blogs/just-explain-it-me/campus-landscapes-so-much-more-marketing](https://insidehighered.com/blogs/just-explain-it-me/campus-landscapes-so-much-more-marketing). Cormen, Thomas, Charles Leiserson, and Ronald Rivest. 1996. *Introduction to Algorithms.* Cambridge, Massachusetts: The MIT Press. Which renders in Markdown as: Bodoh–Creed, Aaron. 2020. “Optimizing for Distributional Goals in School Choice Problems.” Management Science 66 (8): 3657–3676. doi.org/10.1287/mnsc.2019.3376. Milgrom, Paul and John Roberts. 1990. “The Economics of Modern Manufacturing: Technology, Strategy, and Organization.” The American Economic Review 80 (3): 511–528. jstor.org/stable/2006681. Chekuri, Chandra, Jan Vondrák, and Rico Zenklusen. 2014. “Submodular Function Maximization via the Multilinear Relaxation and Contention Resolution Schemes.” SIAM Journal on Computing 43 (6): 3657–3676. doi.org/10.1137/110839655. Bowles, Kathy Johnson. 2022. “Campus Landscapes: So Much More Than Marketing.” Inside Higher Ed, June 24. insidehighered.com/blogs/just-explain-it-me/campus-landscapes-so-much-more-marketing. Cormen, Thomas, Charles Leiserson, and Ronald Rivest. 1996. Introduction to Algorithms. Cambridge, Massachusetts: The MIT Press.
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
strings, rust, formatting Answer: Nice project! From previous experience writing citation formatting in Rust (just a small side project) I would advise you to not try to follow the standards to the letter, that is just a extreme pile of work that is not worth it. Otherwise really nice work. I attached the code with inline comments below, I prefixed the comments with Note: to make it easy to find them back. If you have questions about any of the comments feel free to reach out. // Note: I always use clippy to warn me when code can be written in a nicer way. // See: https://github.com/rust-lang/rust-clippy #![warn(clippy::all, clippy::pedantic, clippy::nursery)] const MONTHS: [&str; 12] = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; pub struct Date { year: u16, month: usize, day: u16, } impl Date { /// Return a string such as "May 23" representing the date fn to_month_day(&self) -> String { format!("{} {}", MONTHS[self.month], self.day) } } pub struct Name { first: String, // Note: some cultures have a slightly different scheme with middle parts, this is commonly added to the last name so it will likely not be a problem, eg Dutch/Flemish: Erik van Huffelen (mind the casing!). last: String, }
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
strings, rust, formatting impl Name { // Note: I personally really like this pattern where you have a function/constructor that // takes a `impl into<String>` and calls `.into()`. In this way I very rarely have to think // about the exact string type any more as it will automatically do all the stuff. And // because it is Rust this will be just as fast as doing it 'by hand' (I assume, I have no // reason to believe otherwise). // This can of course be done just as easily for the Citation types. And `Into` is a very // prevalent trait that can be used in very many places. pub fn new(first: impl Into<String>, last: impl Into<String>) -> Self { Self { first: first.into(), last: last.into(), } } }
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
strings, rust, formatting /// Convert a vector of author names into a string listing them in Chicago style fn list_authors(authors: &[Name]) -> String { // Note: I followed clippy here and replaced `&Vec<Name>` with `&[Name]` same explanation as `link_to_clickable` (line 80). match authors.len() { 0 => panic!("No author given!"), 1 => format!("{}, {}", authors[0].last, authors[0].first), // Note; I used direct indexing here into the array as the index is known and it takes less space visually, it is definitely not wrong to use `first` or `last`. I just want to show you some other ways ;-). 2 => format!( "{}, {} and {} {}", authors[0].last, authors[0].first, authors[1].first, authors[1].last, ), _ => { let mut output = format!("{}, {}, ", authors[0].last, authors[0].first); for author in authors.iter().take(authors.len() - 1).skip(1) { // Note: clippy advised this, but I am not sure if I agree, make your own choice here. output.push_str(&format!("{} {}, ", author.first, author.last)); } output.push_str(&format!( "and {} {}", authors.last().unwrap().first, authors.last().unwrap().last )); output } } } /// Convert "str" to "[str](https://str)", which renders as a link in markdown fn link_to_clickable(url: &str) -> String { // Note: this way it is more general, any `&String` can automatically be dereferenced into `&str`. // Using `&String` is essentially the same from the borrow standpoint, it gives you read access to // a piece of text. Specifying `&String` makes it so that you cannot use this functions with a // `&'static str` or a slice/simple operation of a string, eg [`String::trim`] returns a `&str`. return format!("[{url}](https://{url})"); // Note: You can directly include variables in format strings. }
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
strings, rust, formatting // Note: As you a creating a shared behaviour for a couple of structs introducing a `trait` seems to me // like a logical choice. You could also create a single `enum` with all options, but that gives a slightly // different code architecture you might not like in certain cases. (Like not having the option for downstream // users to implement the trait on their own structs.) pub trait Citation { /// Generate a citation in Chicago style fn citation(&self) -> String; // Note: You could write an extra method which prepares the citation output for markdown. fn md_citation(&self) -> String { // Note: this is an example of course you would add more cases for the other special chars. Each // call to `replace` copies the whole string, if this is a problem you could look into a loop over // all chars concatenating everything with the special encoding in one round. self.citation().replace('-', "&ndash"); // Note: here is an example of the single copy replacement. let citation = self.citation(); let mut output = String::with_capacity(citation.len()); for c in citation.chars() { match c { '-' => output += "&ndash;", n => output.push(n), } } output } } pub struct JournalArticle { authors: Vec<Name>, year: u16, title: String, journal: String, volume: u16, issue: u16, pages: (u16, u16), url: String, }
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
strings, rust, formatting impl Citation for JournalArticle { fn citation(&self) -> String { // Note: I tend to like 'one-liners' above introduced variables that are used only once. If needed the name of the variable being used as documentation can be replaced by a real comment ;-). format!( "{}. {}. &ldquo;{}.&rdquo; *{}* {} ({}): {}&ndash;{}. {}.", list_authors(&self.authors), self.year, self.title, self.journal, self.volume, self.issue, self.pages.0, self.pages.1, link_to_clickable(&self.url) ) // Note: here the return is not necessary } } pub struct NewspaperArticle { authors: Vec<Name>, date: Date, title: String, newspaper: String, url: String, } impl Citation for NewspaperArticle { fn citation(&self) -> String { format!( "{}. {}. &ldquo;{}.&rdquo; *{},* {}. {}.", list_authors(&self.authors), self.date.year, self.title, self.newspaper, self.date.to_month_day(), link_to_clickable(&self.url) ) } } pub struct Book { authors: Vec<Name>, year: u16, title: String, publisher: String, location: String, } impl Book { pub fn new( authors: impl Into<Vec<Name>>, year: u16, title: impl Into<String>, publisher: impl Into<String>, location: impl Into<String>, ) -> Self { Self { authors: authors.into(), year, title: title.into(), publisher: publisher.into(), location: location.into(), } } } impl Citation for Book { fn citation(&self) -> String { format!( "{}. {}. *{}.* {}: {}.", list_authors(&self.authors), self.year, self.title, self.location, self.publisher, ) } }
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
strings, rust, formatting fn main() { // Note: it is best to write these tests as unit tests so that reviewers (and you!) can be certain about // their refactorings. See below for how this is done with the book example. // Journal article with one author let source = JournalArticle { // Note: here you can see the impact of the `new` function with `impl Into<String>`. Additionally I // have an IDE which shows the names of parameters in-line once the definition becomes large, this // makes it so that the explicit names of the fields are not really necessary any more. authors: vec![Name::new("Aaron", "Bodoh&ndash;Creed")], year: 2020, title: String::from("Optimizing for Distributional Goals in School Choice Problems"), journal: String::from("Management Science"), volume: 66, issue: 8, pages: (3657, 3676), url: String::from("doi.org/10.1287/mnsc.2019.3376"), }; println!("{}\n", source.citation()); // Journal article with two authors let source = JournalArticle { authors: vec![ Name { first: String::from("Paul"), last: String::from("Milgrom"), }, Name { first: String::from("John"), last: String::from("Roberts"), }, ], year: 1990, title: String::from( "The Economics of Modern Manufacturing: Technology, Strategy, and Organization", ), journal: String::from("The American Economic Review"), volume: 80, issue: 3, pages: (511, 528), url: String::from("jstor.org/stable/2006681"), }; println!("{}\n", source.citation());
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
strings, rust, formatting println!("{}\n", source.citation()); // Journal article with three authors let source = JournalArticle{ authors: vec![Name{ first: String::from("Chandra"), last: String::from("Chekuri") }, Name{ first: String::from("Jan"), last: String::from("Vondrák") }, Name{ first: String::from("Rico"), last: String::from("Zenklusen") }], year: 2014, title: String::from("Submodular Function Maximization via the Multilinear Relaxation and Contention Resolution Schemes"), journal: String::from("SIAM Journal on Computing"), volume: 43, issue: 6, pages: (3657, 3676), url: String::from("doi.org/10.1137/110839655") }; println!("{}\n", source.citation()); // Newspaper article let source = NewspaperArticle { authors: vec![Name { first: String::from("Kathy Johnson"), // Middle names can be treated as an extension of first names last: String::from("Bowles"), }], date: Date { day: 24, month: 5, year: 2022, }, title: String::from("Campus Landscapes: So Much More Than Marketing"), newspaper: String::from("Inside Higher Ed"), url: String::from( "insidehighered.com/blogs/just-explain-it-me/campus-landscapes-so-much-more-marketing", ), }; println!("{}\n", source.citation()); } #[cfg(test)] // Note: cfg is conditional compilation, so the compiler will not even look at the code in // this module when compiling in a normal mode, this improves the compiling performance somewhat. mod tests { use super::*; // Note: this imports everything of the outer module (the one you are testing).
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
strings, rust, formatting #[test] fn book() { // Book // Note: arrays can be cast `Into` vecs! let source = Book::new( [ Name::new("Thomas", "Cormen"), Name::new("Charles", "Leiserson"), Name::new("Ronald", "Rivest"), ], 1996, "Introduction to Algorithms", "The MIT Press", "Cambridge, Massachusetts", ); assert_eq!( source.citation(), "Cormen, Thomas, Charles Leiserson, and Ronald Rivest. 1996. *Introduction to Algorithms.* Cambridge, Massachusetts: The MIT Press." ); } } ```
{ "domain": "codereview.stackexchange", "id": 43395, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, rust, formatting", "url": null }
c++, callback Title: Event callbacks library Question: This is a small library I wrote to make event callbacks with variadic templates work like C#'s event system (placeholder template by "dyp" at http://stackoverflow.com/a/21664270). Just like in C# you can subscribe/unsubscribe/call multiple function callbacks to a single event (invokable class in my library) using the =, +=, -= and () operators. With the exception of unhook_all() by itself which doesn't fit in with operators very well unless I add an operator for = for comparison to another invokable instance and check for null, which would keep you from ever setting an invokable class to null. Everything works from what I've tested... My only concern is thread-safety and the hash for comparison. Creating an invokable event with input parameters: // Without parameters invokable<> event; // OR // With parameters (int, int) invokable<int, int> event; class myclass { public: void F(int x, int y) {...}; }; myclass inst; callback<int, int> call(&inst, &myclass::F); Hooking and unhooking a callback to/from an event: // Hoook event += call; // OR event.hook(call); // Unhook event -= call; // OR event.unhook(call); // Hook Event & Unhook All Other Hooked events event = call; // OR event.hook_unhook(call); Unhooking all hooked events: event.unhook_all(); Invoking an event--notifies subscribed callbacks: event(10, 10); // OR event.invoke(10, 10); Lambda & Static Class Methods: class myclass { public: static void function() { cout << "Static Call" << endl; } }; invokable<> event; callback<> static_call(&myclass::function); callback<> lambda_call([](){cout << "Lambda Call" << endl;}); ...
{ "domain": "codereview.stackexchange", "id": 43396, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback #pragma once #ifndef INVOKABLE_EVENTS #define INVOKABLE_EVENTS #include <functional> #include <type_traits> #include <vector> #include <algorithm> #include <mutex> /// by "dyp" at http://stackoverflow.com/a/21664270 /// This generates the expansion for vargs into the invokable templated types. #pragma region Placeholder Generator template<int> struct placeholder_template {}; namespace std { template<int N> struct is_placeholder<placeholder_template<N>> : integral_constant<int, N + 1> {}; }; #pragma endregion #pragma region Invokable Callback /// Function binder for dynamic callbacks. template<typename... A> class callback { private: // Unique hash ID. size_t hash; // Bound function. std::function<void(A...)> func; // Creates and binds the function callback with a class instance for member functions. template<typename T, class _Fx, std::size_t... Is> void create(T* obj, _Fx&& func, std::integer_sequence<std::size_t, Is...>) { this->func = std::function<void(A...)>(std::bind(func, obj, placeholder_template<Is>()...)); }; // Creates and binds the function callback for a static/lambda/global function. template<class _Fx, std::size_t... Is> void create(_Fx&& func, std::integer_sequence<std::size_t, Is...>) { this->func = std::function<void(A...)>(std::bind(func, placeholder_template<Is>()...)); };
{ "domain": "codereview.stackexchange", "id": 43396, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback public: /// Compares equality of callbacks. const inline bool operator == (const callback& cb) { return (hash == cb.hash); }; /// Compares not-equality of callbacks. const inline bool operator != (const callback& cb) { return (hash != cb.hash); }; /// Executes this callback with arguments. const inline callback& operator () (A... args) { func(args...); return (*this); }; /// Construct a callback with a template T reference for instance/member functions. template<typename T, class _Fx> callback(T* obj, _Fx&& func) { hash = reinterpret_cast<size_t>(&this->func) ^ (&typeid(callback<A...>))->hash_code(); create(obj, func, std::make_integer_sequence<std::size_t, sizeof...(A)> {}); }; /// Construct a callback with template _Fx for static/lambda/global functions. template<class _Fx> callback(_Fx&& func) { hash = reinterpret_cast<size_t>(&this->func) ^ (&typeid(callback<A...>))->hash_code(); create(func, std::make_integer_sequence<std::size_t, sizeof...(A)> {}); }; /// Executes this callback with arguments. callback& invoke(A... args) { func(args...); return (*this); }; /// Returns this callbacks hash code. constexpr size_t hash_code() const throw() { return hash; }; }; #pragma endregion #pragma region Invokable Event /// Thread-safe event handler for callbacks. template<typename... A> class invokable { private: /// Shared resource to manage multi-thread resource locking. std::mutex safety_lock; /// Vector list of function callbacks associated with this invokable event. std::vector<callback<A...>> callbacks;
{ "domain": "codereview.stackexchange", "id": 43396, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback public: /// Adds a callback to this event. const inline invokable& operator += (const callback<A...>& cb) { if (cb != nullptr) hook(cb); return (*this); }; /// Removes a callback from this event. const inline invokable& operator -= (const callback<A...>& cb) { unhook(cb); return (*this); }; /// Removes all registered callbacks and adds a new callback, unless defaulted then all callbacks are unhooked. const inline invokable& operator = (const callback<A...>& cb) { hook_unhook(cb); return (*this); }; /// Execute all registered callbacks. const inline invokable& operator () (A... args) { invoke(args...); return (*this); }; /// Adds a callback to this event, operator += invokable& hook(callback<A...> cb) { std::lock_guard<std::mutex> g(safety_lock); if (std::find(callbacks.begin(), callbacks.end(), cb) == callbacks.end()) callbacks.push_back(cb); return (*this); }; /// Removes a callback from this event, operator -= invokable& unhook(callback<A...> cb) { std::lock_guard<std::mutex> g(safety_lock); typename std::vector<callback<A...>>::iterator it; it = std::find(callbacks.begin(), callbacks.end(), cb); if (it != callbacks.end()) callbacks.erase(it); return (*this); }; /// Removes all registered callbacks and adds a new callback, operator = invokable& hook_unhook(callback<A...> cb) { std::lock_guard<std::mutex> g(safety_lock); callbacks.clear(); (*this) += cb; return (*this); }; /// Removes all registered callbacks. invokable& unhook_all() { std::lock_guard<std::mutex> g(safety_lock); callbacks.clear();
{ "domain": "codereview.stackexchange", "id": 43396, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback callbacks.clear(); return (*this); }; /// Execute all registered callbacks, operator () invokable& invoke(A... args) { std::lock_guard<std::mutex> g(safety_lock); for (size_t i = 0; i < callbacks.size(); i++) callbacks[i](args...); return (*this); }; }; #pragma endregion #endif ``` Answer: Turn on and fix compiler warnings Compiling your code with strict compiler warnings turned on showed some issues: Stray semicolons after namespaces and function definitions. const return by value from operator==() and operator!=(). The const doesn't do anything here, just remove it. Use more auto and range-for There are a few places where you could use auto and range-for to simplify the code. For example, in unhook() you can write: auto it = std::find(callbacks.begin(), callbacks.end(), cb); And in invoke() you can write: for (auto& callback: callbacks) callback(args...);
{ "domain": "codereview.stackexchange", "id": 43396, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }