text stringlengths 1 2.12k | source dict |
|---|---|
javascript, assembly
alert(
"Line #" + node.lineNumber + ": The '" + node.text +
"' node should have either exactly one child node (unconditional jumping) or exactly three (3) child nodes (comma counts as a child node)!");
return;
}
if (node.children[1].text !== ",") {
alert("Line #" + node.lineNumber +
": Expected a comma (',') instead of '" + node.text + "'!");
return;
}
if (node.children[2].getLabelAddress(context.labels,
context.constants) === "none") {
alert("Line #" + node.lineNumber + ": Label '" +
node.children[2].text + "' is not declared!");
return;
}
if (/^z$/i.test(node.children[0].text))
machineCode[address].hex =
"32" + node.children[2].getLabelAddress(context.labels,
context.constants);
else if (/^nz$/i.test(node.children[0].text))
machineCode[address].hex =
"36" + node.children[2].getLabelAddress(context.labels,
context.constants);
else if (/^c$/i.test(node.children[0].text))
machineCode[address].hex =
"3a" + node.children[2].getLabelAddress(context.labels,
context.constants);
else if (/^nc$/i.test(node.children[0].text))
machineCode[address].hex =
"3e" + node.children[2].getLabelAddress(context.labels,
context.constants);
else {
alert("Line #" + node.lineNumber + ": Invalid flag name '" +
node.children[0].text + "'!");
return;
}
}
address++;
} else if (/^jump@$/i.test(node.text)) {
if (node.children.length !== 1 || node.children[0].text !== "()") { | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
if (node.children.length !== 1 || node.children[0].text !== "()") {
alert("Line #" + node.lineNumber + ": The '" + node.text +
"' node should have exactly one (1) child, and that is '()'");
return;
}
if (node.children[0].children.length !== 3) {
alert(
"Line #" + node.lineNumber +
": The '()' node should have exactly three children (now it has " +
node.children[0].children.length + ")!");
return;
}
if (node.children[0].children[1].text !== ",") {
alert("Line #" + node.lineNumber +
": Expected a comma (',') instead of '" +
node.children[0].children[1].text + "'!");
return;
}
if (node.children[0].children[0].getRegisterNumber(
context.namedRegisters) === "none") {
alert("Line #" + node.lineNumber + ": '" +
node.children[0].children[0].text + "' is not a register name!");
return;
}
if (node.children[0].children[2].getRegisterNumber(
context.namedRegisters) === "none") {
alert("Line #" + node.lineNumber + ": '" +
node.children[0].children[2].text + "' is not a register name!");
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "26" +
node.children[0].children[0].getRegisterNumber(
context.namedRegisters) +
node.children[0].children[2].getRegisterNumber(
context.namedRegisters) +
"0";
address++;
} else if (/^call@$/i.test(node.text)) {
if (node.children.length !== 1 || node.children[0].text !== "()") {
alert("Line #" + node.lineNumber + ": The '" + node.text +
"' node should have exactly one (1) child, and that is '()'");
return;
} | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
"' node should have exactly one (1) child, and that is '()'");
return;
}
if (node.children[0].children.length !== 3) {
alert(
"Line #" + node.lineNumber +
": The '()' node should have exactly three children (now it has " +
node.children[0].children.length + ")!");
return;
}
if (node.children[0].children[1].text !== ",") {
alert("Line #" + node.lineNumber +
": Expected a comma (',') instead of '" +
node.children[0].children[1].text + "'!");
return;
}
if (node.children[0].children[0].getRegisterNumber(
context.namedRegisters) === "none") {
alert("Line #" + node.lineNumber + ": '" +
node.children[0].children[0].text + "' is not a register name!");
return;
}
if (node.children[0].children[2].getRegisterNumber(
context.namedRegisters) === "none") {
alert("Line #" + node.lineNumber + ": '" +
node.children[0].children[2].text + "' is not a register name!");
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "24" +
node.children[0].children[0].getRegisterNumber(
context.namedRegisters) +
node.children[0].children[2].getRegisterNumber(
context.namedRegisters) +
"0";
address++;
} else if (/^call$/i.test(node.text)) {
machineCode[address].line = node.lineNumber;
if (node.children.length === 1) {
if (node.children[0].getLabelAddress(context.labels,
context.constants) === "none") {
alert("Line #" + node.lineNumber + ": Label '" +
node.children[0].text + "' is not declared!");
return;
} | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
node.children[0].text + "' is not declared!");
return;
}
machineCode[address].hex =
"20" +
node.children[0].getLabelAddress(context.labels, context.constants);
} else {
if (node.children.length !== 3) {
alert(
"Line #" + node.lineNumber + ": The '" + node.text +
"' node should have either exactly one child node (unconditional jumping) or exactly three (3) child nodes (comma counts as a child node)!");
return;
}
if (node.children[1].text !== ",") {
alert("Line #" + node.lineNumber +
": Expected a comma (',') instead of '" + node.text + "'!");
return;
}
if (node.children[2].getLabelAddress(context.labels,
context.constants) === "none") {
alert("Line #" + node.lineNumber + ": Label '" +
node.children[2].text + "' is not declared!");
return;
}
if (/^z$/i.test(node.children[0].text))
machineCode[address].hex =
"30" + node.children[2].getLabelAddress(context.labels,
context.constants);
else if (/^nz$/i.test(node.children[0].text))
machineCode[address].hex =
"34" + node.children[2].getLabelAddress(context.labels,
context.constants);
else if (/^c$/i.test(node.children[0].text))
machineCode[address].hex =
"38" + node.children[2].getLabelAddress(context.labels,
context.constants);
else if (/^nc$/i.test(node.children[0].text))
machineCode[address].hex =
"3c" + node.children[2].getLabelAddress(context.labels,
context.constants);
else { | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
context.constants);
else {
alert("Line #" + node.lineNumber + ": Invalid flag name '" +
node.children[0].text + "'!");
return;
}
}
address++;
} else if (/^return$/i.test(node.text)) {
machineCode[address].line = node.lineNumber;
if (!node.children.length)
machineCode[address].hex = "25000";
else if (node.children.length === 1) {
if (/^z$/i.test(node.children[0].text))
machineCode[address].hex = "31000";
else if (/^nz$/i.test(node.children[0].text))
machineCode[address].hex = "35000";
else if (/^c$/i.test(node.children[0].text))
machineCode[address].hex = "39000";
else if (/^nc$/i.test(node.children[0].text))
machineCode[address].hex = "3d000";
else {
alert("Line #" + node.lineNumber + ": Invalid flag name '" +
node.children[0].text + "'");
return;
}
} else {
alert(
"Line #" + node.lineNumber + ": The '" + node.text +
"' node should have either exactly zero (0) child nodes or exactly one (1) child node!");
return;
}
address++;
} else if (/^add$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "1";
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
// If we are adding a constant to a register.
machineCode[address].hex += "1";
else
machineCode[address].hex += "0";
machineCode[address].hex += | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
else
machineCode[address].hex += "0";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
else
machineCode[address].hex +=
node.children[2].getRegisterNumber(context.namedRegisters) + "0";
address++;
} else if (/^addcy?$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "1";
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
// If we are adding a constant to a register.
machineCode[address].hex += "3";
else
machineCode[address].hex += "2";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
else
machineCode[address].hex +=
node.children[2].getRegisterNumber(context.namedRegisters) + "0";
address++;
} else if (/^sub$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!'); | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "1";
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
// If we are subtracting a constant from a register.
machineCode[address].hex += "9";
else
machineCode[address].hex += "8";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
else
machineCode[address].hex +=
node.children[2].getRegisterNumber(context.namedRegisters) + "0";
address++;
} else if (/^subcy?$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "1";
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
// If we are subtracting a constant from a register.
machineCode[address].hex += "b";
else
machineCode[address].hex += "a";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
else
machineCode[address].hex +=
node.children[2].getRegisterNumber(context.namedRegisters) + "0"; | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
node.children[2].getRegisterNumber(context.namedRegisters) + "0";
address++;
} else if (/^and$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "0";
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex += "3";
else
machineCode[address].hex += "2";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
else
machineCode[address].hex +=
node.children[2].getRegisterNumber(context.namedRegisters) + "0";
address++;
} else if (/^or$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "0";
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex += "5";
else
machineCode[address].hex += "4";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none") | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
else
machineCode[address].hex +=
node.children[2].getRegisterNumber(context.namedRegisters) + "0";
address++;
} else if (/^xor$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "0";
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex += "7";
else
machineCode[address].hex += "6";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
else
machineCode[address].hex +=
node.children[2].getRegisterNumber(context.namedRegisters) + "0";
address++;
} else if (/^test$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "0";
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none") | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex += "d";
else
machineCode[address].hex += "c";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
else
machineCode[address].hex +=
node.children[2].getRegisterNumber(context.namedRegisters) + "0";
address++;
} else if (/^testcy?$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "0";
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex += "f";
else
machineCode[address].hex += "e";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
else
machineCode[address].hex +=
node.children[2].getRegisterNumber(context.namedRegisters) + "0";
address++;
} else if (/^comp(are)?$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") { | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "1";
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex += "d";
else
machineCode[address].hex += "c";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
else
machineCode[address].hex +=
node.children[2].getRegisterNumber(context.namedRegisters) + "0";
address++;
} else if (/^comp(are)?cy$/i.test(node.text)) {
check_if_there_are_three_child_nodes_and_the_second_one_is_comma();
if (node.children[0].getRegisterNumber(context.namedRegisters) ===
"none") {
alert("Line #" + node.lineNumber + ': "' + node.children[0].text +
'" is not a register!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "1";
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex += "f";
else
machineCode[address].hex += "e";
machineCode[address].hex +=
node.children[0].getRegisterNumber(context.namedRegisters);
if (node.children[2].getRegisterNumber(context.namedRegisters) === "none")
machineCode[address].hex +=
formatAsByte(node.children[2].interpretAsArithmeticExpression(
context.constants));
else
machineCode[address].hex += | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
context.constants));
else
machineCode[address].hex +=
node.children[2].getRegisterNumber(context.namedRegisters) + "0";
address++;
} else if (/^sl0$/i.test(node.text)) {
check_if_the_only_argument_is_register();
machineCode[address].line = node.lineNumber;
machineCode[address].hex =
"14" + node.children[0].getRegisterNumber(context.namedRegisters) +
"06";
address++;
} else if (/^sl1$/i.test(node.text)) {
check_if_the_only_argument_is_register();
machineCode[address].line = node.lineNumber;
machineCode[address].hex =
"14" + node.children[0].getRegisterNumber(context.namedRegisters) +
"07";
address++;
} else if (/^slx$/i.test(node.text)) {
check_if_the_only_argument_is_register();
machineCode[address].line = node.lineNumber;
machineCode[address].hex =
"14" + node.children[0].getRegisterNumber(context.namedRegisters) +
"04";
address++;
} else if (/^sla$/i.test(node.text)) {
check_if_the_only_argument_is_register();
machineCode[address].line = node.lineNumber;
machineCode[address].hex =
"14" + node.children[0].getRegisterNumber(context.namedRegisters) +
"00";
address++;
} else if (/^rl$/i.test(node.text)) {
check_if_the_only_argument_is_register();
machineCode[address].line = node.lineNumber;
machineCode[address].hex =
"14" + node.children[0].getRegisterNumber(context.namedRegisters) +
"02";
address++;
} else if (/^sr0$/i.test(node.text)) {
check_if_the_only_argument_is_register();
machineCode[address].line = node.lineNumber;
machineCode[address].hex =
"14" + node.children[0].getRegisterNumber(context.namedRegisters) +
"0e";
address++;
} else if (/^sr1$/i.test(node.text)) {
check_if_the_only_argument_is_register(); | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
} else if (/^sr1$/i.test(node.text)) {
check_if_the_only_argument_is_register();
machineCode[address].line = node.lineNumber;
machineCode[address].hex =
"14" + node.children[0].getRegisterNumber(context.namedRegisters) +
"0f";
address++;
} else if (/^srx$/i.test(node.text)) {
check_if_the_only_argument_is_register();
machineCode[address].line = node.lineNumber;
machineCode[address].hex =
"14" + node.children[0].getRegisterNumber(context.namedRegisters) +
"0a";
address++;
} else if (/^sra$/i.test(node.text)) {
check_if_the_only_argument_is_register();
machineCode[address].line = node.lineNumber;
machineCode[address].hex =
"14" + node.children[0].getRegisterNumber(context.namedRegisters) +
"08";
address++;
} else if (/^rr$/i.test(node.text)) {
check_if_the_only_argument_is_register();
machineCode[address].line = node.lineNumber;
machineCode[address].hex =
"14" + node.children[0].getRegisterNumber(context.namedRegisters) +
"0c";
address++;
} else if (/^disable$/i.test(node.text)) {
if (node.children.length !== 1 ||
!/interrupt/i.test(node.children[0].text)) {
alert("Line #" + node.lineNumber + ': The AST node "' + node.text +
'" should have exactly one child node, and that is "interrupt"!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "28000";
address++;
} else if (/^enable$/i.test(node.text)) {
if (node.children.length !== 1 ||
!/interrupt/i.test(node.children[0].text)) {
alert("Line #" + node.lineNumber + ': The AST node "' + node.text +
'" should have exactly one child node, and that is "interrupt"!');
return;
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "28001"; | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
}
machineCode[address].line = node.lineNumber;
machineCode[address].hex = "28001";
address++;
} else if (/^ret(urn)?i$/i.test(node.text)) {
if (node.children.length !== 1) {
alert("Line #" + node.lineNumber + ': The AST node "' + node.text +
'" should have exactly one child node!');
return;
}
if (/^enable$/i.test(node.children[0].text))
machineCode[address].hex = "29001";
else if (/^disable$/i.test(node.children[0].text))
machineCode[address].hex = "29000";
else {
alert("Line #" + node.lineNumber +
': Expected "ENABLE" or "DISABLE" instead of "' +
node.children[0].text + '"!');
return;
}
machineCode[address].line = node.lineNumber;
address++;
} else if (!isDirective(node.text)) {
alert("Line #" + node.lineNumber + ': Sorry about that, the mnemonic "' +
node.text + '" is not implemented.');
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
Answer: descriptive name
function formatAsByte(n) {
Consider calling it formatAsHexByte.
Alternatively, offer one line of
JSDoc.
As it stands, the Gentle Reader is forced to
read the body to learn what the
contract is.
Fortunately it's a short body.
error sentinel
function formatAsInstruction(n) {
...
return "ff";
...
while (ret.length < 5)
ret = "0" + ret;
...
I just don't get that at all.
The contract is to return a well-formed five-digit hex string.
But sometimes it's a two-digit hex string? What?
Possible copy-n-paste issue from the previous helper.
Is there something special about the all-ones byte
so we know it always indicates an error value?
Should the error value here be 2**18 - 1 ?
Would uniformly returning error as 0 from both helpers
improve consistency?
helper for helpers
function formatAs4bits(n) {
zomg, the same code again.
Write formatAsNBits just once, please,
and then these three helpers become one-line calls.
hash map lookup
function isDirective(str) {
...
for (const directive of preprocessor)
if (RegExp("^" + directive + "$", "i").test(str))
return true;
Ok, we get it, caller should pass in a string.
But please, name that string something descriptive.
And give us a one-liner JSDoc.
The function name is very nice,
making it immediately clear that this is a predicate.
Choosing to avoid .toLowerCase() seems odd,
but fine, there's more than one way
to accomplish a case insensive compare.
Looping over preprocessor seems more expensive than necessary.
Prefer to make just a single probe of a hash map.
Populate it with case-smashed entries if need be.
tell us what the code does
function assemble(parsed, context) { | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
tell us what the code does
function assemble(parsed, context) {
Uggh, that's pretty opaque.
I have no idea what the contract is,
what parsed looks like, nor context.
Use JSDoc already.
The OP helpfully offers some context that we're implementing a
Xilinx PicoBlaze
assembler, from which we infer that all instruction opcodes
fit into a single byte.
It's still not apparent why 2**18 is important in this context.
use exceptions
const check_if_the_only_argument_is_register = () => {
Thank you for the descriptive name.
The contract confuses me -- we detect either of two bad situations
and log that we're not pleased with the input, terrific.
But then we just return?!? Carrying on as if everything is fine?
I was expecting to see an assertion throw a fatal error.
Or possibly a predicate, so caller will change behavior in the error case.
Rather than a verb of "check...",
consider using a name that starts with "log..." or "display...",
to make its intended side effect clearer.
I'm starting to see some of the node structure.
The OP didn't offer any context about which software component
did the parsing, and I didn't see any imported libraries
near top-of-file giving me hints about where to seek documentation.
So I'm pretty much in the dark at this point.
why, not how
const check_if_there_are_three_child_nodes_and_the_second_one_is_comma = () => {
Kudos for trying to make this descriptive.
But really, this identifier reads like a comment,
and the text would be better placed within a comment.
(This would be a good identifier if it was part of a unit test suite.)
Isn't there some business term, some domain term,
that corresponds to the "node comma node" situation? Is there maybe an
EBNF
term in some Xilinx grammar that could lend its name here?
It's not yet clear to me why we're defining these functions here,
rather than at top-level scope along with the hex formatters. | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
case smash
if (/^address$/i.test(node.text))
...
else if (/^load$/i.test(node.text)) {
These case insensitive comparisons are just distracting.
Assign node.text.toLowerCase() to a local variable near top-of-loop,
and repeatedly examine that instead.
Or write a comparison helper.
cite your references
Tell us what spec you're writing against,
what spec you're implementing and claim conformance to.
machineCode[address].hex += "7";
else
machineCode[address].hex += "6";
I imagine this code is right. Probably.
But you've not told me where in the Xilinx docs to lookup these
magic numbers,
so I wouldn't know where to verify that this is right.
And if next year Xilinx releases an errata sheet,
or a modified processor that we wish to additionally support,
you're not making it easy to trace details from your code into their docs.
listen to what your code is telling you
Ok, I'm starting to see a pattern. I can't bear to read any more of this.
} else if (/^star$/i.test(node.text)) { ...
} else if (/^store$/i.test(node.text)) { ...
} else if (/^fetch$/i.test(node.text)) { ...
} else if (/^input$/i.test(node.text)) { ...
} else if (/^output$/i.test(node.text)) { ...
} else if (/^outputk$/i.test(node.text)) { ...
} else if (/^regbank$/i.test(node.text)) { ...
} else if (/^hwbuild$/i.test(node.text)) { ...
This is just not well organized.
Put the relevant code into suitably named helper functions,
perhaps assemble_star, assemble_store, assemble_fetch ...
And rather than repeated case insensitive compares,
dispatch via a single probe of a hash map.
You want to map from a string opcode to its corresponding assemble function. | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
javascript, assembly
copy-pasta
Here's the high level advice from this review:
Stop pasting!
Every time you're tempted to copy-n-paste,
pause a moment to consider whether the code
is asking for a parameterized helper function.
Also, it seems clear that you need a simple rule to follow.
So here it is, as simple and direct as I can make it:
If you write a function longer than a screenful, refactor it.
That is, if you need vertical scrolling to view the code,
it's time to Extract Helper.
This codebase achieves a subset of its design goals.
I would not delegate or accept maintenance tasks in the code's current form.
The changes required might be accomplished through
gradual "refactoring", supported by the existing
test suite.
It probably makes more sense to discard this code;
call it a learning exercise and with that experience under your belt
write some brand new target code which passes existing unit tests. | {
"domain": "codereview.stackexchange",
"id": 45174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, assembly",
"url": null
} |
c, image
Title: Filter: BMP Image Filtering Tool
Question: Filter is a C program that allows you to apply filters to BMP images.
Usage:
Usage: filter [OPTIONS] <infile> <outfile>
Review Goals:
General coding comments, style, potential undefined behavior, et cetera.
How can I eliminate the use of the non-standard packed attribute from the code?
Code:
bmp.h:
// BMP-related data types based on Microsoft's own
#include <stdint.h>
// These data types are essentially aliases for C/C++ primitive data types.
// Adapted from http://msdn.microsoft.com/en-us/library/cc230309.aspx.
// See https://en.wikipedia.org/wiki/C_data_types#stdint.h for more on stdint.h.
typedef uint8_t BYTE;
typedef uint32_t DWORD;
typedef int32_t LONG;
typedef uint16_t WORD;
// The BITMAPFILEHEADER structure contains information about the type, size,
// and layout of a file that contains a DIB [device-independent bitmap].
// Adapted from http://msdn.microsoft.com/en-us/library/dd183374(VS.85).aspx.
typedef struct {
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} __attribute__ ((__packed__))
BITMAPFILEHEADER;
// The BITMAPINFOHEADER structure contains information about the
// dimensions and color format of a DIB [device-independent bitmap].
// Adapted from http://msdn.microsoft.com/en-us/library/dd183376(VS.85).aspx.
typedef struct {
DWORD biSize;
LONG biWidth;
LONG biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
LONG biXPelsPerMeter;
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} __attribute__ ((__packed__))
BITMAPINFOHEADER;
// The RGBTRIPLE structure describes a color consisting of relative intensities of
// red, green, and blue. Adapted from http://msdn.microsoft.com/en-us/library/aa922590.aspx.
typedef struct {
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} __attribute__ ((__packed__))
RGBTRIPLE; | {
"domain": "codereview.stackexchange",
"id": 45175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, image",
"url": null
} |
c, image
filter.c:
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif
#ifdef _XOPEN_SOURCE
#undef _XOPEN_SOURCE
#endif
#define _POSIX_C_SOURCE 200819L
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <getopt.h>
#include "helpers.h"
#define ARRAY_CARDINALITY(x) (sizeof (x) / sizeof (*(x)))
static void help(void)
{
puts("Usage: filter [OPTIONS] <infile> <outfile>\n"
"\n\tTransform your BMP images with powerful filters.\n\n"
"Options:\n"
" -s, --sepia Apply a sepia filter for a warm, vintage look.\n"
" -r, --reverse Create a horizontal reflection for a mirror effect.\n"
" -g, --grayscale Convert the image to classic greyscale.\n"
" -b, --blur Add a soft blur to the image.\n"
" -h, --help displays this message and exit.\n");
exit(EXIT_SUCCESS);
}
static void apply_filter(char filter, size_t height, size_t width,
RGBTRIPLE image[height][width])
{
struct filter_map {
const char filter_char;
void (* const func)(size_t x, size_t y, RGBTRIPLE image[x][y]);
} const filter_map[] = {
{ 'b', blur },
{ 'g', grayscale },
{ 'r', reflect },
{ 's', sepia }
};
for (size_t i = 0; i < ARRAY_CARDINALITY(filter_map); ++i) {
if (filter_map[i].filter_char == filter) {
filter_map[i].func(height, width, image);
return;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, image",
"url": null
} |
c, image
static int write_image(const BITMAPFILEHEADER *restrict bf,
const BITMAPINFOHEADER *restrict bi,
FILE *restrict out, size_t height,
size_t width, const RGBTRIPLE image[height][width])
{
// Write outfile's BITMAPFILEHEADER and BITMAPINFOHEADER.
if (fwrite(bf, sizeof *bf, 1, out) != 1
|| fwrite(bi, sizeof *bi, 1, out) != 1) {
fputs("Failed to write to file.\n", stderr);
return -1;
}
// Determine padding for scanlines
const size_t padding = (4 - (width * sizeof (RGBTRIPLE)) % 4) % 4;
const int pad_byte = 0x00;
// Write new pixels to outfile
for (size_t i = 0; i < height; ++i) {
// Write row to outfile, with padding at the end.
if (fwrite(image[i], sizeof image[i][0], width, out) != width
|| fwrite(&pad_byte, 1, padding, out) != padding) {
fputs("Failed to write to file.\n", stderr);
return -1;
}
}
return 0;
}
static void *read_image(BITMAPFILEHEADER *restrict bf,
BITMAPINFOHEADER *restrict bi, size_t *restrict height,
size_t *restrict width, FILE *restrict inptr)
{
// Read infile's BITMAPFILEHEADER and BITMAPINFOHEADER.
if (fread(bf, sizeof *bf, 1, inptr) != 1
|| fread(bi, sizeof *bi, 1, inptr) != 1) {
fputs("Failed to read file.\n", stderr);
return NULL;
}
// Ensure infile is (likely) a 24-bit uncompressed BMP 4.0
if (bf->bfType != 0x4d42 || bf->bfOffBits != 54 || bi->biSize != 40 ||
bi->biBitCount != 24 || bi->biCompression != 0) {
fputs("Unsupported file format.\n", stderr);
return NULL;
}
// Get image's dimensions
*height = (size_t) abs(bi->biHeight);
*width = (size_t) bi->biWidth;
// Allocate memory for image
RGBTRIPLE(*image)[*width] = calloc(*height, *width * sizeof (RGBTRIPLE)); | {
"domain": "codereview.stackexchange",
"id": 45175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, image",
"url": null
} |
c, image
if (!image) {
fputs("Not enough memory to store image.\n", stderr);
return NULL;
}
// Determine padding for scanlines
const long int padding = (4 - (*width * sizeof (RGBTRIPLE)) % 4) % 4;
// Iterate over infile's scanlines
for (size_t i = 0; i < *height; i++) {
// Read row into pixel array
if (fread(image[i], sizeof image[i][0], *width, inptr) != *width) {
fputs("Failed to read file.\n", stderr);
return NULL;
}
// Skip over padding
fseek(inptr, padding, SEEK_CUR);
}
return image;
}
static int process_image(char filter, FILE *restrict inptr, FILE *restrict outptr)
{
// Image's BITMAPFILEHEADER
BITMAPFILEHEADER bf;
// image's BITMAPINFOHEADER
BITMAPINFOHEADER bi;
size_t height = 0;
size_t width = 0;
void *const image = read_image(&bf, &bi, &height, &width, inptr);
if (!image) {
return -1;
}
apply_filter(filter, height, width, image);
if (write_image(&bf, &bi, outptr, height, width, image) == -1) {
return -1;
}
free(image);
return 0;
}
static char parse_args(int argc, char *argv[])
{
// Define allowable filters
static const struct option long_options[] = {
{ "grayscale", no_argument, NULL, 'g' },
{ "reverse", no_argument, NULL, 'r' },
{ "sepia", no_argument, NULL, 's' },
{ "blur", no_argument, NULL, 'b' },
{ "help", no_argument, NULL, 'h' },
{ NULL, 0, NULL, 0 }
};
// Get filter flag and check validity
const int filter = getopt_long(argc, argv, "grsbh", long_options, NULL);
if (filter == '?') {
fputs("Invalid filter.\n", stderr);
return '\0';
} | {
"domain": "codereview.stackexchange",
"id": 45175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, image",
"url": null
} |
c, image
if (filter == '?') {
fputs("Invalid filter.\n", stderr);
return '\0';
}
if (filter == -1 || filter != 'h') {
if (argc != optind + 2) {
fputs("Usage: filter [OPTIONS] <infile> <outfile>\n"
"Try filter -h for help.\n", stderr);
return '\0';
}
return (char) filter;
}
// Ensure single flag
if (getopt_long(argc, argv, "grsbh", long_options, NULL) != -1) {
fputs("Only one filter allowed.\n", stderr);
return '\0';
}
if (filter == 'h' && optind == argc) {
return (char) filter;
}
fputs("Usage: filter [OPTIONS] <infile> <outfile>\n"
"Try filter -h for help.\n", stderr);
return '\0';
}
int main(int argc, char *argv[])
{
const char filter = parse_args(argc, argv);
if (filter == '\0') {
return EXIT_FAILURE;
} else if (filter == 'h') {
help();
}
const char *const infile = argv[optind];
const char *const outfile = argv[optind + 1];
FILE *const inptr = fopen(infile, "rb");
if (!inptr) {
fprintf(stderr, "Could not open %s.\n", infile);
return EXIT_FAILURE;
}
FILE *const outptr = fopen(outfile, "wb");
if (!outptr) {
fclose(inptr);
fprintf(stderr, "Could not create %s.\n", outfile);
return EXIT_FAILURE;
}
if (process_image(filter, inptr, outptr) == -1) {
fclose(inptr);
fclose(outptr);
return EXIT_FAILURE;
}
fclose(inptr);
fclose(outptr);
return EXIT_SUCCESS;
}
helpers.c:
#include "helpers.h"
#include <math.h>
#include <string.h>
static inline int min(int x, int y)
{
return x < y ? x : y;
} | {
"domain": "codereview.stackexchange",
"id": 45175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, image",
"url": null
} |
c, image
static inline int min(int x, int y)
{
return x < y ? x : y;
}
void grayscale(size_t height, size_t width, RGBTRIPLE image[height][width])
{
for (size_t i = 0; i < height; ++i) {
for (size_t j = 0; j < width; ++j) {
const int average = (image[i][j].rgbtBlue + image[i][j].rgbtRed +
image[i][j].rgbtGreen + 1) / 3;
image[i][j].rgbtRed = image[i][j].rgbtGreen = image[i][j].rgbtBlue = (BYTE) average;
}
}
}
void sepia(size_t height, size_t width, RGBTRIPLE image[height][width])
{
for (size_t i = 0; i < height; ++i) {
for (size_t j = 0; j < width; ++j) {
const int sepia_red = round(0.393 * image[i][j].rgbtRed +
0.769 * image[i][j].rgbtGreen +
0.189 * image[i][j].rgbtBlue);
const int sepia_green = round(0.349 * image[i][j].rgbtRed +
0.686 * image[i][j].rgbtGreen +
0.168 * image[i][j].rgbtBlue);
const int sepia_blue = round(0.272 * image[i][j].rgbtRed +
0.534 * image[i][j].rgbtGreen +
0.131 * image[i][j].rgbtBlue);
image[i][j].rgbtRed = (BYTE) min(255, sepia_red);
image[i][j].rgbtBlue = (BYTE) min(255, sepia_blue);
image[i][j].rgbtGreen = (BYTE) min(255, sepia_green);
}
}
}
static inline void swap(RGBTRIPLE *restrict lhs, RGBTRIPLE *restrict rhs)
{
RGBTRIPLE tmp = *lhs;
*lhs = *rhs;
*rhs = tmp;
}
void reflect(size_t height, size_t width, RGBTRIPLE image[height][width])
{
for (size_t i = 0; i < height; ++i) {
size_t start = 0;
size_t end = width - 1;
while (start < end) {
swap(&image[i][start], &image[i][end]);
--end;
++start;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, image",
"url": null
} |
c, image
void blur(size_t height, size_t width, RGBTRIPLE image[height][width])
{
RGBTRIPLE temp[height][width];
memcpy(temp, image, sizeof temp);
for (int i = 0; i < (int) height; ++i) {
for (int j = 0; j < (int) width; ++j) {
int blue = 0, red = 0, green = 0;
double count = 0;
for (int k = i - 1; k < i + 2; ++k) {
/*
* Check for top and bottom edge.
*/
if (k < 0 || k >= (int) height) {
continue;
}
for (int l = j - 1; l < j + 2; ++l) {
/*
* Check for left and right edge.
*/
if (l < 0 || l >= (int) width) {
continue;
}
red += temp[k][l].rgbtRed;
green += temp[k][l].rgbtGreen;
blue += temp[k][l].rgbtBlue;
++count;
}
}
image[i][j].rgbtRed = (BYTE) round(red / count);
image[i][j].rgbtBlue = (BYTE) round(blue / count);
image[i][j].rgbtGreen = (BYTE) round(green / count);
}
}
}
helpers.h:
#include "bmp.h"
#include <stddef.h>
// Convert image to grayscale
void grayscale(size_t height, size_t width, RGBTRIPLE image[height][width]);
// Convert image to sepia
void sepia(size_t height, size_t width, RGBTRIPLE image[height][width]);
// Reflect image horizontally
void reflect(size_t height, size_t width, RGBTRIPLE image[height][width]);
// Blur image
void blur(size_t height, size_t width, RGBTRIPLE image[height][width]); | {
"domain": "codereview.stackexchange",
"id": 45175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, image",
"url": null
} |
c, image
// Blur image
void blur(size_t height, size_t width, RGBTRIPLE image[height][width]);
makefile:
CFLAGS := -std=c17
CFLAGS += -no-pie
# CFLAGS += -g3
# CFLAGS += -ggdb
CFLAGS += -Wall
CFLAGS += -Wextra
CFLAGS += -Warray-bounds
CFLAGS += -Wconversion
CFLAGS += -Wmissing-braces
CFLAGS += -Wno-parentheses
CFLAGS += -Wno-format-truncation
CFLAGS += -Wpedantic
CFLAGS += -Wstrict-prototypes
CFLAGS += -Wwrite-strings
CFLAGS += -Winline
CFLAGS += -s
CFLAGS += -O2
CFLAGS += -D_FORTIFY_SOURCE=2
BINDIR := bin
BIN := $(BINDIR)/filter
SRCS := $(wildcard src/*.c)
OBJS := $(patsubst src/%.c, obj/%.o, $(SRCS))
LDLIBS := -lm
all: $(BIN)
$(BIN): $(OBJS)
$(CC) -o $@ $^ $(CFLAGS) $(LDLIBS)
obj/%.o: src/%.c
$(CC) $(CFLAGS) -c $< -o $@ $(LDLIBS)
clean:
$(RM) -rf $(OBJS)
fclean:
$(RM) -rf $(BIN)
.PHONY: clean all fclean
.DELETE_ON_ERROR:
Or you could instead clone this github repository: Filter
Answer:
typedef uint8_t BYTE;
typedef uint32_t DWORD;
typedef int32_t LONG;
typedef uint16_t WORD;
These definitions just serve to obscure the code (perhaps they are written as a crutch for someone more familiar with a different language?). Do your (C programmer) readers a favour and use the <stdint.h> types directly. It's a lot easier if we can understand the data structure without having to refer back to these definitions.
Or perhaps they were used just so we could copy the structure definitions from the other language? In which case a sensible option might be to use macros, which we could #undef at the end of the header so they don't infect the implementation files.
Please don't use all-caps for type names - that makes them look like macros, which they are not. We use all-caps for macros so that we can quickly see that they are text substitutions rather than real C code.
#define ARRAY_CARDINALITY(x) (sizeof (x) / sizeof (*(x))) | {
"domain": "codereview.stackexchange",
"id": 45175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, image",
"url": null
} |
c, image
#define ARRAY_CARDINALITY(x) (sizeof (x) / sizeof (*(x)))
It's good to use plenty of parens when writing macros, because we don't know what kind of expression the argument might be nor do we know the context in which it's expanded. So the parens around x are needed, and those around the entire expression. But we don't need the ones that enclose *(x):
#define ARRAY_CARDINALITY(x) (sizeof (x) / sizeof *(x))
Do take care when using this macro that there's no guard against misusing it with a pointer argument. The equivalent that's used in the Linux kernel has an ugly (but effective) guard to ensure it's only applied to arrays, but in this code, we're relying on programmer care.
const size_t padding = (4 - (width * sizeof (RGBTRIPLE)) % 4) % 4;
There's no explanation of the magic number 4 here. If it's a requirement of the file format, we should have at least a comment for this.
*height = (size_t) abs(bi->biHeight);
*width = (size_t) bi->biWidth;
It's not clear why height may be the wrong sign, but not width - again, needs a comment to explain the vagaries of the file format.
Since biWidth is a LONG, which is a int32_t, conversion to int may truncate the value on systems with 16-bit int. That's a standard problem in using the fixed-width types in C. I suggest using labs(), since long must be at least 32 bits. The best approach here is probably to write a simple abs32() of our own such as:
uint32_t abs32(int32_t x) { return x < 0 ? 0u - (uint32_t)x : (uint32_t)x; }
We could be more robust about trusting the values of width and height, and not only because calloc() is implementation-defined when either is zero. A more defensive approach to malformed input is a good thing generally; for example, we should be checking the width to ensure it won't overflow when multiplied by sizeof (RGBTRIPLE).
fseek(inptr, padding, SEEK_CUR); | {
"domain": "codereview.stackexchange",
"id": 45175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, image",
"url": null
} |
c, image
fseek(inptr, padding, SEEK_CUR);
Why are we ignoring the return value here?
It's probably better to use fread() and discard the input, so that we can parse images from non-seekable sources such as pipes. That would make the program much more flexible.
// Ensure single flag
if (getopt_long(argc, argv, "grsbh", long_options, NULL) != -1) {
fputs("Only one filter allowed.\n", stderr);
return '\0';
}
We have completely lost the advantage of using a single program if it can only perform one operation - it would be simpler to have separate programs (built from shared functions) that each perform one transformation.
All through this code, I had assumed that the whole point of this being a single program was that we could perform several transformations without having to decode and re-encode the image between each, so it's a disappointment to get here and discover that we've squandered that advantage.
obj/%.o: src/%.c
$(CC) $(CFLAGS) -c $< -o $@ $(LDLIBS)
You're working against Make here by insisting on writing the object files to a subdirectory. There's no need to write our own rule, if we work with Make, allowing it to put the objects alongside the sources, or using VPATH so that they end up in the working directory.
The same is true of the executable program: with the object files in the working directory, we should just be able to write its dependency on the object files and let Make do the rest.
And neither of those rules has been correctly copied from Make's built-in rules anyway; if you're really going to insist on that layout, at least do it right:
$(BIN): $(OBJS)
$(LINK.o) $^ $(LOADLIBES) $(LDLIBS) -o $@
obj/%.o: src/%.c
$(COMPILE.c) $(OUTPUT_OPTION) $<
We're completely missing the dependencies of object files on any of the headers. I recommend you make that automatic: add CFLAGS += -MM (or related option) and then use include to reference the resultant .d files in the Makefile. | {
"domain": "codereview.stackexchange",
"id": 45175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, image",
"url": null
} |
python, python-3.x, pygame, pong
Title: Pong using pygame module
Question: I made a game in Python where you play Pong against an AI. As I am quite new to pygame, I would be grateful to hear any possible improvements.
This is my code:
import random
import pygame
from pygame.locals import (
K_UP, K_DOWN,
K_w, K_s,
QUIT
)
BG_COLOR = (255,) * 3
FG_COLOR = (0,) * 3
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 500
PADDLE_X = SCREEN_WIDTH / 15
PADDLE_Y = SCREEN_HEIGHT / 2
PADDLE_WIDTH = SCREEN_WIDTH / 30
PADDLE_HEIGHT = SCREEN_HEIGHT / 5
SPEED_MULTIPLIER = 3
class Paddle(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, *groups):
super().__init__(*groups)
self.image = pygame.Surface((width, height))
self.image.fill(FG_COLOR)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def update(self):
if self.rect.collidepoint(self.rect.x, 0):
self.rect.y += SPEED_MULTIPLIER
elif self.rect.collidepoint(self.rect.x, SCREEN_HEIGHT):
self.rect.y -= SPEED_MULTIPLIER
class Ball(pygame.sprite.Sprite):
def __init__(self, x, y, r, *groups):
super().__init__(*groups)
self.image = pygame.Surface((r * 2,) * 2, pygame.SRCALPHA)
self.image = self.image.convert_alpha()
pygame.draw.circle(self.image, FG_COLOR, (r, r), r)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.dx = random.choice((-1, 1))
self.dy = random.choice((random.uniform(1, -0.7), random.uniform(0.7, 1)))
self.radius = r
def update(self):
self.rect.x += self.dx * SPEED_MULTIPLIER
self.rect.y += self.dy * SPEED_MULTIPLIER
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
sprites = pygame.sprite.Group() | {
"domain": "codereview.stackexchange",
"id": 45176,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pygame, pong",
"url": null
} |
python, python-3.x, pygame, pong
clock = pygame.time.Clock()
sprites = pygame.sprite.Group()
computer_paddle = Paddle(
PADDLE_X, PADDLE_Y,
PADDLE_WIDTH, PADDLE_HEIGHT,
sprites
)
human_paddle = Paddle(
SCREEN_WIDTH - 2 * PADDLE_X, PADDLE_Y,
PADDLE_WIDTH, PADDLE_HEIGHT,
sprites
)
ball = Ball(
SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2,
SCREEN_WIDTH / 40,
sprites
)
while True:
if any([event.type == QUIT for event in pygame.event.get()]):
break
screen.fill(BG_COLOR)
keys_pressed = pygame.key.get_pressed()
# right paddle controls
if keys_pressed[K_UP] or keys_pressed[K_w]:
human_paddle.rect.y -= SPEED_MULTIPLIER
if keys_pressed[K_DOWN] or keys_pressed[K_s]:
human_paddle.rect.y += SPEED_MULTIPLIER
# computer logic
if ball.rect.centerx < SCREEN_WIDTH / 2:
if ball.rect.centery > computer_paddle.rect.centery:
computer_paddle.rect.centery += SPEED_MULTIPLIER
else:
computer_paddle.rect.centery -= SPEED_MULTIPLIER
elif abs(computer_paddle.rect.centery - SCREEN_HEIGHT / 2) > SCREEN_HEIGHT / 10:
if computer_paddle.rect.centery > SCREEN_HEIGHT / 2:
computer_paddle.rect.centery -= SPEED_MULTIPLIER
else:
computer_paddle.rect.centery += SPEED_MULTIPLIER
# move the ball
if ball.rect.colliderect(computer_paddle.rect) \
or ball.rect.colliderect(human_paddle.rect):
ball.dx *= -1
# while ball isn't touching either paddle
while not (ball.rect.colliderect(computer_paddle.rect)
or ball.rect.colliderect(human_paddle.rect)):
ball.rect.x += ball.dx
ball.dy += random.uniform(-0.2, 0.2) # random bounces
if not (0 < ball.rect.y and ball.rect.y + ball.rect.height < SCREEN_HEIGHT):
ball.dy *= random.uniform(-1.2, -0.8) # random bounces
# check if game is over
if not 0 < ball.rect.x < SCREEN_WIDTH:
break | {
"domain": "codereview.stackexchange",
"id": 45176,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pygame, pong",
"url": null
} |
python, python-3.x, pygame, pong
# check if game is over
if not 0 < ball.rect.x < SCREEN_WIDTH:
break
sprites.update()
sprites.draw(screen)
pygame.display.flip()
clock.tick(120)
pygame.quit()
Game window:
Answer: Nice effort, this is some good looking code!
init bug
self.dy = random.choice((random.uniform(1, -0.7), random.uniform(0.7, 1)))
That doesn't make sense to me.
During play we observe the initial vector is sometimes nearly horizontal.
It appears you wanted
self.dy = random.choice((random.uniform(-1, -0.7), random.uniform(0.7, 1)))
Such a "give magic number twice" bug would have been unlikely
if you'd instead phrased it
self.dy = random.choice((-1, 1)) * random.uniform(0.7, 1)
symmetry
Some of your
magic numbers
are just fine as-is.
For example, starting the ball at center of screen seems a perfectly natural choice.
This expression seems weird:
human_paddle = Paddle(
SCREEN_WIDTH - 2 * PADDLE_X, ...
I would have expected SCREEN_WIDTH - PADDLE_X - PADDLE_WIDTH,
for symmetry with computer_paddle.
extract helper
There's not a lot to
DRY
up here, but to make the logic more readable
I do recommend you define this predicate:
def is_colliding() -> bool:
return (ball.rect.colliderect(computer_paddle.rect)
or ball.rect.colliderect(human_paddle.rect))
Consider defining an is_vertically_in_bounds predicate,
just to improve legibility of not is_vertically_in_bounds(),
as the current code doesn't exactly read like an English sentence.
No biggie.
Or consider applying
De Morgan
to the bounds check. Why?
The computer doesn't care which way you phrase it,
but humans do better when reasoning
about the positive instead of the negative. | {
"domain": "codereview.stackexchange",
"id": 45176,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pygame, pong",
"url": null
} |
python, python-3.x, pygame, pong
bounds check
OTOH, the horizontally in bounds test appears to be buggy.
On the left, it's fine.
But on the right you want to pay the same careful attention
to detail as when you were doing the vertical check.
That is, the ball.rect.x + ball.rect.width right-hand side
is what matters, rather than the left-hand side that you currently check.
During play we occasionally see glitches where ball bounces
behind the human's paddle and re-enters play.
The ball's horizontal movement usually happens, very nicely, in this way:
def update(self):
self.rect.x += self.dx * SPEED_MULTIPLIER
I don't understand this business:
# move the ball
if is_colliding():
ball.dx *= -1
# while ball isn't touching either paddle
while not is_colliding():
ball.rect.x += ball.dx
(I paraphrased slightly, to simplify.)
I assume the goal was to ensure that we are not is_colliding()
when we emerge from that code.
So the negation of while not doesn't make sense -- surely
we wanted the positive instead?
You would better reveal Author's Intent if you appended
assert not is_colliding()
after that code.
Plus, if it turns out there are glitches, that would help you chase them down.
refactor
The main loop is a little on the long side -- we have to
scroll vertically to read all of it.
Consider breaking out helpers:
def read_keyboard(),
def move_paddles(), and maybe even
def adjust_ball_speed().
This code achieves most of its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45176,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pygame, pong",
"url": null
} |
algorithm, swift
Title: Bubble Sort as extension to Swift-Arrays
Question: Task description:
Implement an extension for Array, which sorts the elements using the Bubble Sort-algorithm.
My implementation:
extension Array where Element: Comparable {
mutating func bubbleSort() -> Array {
var i = 0
var j = 0
while i < self.count - 1 {
while j < self.count - 1 - i {
if self[j] > self[j + 1] {
self.swapAt(j, j + 1)
}
j += 1
}
j = 0
i += 1
}
return self
}
}
// Provided test-samples
var iArray = [12, 5, 4, 9, 3, 2, 1]
print(iArray.bubbleSort())
var iArray2 = ["f", "a", "b"]
print(iArray2.bubbleSort())
var iArray3 = [String]()
print(iArray3.bubbleSort())
It works fine with the provided samples, so I consider it correct (formally).
But are there any flaws within my solution? Can it be improved?
Would you have done it totally different? Why and how?
Answer: One natural modification I'd consider an improvement is the use of for for the inner loop.
I think it more direct to let the outer control variable (i above) decrease rather than having it increase and subtract it from the number of items.
I find the Bubble Sort variant using a flag to remember whether there was any swap in the current outer iteration inconsequent - if you want to improve over just decreasing the limit for the inner loop (for loop, again), keep the highest index among swaps and use as the limit next time around. | {
"domain": "codereview.stackexchange",
"id": 45177,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, swift",
"url": null
} |
java, strings, programming-challenge, formatting
Title: Output two columns
Question: Output formatting:
Input Format
Every line of input will contain a String followed by an integer.
Each String will have a maximum of 10 alphabetic characters, and each integer will be in the inclusive range from 0 to 999.
Output Format
In each line of output there should be two columns:
The first column contains the String and is left justified using exactly 15 characters.
The second column contains the integer, expressed in exactly 3 digits; if the original input has less than three digits, you must pad your output's leading digits with zeroes.
Sample Input
java 100
cpp 65
python 50
Sample Output
================================
java 100
cpp 065
python 050
================================
printf is pretty straightforward. Two formats per row, newline at the end. The lines that don't need to be formatted (first and last) can be put on the screen using println instead. To the best of my knowledge it isn't possible to put both printf statements in one printing statement, so I made it a function instead. Keeps things neat.
My naming is probably horrible. As usual.
import java.util.Scanner;
public class Solution {
private static void printRowOutlined(String left, int right) {
System.out.printf("%-15s", left);
System.out.printf("%03d\n", right);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i = 0; i < 3; i++){
String text = sc.next();
int number = sc.nextInt();
printRowOutlined(text, number);
}
System.out.println("================================");
}
}
Answer:
To the best of my knowledge it isn't possible to put both printf statements in one printing statement, so I made it a function instead. | {
"domain": "codereview.stackexchange",
"id": 45178,
"lm_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, strings, programming-challenge, formatting",
"url": null
} |
java, strings, programming-challenge, formatting
It is possible: the printf method takes a varargs as second argument, so you can give it multiple arguments to format. When you have multiple arguments, each parameter can be refered to as %[argument_index$] in the format String (as per Formatter Javadoc), where argument_index is the index of the argument in the varargs. In this case, we can have:
private static void printRowOutlined(String left, int right) {
System.out.printf("%-15s%03d%n", left, right);
}
Since each parameter in the format String are refered to in the order in which they are given in the arguments, we don't even need to specify the index (but we could have "%1$-15s%2$03d%n" as the format String). Regardless of that, I think having a separate method for the printing operation is still cleaner.
Also, don't use \n. You can use the %n specifier, which will use the line separator of the current system.
Furthermore, I notice you're not doing any validation on your input, you could verify that the integer is correct, in the right range, and that the String to format has the right numbers of characters. | {
"domain": "codereview.stackexchange",
"id": 45178,
"lm_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, strings, programming-challenge, formatting",
"url": null
} |
c, playing-cards
Title: Poker Hand Evaluation evaluation
Question: Several days ago, a question on this topic was posted to SO. The problem turned out to be the OP's test cases did not reveal a deficiency in the code. This challenge caught my attention. Writing the following has provided entertainment for a number of rainy hours.
I've had a look at several "Review" postings (looking for C language solutions). I believe this code embodies a representation of the data (card values and tallies) that improves upon those I've seen. (Without its verbose commentary, assess() is almost trivial.) My focus has been on the code, with little interest in the game of poker. Thank you for your time.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
enum {
highCard, onePair, twoPair, threeOfKind, straight,
flush, fullhouse, fourOfKind, str8Fl, royalFl,
nTallies,
nCard = 7, // # of cards in one hand
aFlush = 5, // # of cards in a flush, royal or otherwise
oneSuit = 0x10, // # "suits" contain cards represented by 0 to 0xC of 0 to 0xF (4 bits)
b43210 = 0x1F // bits 4 to bit 0 (five contiguous set bits)
};
char *name[] = { // for outout
"0 High Card", "1 One Pair", "2 Two Pair", "3 Three of a kind", "4 Straight",
"5 Flush", "6 Full House", "7 Four of a kind", "8 Straight Flush", "9 Royal Flush",
};
int isSTR8( uint64_t x ) { // determine if low order 13 bits contain a "straight"
for( x &= 0x1FFF; x >= b43210; x >>= 1 ) // return as soon as search becomes futile
if( (x & b43210) == b43210 ) return 1;
return 0;
}
int assess( int h[] ) { // assess the hand into one of the ten categories
uint64_t bits = 0, str8 = 0, popS = 0, popV = 0, big1 = 1; | {
"domain": "codereview.stackexchange",
"id": 45179,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, playing-cards",
"url": null
} |
c, playing-cards
// convert 7 unique card values into one 64 bit field
// 'bits' assembled as 4x16 bit fields, one for each suit
// used bits: b60-b48, b44-b32, b28-b16, b12-b0 ==> single bit in 1 of 4 "suits"
// 'bits' will eventually have only 7 set bits representing the 7 cards' suits & values
// 'popS' accumulates counts of each suit present in the hand
// max possible cnt for any one suit is all seven cards in same suit. ie: 7
// popS uses each 4x4 bit field to sum values in range of 0 to 7 (3 bits)
// 'popV' accumulates counts of each value present in the hand
// max possible cnt for any one value is 4 (eg: 4 Jacks)
// popV uses each 13x4 bit field to sum values in range of 0 to 4 (3 bits)
for( size_t i = 0; i < nCard; i++ ) {
bits |= big1 << h[ i ]; // as single set bit
popS += big1 << (4*(h[ i ] >> 4)); // cnt 'n' in each suit
popV += big1 << (4*(h[ i ] & 0xF)); // cnt 'n' of this face value
}
// destroy 'bits' (right shift)
// if a 'flush' is found, determine "royal", "straight" or "ordinary"
// otherwise, accumulate bits to determine a (mixed) straight soon
for( ; bits; bits >>= oneSuit, popS >>= 4 ) { // finish search asap!
if( (popS & 0xF) >= aFlush )
return (bits & 0x1E01) == 0x1E01 ? royalFl : isSTR8( bits ) ? str8Fl : flush;
str8 |= bits;
}
if( isSTR8( str8 ) ) return straight; // should be obvious
// determine highest and 2nd highest tallies of card face values
int hi1 = 0, hi2 = 0;
for( ; popV; popV >>= 4 ) { // finish search asap!
int pop = (int)(popV & 0xF);
if( hi1 < pop ) { hi2 = hi1; hi1 = pop; }
else if( hi2 < pop ) hi2 = pop;
}
switch( hi1 ) { // dispatch...
case 4: return fourOfKind;
case 3: return hi2 >= 2 ? fullhouse : threeOfKind;
case 2: return hi2 == 2 ? twoPair : onePair;
default: return highCard;
}
} | {
"domain": "codereview.stackexchange",
"id": 45179,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, playing-cards",
"url": null
} |
c, playing-cards
int *show( int *h ) { // called by test()
for( int i = 0; i < nCard; i++ )
printf( "%c%c ", "hcds"[h[i]/oneSuit], "A23456789XJQK"[h[i]%oneSuit] );
return h;
}
void test( void ) {
// 4 suits of 13 cards each ('X' == 10).
// Note range for each suit changes with each Ace
enum {
hA = 0x00, h2, h3, h4, h5, h6, h7, h8, h9, hX, hJ, hQ, hK, // hearts
cA = 0x10, c2, c3, c4, c5, c6, c7, c8, c9, cX, cJ, cQ, cK, // clubs
dA = 0x20, d2, d3, d4, d5, d6, d7, d8, d9, dX, dJ, dQ, dK, // diamonds
sA = 0x30, s2, s3, s4, s5, s6, s7, s8, s9, sX, sJ, sQ, sK // spades
};
// 10 composed samples to test assess(). Left-to-right order is not special
int i, hands[][ nCard ] = {
{ h4, cJ, d9, d5, s3, h7, sA }, // high card
{ h4, c3, d9, d5, s3, h7, sA }, // one pair
{ h9, c3, d9, d5, s3, h7, sA }, // two pair
{ h9, c3, d9, d5, s9, h7, sA }, // three of a kind
{ d5, c6, sA, h8, s5, c7, d4 }, // straight
{ d5, dJ, dX, dQ, s5, c7, d6 }, // flush
{ d8, h8, s8, hQ, c7, sK, s7 }, // full house
{ h9, c9, d9, d5, s9, h7, sA }, // four of a kind
{ s5, s7, s6, s8, d5, c7, s4 }, // straight flush
{ dA, dJ, dX, dQ, s5, c7, dK }, // royal flush
};
for( i = 0; i < sizeof hands/sizeof hands[0]; i++ )
printf( "... %s\n", name[ assess( show( hands[ i ] ) ) ] );
}
int *deal( int *p ) { // called by run()
// not interested in true randomness and fairness
// sufficient to compose array of 7 unique values (cards) between 0 and 63
// encoding values rejects values 13, 14, 15 in any suit
for( int x, i = 0; i < nCard; ) {
p[i] = rand() % 64;
if( ( p[i] & 0xF ) <= 12 ) { // face is "Ace to King" (0 to 12)?
for( x = 0; x < i && p[x] != p[i]; ) x++; // no duplicates!
i += x == i;
}
}
return p;
}
void run( int nLoop ) {
srand( time( NULL ) ); | {
"domain": "codereview.stackexchange",
"id": 45179,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, playing-cards",
"url": null
} |
c, playing-cards
void run( int nLoop ) {
srand( time( NULL ) );
int i, cnt[ nTallies ] = { 0 }; // simple 'histogram' accumulator for 10 types
int hand[ nCard ];
for( i = 0; i < nLoop; i++ )
++cnt[ assess( deal( hand ) ) ]; // deal, assess, tabulate, repeat
for( i = 0; i < nTallies; i++ )
printf( "%.6f - %s\n", cnt[i]*1. / nLoop, name[ i ] ); // report
}
int main( void ) {
// Activate one or other... or both.
test();
run( 10 * 1000 ); // # of trials
return 0;
}
Results of one run with both test() and run() active:
h4 cJ d9 d5 s3 h7 sA ... 0 High Card
h4 c3 d9 d5 s3 h7 sA ... 1 One Pair
h9 c3 d9 d5 s3 h7 sA ... 2 Two Pair
h9 c3 d9 d5 s9 h7 sA ... 3 Three of a kind
d5 c6 sA h8 s5 c7 d4 ... 4 Straight
d5 dJ dX dQ s5 c7 d6 ... 5 Flush
d8 h8 s8 hQ c7 sK s7 ... 6 Full House
h9 c9 d9 d5 s9 h7 sA ... 7 Four of a kind
s5 s7 s6 s8 d5 c7 s4 ... 8 Straight Flush
dA dJ dX dQ s5 c7 dK ... 9 Royal Flush
0.165100 - 0 High Card
0.446500 - 1 One Pair
0.244800 - 2 Two Pair
0.048300 - 3 Three of a kind
0.042600 - 4 Straight
0.028600 - 5 Flush
0.023000 - 6 Full House
0.000800 - 7 Four of a kind
0.000200 - 8 Straight Flush
0.000100 - 9 Royal Flush
EDIT:
What's the mantra? "Always consider edge cases!"
Thanks to @TobySpeight for finding a deficiency in the code above. It fails to find a "royal straight" composed of Ace, King, Queen, Jack, 10 of diverse suits... Doh!
A quick fix would be to change:
if( isSTR8( str8 ) ) return straight; // should be obvious
to
if( ((str8 & 0x1E01) == 0x1E01) || isSTR8( str8 ) ) return straight;
testing for this non-contiguous but valid pattern.
Only 52! - 45! possibilities of hands to test this code... Now, a few less. Thanks again for Toby's sharp eyes.
Answer: In general, I believe it's a good idea to always use braced blocks for conditionals and loops, rather than bare statements. It makes code easier to modify in future and costs us nothing.
This definition looks good so far: | {
"domain": "codereview.stackexchange",
"id": 45179,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, playing-cards",
"url": null
} |
c, playing-cards
enum {
highCard, onePair, twoPair, threeOfKind, straight,
flush, fullhouse, fourOfKind, str8Fl, royalFl,
But then we have:
nTallies,
nCard = 7, // # of cards in one hand
aFlush = 5, // # of cards in a flush, royal or otherwise
oneSuit = 0x10, // # "suits" contain cards represented by 0 to 0xC of 0 to 0xF (4 bits)
b43210 = 0x1F // bits 4 to bit 0 (five contiguous set bits)
These look like totally unrelated things stuffed into the same enumeration. That's very strange and confusing - I think these things ought to be individual constants of appropriate types. At least some of them can be reduced in scope, too.
Good use of enums can be advantageous - for one thing, a decent compiler will warn when we have a switch that doesn't have cases for all the members.
I don't like the inconsistency in the names - we have camel-case for onePair, but all lower-case for fullhouse. And I find the cutesy str8Fl much harder to read than straightFlush.
char *name[] = { // for outout
Be aware that it's undefined behaviour to modify a string literal. Safer to declare as char const *name[]. And I guess outout is a type for output?
int isSTR8( uint64_t x ) {
Be careful that you fully understand the identifiers that are reserved for future library extension. This one is okay, because S is not a lower-case letter, but many authors are unaware of the exact rules.
uint64_t is not defined, because we never included <stdint.h>. In any case, I don't think we need exactly 64 bits, and this code should be able to function on platforms that can't provide uint64_t - I suggest using uint_fast64_t instead. And I'd probably give the type a name that expresses what we're using it for, to distinguish from other values of the same type:
typedef uint_fast64_t card_bit_vector;
For this particular function, given that the first thing we do is mask x down to 13 bits, we could be using a narrower type for the arithmetic.
#include <stdbool.h>
#include <stdint.h> | {
"domain": "codereview.stackexchange",
"id": 45179,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, playing-cards",
"url": null
} |
c, playing-cards
static bool isStraight(card_bit_vector cards)
{
static const uint_fast16_t low_five_bits = 0x1f;
/* determine whether low order 13 bits contain a straight - five consecutive 1s */
for (uint_fast16_t x = cards & 0x1FFF; x >= low_five_bits; x >>= 1) {
if ((x & low_five_bits) == low_five_bits) { return 1; }
}
/* not a straight */
return 0;
}
The serious bug in this function, due to a missing test case, is that in poker, an ace may be either high or low, but we always use it as its low value here. We need to duplicate the ace into bit 13 and consider it there as well:
uint_fast16_t x = cards & 0x1FFF;
/* Duplicate the ace so it's both high and low */
x |= (x & 1) << 13;
Now we get to the big function, assess(). I see no reason for it to be modifying the members of the hand argument, so we should make that an array-of-const - and return a strongly-typed enum rather than int:
enum hand {
highCard, onePair, twoPair, threeOfKind, straight,
flush, fullHouse, fourOfKind, straightFlush, royalFlush,
};
enum hand assess(const int h[]) | {
"domain": "codereview.stackexchange",
"id": 45179,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, playing-cards",
"url": null
} |
c, playing-cards
enum hand assess(const int h[])
Modern C doesn't require us to declare all variables before the first statement in the scope as we had to in the 1990s and before. It's better for the reader's cognition to minimise what's in their heads at any time.
Also, big1 must not be modified, so make that const.
The population counts of values and suits shouldn't be packed into single integers like that. It will be more time-efficient to represent them as arrays. If space were at a premium, we could pack all 17 counts into a single 64-bit quantity, but here we're in a function, and stack space for a couple of small arrays is not unreasonable.
If we had portable access to an efficient "population count" function, we would be able to get those population counts directly by masking the cards bit-vector. That's something to consider as a future enhancement for compilers that provide such a function.
Be careful in the comments with abbreviations. In particular cnt appears to me as a more offensive word than you intended - count would be much better.
Now, let's move on to the tests.
As I mentioned earlier, there are some missing tests. We should be testing the lowest straight (A2345) and the highest straight (XJQKA) as well as (or instead of) the medium straight. And we should also be testing some hands that match both flush and straight, but where the cards in the straight are not all the same suit:
{ d5, c3, sA, h2, s5, cA, d4 }, // bottom straight
{ dK, cJ, sA, hQ, sX, cA, dX }, // top straight
{ d4, d8, dX, dQ, s5, cX, d6 }, // flush beats straight | {
"domain": "codereview.stackexchange",
"id": 45179,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, playing-cards",
"url": null
} |
c, playing-cards
I think the enumeration of all the cards and their corresponding bit numbers is valuable enough to be part of the program, not just confined to the tests. And we should use its type for passing cards around.
When we deal randomly, I think it would be clearer to select one of 52 values, and convert that to a valid card, rather than doing rejection and resampling:
for (int i = 0; i < nCard; ++i) {
int x = rand() % 52;
/* modify x to skip the non-card values */
p[i] = x + x / 13 * 3;
}
Instead of seeding the random number generator from the current time, consider allowing the user to specify seed, so we can have reproducible tests.
Six decimal places of precision in the histogram is misleading if we only examine 10,000 hands.
Modified code
Here's a version that I think is clearer and more maintainable. And it fixes the bug.
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 4 suits of 13 cards each ('X' == 10).
// Note range for each suit changes with each Ace
enum card {
hA = 0x00, h2, h3, h4, h5, h6, h7, h8, h9, hX, hJ, hQ, hK, // hearts
cA = 0x10, c2, c3, c4, c5, c6, c7, c8, c9, cX, cJ, cQ, cK, // clubs
dA = 0x20, d2, d3, d4, d5, d6, d7, d8, d9, dX, dJ, dQ, dK, // diamonds
sA = 0x30, s2, s3, s4, s5, s6, s7, s8, s9, sX, sJ, sQ, sK // spades
};
// Representation of a hand of cards - a bit is set for each card in
// hand, or unset if not in hand.
typedef uint_fast64_t card_bit_vector;
enum hand {
highCard, onePair, twoPair, threeOfKind, straight,
flush, fullHouse, fourOfKind, straightFlush, royalFlush,
};
enum {
/* misc compile-time constants */
nCard = 7, // number of cards available for hand
oneSuit = 0x10, // offset from one suit to next in enum card
};
static unsigned suit_of(enum card c)
{
return c / oneSuit;
}
static unsigned value_of(enum card c)
{
return c % oneSuit;
} | {
"domain": "codereview.stackexchange",
"id": 45179,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, playing-cards",
"url": null
} |
c, playing-cards
static unsigned value_of(enum card c)
{
return c % oneSuit;
}
static bool is_top_straight(card_bit_vector cards)
{
return (cards & 0x1E01) == 0x1E01;
}
static bool is_straight(card_bit_vector cards)
{
if (is_top_straight(cards)) {
return true;
}
static const uint_fast16_t low_five_bits = 0x1f;
/* determine whether low order 13 bits contain five consecutive 1s */
for (uint_fast16_t x = cards & 0x1FFF; x >= low_five_bits; x >>= 1) {
if ((x & low_five_bits) == low_five_bits) {
/* found one */
return true;
}
}
/* not a straight */
return false;
}
enum hand assess(const enum card h[])
{
// Assess the hand into one of the ten categories.
card_bit_vector bits = 0;
int suit_count[4] = { 0 };
int value_count[13] = { 0 };
// Convert 7 unique card values into a bit-vector.
// Also accumulate totals for each suit and rank
static const card_bit_vector big1 = 1;
for (size_t i = 0; i < nCard; ++i) {
bits |= big1 << h[i]; // as single set bit
++suit_count[suit_of(h[i])];
++value_count[value_of(h[i])];
}
// destroy 'bits' (right shift)
// If a flush is found, determine whether it contains a straight.
// Otherwise, accumulate bits to determine a(mixed) straight soon.
static const int aFlush = 5; // no. of cards in a flush, royal or otherwise
card_bit_vector straight_bits = 0;
for (int *n_suit = suit_count; bits; bits >>= oneSuit, ++n_suit) {
if (*n_suit >= aFlush) {
return is_top_straight(bits) ? royalFlush
: is_straight(bits) ? straightFlush
: flush;
}
straight_bits |= bits;
}
if (is_straight(straight_bits)) {
return straight;
} | {
"domain": "codereview.stackexchange",
"id": 45179,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, playing-cards",
"url": null
} |
c, playing-cards
if (is_straight(straight_bits)) {
return straight;
}
/* Now consider cards of matching rank (pairs, triples, etc) */
int same_value[5] = { 0 }; /* count of absents, singletons, pairs, ..., quads */
for (int *n_value = value_count; n_value < value_count + 13; ++n_value) {
++same_value[*n_value];
}
return same_value[4] > 0 ? fourOfKind
: same_value[3] > 1 ? fullHouse
: same_value[3] > 0 && same_value[2] > 0 ? fullHouse
: same_value[3] > 0 ? threeOfKind
: same_value[2] > 1 ? twoPair
: same_value[2] > 0 ? onePair
: highCard;
}
/// Test code
static char const *name(enum hand h)
{
switch (h) {
case highCard: return "0 High Card";
case onePair: return "1 One Pair";
case twoPair: return "2 Two Pair";
case threeOfKind: return "3 Three of a kind";
case straight: return "4 Straight";
case flush: return "5 Flush";
case fullHouse: return "6 Full House";
case fourOfKind: return "7 Four of a kind";
case straightFlush: return "8 Straight Flush";
case royalFlush: return "9 Royal Flush";
}
/* invalid; can't happen */
return "???";
}
static void show(const enum card h[nCard]) {
for (int i = 0; i < nCard; ++i) {
printf("%c%c ",
"hcds"[suit_of(h[i])],
"A23456789XJQK"[value_of(h[i])]);
}
} | {
"domain": "codereview.stackexchange",
"id": 45179,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, playing-cards",
"url": null
} |
c, playing-cards
static void test(void) {
// 10 composed samples to test assess(). Left-to-right order is not special
const enum card hands[][nCard] = {
{ h4, cJ, d9, d5, s3, h7, sA }, // high card
{ h4, c3, d9, d5, s3, h7, sA }, // one pair
{ h9, c3, d9, d5, s3, h7, sA }, // two pair
{ h9, c3, d9, d5, s9, h7, sA }, // three of a kind
{ d5, c6, sA, h8, s5, c7, d4 }, // straight
{ d5, c3, sA, h2, s5, cA, d4 }, // bottom straight
{ dK, cJ, sA, hQ, sX, cA, dX }, // top straight
{ d5, dJ, dX, dQ, s5, c7, d6 }, // flush
{ d4, d8, dX, dQ, s5, cX, d6 }, // flush beats straight
{ d8, h8, s8, hQ, c7, sK, s7 }, // full house
{ h9, c9, d9, d5, s9, h7, sA }, // four of a kind
{ s5, s7, s6, s8, d5, c7, s4 }, // straight flush
{ dA, dJ, dX, dQ, s5, c7, dK }, // royal flush
};
for (unsigned i = 0; i < sizeof hands/sizeof hands[0]; i++) {
show(hands[i]);
printf("... %s\n", name(assess(hands[i])));
}
}
static enum card *deal(enum card p[nCard])
{
// We don't need strict uniformity or strong randomness for this
// test.
for (int i = 0; i < nCard; ++i) {
int x = rand() % 52;
/* modify x to skip the non-card values */
p[i] = x + x / 13 * 3;
}
return p;
}
static void run(unsigned nLoop)
{
const char *seed_string = getenv("TEST_SEED");
if (!seed_string) { seed_string = "0"; }
int seed = atoi(seed_string); /* 0 if it fails - fall back to time-based seed */
if (!seed) {
seed = (int)time(NULL);
}
srand((unsigned)seed);
unsigned count[royalFlush + 1] = { 0 }; // simple histogram accumulator for 10 types
enum card hand[nCard];
for (unsigned i = 0; i < nLoop; ++i) {
++count[assess(deal(hand))];
} | {
"domain": "codereview.stackexchange",
"id": 45179,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, playing-cards",
"url": null
} |
c, playing-cards
/* Determine a suitable precision for output, according to number of samples */
int precision = 1;
for (unsigned x = 100; x <= nLoop && precision < 10; x *= 10) {
++precision;
}
for (unsigned i = highCard; i <= royalFlush; ++i) {
printf("%.*f - %s\n", precision,
count[i] * 1. / nLoop,
name(i));
}
}
int main(void)
{
test();
run(100000);
}
Note that this still only classifies the hands. It doesn't provide the information needed to determine which hand wins amongst those in the same group. | {
"domain": "codereview.stackexchange",
"id": 45179,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, playing-cards",
"url": null
} |
java, algorithm, iteration
Title: Another cash machine with special bill values in Java
Question: Task:
An ATM dispenses banknotes with the following values/denominations: {5, 30, 35, 40, 150, 200}. The user should be able to repeatedly enter an amount divisible by 5 without leaving a remainder. The denomination of banknotes with the smallest possible number of notes should be issued that corresponds to the amount. Recursive calls are not allowed to use.
Questions:
Can you take a look at my code? Are the variable names unique? Is the approach ok, or is there anything to improve? What is the best way to calculate the depth constant?
/**
* This utility method calculates the minimal amounts of bills (5, 30, 35, 40, 150, 200) needed for a given amount.
* The amount argument should be between 0 and 10000 and be divisible by 5.
*
* @param amount the amount (between 0 and 10000 and divisible by 5) to be patched
* @return an array with the minimal amounts of bills needed
*/
public static int[] patch(final int amount) {
if (amount < 0 || amount > 10000 || amount % 5 != 0) {
throw new IllegalArgumentException("Invalid amount");
}
final int[] bills = {5, 30, 35, 40, 150, 200};
final int depth = Math.min(amount / bills[0] + 1, 50);
// (How can you calculate the best depth here?)
int bestCount = Integer.MAX_VALUE;
int[] bestResult = new int[bills.length];
int[] indexes = new int[bills.length];
a:
for (int i = 0; ; ) {
// calculates the current count of bills and sum
int count = 0;
int sum = 0;
for (int j = 0; j < indexes.length; j++) {
count += indexes[j];
sum += indexes[j] * bills[j];
} | {
"domain": "codereview.stackexchange",
"id": 45180,
"lm_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, algorithm, iteration",
"url": null
} |
java, algorithm, iteration
// checks if the current count is the best, and terminates this iteration if no further solution can be found
if (amount - sum <= 0) {
if (amount - sum == 0 && count <= bestCount) {
bestCount = count;
System.arraycopy(indexes, 0, bestResult, 0, indexes.length);
}
indexes[i] = depth - 1;
}
// increments the indexes (or leaves the entire loop)
indexes[i]++;
if (indexes[i] == depth) {
do {
indexes[i] = 0;
i++;
// overflow protection , time to leave
if (i == indexes.length) {
break a;
}
} while (indexes[i] == depth);
indexes[i]++;
i = 0;
}
}
return bestResult;
}
Answer: cite your references
This is a well known problem.
But you do not appear to be using a well known solution technique.
That is, this code is "tricky".
(It seems to be using Dynamic Programming, but I'm at a loss
to describe the meaning of what it stores.)
Tell us what approach you're using,
perhaps by citing a blog, textbook, or wikipedia article.
Then the Gentle Reader can follow along,
tracing the corresponding elements between article and code,
to verify that each element is correctly implemented.
As written, you have needlessly made that a more difficult process.
repetition
Thank you for the introductory javadoc.
* This ....
* The amount argument should be between 0 and 10000 and be divisible by 5.
*
* @param amount the amount (between 0 and 10000 and divisible by 5) to be patched | {
"domain": "codereview.stackexchange",
"id": 45180,
"lm_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, algorithm, iteration",
"url": null
} |
java, algorithm, iteration
DRY
up that second sentence; simply delete it.
It's completely redundant with the very helpful @param amount description.
Why do we keep our code DRY?
Suppose the max increased to 20_000 a few months down the road.
Now we have to not only keep revised code + @param doc in sync,
but we have to chase down other instances as well.
We try to minimize the number of occurrences that might drift out of sync.
That makes all of our documentation more believable,
even documentation for shopworn code.
design of Public API
final int[] bills = {5, 30, 35, 40, 150, 200};
It's kind of weird that the function signature doesn't accept such an array,
given that the return value is very much in terms of these denominations.
Alternatively we should give some distinctive name to this currency system,
and use a related name for the function, showing it is a special purpose
function that is tightly linked to that system.
On which topic: This function is named patch ?!? What?
I can't imagine how that's relevant.
I would have expected a name like dispenseBills or perhaps makeChange.
diagnostic message
throw new IllegalArgumentException("Invalid amount");
This is some lovely error checking, you can certainly retain it as-is.
But imagine that application code triggered this error,
and some poor maintenance engineer reading the web logs
needs to track down the details, to figure out which component
did the Wrong Thing and should be repaired.
First question that comes to mind will be "what was the amount?"
Did it run afoul of the negative check? Too big? Lacked a factor of five?
We can make that debugging process a little easier by
throwing an error with formatted string which includes the amount in question.
dynamic allocation
final int depth = Math.min(amount / bills[0] + 1, 50); | {
"domain": "codereview.stackexchange",
"id": 45180,
"lm_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, algorithm, iteration",
"url": null
} |
java, algorithm, iteration
dynamic allocation
final int depth = Math.min(amount / bills[0] + 1, 50);
This expression does not seem well motivated.
The worst case would be min(2_001, 50),
and those two numbers don't seem to be of very different magnitude to me;
it's just a "small" difference in memory allocation, a factor of forty.
We made a
promise
up in the javadoc, we will deliver "minimal amounts of bills"
if caller did the right thing.
And we verified the right thing when we did the precondition check.
Turning a total function into partial one, to save a little RAM,
doesn't seem wise and in any event it certainly requires documentation
of this new potential failure mode.
Better to design such details out of the system.
You don't want to allocate zeros which typically will never be used?
Fine. Rather than using a "hard to size" static datastructure such as array,
prefer a dynamic datastructure such as HashMap.
With Integer keys, it offers you the same interface.
// (How can you calculate the best depth here?)
If you choose to retain depth then you'll want to include a
GCD calculation.
Imagine we drop the "divisible by 5" requirement,
report "impossible" by returning all zero counts or throwing an error,
and adopt this alternate currency system:
final int[] altBillValues = {29, 30, 35, 40, 150, 200};
Then even with the 10_000 ceiling,
we would definitely need a much greater maximum depth.
while loop
This is a bit weird:
a:
for (int i = 0; ; ) {
...
if ( ... ) {
break a;
You had an opportunity to name that location, but used meaningless a instead.
Sigh!
Here is more standard control flow that you might use:
i = 0;
while ( ... ) {
... | {
"domain": "codereview.stackexchange",
"id": 45180,
"lm_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, algorithm, iteration",
"url": null
} |
java, algorithm, iteration
That leaves us with deciding what predicate the while should use, different from the while (True) that OP essentially uses.
I am a little surprised that we're not comparing "amount dispensed so far"
against "amount we were asked to dispense".
This all seems to be fallout from the decision to artificially impose
a "max depth" constraint, something that was not present in the original
problem definition.
Perhaps the OP algorithm always terminates, but from a cursory reading
there's no obvious loop variant that always drives us closer to
termination. If the maximum allowed depth was "small", say 4, it appears
the algorithm could return bestResult containing wrong bill counts.
The current control structure does not inspire confidence in correctness.
Resizing the array when needed, or relying on a HashMap, would simplify the code.
positive infinity
This is very clear:
int bestCount = Integer.MAX_VALUE;
These? Less so.
indexes[i] = depth - 1;
...
indexes[i]++;
if (indexes[i] == depth) {
We seem to be dancing around the notion of positive infinity here,
in a needlessly complex way. If a comparison of indexes[i] >= depth
denotes "solution impossible" we could get away with slightly less
complex code. Designing such artifacts out of the solution entirely
seems preferable.
naming
This potentially is a good identifier:
final int[] bills = {5, 30, 35, 40, 150, 200}; | {
"domain": "codereview.stackexchange",
"id": 45180,
"lm_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, algorithm, iteration",
"url": null
} |
java, algorithm, iteration
naming
This potentially is a good identifier:
final int[] bills = {5, 30, 35, 40, 150, 200};
But it turns out to be a little on the vague side,
given that bills are central to the problem we're solving.
Consider using billValues instead.
amount is a good parameter name.
Again a little on the vague side, consider desiredAmount. No biggie.
bestCount is a good name, but we maybe don't need it at all,
since it's redundant with sum of bestResult.
A helper function could recompute it as needed.
OTOH indexes is a truly terrible name, which should have been billCounts.
It appears many times, and obscures the meaning of the code.
With such a rename, rather than "result" go for parallel structure
with a name like bestCounts or bestBillCounts.
The identifiers i, j, count, sum are all perfect as-is.
obscure tests
if (amount - sum <= 0) {
if (amount - sum == 0 && count <= bestCount) {
It's unclear why that's the best way to phrase the checks, instead of:
if (amount <= sum) {
if (amount == sum && count <= bestCount) {
It might have been the best way if there was a difference
we were tracking through the code, perhaps a difference that is
part of a loop variant, or that appears in a cited reference.
But as it stands it's just a cognitive speed bump.
This codebase appears to achieve a subset of its design goals.
I would not be willing to delegate or accept maintenance tasks on it.
Recommend "discard and begin again, with a cited standard algorithm",
rather than "refactor the existing code".
You might choose to tackle a simpler variant first.
Ignore the "no recursion!" requirement, and produce a
well-tested
recursive solution. With that in hand, you'll be in
a good position to refactor it into a solution where you
manually maintain a stack or you maintain a
DP array. | {
"domain": "codereview.stackexchange",
"id": 45180,
"lm_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, algorithm, iteration",
"url": null
} |
c++, reinventing-the-wheel
Title: Shared_ptr Implementation with Derived class Awareness
Question: Another shared_ptr implementation. My main idea was to write it in a way you could do:
MySharedPtr derivedPt(new derived());
MySharedPtr<base> basePt(move(derivedPt));
basePt.reset();
where the derived class is destroyed properly without a virtual destructor. I did not find a similar one so thought to try and write one.
namespace details {
template<typename T>
class DefaultDeleter {
public:
void operator()(T* p) {
delete p;
}
};
struct ControlBlock_base {
explicit ControlBlock_base(size_t refCounter):refCounter(refCounter) {}
//not sure if there is some way to avoid void* maybe std::any as it looks a bit dirty.
virtual void deletePtr(void* t) = 0;
size_t refCounter;
};
template<typename T>
struct ControlBlock: public ControlBlock_base {
template<typename Deleter = details::DefaultDeleter<T>>
ControlBlock(size_t refCounter, Deleter d = {}) :ControlBlock_base(refCounter), deleter(d) {
}
void deletePtr(void* t) override {
deleter(static_cast<T*>(t));
}
function<void(T*)> deleter;
};
}
template<typename T>
class MySharedPtr {
using ControlBlock_base = details::ControlBlock_base;
template<typename T>
using ControlBlock = details::ControlBlock<T>;
template<typename k>
friend class MySharedPtr;
public:
MySharedPtr() = default;
template<typename Deleter = details::DefaultDeleter<T>>
MySharedPtr(T* p, Deleter d = {}) :payload(p) {
if (p != nullptr) {
cb = new ControlBlock<T>(1, d);
}
}
MySharedPtr(const MySharedPtr& other) : payload(other.payload), cb(other.cb) {
if (cb) {
cb->refCounter++;
}
}
template <typename U>
requires derived_from<remove_cvref_t<U>, remove_cvref_t<T>>
MySharedPtr(const MySharedPtr<U>& other): payload(other.payload),cb(other.cb) {
if (cb) {
cb->refCounter++;
}
}
MySharedPtr(MySharedPtr&& other) noexcept {
swap(other);
} | {
"domain": "codereview.stackexchange",
"id": 45181,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel",
"url": null
} |
c++, reinventing-the-wheel
MySharedPtr(MySharedPtr&& other) noexcept {
swap(other);
}
template<typename U>
requires derived_from<remove_cvref_t<U>, remove_cvref_t<T>>
MySharedPtr(MySharedPtr<U>&& other) noexcept {
swap(other);
}
MySharedPtr& operator=(MySharedPtr&& other) noexcept {
return moveAssignment(move(other));
}
template<typename U>
requires derived_from<remove_cvref_t<U>, remove_cvref_t<T>>
MySharedPtr& operator=(MySharedPtr<U>&& other) noexcept {
return moveAssignment(move(other));
}
MySharedPtr& operator=(const MySharedPtr& other) {
return copyAssignment(other);
}
template<typename U>
requires derived_from<remove_cvref_t<U>,remove_cvref_t<T>>
MySharedPtr& operator=(const MySharedPtr<U>& other) {
return copyAssignment(other);
}
~MySharedPtr() {
if (cb) {
decrement_destructor();
}
}
template<typename Deleter = details::DefaultDeleter<T>>
void reset(T* payload = nullptr, Deleter d = {}) {
MySharedPtr other(payload, d);
swap(other);
}
explicit operator bool() const { return payload != nullptr; }
bool operator==(const MySharedPtr& o) const { return payload == o.payload; }
bool operator!=(const MySharedPtr& o) const { return *this != o; }
T* get() { return payload; }
T& operator*() { return *payload; }
T* operator->() { return payload; }
private:
template<typename U>
MySharedPtr& copyAssignment(const MySharedPtr<U>& other) {
if (cb != other.cb) {
MySharedPtr tmp(other);
swap(tmp);
}
return *this;
}
template<typename U>
MySharedPtr& moveAssignment(MySharedPtr<U>&& other) {
MySharedPtr tmp(move(other));
swap(tmp);
return *this;
}
void decrement_destructor() {
cb->refCounter--;
if (cb->refCounter == 0) {
cb->deletePtr(payload);
delete cb;
}
}
template<typename U>
void swap(MySharedPtr<U>& other) {
std::swap(cb, other.cb);
T* tmp{ payload };
payload = static_cast<T*>(other.payload);
other.payload = static_cast<U*>(payload);
} | {
"domain": "codereview.stackexchange",
"id": 45181,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel",
"url": null
} |
c++, reinventing-the-wheel
T* payload{ nullptr };
ControlBlock_base* cb{ nullptr };
};
Example program/test of the above:
class base {
public:
base() = default;
~base() {
cout << "base destructor";
}
};
class derived : public base {
public:
derived() = default;
~derived() {
cout << "derived destructor";
}
};
int main() {
MySharedPtr derivedPt(new derived());
MySharedPtr<base> basePt(move(derivedPt));
basePt.reset();//delete via derived destructor
int* t = new int(2);
int* z = new int(2);
auto customDestructor = [](int* t) {};
MySharedPtr<int> sharedWithCustomDel(t, customDestructor);
MySharedPtr<int> copyAssignTest;
copyAssignTest = sharedWithCustomDel;//copy assignment
copyAssignTest.reset(new int(3));//should call cD destructor
MySharedPtr<int> moveConstructed(move(copyAssignTest));//move constructor
MySharedPtr<int> copyConstructed(moveConstructed);//copy const
MySharedPtr<int> moveAssigned;
moveAssigned = move(moveConstructed);//move assign
assert(*moveAssigned == 3);
}
Answer: Overall
Bug. In your != test means it will recursively call itself forever!
No other major issues.
You could do something about moving the Deleter in the control block rather than copying.
Your constructor could be improved:
Make it explicit.
Allowing nullptr
Personally, I found your indentation style hard to read. I assume you are conforming to your teams standards though (please make sure you are).
Code Review
I vaguely see potentially why you want to break ControlBlock_base and ControlBlock into two separate classes. BUT I don't see any specific use cases for it currently. Uncomplicate your code and reduce this to a single class until you have a use case where this is something you use.
struct ControlBlock_base {....};
template<typename T>
struct ControlBlock: public ControlBlock_base {...}; | {
"domain": "codereview.stackexchange",
"id": 45181,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel",
"url": null
} |
c++, reinventing-the-wheel
template<typename T>
struct ControlBlock: public ControlBlock_base {...};
Also all your shared pointer classes now contain two pointers. Why not have the control block also contain the pointer to the managed memory. Then some of the code could be moved into here as well and reduce the complexity of your main class.
What happens if the new fails?
template<typename Deleter = details::DefaultDeleter<T>>
MySharedPtr(T* p, Deleter d = {}) :payload(p) {
if (p != nullptr) {
cb = new ControlBlock<T>(1, d);
}
}
You have just leaked the pointer you were asked to look after.
I would also mark this constructor explicit to prevent accidentally creating these objects where you don't expect to!
void doWorkPart1(MySharedPtr<int> data);
void doWorkPart2(MySharedPtr<int> data);
int main()
{
int* data = new int(5);
doWorkPart1(data); // parameter takes ownership and deletes on return
doWorkPart1(data); // Here you are passing a freed pointer.
// It would be nice to prevent this kind of accidental call
}
Also you don't allow for construction with nullptr. Sure it is rare, but it would be nice if you could explicitly use nullptr without having to do anything special.
MySharedPtr<int> value(nullptr); // fails to compile.
I would consider this old school.
MySharedPtr& operator=(MySharedPtr&& other) noexcept {
return moveAssignment(move(other));
}
MySharedPtr& operator=(const MySharedPtr& other) {
return copyAssignment(other);
}
template<typename U>
MySharedPtr& copyAssignment(const MySharedPtr<U>& other) {
if (cb != other.cb) {
MySharedPtr tmp(other);
swap(tmp);
}
return *this;
}
template<typename U>
MySharedPtr& moveAssignment(MySharedPtr<U>&& other) {
MySharedPtr tmp(move(other));
swap(tmp);
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 45181,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel",
"url": null
} |
c++, reinventing-the-wheel
The simpler technique is to treat both copy and move assignment the same way. Let the compiler work out the details.
MySharedPtr& operator=(MySharedPtr other) noexcept {
swap(other);
return *this;
}
// Sure your copy prevents one increment and decrement and a couple of assignments.
// But the cost of these operations are insignificant compared
// to the cost of branch predication failure. Simpler to do it this way.
Notice the parameter is a value. Thus if you pass an r-value reference other is created by move otherwise it is created by a copy. Then you simply swap and return a reference to yourself.
So you have achieved the same results as above with a lot fewer lines of code.
I think this is slightly error prone.
~MySharedPtr() {
if (cb) {
decrement_destructor();
}
}
void decrement_destructor() {
cb->refCounter--;
if (cb->refCounter == 0) {
cb->deletePtr(payload);
delete cb;
}
}
Before calling decrement_destructor you always have to check that cb is not null. So why not move that check into decrement_destructor then everybody can call without the check. This will prevent slip ups in the future.
Bug:
bool operator!=(const MySharedPtr& o) const { return *this != o; }
As mentioned above this is a recursive call to yourself.
Simple Fix (call the operator ==).
bool operator!=(const MySharedPtr& o) const { return !(*this == o); }
Should there not be const versions of these functions?
T* get() { return payload; }
T& operator*() { return *payload; }
T* operator->() { return payload; } | {
"domain": "codereview.stackexchange",
"id": 45181,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel",
"url": null
} |
c++, reinventing-the-wheel
Title: String partial implementation using a vector
Question: I saw few similar solutions, but they all relied on C-style arrays and str utils, so I thought I would write a higher level C++ only implementation with a vector as an exercise. I have not implemented all the functions yet but wanted to first check if this looks to be on the right path or if there are some major issues.
class mystring {
public:
mystring() = default;
explicit mystring(const char* str) {
if (str != nullptr) {
data = std::vector<char>(str, str + strlen(str));
}
}
mystring& operator=(const char* str) {
data.clear();
copy(str, str + strlen(str), back_inserter(data));
}
mystring& operator+=(const mystring& other) {
data.insert(data.end(), other.data.begin(),other.data.end());
return *this;
}
mystring operator+(const mystring& other) const {
mystring result(other);
result += other;
return result;
}
explicit operator const char* () const {
return c_str();
}
const char& operator[](size_t idx) const {
return data[idx];
}
char& operator[](size_t idx) {
return data[idx];
}
void replace(size_t b, size_t e, const char* str) {
data.erase(data.begin()+b, data.begin() + e);
data.insert(data.begin()+b,str,str+strlen(str));
}
friend ostream& operator<<(ostream& cout, const mystring& s);
bool operator==(const mystring& o) const =default;
const char* c_str() const {
return data.data();
}
private:
std::vector<char> data;
}; | {
"domain": "codereview.stackexchange",
"id": 45182,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel",
"url": null
} |
c++, reinventing-the-wheel
const char* c_str() const {
return data.data();
}
private:
std::vector<char> data;
};
Answer: Inconsistent handling of nullptrs
Your constructor checks if str might be nullptr, but your assignment operator does not. Choose whether you want to support nullptr arguments, and then handle it consistently.
I would personally choose to not allow nullptr arguments, and add assert(str) statements to check for that in debug builds. Consider that the C string functions also don't handle NULL.
Missing NUL-byte
When you construct a mystring, you only copy everything but the terminating NUL-byte. However, that means c_str() will return a pointer to a non-terminated string. Make sure you always have a terminating NUL-byte at the end of data.
Consider not adding any assignment operator
You declared an assignment operator that handles const char*s, but the compiler also generated a default assignment operator that takes another mystring as the right hand side, as if there was:
mystring& operator=(const mystring& other) = default; | {
"domain": "codereview.stackexchange",
"id": 45182,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel",
"url": null
} |
c++, reinventing-the-wheel
If you would remove your custom assignment operator, then assignments from const char* will still work: since you have a constructor that takes const char*, the compiler will see that it can construct a new mystring from it first, and then assign it. Since it will also implement the move assignment operator automatically, it's even as efficient, or even more so (as copy(…, back_inserter(…)) might inefficiently insert one character at a time).
replace() is inefficient
Your replace() function will likely move parts of the string twice: once during erasure, and other time during insertion. It is probably more efficient to overwrite as much as possible, then just erase or insert the remainder.
std::string doesn't have an operator const char*()
There is no conversion operator from std::string to const char*. It's good that you made yours explicit, that avoids a lot of problems. However, it might be better to omit it altogether, to avoid any accidental conversions. | {
"domain": "codereview.stackexchange",
"id": 45182,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel",
"url": null
} |
php, laravel
Title: Update specific model attributes from a request
Question: Background
This is for an API and I'd like to use this Upsert action to take data from a request and only update the requested fields. I.e. These are partial updates and I will not update every field from a model in every request. A previous version from examples I was working through took the incoming data and updated all fields which resulted in a lot of nulls which overwrote the original models.
A rough old example was along the lines of:
$model->attribute1 = $modelData->attribute1;
$model->attribute2 = $modelData->attribute2;
$model->save();
Please don't review that code, I know it's garbage.
I was thinking about doing something hideous and long-winded like checking for the presence of each one like this:
if ($modelData->attribtue1 !== null) {
$model->attribute1 = $modelData->attribute1;
}
I was also thinking perhaps I could iterate over the keys of the incoming model data and only update those but that feels like it could be exploited.
My solution
My solution was to pull in the fillable attributes from the model and iterate over those instead. My current solution is as follows:
<?php
namespace App\Actions;
use App\DataTransferObjects\MyModelData;
use App\Models\MyModel;
class UpsertMyModelAction
{
public function execute(MyModel $myModel, MyModelData $myModelData): MyModel
{
$attributes = app(MyModel::class)->getFillable();
foreach ($attributes as $attribute) {
/* if ($myModelData->{$attribute} !== null) { */
/*
* Edit - this won't let me set a value to null
* if I want to. Altered to check specifically
* for the property instead.
*/
if (property_exists($myModelData, $attribute)) {
$myModel->{$attribute} = $myModelData->{$attribute};
}
}
$myModel->save();
return $myModel;
}
} | {
"domain": "codereview.stackexchange",
"id": 45183,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
php, laravel
return $myModel;
}
}
My thinking being that the fillable attributes are defined and controlled by me, this looks a lot cleaner than writing an if statement per attribute and it should be re-usable for different requests.
This MUST come up all the time, I just haven't found any good examples online. How does this look? Is there a cleaner way?
Answer:
How does this look?
It looks okay. It appears to mostly adhere to PSR-12 and is easy to read. While there is only one method with a single loop it isn't very complicated. The variable names are appropriate.
Is there a cleaner way?
I’ve used Laravel for more than 8 years and grown to primarily use controller methods to update models. I've read about using the repository pattern to have thin controllers methods. I haven't seen the manual mention actions though I do see the laravel-actions package - is that what is being utilized here?
If you look at the source of the update() method within src/Illuminate/Database/Eloquent
/Model.php notice that the last line of the method calls the fill() method before calling the save() method.
/**
* Update the model in the database.
*
* @param array $attributes
* @param array $options
* @return bool
*/
public function update(array $attributes = [], array $options = [])
{
if (! $this->exists) {
return false;
}
return $this->fill($attributes)->save($options);
}
The fill() method calls $this->fillableFromArray() passing along the $attributes parameter.
/**
* Fill the model with an array of attributes.
*
* @param array $attributes
* @return $this
*
* @throws \Illuminate\Database\Eloquent\MassAssignmentException
*/
public function fill(array $attributes)
{
$totallyGuarded = $this->totallyGuarded();
$fillable = $this->fillableFromArray($attributes);
And that method calls getFillable() to determine which attributes can be filled based on the $attributes parameter. | {
"domain": "codereview.stackexchange",
"id": 45183,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
php, laravel
/**
* Get the fillable attributes of a given array.
*
* @param array $attributes
* @return array
*/
protected function fillableFromArray(array $attributes)
{
if (count($this->getFillable()) > 0 && ! static::$unguarded) {
return array_intersect_key($attributes, array_flip($this->getFillable()));
}
return $attributes;
}
Consequently one can simply call the update() method passing in the attributes to be set on the model. The foreach loop can be removed and the save() call replaced with a call to update() - using a method to get the attributes from MyModelData or with a reflection class and its getProperties() method. | {
"domain": "codereview.stackexchange",
"id": 45183,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
python, unit-testing
Title: Test suite for population-count function, using random input
Question: For the purpose of this discussion, I have the following function:
def countSetBits(num):
cnt = 0
while num:
cnt += num & 0b1
num >>= 1
return cnt
It counts the number of set bits in a given num's binary representation. For example, take 10 whose binary rep is 0b1010 -- countSetBits(10) should equal 2.
I have written a "test suite" that generates random input -- numbers of known set bit count and use that to test my countSetBits function.
import random
import unittest
class TestCountSetBits(unittest.TestCase):
NUM_TESTS = 100
MAX_SET_BIT_CNT = 10
def test_suite(self):
for _ in range(self.NUM_TESTS):
k = expectedCnt = random.randint(0, self.MAX_SET_BIT_CNT)
# Generate a random integer with `k` set bits
setBitPositions = random.sample(range(k * 2), k)
num = sum(0b1 << pos for pos in setBitPositions)
computedCnt = countSetBits(num)
self.assertEqual(computedCnt,
expectedCnt,
msg=f'Got {computedCnt}, but expected {expectedCnt}')
print('Success!')
TestCountSetBits().test_suite()
My questions are:
Should I use cls instead of self?
Is there a more pythonic way to write this "test suite". I may be reading too much into this, but Python Doc's unittest page has a Basic Example in which each def test_* has only one assertEqual. My def test_suite has the assertEqual inside a for loop. Is this bad style?
Any suggestions are welcome! Thanks!
Scrolling down the unittest page, I see subTest which may tidy things up:
class TestCountSetBits(unittest.TestCase):
NUM_TESTS = 100
MAX_SET_BIT_CNT = 10
def test_suite(self):
for _ in range(self.NUM_TESTS):
k = expectedCnt = random.randint(0, self.MAX_SET_BIT_CNT) | {
"domain": "codereview.stackexchange",
"id": 45184,
"lm_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, unit-testing",
"url": null
} |
python, unit-testing
# Generate a random integer with `k` set bits
setBitPositions = random.sample(range(k * 2), k)
num = sum(0b1 << pos for pos in setBitPositions)
computedCnt = countSetBits(num)
# Diff starts here
with self.subTest():
self.assertEqual(computedCnt,
expectedCnt,
msg=f'Got {computedCnt}, but expected {expectedCnt}')
# Diff ends here
print('Success!')
TestCountSetBits().test_suite()
Answer: PEP-8
def countSetBits(num):
Ummm, yeah, let me stop you right there.
Pythonically we would avoid the java-esque camelCase.
And maybe even let the Gentle Reader know we anticipate an int
that we can do bit operations on.
And describe what we return.
def count_set_bits(num: int) -> int:
In many languages we would conventionally name that
pop_count.
Ξένη Γήινος observes that this is
re-inventing the wheel since the builtin
bit_count
gives the identical answer much quicker.
Similar snake_case remarks for {expected,computed}_cnt
and for set_bit_positions.
The unittest module is rather old,
and comes from a time when we had fewer clear conventions,
hence names like assertEqual.
For extra pythonic brownie points,
write a single English sentence as a """docstring""".
def test_suite(self):
...
for _ in range(self.NUM_TESTS):
... self.MAX_SET_BIT_CNT ...
Should I use cls instead of self? | {
"domain": "codereview.stackexchange",
"id": 45184,
"lm_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, unit-testing",
"url": null
} |
python, unit-testing
Should I use cls instead of self?
No.
There are times for such a practice, in your target code.
But not in this test code.
BTW, it's fine to invest zero effort in devising a name
for each test method.
The obvious name for this method would be test_count_set_bits.
The module being tested is presumably in count_set_bits.py,
and the TestCountSetBits class name you chose is absolutely perfect.
Typically there's not a ton of creativity that goes into making up
identifiers in a test, and we count that as a good thing,
we like simple boring tests.
... has the assertEqual inside a for loop. Is this bad style?
No, not at all, it is just fine as-is.
A unit test should look like AAA, arrange act assert.
It could have just a single instance of that,
and then we move on to another AAA in the next test method.
But here, we have to do a bit of Arrange work before
we're ready for the rest, and it makes perfect sense
to loop as you have done.
An even simpler test method might start with
self.assertEqual(count_set_bits(10), 2)
self.assertEqual(count_set_bits(11), 3) | {
"domain": "codereview.stackexchange",
"id": 45184,
"lm_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, unit-testing",
"url": null
} |
python, unit-testing
and that would be perfectly fine, no need for two methods.
We anticipate that most tests are Green, most of the time.
What's the downside to having multiple asserts in a test?
Some of them won't run in the event of Red failure.
So we learn less from that run.
It's a tradeoff.
If there is little Arrange overhead, create distinct tests.
If during arranging you had to go through a bunch of ceremony,
feel free to amortize that over multiple asserts in a single test method.
This is language-agnostic advice. There's nothing python specific about it.
EDIT
Let me revisit the two lines I proposed.
The first line came straight from your English language example
where you expressed ten as 10 in decimal notation,
and then I slightly tweaked the second line.
I'd like to respond to your comment about
"a lot of Arrange code" relative to small
amount of target code.
I feel a better way for me to express those two lines would be:
self.assertEqual(count_set_bits(0b1010), 2)
self.assertEqual(count_set_bits(0b1011), 3)
Now the Gentle Reader can visually scan the
input that we have Arranged and immediately see the answer.
That is to say, this test is now "obvious".
I count half a dozen characters of Arrange,
much less than the several lines which your
very nice and far more powerful test wound up using.
Both my boring test and your flexible test are good;
both belong in the test suite, as they do different things.
The small test has didactic value
while your longer test tries to exercise a larger portion
of the (infinite!) space of valid input values.
Also, significantly, the short test instills confidence
that the more flexible test is actually working properly.
Imagine that buggy target code always returned 0,
and buggy test code accidentally cleared all bits so it
was asking for pop count of zero and wrongly showing us Green.
The dirt simple test would catch such a travesty.
Any suggestions are welcome! | {
"domain": "codereview.stackexchange",
"id": 45184,
"lm_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, unit-testing",
"url": null
} |
python, unit-testing
Any suggestions are welcome!
I see what you're trying to do with the 0b1 thing that you left-shift,
and I'm somewhat sympathetic.
But it's kind of weird.
It's not like you're going for parallel structure with other nearby binary constants.
A 1 is going to mean the same thing in hex, decimal, octal, binary.
Recommend you just use 1 in the source.
Now, if we had e.g. x & 255 masking and x | 256 bit setting,
I would definitely insist on expressing those as 0xff and 0x100,
in order to prevent bugs via better readability.
But 1? Meh.
I feel that verifying count_set_bits(0) == 0
is an important enough edge case that it's worth
coding manually, rather than hoping the PRNG
managed to hit it.
And then maybe walk a single bit up from 1 to
some power of two, verifying the count is always one.
Scrolling down the unittest page, I see subTest
Hmmm, interesting.
I don't recall that I've ever seen
subTest
used in production code that I've reviewed.
Thank you for bringing it to my attention.
Sure, go for it, use it in good health.
Imagine there was some population count bug.
Maybe it fails just for multiples of twelve.
Or maybe it always returns 0.
In the first case, seeing that one-twelfth of tests
failed would be very informative, and might reduce debugging time.
In the second case, we'd be spammed with a ton of failures.
Use what you feel would best support your development efforts.
I'd be fine with either, since in both cases I will
work toward turning the tests completely Green,
and will definitely augment the automated test observations
with single-step observations from within a debugger.
CLI
TestCountSetBits().test_suite()
I understand why you wrote this,
it is a perfectly sensible way to execute the test runner.
Especially when protected by a guard:
if __name__ == "__main__":
TestCountSetBits().test_suite()
But I stopped appending such boilerplate to my tests long ago,
preferring to habitually run
$ python -m unittest tests/*_test.py | {
"domain": "codereview.stackexchange",
"id": 45184,
"lm_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, unit-testing",
"url": null
} |
python, unit-testing
Or I let $ make test do that for me.
Or I ask pytest
to run it, while still inheriting from TestCase.
Typically that's because I want to make a $ pytest --cov code coverage
measurement.
repeatable tests
I admire that you want to test "lots of inputs",
more adventurous inputs than the boring ones
you might have dreamt up and manually typed in.
But please understand that Random Tests Are Bad.
That is, if you get a failed Red test you won't
necessarily be able to learn much from it.
It's not a sure thing you can reproduce the bug.
So if you do go with random, definitely
seed()
the PRNG, maybe with 0, or with 42,
so that subsequent runs will test the same inputs.
Or use a PRNG once to produce input.csv,
and feed that same file to all subsequent test runs.
torture test
Consider using the amazing
hypothesis
testing library, if you're keen to find the edge cases.
It's not always a fit.
It works best when you can offer an "oracle" for correctness,
such as reversible {serialize, deserialize}, {encrypt, decrypt},
or {compress, decompress} pairs.
It's very good at exploring the space of unusual inputs,
and then having found a failing input it will boil it
down to the simplest such failing input that it can find.
This codebase achieves its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45184,
"lm_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, unit-testing",
"url": null
} |
c++, c++20, stl
Title: Alarm - Timer - Stopwatch with
Question: Alarm, timer and stopwatch in the style of the standard library.
Important design notes:
The accessors do not update internal state, the user is responsible to call check() or update() prior to access to ensure latest state.
The classes are not thread-safe for performance and simplicity, the user is responsible for the thread-safety measures in a multi-threading context.
Important points for review:
The check() function in alarm/timer and the update() function in stopwatch have to be called by the user to update the internal state. This is for uses where the alarm/timer is polled by a regularly-updating entity such as Boost.ASIO's io_context or any game engine's update loop. The user can alternatively call wait() or async_wait() in the case of alarm/timer. I feel that this manual call to check() and update() is bad design. I need confirmation, and a better solution which is the main reason I am posting this.
#pragma once
#include <chrono>
#include <functional>
#include <future>
#include <thread>
namespace mak::time
{
template <typename _clock_type>
class alarm
{
public:
using clock_type = _clock_type;
using time_point_type = typename clock_type::time_point;
using callback_type = std::function<void()>;
explicit alarm (
const time_point_type& time_point,
const callback_type& callback ,
const bool active = true)
: time_point_(time_point)
, callback_ (callback )
, active_ (active && is_in_future(time_point_))
{
}
alarm (const alarm& that) = default;
alarm ( alarm&& temp) = default;
virtual ~alarm () = default;
alarm& operator=(const alarm& that) = default;
alarm& operator=( alarm&& temp) = default; | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
// Synchronous check, synchronous (blocking) and asynchronous (non-blocking) wait.
void check ()
{
if (active_ && !is_in_future(time_point_))
{
active_ = false;
if (callback_)
callback_();
}
}
void wait ()
{
if (active_)
{
std::this_thread::sleep_until(time_point_);
check();
}
}
[[nodiscard]]
std::future<void> async_wait ()
{
return std::async(std::launch::async, [&] { wait(); });
}
// Semantic mutators (real alarm clocks have cancel and reset functions).
void cancel ()
{
set_active (false);
}
void reset (const time_point_type& time_point, const bool active = true)
{
set_active (active);
set_time_point(time_point);
}
// Mutators.
void set_time_point(const time_point_type& time_point)
{
time_point_ = time_point;
active_ = active_ && is_in_future(time_point_);
}
void set_callback (const callback_type& callback )
{
callback_ = callback;
}
void set_active (const bool active )
{
active_ = active;
}
// Accessors.
[[nodiscard]]
const time_point_type& time_point () const
{
return time_point_;
}
[[nodiscard]]
const callback_type& callback () const
{
return callback_;
}
[[nodiscard]]
bool active () const
{
return active_;
}
protected:
[[nodiscard]]
static bool is_in_future (const time_point_type& time_point)
{
return clock_type::now() < time_point;
}
// Arguments (accessible and mutable).
time_point_type time_point_;
callback_type callback_;
bool active_;
}; | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
template <typename _clock_type>
class timer
{
public:
using clock_type = _clock_type;
using duration_type = typename clock_type::duration;
using time_point_type = typename clock_type::time_point;
using callback_type = std::function<void()>;
explicit timer (
const duration_type& duration,
const callback_type& callback,
const bool active = true)
: total_duration_ (duration)
, callback_ (callback)
, active_ (active)
, elapsed_duration_()
, last_check_time_ (clock_type::now())
{
}
timer (const timer& that) = default;
timer ( timer&& temp) = default;
virtual ~timer () = default;
timer& operator=(const timer& that) = default;
timer& operator=( timer&& temp) = default;
// Synchronous check, synchronous (blocking) and asynchronous (non-blocking) wait.
void check ()
{
if (active_)
{
const auto time = clock_type::now();
const auto delta_time = time - last_check_time_;
last_check_time_ = time;
elapsed_duration_ += delta_time;
if (elapsed_duration_ >= total_duration_)
{
active_ = false;
elapsed_duration_ = total_duration_; // To prevent negative remaining duration.
if (callback_)
callback_();
}
}
}
void wait ()
{
if (active_)
{
check(); // Triggers a check to update elapsed (and remaining) duration.
std::this_thread::sleep_for(remaining_duration());
check();
}
}
[[nodiscard]]
std::future<void> async_wait ()
{
return std::async(std::launch::async, [&] { wait(); });
} | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
// Semantic mutators (real timers have start, stop and reset functions).
void start ()
{
set_active(true);
}
void stop ()
{
check (); // Triggers a check to update elapsed (and remaining) duration.
set_active(false);
}
void reset ( const bool active = true)
{
set_active(active);
elapsed_duration_ = {};
}
void reset (const duration_type& duration, const bool active = true)
{
set_total_duration(duration);
reset (active);
}
// Mutators.
void set_total_duration(const duration_type& duration)
{
total_duration_ = duration;
if (elapsed_duration_ >= total_duration_)
elapsed_duration_ = total_duration_; // To prevent negative remaining duration.
}
void set_callback (const callback_type& callback)
{
callback_ = callback;
}
void set_active (const bool active )
{
if (!active_ && active)
last_check_time_ = clock_type::now();
active_ = active;
}
// Semantic accessors (real timers show remaining duration).
[[nodiscard]]
const duration_type& remaining_duration() const
{
return total_duration_ - elapsed_duration_;
}
// Accessors.
[[nodiscard]]
const duration_type& total_duration () const
{
return total_duration_;
}
[[nodiscard]]
const callback_type& callback () const
{
return callback_;
}
[[nodiscard]]
bool active () const
{
return active_;
}
[[nodiscard]]
const duration_type& elapsed_duration () const
{
return elapsed_duration_;
}
[[nodiscard]]
const time_point_type& last_check_time () const
{
return last_check_time_;
} | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
protected:
// Arguments (accessible and mutable).
duration_type total_duration_;
callback_type callback_;
bool active_;
// Book-keeping variables (accessible but not mutable).
duration_type elapsed_duration_;
time_point_type last_check_time_;
};
template <typename _clock_type>
class stopwatch
{
public:
using clock_type = _clock_type;
using duration_type = typename clock_type::duration;
using time_point_type = typename clock_type::time_point;
explicit stopwatch (const bool active = true)
: active_ (active)
, total_duration_ ()
, last_update_time_(clock_type::now())
, last_split_time_ (clock_type::now())
{
}
stopwatch (const stopwatch& that) = default;
stopwatch ( stopwatch&& temp) = default;
virtual ~stopwatch () = default;
stopwatch& operator=(const stopwatch& that) = default;
stopwatch& operator=( stopwatch&& temp) = default;
// Synchronous update.
void update ()
{
if (active_)
{
const auto time = clock_type::now();
const auto delta_time = time - last_update_time_;
last_update_time_ = time;
total_duration_ += delta_time;
}
} | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
// Semantic mutators (real stopwatches have start, stop, split and reset functions).
void start ()
{
set_active(true);
}
void stop ()
{
update(); // Triggers an update to total duration.
set_active(false);
}
[[nodiscard]]
duration_type split ()
{
update(); // Triggers an update to last update time.
const auto result = last_update_time_ - last_split_time_;
last_split_time_ = last_update_time_;
return result;
}
void reset (const bool active = true)
{
set_active(active);
total_duration_ = {};
last_update_time_ = clock_type::now();
last_split_time_ = clock_type::now();
}
// Mutators.
void set_active (const bool active)
{
if (!active_ && active)
{
const auto time = clock_type::now();
last_update_time_ = time;
last_split_time_ = time;
}
active_ = active;
}
// Accessors.
[[nodiscard]]
bool active () const
{
return active_;
}
[[nodiscard]]
const duration_type& total_duration () const
{
return total_duration_;
}
[[nodiscard]]
const time_point_type& last_update_time() const
{
return last_update_time_;
}
[[nodiscard]]
const time_point_type& last_split_time () const
{
return last_split_time_;
}
protected:
// Arguments (accessible and mutable).
bool active_;
// Book-keeping variables (accessible but not mutable).
duration_type total_duration_ ;
time_point_type last_update_time_;
time_point_type last_split_time_ ;
}; | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
using system_alarm = alarm<std::chrono::system_clock>;
using steady_alarm = alarm<std::chrono::steady_clock>;
using high_resolution_alarm = alarm<std::chrono::high_resolution_clock>;
using utc_alarm = alarm<std::chrono::utc_clock>;
using tai_alarm = alarm<std::chrono::tai_clock>;
using gps_alarm = alarm<std::chrono::gps_clock>;
using system_timer = timer<std::chrono::system_clock>;
using steady_timer = timer<std::chrono::steady_clock>;
using high_resolution_timer = timer<std::chrono::high_resolution_clock>;
using utc_timer = timer<std::chrono::utc_clock>;
using tai_timer = timer<std::chrono::tai_clock>;
using gps_timer = timer<std::chrono::gps_clock>;
using system_stopwatch = stopwatch<std::chrono::system_clock>;
using steady_stopwatch = stopwatch<std::chrono::steady_clock>;
using high_resolution_stopwatch = stopwatch<std::chrono::high_resolution_clock>;
using utc_stopwatch = stopwatch<std::chrono::utc_clock>;
using tai_stopwatch = stopwatch<std::chrono::tai_clock>;
using gps_stopwatch = stopwatch<std::chrono::gps_clock>;
} | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
Answer: This library is a cool idea. It’s something I could see myself using.
So, you’re concerned about the need to manually check/update the alarm/timer/stopwatch, and I agree that’s not great. But it also doesn’t need to be a problem. For the alarm/timer, all you need to do is wait in the destructor. This kinda sucks if you carelessly create an alarm/timer and just… forget about it… because it means there will be a “freeze” at scope end. But in that case… the coder kinda asked for it, so they can hardly complain. And it’s easy to avoid; if they get to a point where they don’t care whether the alarm/timer has fired or not, and don’t care whether the callback has run, they can always just cancel it at that point. (For the stopwatch, you don’t actually need to do anything. If you never take/check the split time or check the total time… no big dealio. )
From a design perspective, the only major problem is over-complication, mostly arising from unnecessary flexibility. Two of the core guidelines of engineering design are “KISS”—or, “keep it simple, silly”—and “YAGNI”—or “you ain’t gonna need it”.
For example, the timer: the timer has, in essence, three properties:
the delay
the callback; and
a flag to indicate whether it’s active. | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
You have made it possible to individually and separately change every single one of these properties. Is that really necessary? Is it really necessary to be able to create a timer to do foo() after 10 seconds… and then a few seconds later, change your mind and decide to do bar() instead… and then a few seconds after that, change your mind and decide it should happen 15 seconds from now… and so on. That’s a little gratuitous.
I would suggest paring it down a bit. Once a timer is created, the only “change” you should be able to make to it is to cancel it. That’s all you need. If you want a new callback behaviour, or a new delay, just create a new timer. Hell, even if you want a new callback but the same set time, just create a new timer. If you want to “reuse” a timer, just move-assign a new timer to it.
That will not only massively simplify the class, it will also solve a host of other problems. For example, if the only thing you change with an alarm is whether or not it is active, it is now trivial to make it thread-safe. If it is possible to change everything, it is practically impossible to avoid a data race, because there can be situations where you change one property, then something else interrupts concurrently before you can change the second. To prevent that, you would have to package a mutex in the alarm/timer/stopwatch… which is absurd.
The more “features” you add to a class, the greater the technical burden. You have to do more testing to cover every angle. You have to keep track of more variation in class invariants. It just makes everything harder. As a great engineer once said: “The more they overthink the plumbing, the easier it is to stop up the drain.” | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
The other cause of over-complication is not recognizing opportunities for reuse. For example, an alarm and a timer are exactly the same thing. Literally the only difference is one is set with a time point, and the other with a duration. Both cases could trivially be handled by a pair of constructors in a single class.
The biggest problem with the actual code is a completely ridiculous abuse of whitespace.
Just… take a look at this:
void reset ( const bool active = true) | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
That is literally a 100 characters wide… and for what? For this: void reset(bool active = true) (the const is also superfluous; the function is literally two lines; pretty sure there is no chance of accidentally resetting active and not noticing). 63% of the line is useless, completely devoid of meaningful information (69% of you include the unnecessary const). A short, 30 character function prologue gets stretched so wide, it won’t even fit on the screen without a horizontal scroll bar.
The logic behind such absurd horizontal spacing seems to be line up member function names… all member function names in the entire class… which means the horizontal position of all member function names is determined by the longest return type (which happens to be const time_point_type& here).
Is it really necessary to explain why this is so silly?
I mean, let’s not even consider the fact that if ever the class is modified so a return type (on any function) exceeds the current max length, you would have to edit the prologue of every single member function in the class. Even if that never happens, there is no sensible reason to lock every function name to a common horizontal position. I don’t know about you, but when I study a class, I do it one function at a time. I basically ignore the rest of the class while focusing on a single member function. I don’t care if the names don’t line up horizontally; if they do, it doesn’t help my parsing of the code at all.
And to make matters ever more ridiculous, while there is an absurd overuse of horizontal space… all the member functions are jammed together vertically with no space between. It’s hard to tell where one ends and the next begins, even without the fact that it’s hard to identify function prologues because they stretch right out of the visible window. | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
If you really must line up member function names… might I suggest looking into trailing return syntax. at least in that case, the longest “return type” will always be auto… a whole lot shorter than const time_point_type&.
Okay, on to the review!
#pragma once | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
Don’t use #pragma once. It is not standard C++, and for a very good reason.
template <typename _clock_type>
This isn’t wrong, and if you’re going to be consistent about it, that’s fine… but it is weird to name template parameters that way. The universal practice is to use UpperCamelCase for template parameters.
However, I would suggest you take advantage of concepts.
To do that, you would need a clock type concept. No problem; most of the work is already done:
template <typename T>
concept clock_type = std::chrono::is_clock_v<T>;
So now:
template <clock_type ClockType>
class alarm
{
// ...
To go even further, I would suggest templating on the callback type as well. std::function is okay for a general case, but there are many situations where it is not ideal. You may want to use std::move_only_function instead. Or you may be in a high-performance situation where neither want nor need std::function to dynamically allocate memory, and instead want to use a custom function object, like a lambda type. Even something as simple as wanting to use a function that doesn’t return void requires extra work to use if you’ve hard-coded std::function<void()> as the callback type.
And, hell, what if you don’t want a callback at all? What if you just want to know when time is up? Then your callback type could just be void.
So, like:
template <typename T>
concept clock_type = std::chrono::is_clock_v<T>;
template <
clock_type Clock,
typename Callback
>
requires std::invocable<Callback> or std::same_as<Callback, void>
class alarm
{
public:
using clock_type = Clock;
using callback_type = Callback;
constexpr explicit alarm(typename clock_type::time_point tp)
requires std::same_as<Callback, void>
: time_point_{std::move(tp)}
, active_{is_in_future(time_point_)}
{} | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
constexpr alarm(typename clock_type::time_point tp, callback_type cb)
requires not std::same_as<Callback, void>
: time_point_{std::move(tp)}
, callback_{std::move(cb)}
, active_{is_in_future(time_point_)}
{
// If the time is already past, do the callback immediately.
if (not active_)
std::ignore = callback_();
}
// ...
};
It would be a bit more complicated than that, because we don’t have regular void, but not by much.
I would also not bother with the ability to create “inactive” alarms. What would be the point? It’s just one more thing to test. And who would ever need to create an alarm that doesn’t actually alarm? (And even if someone does want to make an alarm object that is not set, so it can be set later, they can always do so by using move assignment: alarm = mak::time::alarm{/* new time and/or callback */};
alarm (const alarm& that) = default;
alarm ( alarm&& temp) = default;
virtual ~alarm () = default;
alarm& operator=(const alarm& that) = default;
alarm& operator=( alarm&& temp) = default; | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
So, first, I would say that if you’re just going to default everything, there’s really no need to spell it out like that.
Also, there is no need to give names to the parameters, which would save some keystrokes, horizontal space, and complexity.
However, I have to ask if it really makes sense for an alarm to be copyable. Let’s say you have an alarm that updates something after 10 s… what would it mean to copy that alarm? Do the update twice? Seems dangerous.
I also have to ask what is the point of making the destructor virtual, and all the class internals protected? Normally that would suggest that the intention of this class is to be a base class. But… really? In what situation would it be useful to derive from an alarm? All it does is wait a bit then call a function. What could you possibly do differently?
This is another case of YAGNI. Making a class flexible is usually a good thing… but not always; not when it comes with costs. There are costs to adding even a single virtual function to a type: now every single instance has to truck around a pointer to a vtable. And for what is everyone paying this cost? The only virtual function in your interface is the destructor. It’s not even like a derived class could change the behaviour of, say, check(). So you have a situation where you are paying a cost… and really getting nothing out of it. (You could make all the functions virtual, which would now actually make the class customizable… except now you would making every single operation a virtual call… which is even more cost.)
I would suggest not paying this useless cost at all. Don’t make the destructor virtual, don’t bother with protected; there is no reason to derive from alarm. It has one, simple behaviour: wait a bit, then call a function. There is no reason to tweak that. There is no reason to make alarm more expensive for an ability to tweak its behaviour, that no one will ever use. YAGNI. | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
Now, as for the move ops, they should be noexcept whenever possible… which in this case, depends on whether the callback is no-throw movable. Also, you can’t really just default them, because if you do, active_ will be true in both the moved-from and the moved-to alarms. You’ll end up with two active alarms… which, in effect, is a copy, which is probably not what you want.
And while we’re at it, you probably don’t want to default the destructor either. You probably want to do wait(), so the scheduled callback will be run, if it hasn’t been already.
So, in summary:
// Non-copyable:
alarm(alarm const&) = delete;
auto operator=(alarm const&) -> alarm& = delete; | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
// Move ops:
constexpr alarm(alarm&& other) noexcept(std::is_nothrow_move_constructible_v<Callback>)
: time_point_{std::move(other.time_point_)}
, callback_{std::move(other.callback_)}
, active_{std::exchange(other.active_, false)} // NOTE!
{}
constexpr auto operator=(alarm&& other) noexcept(std::is_nothrow_move_assignable_v<Callback>) -> alarm&
{
time_point_ = std::move(other.time_point_);
callback_ = std::move(other.callback_);
active_ = std::exchange(other.active_, false); // NOTE!
return *this;
}
// Destructor
~alarm() noexcept(callback_())
{
wait();
}
check() is fine, but in wait():
void wait ()
{
if (active_)
{
std::this_thread::sleep_until(time_point_);
check();
}
}
I would suggest that instead of if, you should use while. In theory, this_thread::sleep_until() should always return after the time point. But… why leave it to chance? In practice, it will probably only ever loop one or zero times. Better safe than sorry; program defensively.
[[nodiscard]]
std::future<void> async_wait ()
{
return std::async(std::launch::async, [&] { wait(); });
}
Now this is dangerous. Consider:
auto waiter = std::future<void>{};
{
auto alarm = mak::time::alarm{later, func};
waiter = alarm.async_wait();
// alarm is destroyed
}
// but waiter still holds a future that refers to alarm
If you want to allow asynchronous waiting, you might have to rethink the design.
One way to do it might be to keep a promise, and hand out shared futures. Or something like:
template <typename T>
concept clock_type = std::chrono::is_clock_v<T>;
template <
clock_type Clock,
typename Callback
>
requires std::invocable<Callback>
class alarm
{
public:
using clock_type = Clock;
using callback_type = Callback; | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
alarm(typename clock_type::time_point tp, callback_type cb)
{
auto promise = std::promise<std::invoke_result_t<callback_type>>{};
_future = promise.get_future();
if (clock_type::now() < _time_point)
{
auto thread = std::thread{thread_func, std::move(promise), std::move(tp), std::move(cb)};
thread.detach();
}
else
{
try
{
promise.set_value(callback());
}
catch (...)
{
promise.set_exception(std::current_exception());
}
}
}
auto get() -> decltype(auto)
{
return _future.get();
}
auto wait()
{
return _future.wait();
}
template <typename Rep, typename Period>
auto wait_for(std::chrono::duration<Rep,Period> const& d)
{
return _future.wait_for(d);
}
template <typename Clock, typename Duration>
auto wait_until(std::chrono::time_point<Clock,Duration> const& t)
{
return _future.wait_until(t);
}
private:
static auto thread_func(std::promise<std::invoke_result_t<callback_type>> promise, typename clock_type::time_point time_point, callback_type callback) -> void
{
try
{
while (clock_type::now() < _time_point)
std::this_thread::sleep_until(time_point);
promise.set_value_at_thread_exit(callback());
}
catch (...)
{
promise.set_exception_at_thread_exit(std::current_exception());
}
}
std::future<std::invoke_result_t<callback_type>> _future;
}; | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
std::future<std::invoke_result_t<callback_type>> _future;
};
Of course, you could just replace the class above with a function that just returns the future.
The heart of the problem of asynchronously waiting is that you want to make sure that the alarm stays alive so long as the future exists. And there’s no practical way to do that without things getting at least a little bit expensive. Pretty much everything meant to be used concurrently—futures/promises, coroutines, etc.—all require dynamic allocation, so they can survive even outside of their scope. An asynchronous timer/alarm would probably need that too, or at least some sort of help from the OS.
So you might want to consider having a simple, high-efficiency alarm without asynchronous waiting… and a second alarm that is a bit more expensive, but allows asynchronous waiting. Indeed, that second “alarm” could be nothing more than a function that returns a void future that doesn’t turn ready until after the delay. Sorta like:
// A low-cost, high-performance, synchronous-only alarm ////////
//
// Basically: what you already have.
// Will call func at or after time_point:
auto alarm = mak::time::alarm{time_point, func};
// Will call func at or after duration:
auto alarm = mak::time::alarm{duration, func};
// If time is up and func hasn't already been called,
// calls func; otherwise returns immediately.
alarm.check();
// Wait for specified time, duration, or forever for time to be
// up and func to run:
alarm.wait();
alarm.wait_for(5s);
alarm.wait_until(later);
// If you want, you can add cancellation, so func won't be run
// even when time is up:
alarm.cancel();
// If func hasn't already been called, and it hasn't been
// cancelled, the destructor waits until time is up,
// then calls func (effectively, calls wait())"
//~alarm();
// A higher-cost, asynchronous delay ///////////////////////////
//
// Simply returns a void future that turns ready after the time
// is up. | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
auto future = mak::time::delay_for(5s);
auto future = mak::time::delay_until(later);
// Could be used as a synchronous alarm, to wait for whatever
// time is remaining in the delay before calling func:
future.wait(); // or future.get();
func();
// Could be used as an asynchronous alarm like so:
mak::time::delay_for(5s).and_then(func);
// The above assumes std::future will get monadic operations
// eventually. For now, you'd have to write your own:
//and_then(mak::time::delay_for(5s), func);
// or:
//chain(mak::time::delay_for(5s), func);
// or something like that.
Now, as for reset(), this can be done just as easily by move assigning a new alarm. So this function is not necessary.
// Mutators.
void set_time_point(const time_point_type& time_point)
{
time_point_ = time_point;
active_ = active_ && is_in_future(time_point_);
}
void set_callback (const callback_type& callback )
{
callback_ = callback;
}
void set_active (const bool active )
{
active_ = active;
}
// Accessors.
[[nodiscard]]
const time_point_type& time_point () const
{
return time_point_;
}
[[nodiscard]]
const callback_type& callback () const
{
return callback_;
}
[[nodiscard]]
bool active () const
{
return active_;
} | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
When you’re just doing get_X() and set_X() for every private data member X, that is an anti-pattern. You might as well just make the data member public.
The one exception here is the time point, because there is a little more to the logic than just setting a private data member. However, there doesn’t seem to be a need for the ability to change an alarm’s time. And if you really want to do that, you can just move assign.
Now, I mentioned that you probably don’t want to allow asynchronous waiting on a basic alarm, because that will massively increase the complexity and cost even for non-asynchronous use (though you may consider adding a second alarm class for asynchronous use). However, you can still make even the most basic alarm type safe to use across threads, for (almost!) zero cost.
The trick to making this possible is to make it so that the only variable that can change in the class is whether it’s active or not. If you allow any other data members to mutate, you invite race conditions.
If only “active” can mutate, then we can make it atomic, and get thread-safe behaviour quite easily. Well… sorta easily. As long as the callback type does not have throwing move ops.
template <clock_type Clock, std::invocable Func>
class alarm
{
std::atomic<bool> handled_;
typename Clock::time_point time_point_;
Func callback_;
public:
using clock_type = Clock;
using callback_type = Func; | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
public:
using clock_type = Clock;
using callback_type = Func;
// Note: constructor does *NOT* check to see if the alarm
// should have already gone off.
//
// Why? Because if the time *HAS* passed, and we call the
// callback, and it throws... we have no way of knowing
// whether it was the callback that failed, or *moving*
// the callback. So we can never know if the callback was
// run.
//
// Better to construct the alarm, then check. If the
// construction failed, we will know the callback never
// ran. If the construction succeeded, but the check failed
// we know the callback was run (but failed).
constexpr alarm(typename clock_type::time_point tp, callback_type cb)
: time_point_{std::move(tp)}
, callback_{std::move(cb)}
{}
// Note: handled_ *must* be the first data member of `other`
// that we touch. We set it to true immediately, and save
// its actual value. That way, if any other thread is
// checking the original object, it will not try to run the
// callback that has been moved-from.
//
// The only problem with this arises if the callback is not
// no-fail movable. In that case, we may mark the callback
// handled in `other`, then try to move the callback, and
// fail... but there is no way to recover the original value
// of handled in `other`. There is nothing we can do to fix
// this, so maybe you might want to ban functions with
// throwing move-ops. Or simply say that if the move does
// throw, the callback may just never be called.
//
// (Well, it is *possible* to deal with callbacks with
// throwing move-ops, but... *EXTREMELY* complicated.)
constexpr alarm(alarm&& other)
: handled_{other.exchange(true, std::memory_order::acq_rel)}
, time_point_{std::move(other.time_point_)}
, callback_{std::move(other.callback_)}
{} | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
constexpr ~alarm()
{
wait();
}
constexpr auto check()
{
if (_time_is_up() and not handled_.load(std::memory_order::relaxed))
{
// If we detect that handled is false, we are the
// first and only entity that could have done so.
if (handled_.exchange(true, std::memory_order::acq_rel) == false)
std::ignore = callback_();
}
}
constexpr auto wait()
{
if (not handled_.load(std::memory_order::acquire))
{
while (not _time_is_up())
std::this_thread::sleep_until(time_point_);
if (handled_.exchange(true, std::memory_order::acq_rel) == false)
std::ignore = callback_();
}
}
constexpr auto cancel() noexcept
{
handled_.store(true, std::memory_order::release);
}
// Same note about callback types with throwing move ops as
// the move constructor, though it is possible to deal with
// it here (though complicated).
constexpr auto operator=(alarm&& other) noexcept -> alarm&
{
handled_ = other.exchange(true, std::memory_order::acq_rel);
time_point_ = std::move(other.time_point_);
callback_ = std::move(other.callback_);
return *this;
}
alarm(alarm const&) = delete;
auto operator=(alarm const&) -> alarm& = delete;
}; | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
I’m not going to bother reviewing timer because it’s basically identical to alarm. The only difference is all the gymnastics you have to do to convert time points to durations. Assuming you don’t want the ability to pause a timer, then there is no difference between alarm{clock::now() + 5s} and timer{5s} (or alarm{midnight} and timer{midnight - clock::now()}). (That is, there is no difference if the clock is steady. If the clock is not steady, then all bets are off anyway. But it would be silly to use a non-steady clock for alarms or timing, if you actually care about anything resembling accuracy.)
On to stopwatch.
So, I’m a little bit confused about how stopwatch is supposed to be used. Real-life stop watches have two buttons: start/stop, and split/reset. The latter does “split” when the stopwatch is running, and “reset” when it is not, so it is really two operations, which means a stopwatch technically has three buttons: start/stop, split, and reset. And, since start and stop are also technical distinct operations that makes four buttons. However, when I look at your interface, I see five buttons: start, stop, split, reset… and “update”. What is “update” supposed to do? (I am asking rhetorically, because I can see what it does. I am just pointing out that it doesn’t make sense from an interface perspective. So, if nothing else, it should be private.) | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
I would also suggest that while a real life stopwatch has those four functions, two are not really necessary. There is actually no reason a virtual stopwatch has to be able stop, or reset. In real life, it is so you can time something that may be interrupted: you start the stopwatch, then when an interruption happens, you stop it, then when the interruption is over you start it again. But this is because, in real life, it is impractical to have two (or more) stopwatches—one for before the interruption, and one for after (and another one for every other interruption that may happen). But with virtual stopwatches… why not? You can have as many as you want. There are no real practical limitations. If you want to time around interruptions, simply make another stopwatch, and then sum up the durations.
Watch how much this line of thinking simplifies things:
template <clock_type Clock>
class stopwatch
{
typename Clock::time_point _start = Clock::now(); | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
public:
// default constructor, copy/move ops and destructor are fine
constexpr auto split() const noexcept
{
return Clock::now() - _start;
}
};
No joke, that’s it. That’s literally all you need for every conceivable use of a stopwatch.
It starts in the constructor. It never stops, but that’s fine because it’s zero cost. Since it never stops, it never needs resetting… though if you do want to “reset”, you can just do sw = stopwatch{};. And it gives the splits on demand. Everything you need.
using system_alarm = alarm<std::chrono::system_clock>;
using steady_alarm = alarm<std::chrono::steady_clock>;
using high_resolution_alarm = alarm<std::chrono::high_resolution_clock>;
using utc_alarm = alarm<std::chrono::utc_clock>;
using tai_alarm = alarm<std::chrono::tai_clock>;
using gps_alarm = alarm<std::chrono::gps_clock>; | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
Using some standard clocks as defaults is not a bad idea. However, trying to define an alias for every single standard clock type is a bit gratuitous. You will ultimately fall behind as new clocks are added. Even now, you’ve forgotten std::chrono::file_clock.
But there is a deeper design issue of what you are trying to say about your types and API by defining aliases like this. Doing this basically says that you think all these alarm types are valid. But… are they?
Consider a timer. If the purpose of a timer is to wait a specified time period, then the only type of clock that makes sense for a timer is a steady clock. Using a non-steady clock with a timer is arguably a mistake. If a programmer really, really wants to use a non-steady clock with a timer, then I suppose you can allow it, but you should not bless it.
So what does the above paragraph mean to an API? Well, it means that you should provide only steady clocks for the timer type. That way you send the message that only steady clocks are “correct”. Of course, if a programmer really wants to use a non-steady clock, they can… but you should not encourage that.
That would mean:
template <clock_type Clock>
class timer { /* ... */ };
using steady_timer = timer<std::chrono::steady_clock>;
// no other aliases!
But, since there is only a single steady clock, we can do even better:
template <clock_type Clock>
class basic_timer { /* ... */ };
using timer = basic_timer<std::chrono::steady_clock>;
// no other aliases! | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
using timer = basic_timer<std::chrono::steady_clock>;
// no other aliases!
Now a user who takes the easy path and simply uses timer gets the correct type, and the correct behaviour. But a coder who wants to risk using a non-steady clock can always do basic_timer<other_clock_type>, which is syntactically noisier, but that’s good because it is dangerous and unwise. If the coder wants to alias it to something shorter to disguise the danger of it, that’s on their head.
For alarms, a reasonable user may want an alarm that depends on system time, even though that is not steady. If a user is running a program that schedules an operation for later in the afternoon, and then the user changes the system clock… well, I mean, that’s on the user’s head. It would probably make sense for just alarm to refer to system time, but also to have aliases for UTC and TAI. GPS time is a fuzzier issue. It probably doesn’t make sense to provide aliases for file time or the high-resolution clock, or even steady_clock (because that has no real connection to real-life time points). This is something you, the designer, will have to think about.
For a stopwatch, again, the only sensible option is a steady clock, though you might also want to provide an alias to the high-resolution clock with a warning that it might give bullshit results in some situation. Or you could provide the alias if and only if std::chrono::high_resolution_clock::is_steady is true (though, I am not a fan of having APIs conditionally vary like that). Again, that is a design decision for you to make. But the key point I’m making is: | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
The easiest, most natural choice should always be the best choice. For timers and stopwatches, the best choice is to use a steady clock. So that’s what timer and stopwatch should do.
Other choices that are okay, but not the best, should be possible, but require a bit more from the coder to get at. Using a non-steady clock with a timer or stopwatch is okay, so long as the risks are understood. Requiring the coder to spell out basic_timer<std::chrono::high_resolution_clock> forces them to think a little bit harder about whether that’s really what they want to do (it almost never is).
Choices that are just plain objectively wrong should be banned completely. For example, using anything but a clock type as the template parameter. This is why I recommended using a concept.
That is the essence of a good API design.
And finally:
}
When a stray brace appears in a source code file hundreds (or, sometimes thousands) of lines away from its sibling, it’s a good idea to comment it so the connection is clear. For example:
namespace mak::time {
// ... ~400 lines of code ...
} // namespace mak::time
That’s all for the review!
In summary:
Avoid over-complication. Figure out the essence of a thing, and only add the functionally required to capture that essence.
All timer needs to do is run its function when time has expired, and maybe be cancelled (that is, be told not to run the function when time has expired); it does not need to be able to be enabled/disabled repeatedly, have its set time changed repeated, or have its function changed repeatedly. All that unnecessary stuff adds is complexity, and it often makes extra capabilities (like being thread-safe) difficult or impossible.
Even when functionality is “free” to add (it doesn’t require extra data members or efficiency costs)… resist the temptation. Every thing a class can do must be tested, so no functionality is really free. KISS, and YAGNI. | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
c++, c++20, stl
Less horiztonal whitespace, more vertical whitespace.
Lining up everything horizontally makes little sense… and it makes absolutely zero sense when you are lining up stuff that isn’t even visible on a single screen. Unless stuff is directly next to each other, vertically—like with a list of type aliases— horizontal alignment doesn’t matter. (For example, horizontally aligning function prologues when entire function bodies separate them? Absolutely ridiculous.)
Asynchronous support is cool, but expensive, because it usually requires dynamic allocation to allow stuff to exist across non-overlapping scopes.
It’s probably best to keep simple types simple, and, if desired, have asynchronous types available only as an option for those willing to pay the cost.
The design of an API signals to users how a library or class is supposed to be used. The natural, correct, and intended use should be the easiest thing to do. Indeed, doing anything else should often be hard. Yes, allowing flexibility is a good thing, but whenever something would be dangerous or unwise, it should be harder to do, if not impossible.
That’s all! Have a good one! | {
"domain": "codereview.stackexchange",
"id": 45185,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, stl",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.