text
stringlengths
1
2.12k
source
dict
java, mysql, jdbc return id.equals(dbId) && name.equals(dbName) && surname.equals(dbSurname); } } } Just to summarize, my question is: does this code follow common best practices in the java.sql word, or is this solution a bad one? Am I not seeing a much simpler way to extract and store the db data in a Java application? Answer: I have a couple of more direct alternatives. Depending of a larger context. public boolean checkCredentials(String id, String name, String surname) throws SQLException { var sql = """ select w.workerName, w.workerSurname from worker w where w.ID = ? """; try (var st = connection.prepareStatement(sql)) { st.setString(1, id); try (var resultSet = st.executeQuery()) { record Worker(String id, String name, String surname) { }; if (resultSet.next()) { Worker worker = new Worker(id, resultSet.getString(2), resultSet.getString(3)); return worker.equals(new Worker(id, name, surname)); } return false; } } } public boolean checkCredentials(String id, String name, String surname) throws SQLException { var sql = """ select 1 from worker w where w.ID = ? and m.name = ? and surname = ? """; try (var st = connection.prepareStatement(sql)) { st.setString(1, id); st.setString(2, name); st.setString(3, surname); try (var resultSet = st.executeQuery()) { return resultSet.next(); } } }
{ "domain": "codereview.stackexchange", "id": 44261, "lm_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, mysql, jdbc", "url": null }
java, mysql, jdbc public boolean checkCredentials(String id, String name, String surname) throws SQLException { var sql = """ exists (select * from worker w where w.ID = ? and m.name = ? and surname = ?) """; try (var st = connection.prepareStatement(sql)) { st.setString(1, id); st.setString(2, name); st.setString(3, surname); try (var resultSet = st.executeQuery()) { return resultSet.next() && resultSet.getBoolean(1); } } } try-with-resources will ensure closing of the variable, even when an exception is thrown, or a return happens. Needed for statement and result set. Shuffling a record into a Map results in an ugly usage, often "improved" by constants for map keys (fields). It also poses an overhead. Granted a map is more generally usable, but it is awkward when needing to do something with the fields. A List is also not needed. Assuming that ID is the primary key. BTW use interfaces Map and List rather than the implementing classes. This allows combinations of List.of(...) and is more versatile. Here I offer an alternative of a record class, which also offers an equals. Best would be to leave the check to the database. The other methods are not needed. Laudable is the multiline string for the SQL. Of course the alias w is not needed here. One questionable issue is whether the ID does not suffice. I assume that name and surname are extra checks against stealing others' IDs or such.
{ "domain": "codereview.stackexchange", "id": 44261, "lm_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, mysql, jdbc", "url": null }
lua Title: Get list of buffers from current neovim instance Question: The function below is written in Lua and returns the list of buffers from the current neovim session, it also allows the option to specify a optional table (object) as a parameter, with a listed property to filter the type of buffer returned by the function (only listed buffers, or every single one). local function get_buffers(options) local buffers = {} for buffer = 1, vim.fn.bufnr('$') do local is_listed = vim.fn.buflisted(buffer) == 1 if options.listed and is_listed then table.insert(buffers, buffer) else table.insert(buffers, buffer) end end return buffers end return get_buffers The if..else part seems a little bit off for me, I'm not sure if it can be improved, but something tells me that there's some way to make this less repetitive Answer: The only case when you don't want a buffer included is when options.listed is truthy and is_listed is falsy In every other case you want it included. If my understanding is correct you can simplify the if to a single branch: ... local is_listed = vim.fn.buflisted(buffer) == 1 if not (options.listed and is_listed) then table.insert(buffers, buffer) end ... That code is still calculating is_listed on every iteration. If you move it inside the conditional and remove the parenthesis, the code will be a bit more efficient (is_listed won't be calculated at all when options.listed is falsy) ... if not options.listed or vim.fn.buflisted(buffer) ~= 1 then table.insert(buffers, buffer) end ...
{ "domain": "codereview.stackexchange", "id": 44262, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "lua", "url": null }
lua I think that is good enough. There's some extra perf changes chat can be done. options.listed and vim.fn could be localized into a local variable to make it slightly faster, too. And using table.insert is slower than direct table insertion. Final result: local function get_buffers(options) local buffers = {} local len = 0 local options_listed = options.listed local vim_fn = vim.fn local buflisted = vim_fn.buflisted for buffer = 1, vim_fn.bufnr('$') do if not options_listed or buflisted(buffer) ~= 1 then len = len + 1 buffers[len] = buffer end end return buffers end There is an API question that is still worth mentioning. In most cases, I try to avoid boolean parameters completely. Instead, consider using two functions: get_all_buffers() (no params) to get all buffers, and get_listed_buffers() (no params) to get only the listed buffers.
{ "domain": "codereview.stackexchange", "id": 44262, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "lua", "url": null }
c++, performance, parsing, csv Title: Read a large CSV order book Question: I am trying to read entries of my CSV file into an entries vector whose data type is object OrderBookEntry, which is an object that stores the tokenized variables from the CSV line which itself is converted through the function tokenise. My problem is that my CSV file has around a million lines and it takes over 30 seconds to load; how can I reduce this? This is my code that actually reads lines from the file and converts them into entries. std::vector<OrderBookEntry> CSVReader::readCSV(std::string csvFilename) { std::vector<OrderBookEntry> entries; std::ifstream csvFile{csvFilename}; std::string line; if (csvFile.is_open()) { while(std::getline(csvFile, line)) { try { OrderBookEntry obe = stringsToOBE(tokenise(line, ',')); entries.push_back(obe); //std::cout << "pushing entry" << std::endl; }catch(const std::exception& e) { //std::cout << "CSVReader::readCSV bad data" << std::endl; } }// end of while } std::cout << "CSVReader::readCSV read " << entries.size() << " entries" << std::endl; return entries; }
{ "domain": "codereview.stackexchange", "id": 44263, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, parsing, csv", "url": null }
c++, performance, parsing, csv This is the part of my code that tokenises the read line: std::vector<std::string> CSVReader::tokenise(std::string csvLine, char separator) { std::vector<std::string> tokens; signed int start, end; std::string token; start = csvLine.find_first_not_of(separator, 0); do{ end = csvLine.find_first_of(separator, start); if (start == csvLine.length() || start == end) break; if (end >= 0) token = csvLine.substr(start, end - start); else token = csvLine.substr(start, csvLine.length() - start); tokens.push_back(token); start = end + 1; }while(end > 0); return tokens; } This is the part of my code that converts the tokens into a suitable object to work with: OrderBookEntry CSVReader::stringsToOBE(std::vector<std::string> tokens) { double price, amount; if (tokens.size() != 5) // bad { //std::cout << "Bad line " << std::endl; throw std::exception{}; } // we have 5 tokens try { price = std::stod(tokens[3]); amount = std::stod(tokens[4]); }catch(const std::exception& e){ std::cout << "Bad float! " << tokens[3]<< std::endl; std::cout << "Bad float! " << tokens[4]<< std::endl; throw; } OrderBookEntry obe{price, amount, tokens[0], tokens[1], OrderBookEntry::stringToOrderBookType(tokens[2])}; return obe; } Do advise on how I can make the code faster.
{ "domain": "codereview.stackexchange", "id": 44263, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, parsing, csv", "url": null }
c++, performance, parsing, csv Do advise on how I can make the code faster. Answer: Avoid throwing exceptions if they are not exceptional You throw exceptions on parse errors, but in C++, exceptions are free if you don't throw them (i.e., you don't pay for the try-catch), but they can be very slow when you do throw. So you should only use that for exceptional situations, as the name implies. If your input file has lots of empty lines or lines with comments instead of data, then you throw exceptions a lot, slowing down your code significantly. Consider using a different way to signal that a line could not be parsed, for example by returning a std::optional<OrderBookEntry> from stringsToOBE(). Avoid memory allocations std::vector and std::string perform memory allocations under the hood. As slepic mentioned, pass std::string by const reference where possible. But you can also consider using std::string_view. In particular, tokenise() could take csvLine as a std::string_view and return a std::vector<std::string_view>. This way it doesn't pay for string allocations. If you know each line should have exactly 5 tokens, then you could also consider returning a std::array<std::string_view, 5>.
{ "domain": "codereview.stackexchange", "id": 44263, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, parsing, csv", "url": null }
java, mvc, swing Title: Java Sound GUI using MVC model Question: I have made a Java Swing application that detects and displays audio pitch and level from an input (e.g microphone). I would like feedback on the current structure of my project, I'm attempting to follow the modified MVC pattern found here, diagram of my project below: I'm seeking feedback on the structure and any other criticisms. Some thoughts: I don't know if I need the PitchLabel class, it's quite small and doesn't do much, so could be needless. I start a thread for the audio dispatcher (from a public pitch detection API "TarsosDSP"), but I'm not sure if this is the best way to implement it. I only have one user interface on the App's JFrame, that being the record button, but should I add another I think I would need to change the model, to encapsulate the controllers. App.java - GUI import com.formdev.flatlaf.FlatLightLaf; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; public class App { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { FlatLightLaf.setup(); JFrame mainFrame = new JFrame("JavaTuner"); mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); mainFrame.setSize(1024, 600); JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(new EmptyBorder(25, 50, 25, 50)); AudioBar bar = new AudioBar(); bar.setPreferredSize(new Dimension(20, 100)); panel.add(bar, BorderLayout.EAST); PitchLabel pitchLabel = new PitchLabel("Pitch: ", SwingConstants.CENTER); Action recordBtnAction = new RecordButtonAction(bar, pitchLabel); recordBtnAction.putValue(Action.NAME, "Start Recording"); JToggleButton recordBtn = new JToggleButton(recordBtnAction);
{ "domain": "codereview.stackexchange", "id": 44264, "lm_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, mvc, swing", "url": null }
java, mvc, swing JToggleButton recordBtn = new JToggleButton(recordBtnAction); panel.add(pitchLabel, BorderLayout.CENTER); mainFrame.setContentPane(panel); mainFrame.add(recordBtn, BorderLayout.WEST); mainFrame.setVisible(true); } }); } } RecordButtonAction.java - Acts when the 'Start Recording' button is pressed import javax.swing.*; import java.awt.event.ActionEvent; public class RecordButtonAction extends AbstractAction { private final AudioBar bar; private final PitchLabel label; private Mic m; public RecordButtonAction(AudioBar bar, PitchLabel label){ this.bar = bar; this.label = label; } @Override public void actionPerformed(ActionEvent e) { JToggleButton toggle = (JToggleButton)e.getSource(); if(toggle.isSelected()){ toggle.setText("Stop Recording"); System.out.println("Streaming Started"); m = new Mic(RecordButtonAction.this); } else{ toggle.setText("Start Recording"); System.out.println("Recording Ended"); m.stopRecording(); updateLabel("Stopped Recording"); } } public void updateLabel(String str){ label.setText(str); } public void updateAudioBar(float rms) { bar.setAmplitude(rms); } } Mic.java - Responsible for recording audio from input import be.tarsos.dsp.AudioDispatcher; import be.tarsos.dsp.AudioEvent; import be.tarsos.dsp.io.jvm.JVMAudioInputStream; import be.tarsos.dsp.pitch.*; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.TargetDataLine; import java.util.*;
{ "domain": "codereview.stackexchange", "id": 44264, "lm_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, mvc, swing", "url": null }
java, mvc, swing public class Mic{ private final RecordButtonAction recordButtonAction; private static AudioDispatcher dispatcher; private TargetDataLine targetLine; private AudioInputStream inputStream; public Mic(RecordButtonAction recordBtnAction) { this.recordButtonAction = recordBtnAction; this.initDataLines(); this.startRecording(); } private void initDataLines() { AudioFormat format = new AudioFormat(44100.0F, 16, 2, true, false); try { DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); targetLine = (TargetDataLine)AudioSystem.getLine(info); targetLine.open(); inputStream = new AudioInputStream(targetLine); } catch (LineUnavailableException e) { e.printStackTrace(); } } private void startRecording() { JVMAudioInputStream audioInputStream = new JVMAudioInputStream(inputStream); targetLine.start(); float sampleRate = 44100; int bufferSize = 6000; int overlap = 0; dispatcher = new AudioDispatcher(audioInputStream, bufferSize, overlap); dispatcher.addAudioProcessor(new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.YIN, sampleRate, bufferSize, new Pitch(recordButtonAction))); new Thread(dispatcher, "Mic Audio Dispatch Thread").start(); } public void stopRecording(){ dispatcher.stop(); targetLine.close(); targetLine.stop(); } } Pitch.java - Responsible for pitch detection, implements interface from TarsosDSP public pitch detection API import be.tarsos.dsp.AudioEvent; import be.tarsos.dsp.pitch.PitchDetectionHandler; import be.tarsos.dsp.pitch.PitchDetectionResult; import java.util.ArrayDeque; import java.util.Queue; public class Pitch implements PitchDetectionHandler { private final int RMS_STORE_SIZE = 10;
{ "domain": "codereview.stackexchange", "id": 44264, "lm_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, mvc, swing", "url": null }
java, mvc, swing public class Pitch implements PitchDetectionHandler { private final int RMS_STORE_SIZE = 10; // For testing purposes private final double MIC_AMBIENCE_RMS = 0.000711; private final RecordButtonAction recordBtnAction; private final Queue<Double> previousRMSUnits; private double avgPreviousRMSUnits = 0; public Pitch(RecordButtonAction recordBtnAction){ this.recordBtnAction = recordBtnAction; previousRMSUnits = new ArrayDeque<Double>(); } // handlePitch is called after the Mic.startRecording() method, and runs continuously // until Mic.stopRecording() is called @Override public void handlePitch(PitchDetectionResult pitchDetectionResult, AudioEvent audioEvent) { if(previousRMSUnits.size() == RMS_STORE_SIZE){ previousRMSUnits.remove(); previousRMSUnits.add(audioEvent.getRMS()); double sum = previousRMSUnits.stream().reduce(Double::sum).get(); avgPreviousRMSUnits = sum / RMS_STORE_SIZE; } else{ previousRMSUnits.add(audioEvent.getTimeStamp()); } recordBtnAction.updateAudioBar((float) (avgPreviousRMSUnits + MIC_AMBIENCE_RMS) * 5); if(pitchDetectionResult.getPitch() != -1){ double timeStamp = audioEvent.getTimeStamp(); float pitch = pitchDetectionResult.getPitch(); recordBtnAction.updateLabel((String.format("Pitch detected at %.2fs: %.2fHz\n", timeStamp, pitch*2))); } } } AudioBar.java - Graphics component, a volume bar import javax.swing.*; import java.awt.*; // Using implementation from Radiodef's stackoverflow answer // Link: https://stackoverflow.com/questions/26574326/how-to-calculate-the-level-amplitude-db-of-audio-signal-in-java public class AudioBar extends JComponent { private int meterWidth = 10; private float amp = 0f; public void setAmplitude(float amp) { this.amp = Math.abs(amp); repaint(); }
{ "domain": "codereview.stackexchange", "id": 44264, "lm_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, mvc, swing", "url": null }
java, mvc, swing public void setAmplitude(float amp) { this.amp = Math.abs(amp); repaint(); } public void setMeterWidth(int meterWidth) { this.meterWidth = meterWidth; } @Override protected void paintComponent(Graphics g) { int w = Math.min(meterWidth, getWidth()); int h = getHeight(); int x = getWidth() / 2 - w / 2; int y = 0; g.setColor(Color.LIGHT_GRAY); g.fillRect(x, y, w, h); g.setColor(Color.BLACK); g.drawRect(x, y, w - 1, h - 1); int a = Math.round(amp * (h - 2)); g.setColor(Color.GREEN); g.fillRect(x + 1, y + h - 1 - a, w - 2, a); } @Override public Dimension getMinimumSize() { Dimension min = super.getMinimumSize(); if (min.width < meterWidth) min.width = meterWidth; if (min.height < meterWidth) min.height = meterWidth; return min; } @Override public Dimension getPreferredSize() { Dimension pref = super.getPreferredSize(); pref.width = meterWidth; return pref; } @Override public void setPreferredSize(Dimension pref) { super.setPreferredSize(pref); setMeterWidth(pref.width); } } PitchLabel.java - Graphics component, a label that displays the pitch of audio streaming import javax.swing.*; import java.awt.*; public class PitchLabel extends JLabel { private final Font f = new Font("Segoe UI", Font.PLAIN, 22); public PitchLabel(String text, int horizontalAlignment) { super(text, horizontalAlignment); this.setFont(f); } @Override public void setText(String text) { super.setText(text); } } Code in git repo here
{ "domain": "codereview.stackexchange", "id": 44264, "lm_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, mvc, swing", "url": null }
java, mvc, swing Answer: It's not a bad implementation. I did find the architecture a bit questionable at times, but it's definitely not awful. That said, I do find the communication between components to be a bit muddled, and the RecordButtonAction class in particular feels a bit overloaded. But this leaves the question: How do we update the display (audiobar and label) upon receiving an event? An intuitive way to do that would be to either send that event to each of those components directly by making them implement PitchDetectionHandler, or to have some parent component which does that. Since there is a single JPanel which contains all presentation-related components, making that panel handle the events isn't unreasonable, but some might argue that it could be more future-proof to use multiple PitchDetectionHandlers instead. Either way, Mic could then take a PitchDetectionHandler (or perhaps a Collection of them), which it attaches to the dispatcher. That way, once the Mic has been created, the record button needn't know who actually listens to the mic - the mic knows who to talk to, and the record button knows about the mic, and that's enough. Makes for a fairly neat data flow in my eyes. I also have a few other comments about a few of the classes RecordButtonAction The idea behind Action is that the action provides state that the button respects, while the action itself needn't know about the button (and can thus be attached to multiple buttons at once if need be). This action, however, explicitly checks the state of the button it's attached to and directly modifies the button as well. Conventionally, the state would be stored on the action rather than the button, and instead of updating the button directly, the action would update its own properties (NAME and SELECTED_KEY seem appropriate here)
{ "domain": "codereview.stackexchange", "id": 44264, "lm_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, mvc, swing", "url": null }
java, mvc, swing And, briefly going back to the subject of communication, updateLabel and updateAudioBar kind of feel like they don't belong here. The Action itself never actually touches the AudioBar, so expecting others to go through this Action to get to it feels a bit strange to me. Mic initDataLines swallows an exception and returns successfully, but if that exception was thrown in the first place, the Mic object will not have a valid audio line, and future uses of the Mic will probably fail with something akin to a NullPointerException or IllegalStateException. I'd argue that initDataLines (and, by extension, the constructor itself) should be declared as throws LineUnavailableException, or at the very least the exception could be wrapped in an unchecked exception and re-thrown to make sure it fails sooner rather than later. Pitch handlePitch adding timestamps instead of RMSs at the start looks like it might be a mistake. I'm also not seeing an obvious reason to not calculate the average while there are fewer than 10 entries in the RMS list. PitchLabel In its current state, I don't think this is terribly useful. All it is is a JLabel that sets its own font to Segoe UI. It's only used in one place. It might be easier to just create a regular JLabel and set its font manually. Put that all together, what do you get? Well, there are many ways to do it, but it might look a bit like the following: App.java import java.awt.BorderLayout; import java.awt.EventQueue; import javax.sound.sampled.LineUnavailableException; import javax.swing.JFrame; import javax.swing.JToggleButton; import javax.swing.JOptionPane; import javax.swing.WindowConstants; import javax.swing.border.EmptyBorder;
{ "domain": "codereview.stackexchange", "id": 44264, "lm_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, mvc, swing", "url": null }
java, mvc, swing public class App { public static void main(String[] args) throws LineUnavailableException { EventQueue.invokeLater(() -> { try { JFrame mainFrame = new JFrame("JavaTuner"); mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); mainFrame.setSize(1024, 600); PitchPanel displayPanel = new PitchPanel(); JToggleButton recordBtn = new JToggleButton(new RecordButtonAction(new Mic(displayPanel))); mainFrame.setContentPane(displayPanel); mainFrame.add(recordBtn, BorderLayout.WEST); mainFrame.setVisible(true); } catch (LineUnavailableException ex) { JOptionPane.showMessageDialog(null, "Mic not available."); } }); } } AudioBar.java (unchanged) Mic.java import be.tarsos.dsp.AudioDispatcher; import be.tarsos.dsp.io.jvm.JVMAudioInputStream; import be.tarsos.dsp.pitch.PitchDetectionHandler; import be.tarsos.dsp.pitch.PitchDetectionResult; import be.tarsos.dsp.pitch.PitchProcessor; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.TargetDataLine; public class Mic { private static final AudioFormat AUDIO_FORMAT = new AudioFormat(44100.0F, 16, 2, true, false); private AudioDispatcher dispatcher; private AudioInputStream inputStream; private final TargetDataLine line; private final PitchDetectionHandler onDetection; public Mic(PitchDetectionHandler onDetection) throws LineUnavailableException { this.onDetection = onDetection; DataLine.Info info = new DataLine.Info(TargetDataLine.class, AUDIO_FORMAT); line = (TargetDataLine) AudioSystem.getLine(info); this.startRecording(); }
{ "domain": "codereview.stackexchange", "id": 44264, "lm_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, mvc, swing", "url": null }
java, mvc, swing public void startRecording() throws LineUnavailableException { line.open(); JVMAudioInputStream audioInputStream = new JVMAudioInputStream(new AudioInputStream(line)); line.start(); float sampleRate = 44100; int bufferSize = 6000; int overlap = 0; dispatcher = new AudioDispatcher(audioInputStream, bufferSize, overlap); dispatcher.addAudioProcessor(new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.YIN, sampleRate, bufferSize, onDetection)); new Thread(dispatcher, "Mic Audio Dispatch Thread").start(); } public void stopRecording() { dispatcher.stop(); line.stop(); line.close(); } } PitchPanel.java import be.tarsos.dsp.AudioEvent; import be.tarsos.dsp.pitch.PitchDetectionHandler; import be.tarsos.dsp.pitch.PitchDetectionResult; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.util.ArrayDeque; import java.util.Queue; import javax.sound.sampled.LineUnavailableException; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; public class PitchPanel extends JPanel implements PitchDetectionHandler { private static final int RMS_STORE_SIZE = 10; // For testing purposes private static final double MIC_AMBIENCE_RMS = 0.000711; private static final Font PITCH_LABEL_FONT = new Font("Segoe UI", Font.PLAIN, 22); private final JLabel pitchLabel; private final AudioBar bar; private final Queue<Double> previousRMSUnits = new ArrayDeque<>(); public PitchPanel() throws LineUnavailableException { super(new BorderLayout()); setBorder(new EmptyBorder(25, 50, 25, 50)); bar = new AudioBar(); bar.setPreferredSize(new Dimension(20, 100)); add(bar, BorderLayout.EAST); pitchLabel = new JLabel("Pitch: ", SwingConstants.CENTER);
{ "domain": "codereview.stackexchange", "id": 44264, "lm_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, mvc, swing", "url": null }
java, mvc, swing pitchLabel = new JLabel("Pitch: ", SwingConstants.CENTER); pitchLabel.setFont(PITCH_LABEL_FONT); add(pitchLabel, BorderLayout.CENTER); } @Override public void handlePitch(PitchDetectionResult result, AudioEvent event) { double avgPreviousRMSUnits = 0; previousRMSUnits.add(event.getRMS()); if (previousRMSUnits.size() > RMS_STORE_SIZE) { previousRMSUnits.remove(); double sum = previousRMSUnits.stream().reduce(Double::sum).get(); avgPreviousRMSUnits = sum / RMS_STORE_SIZE; } bar.setAmplitude((float) (avgPreviousRMSUnits + MIC_AMBIENCE_RMS) * 5); if (result.getPitch() != -1){ double timeStamp = event.getTimeStamp(); float pitch = result.getPitch(); pitchLabel.setText(String.format("Pitch detected at %.2fs: %.2fHz\n", timeStamp, pitch * 2)); } } } RecordButtonAction.java import javax.sound.sampled.LineUnavailableException; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JOptionPane; public class RecordButtonAction extends AbstractAction { private final Mic mic; private boolean isRecording; { isRecording = false; updateValues(); } public RecordButtonAction(Mic mic) throws LineUnavailableException { this.mic = mic; } @Override public void actionPerformed(ActionEvent event) { try { if (isRecording) { mic.stopRecording(); } else { mic.startRecording(); } isRecording = ! isRecording; updateValues(); } catch (LineUnavailableException ex) { JOptionPane.showMessageDialog(null, "Mic not available, try again later.", "Error", JOptionPane.ERROR_MESSAGE); } }
{ "domain": "codereview.stackexchange", "id": 44264, "lm_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, mvc, swing", "url": null }
java, mvc, swing private void updateValues() { putValue(SELECTED_KEY, isRecording); putValue(NAME, isRecording ? "Stop recording" : "Record"); } }
{ "domain": "codereview.stackexchange", "id": 44264, "lm_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, mvc, swing", "url": null }
makefile, make Title: Makefile: Include a generated-on-demand file Question: For the record, I'm writing according to the NEXT - Version 5 of Single Unix Specification, which is Issue 8 if you count the days when it was named XPG. In this new standard, a few new already-common-place features are being added, such as delayed and immediate expansion macros, and re-making of include files. Parts of the proposed changes are available here. My end-goal is to include something generated by more complex scripts, and this is just me practicing. For example, I want to create a "make" prerequisite listing of C/C++ include files; Or I want to extract a list of contributors to my project, and put this list in the "make" target for documentations. What I'm trying to achieve, is to include a file in the main Makefile, and this file is always generated on-demand whenever the build targets are requested to make (thus excluding auxiliary targets such as clean, install, etc.) Here's my Makefile .PHONY: all clean timestamping all: main.c ${CC} -o main -D LIB_RET=1${lib_ret} main.c clean: rm -f main include.mk time.stamp all: timestamping timestamping: date -u '+%Y-%m-%d T %H:%M:%S %Z' > time.stamp time.stamp:; : include.mk: time.stamp printf 'lib_ret='`date +%S` > include.mk include include.mk Here's "main.c": #include <stdio.h> int main(void){ return LIB_RET; } I'm quite satisfied with the current form of it, but I'm sure suggests for improvements will be plenty. I'm mostly concerned about the portability of this Makefile on FOSS makes, such as GNU make and pmake. One part I'm not satisified is that the commands for timestamping and time.stamp gets executed twice on the make supplied by the Xcode toolchains (which uses GNU Make version 3.81 as of Xcode Version 14.2 (14C18) 2022-12-27). Answer: It seems strange to be writing a non-text file here (i.e. lacking a final newline): printf 'lib_ret='`date +%S` > include.mk
{ "domain": "codereview.stackexchange", "id": 44265, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "makefile, make", "url": null }
makefile, make printf 'lib_ret='`date +%S` > include.mk I would have written it with a newline, using date +lib_ret=%S >$@ It's also strange that it depends on time.stamp but doesn't use that dependency. It's like you intended date -d $(cat $<) +lib_ret=%S >$@ Or perhaps not have the timestamping and time.stamp targets at all (and have .PHONY: include.mk instead). Instead of all: main.c, we could let the default rules build main from main.c: CFLAGS += -DLIB_RET=1${lib_ret} all: main If we can assume GNU Make is available (and that's a good assumption these days), then we could simplify the entire Makefile to .PHONY: main clean main: CFLAGS += -DLIB_RET=$(shell date +1%S) clean:: $(RM) main Even without GNU Make, we could use $$(date +1%S) in CFLAGS. And I'd recommend including at least -Wall -Wextra when compiling C sources. Be aware that the whole concept of including timestamps in your builds is something the free software community has made great efforts to eliminate in recent years in the pursuit of reproducible builds, so I strongly urge you to reconsider whether this is something you really should be doing at all.
{ "domain": "codereview.stackexchange", "id": 44265, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "makefile, make", "url": null }
python, performance, vectors, easing Title: Built a Vector2 class with easing functions, that can be unpacked Question: import math def root(cls, nth): return cls.__root__(nth) class Vector2(object): def __init__(self, x=0.0, y=0.0): self.points = (x, y) self._index = 0 @property def x(self): return self.points[0] @property def y(self): return self.points[1] # __str__ for customers, __repr__ for developers def __str__(self): return "(%s, %s)" % (self.x, self.y) def __repr__(self): return "%r(%r)" % (self.__class__, self.__dict__) def __iter__(self): self.index = 0 return iter((self.x, self.y)) def __next__(self): if self.index >= len(self.points): self._index = 0 result = self.points[self.index] self._index += 1 return result def __getitem__(self, index): return self.points[index] def __setitem__(self, index, value): self.points[index] = value self.points = tuple(*self.points) # Right Hand Side == rhs def __add__(self, rhs): '''Add two Vector2 together''' return Vector2(self.x + rhs.x, self.y + rhs.y) def __sub__(self, rhs): '''Subtract one Vector2 from another''' return Vector2(self.x - rhs.x, self.y - rhs.y) def __neg__(self): '''Return Vector2 in reverse direction''' return Vector2(-self.x, -self.y) def __mul__(self, scalar): '''Multiply Vector2 by a scalar''' return Vector2(self.x * scalar, self.y * scalar) def __truediv__(self, scalar): '''Divide Vector2 by a scalar''' return Vector2(self.x / scalar, self.y / scalar) def __floordiv__(self, scalar): '''Divide Vector2 by a scalar''' return Vector2(self.x // scalar, self.y // scalar)
{ "domain": "codereview.stackexchange", "id": 44266, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, vectors, easing", "url": null }
python, performance, vectors, easing def __mod__(self, scalar): '''Return floated modulo Vector by a scalar''' return Vector2(math.fmod(self.x, scalar), math.fmod(self.y, scalar)) def __pow__(self, scalar): '''Return exponential pow of Vector, use root for nth roots''' return Vector2(pow(self.x, scalar), pow(self.y, scalar)) def __root__(self, nth): '''Return the nth root of a vector''' return Vector2(pow(self.x, 1/nth), pow(self.y, 1/nth)) def __round__(self): '''Round numbers to integer''' return Vector2(round(self.x), round(self.y)) def __abs__(self): '''Return absolute values of Vector''' return Vector2(abs(self.x), abs(self.y)) def __int__(self): '''Return integer values of Vector''' return Vector2(int(self.x), int(self.y)) def __float__(self): '''Return floating point values of Vector''' return Vector2(float(self.x), float(self.y)) def __complex__(self): '''Return absolute values of Vector''' return Vector2(complex(self.x), complex(self.y)) def __ceil__(self): '''Return ceiling values of Vector''' return Vector2(math.ceil(self.x), math.ceil(self.y)) def __floor__(self): '''Return floored values of Vector''' return Vector2(math.floor(self.x), math.floor(self.y)) def __trunc__(self): '''Return absolute values of Vector''' return Vector2(math.trunc(self.x), math.trunc(self.y)) def __bool__(self): '''If Vector is not (0.0, 0.0) return True''' if self.x != 0 and self.y != 0: return True else: return False def __lt__(self, rhs): '''Truthy statement of less than''' if self.x < rhs.x and self.y < rhs.y: return True else: return False def __le__(self, rhs): '''Truthy statement of less than or equal to''' if self.x <= rhs.x and self.y <= rhs.y: return True else: return False
{ "domain": "codereview.stackexchange", "id": 44266, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, vectors, easing", "url": null }
python, performance, vectors, easing def __eq__(self, rhs): '''Truthy statement of equal to''' if self.x == rhs.x and self.y == rhs.y: return True else: return False def __ne__(self, rhs): '''Truthy statement of not equal to''' if self.x != rhs.x and self.y != rhs.y: return True else: return False def __gt__(self, rhs): '''Truthy statement of greater than''' if self.x > rhs.x and self.y > rhs.y: return True else: return False def __ge__(self, rhs): '''Truthy statement of less than or equal to''' if self.x >= rhs.x and self.y >= rhs.y: return True else: return False def __invert__(self): '''Return rounded Vector by inverted bitwise not''' x, y = round(self.x), round(self.y) return Vector2(~x, ~y) def __reversed__(self): '''Return Vector x,y swapped''' return Vector2(*tuple(reversed(self.points))) @staticmethod def from_points(P1, P2): return Vector2(P2[0] - P1[0], P2[1] - P1[1]) @property def magnitude(self): return pow((self.x**2 + self.y**2), 1/2) def magnitude_squared(self): '''Return the squared magnitude (length) of the Vector2''' return self.x**2 + self.y**2 @property def normalized(self): magnitude = self.magnitude self.points = (self.x / magnitude, self.y / magnitude) return Vector2(self.x, self.y) def lerp(self, rhs, scalar): '''Linear Interpolation''' return self + (rhs - self) * scalar def easeInQuad(self, rhs, scalar): '''Quadratic easing''' return self.lerp(rhs, scalar**2) def easeOutQuad(self, rhs, scalar): '''Quadratic easing''' return self.lerp(rhs, 1 - (1 - scalar)**2)
{ "domain": "codereview.stackexchange", "id": 44266, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, vectors, easing", "url": null }
python, performance, vectors, easing def easeInOutQuad(self, rhs, scalar): '''Quadratic easing''' if scalar < 0.5: return self.easeInQuad(rhs, scalar * 2) else: return self.easeOutQuad(rhs, (scalar - 0.5) * 2) def easeInCubic(self, rhs, scalar): '''Cubic easing''' return self.lerp(rhs, scalar**3) def easeOutCubic(self, rhs, scalar): '''Cubic easing''' return self.lerp(rhs, 1 - (1 - scalar)**3) def easeInOutCubic(self, rhs, scalar): '''Cubic easing''' if scalar < 0.5: return self.easeInCubic(rhs, scalar * 2) else: return self.easeOutCubic(rhs, (scalar - 0.5) * 2) def easeInQuart(self, rhs, scalar): '''Quartic easing''' return self.lerp(rhs, scalar**4) def easeOutQuart(self, rhs, scalar): '''Quartic easing''' return self.lerp(rhs, 1 - (1 - scalar)**4) def easeInOutQuart(self, rhs, scalar): '''Quartic easing''' if scalar < 0.5: return self.easeInQuart(rhs, scalar * 2) else: return self.easeOutQuart(rhs, (scalar - 0.5) * 2) def easeOutQuint(self, rhs, scalar): '''Quintic easing''' return self.lerp(rhs, 1 - (1 - scalar)**5) def easeInOutQuint(self, rhs, scalar): '''Quintic easing''' if scalar < 0.5: return self.easeInQuint(rhs, scalar * 2) else: return self.easeOutQuint(rhs, (scalar - 0.5) * 2) def easeInSine(self, rhs, scalar): '''Sinusoidal easing''' return self.lerp(rhs, 1 - math.cos(scalar * math.pi / 2)) def easeOutSine(self, rhs, scalar): '''Sinusoidal easing''' return self.lerp(rhs, math.sin(scalar * math.pi / 2)) def easeInOutSine(self, rhs, scalar): '''Sinusoidal easing''' return self.lerp(rhs, -0.5 * (math.cos(math.pi * scalar) - 1))
{ "domain": "codereview.stackexchange", "id": 44266, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, vectors, easing", "url": null }
python, performance, vectors, easing def easeInExpo(self, rhs, scalar): '''Exponential easing''' if scalar == 0: return self else: return self.lerp(rhs, 2**(10 * (scalar - 1))) def easeOutExpo(self, rhs, scalar): '''Exponential easing''' if scalar == 1: return self else: return self.lerp(rhs, -2**(-10 * scalar) + 1) def easeInOutExpo(self, rhs, scalar): '''Exponential easing''' if scalar == 0: return self elif scalar == 1: return self elif scalar < 0.5: return self.easeInExpo(rhs, scalar * 2) else: return self.easeOutExpo(rhs, (scalar - 0.5) * 2) def easeInCirc(self, rhs, scalar): '''Circular easing''' return self.lerp(rhs, 1 - math.sqrt(1 - scalar**2)) def easeOutCirc(self, rhs, scalar): '''Circular easing''' return self.lerp(rhs, math.sqrt(1 - (1 - scalar)**2)) def easeInOutCirc(self, rhs, scalar): '''Circular easing''' if scalar < 0.5: return self.easeInCirc(rhs, scalar * 2) else: return self.easeOutCirc(rhs, (scalar - 0.5) * 2) def easeInElastic(self, rhs, scalar, period=0.3): '''Elastic easing''' if scalar == 0: return self elif scalar == 1: return rhs s = period / 4 scalar -= 1 return self.lerp(rhs, -2**(10 * scalar) * math.sin((scalar - s) * (2 * math.pi) / period)) def easeOutElastic(self, rhs, scalar, period=0.3): '''Elastic easing''' if scalar == 0: return self elif scalar == 1: return rhs s = period / 4 return self.lerp(rhs, 2**(-10 * scalar) * math.sin((scalar - s) * (2 * math.pi) / period) + 1)
{ "domain": "codereview.stackexchange", "id": 44266, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, vectors, easing", "url": null }
python, performance, vectors, easing def easeInOutElastic(self, rhs, scalar, period=0.3): '''Elastic easing''' if scalar == 0: return self elif scalar == 1: return rhs s = period / 4 scalar *= 2 if scalar < 1: return self.lerp(rhs, -0.5 * 2**(10 * (scalar - 1)) * math.sin((scalar - 1 - s) * (2 * math.pi) / period)) else: return self.lerp(rhs, 2**(-10 * (scalar - 1)) * math.sin((scalar - 1 - s) * (2 * math.pi) / period) * 0.5 + 1) Where I'm at: Read a bunch of books from: No Starch Press and O'Reilly publishers concerning python. Read a bunch of code from github & here on stackoverflow. Watched (probably too much) youtube concerning gameDev in python, but channels such as: Clear Code, EuroPython Conference, ArjanCodes, mCoding, etc... Hoping for: Suggestions of better ways to handle and/or optimize this class or at least some good pointers of direction to take in research. For any and all help, I thank you ahead of time. Please note I am a hobbyist coder with a mentor, and there is a bunch of bits and pieces I'm still learning about when it comes to programming.
{ "domain": "codereview.stackexchange", "id": 44266, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, vectors, easing", "url": null }
python, performance, vectors, easing Answer: Your code looks mostly fine to me, but I can see a few things that can be worked on. No need to inherit from object Assuming you're working with Python 3 (and you should), all classes inherit from object, whether you explicitly do so or not. Naming conventions PEP8 recommends using snake_case for method names, which you actually use for some methods (like magnitude_squared) while others use camelCase (like easeInQuad). Even if you have a strong argument for preferring something other than snake_case, you should at least be consistent. Naming I think points is a poor fit to hold the x- and y-coordinates of the vector. To my understanding, points would each be a pair of coordinates. coordinates would probably be a better fit. YAGNI You Ain't Gonna Need It, or probably not, at least. Unless you aim on making a full, general-purpose game engine, there is probably no need for all of these ease in/ease out methods, you'll probably end up using just a couple of these, at most. But maybe there are some things missing If you intend to to any computation on your 2D vectors, chances are high you'll have to use dot- and cross-products, and you'll likely benefit from implementing these methods. Same goes from converting to and from polar coordinates, scaling, or rotating a vector. About magic methods Magic methods (those with names surrounded by double-underscores) are very useful, but to work as intended, they should be implemented properly. Implementing as many as you can is probably a good idea, but you shouldn't implement those that don't make much sense for your class. root() function and __root__ method I hesitated to include this in the "YAGNI" paragraph (you probably won't ever need to compute a vector with square root coordinates of the original vector), but it goes a bit further than that: you create a new convention. I can see what the appeal is, but it looks like it can create a lot of confusion.
{ "domain": "codereview.stackexchange", "id": 44266, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, vectors, easing", "url": null }
python, performance, vectors, easing Magic methods exist so that you can implement expected common behavior in your class. You'd expect to be able to add 2 vectors, and implementing __add__ allows the user to seamlessly do that, which is nice. But nobody expects to be able to call root on any numeric type, so the pattern doesn't really work. __pow__ Does raising a vector to a power make sense? I'd argue that it doesn't. Even a simple case, such as pow(v, 2) isn't trivial, as you didn't define what the product of two vectors is. Even if you did, should I expect a cross-product or a dot-product? In any case, the result would be a scalar. But pow(v, 3) would be a vector, then. What about pow(v, 2.5)? You decided to go with raising each of the coordinates to said power, but this doesn't represent any common mathematical operation. You should remove this magic method IMO. Type conversion The int(), float() and complex() functions, and their associated magic methods __int__, __float__ and __complex__ are intended to be used to for type conversion. However, you use them to convert the underlying data type of your vector, while returning a Vector2. This is bad, as I'd expect to be working with an int after calling int(foo), whatever type foo was to begin with. I suppose it doesn't make much sense to implement __int__ and __float__ in your case, but implementing __complex__ can work: def __complex__(self): return complex(self.x, self.y)
{ "domain": "codereview.stackexchange", "id": 44266, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, vectors, easing", "url": null }
python, performance, vectors, easing Inequality operators There is no commonly-agreed-upon way to sort vectors. Is (-20, -10) really smaller than (1, 1)? But it's magnitude is greater! How can you compare (-1, 1) and (1, -1)? What if I want lexicographic ordering? By implementing __lt__, __le__, __gt__ and __ge__, you impose a comparison paradigm, which doesn't match usual vector comparison, and is confusing as it breaks the assumption that not a > b is equivalent to a <= b Absolute value Almost, if not all, vector library I ever used use abs(v) or equivalent to return the magnitude of the vector. It makes sense from a mathematical point of view, where the magnitude of a vector and the absolute value of a complex number basically share their definition. About performance There isn't much room for improvement performance-wise, as all methods of your class are pretty basic and don't have a lot of possible ways to implement them. I'd suspect packing the vector coordinates into a tuple add a bit of overhead and it might be somewhat faster to keep them as individual members, but that would require some verification. Now, this is a pure Python class, so performance won't be great. Performance-critical Python code will usually be compiled C code with a Python wrapper, so if performance starts to be an issue, you'd need to look into that, but that is on a whole other level. Maybe you'll get to this some day. Otherwise, your best bet for performance is to use performance-optimized libraries as much as you can.
{ "domain": "codereview.stackexchange", "id": 44266, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, vectors, easing", "url": null }
python, python-3.x, game, console, chess Title: Text based chess game in Python Question: I have reached a significant milestone since the start of my chess game project. I have implemented all basic functionality. There is no castling, en passant and pawn promotion yet but I have implemented checks and checkmate functionality. I would like my code to be reviewed before going further in the project so that I can optimize the code beforehand. I would appreciate any improvements and also bugs found. Here is my code: constants.py WHITE = True BLACK = False RANK: dict[str, int] = { "a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5, "g": 6, "h": 7 } position.py from constants import * class Position: def __init__(self, y: int, x: int) -> None: self.y = y self.x = x def __add__(self, other): return Position(self.y + other.y, self.x + other.x) def __sub__(self, other): return Position(self.y - other.y, self.x - other.x) def __mul__(self, value: int): return Position(self.y * value, self.x * value) def __eq__(self, other) -> bool: return self.y == other.y and self.x == other.x def __repr__(self) -> str: return f"(y: {self.y}, x: {self.x})" def __str__(self) -> str: flipped_rank = {v: k for k, v in RANK.items()} return f"{flipped_rank[self.x]}{self.y + 1}" def abs(self): return Position(abs(self.y), abs(self.x)) support.py from position import * def is_same_color(*pieces: list[str]) -> bool: for i in range(len(pieces) - 1): if is_white(pieces[i]) == is_white(pieces[i + 1]): return False return True def is_white(piece: str) -> bool: return piece.isupper() def is_black(piece: str) -> bool: return piece.islower() def is_king(piece: str) -> bool: return piece.lower() == "k" def is_queen(piece: str) -> bool: return piece.lower() == "q" def is_rook(piece: str) -> bool: return piece.lower() == "r"
{ "domain": "codereview.stackexchange", "id": 44267, "lm_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, game, console, chess", "url": null }
python, python-3.x, game, console, chess def is_rook(piece: str) -> bool: return piece.lower() == "r" def is_knight(piece: str) -> bool: return piece.lower() == "n" def is_bishop(piece: str) -> bool: return piece.lower() == "b" def is_pawn(piece: str) -> bool: return piece.lower() == "p" def is_empty(piece: str) -> bool: return piece == "." def extract_move(move: str) -> tuple[Position, Position]: try: start_pos = Position(int(move[1]) - 1, RANK[move[0]]) end_pos = Position(int(move[3]) - 1, RANK[move[2]]) return start_pos, end_pos except: raise ValueError(f"Invalid position {move}") def sign(x: int | float): if x < 0: return -1 elif x > 0: return 1 elif x == 0: return 0 main.py from support import * from copy import deepcopy start_position = [ ["R", "N", "B", "Q", "K", "B", "N", "R"], ["P", "P", "P", "P", "P", "P", "P", "P"], [".", ".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", ".", ".", "."], ["p", "p", "p", "p", "p", "p", "p", "p"], ["r", "n", "b", "q", "k", "b", "n", "r"] ] class Board: def __init__(self, board): self.board = board self.current_turn = WHITE self.legal_moves = self.generate_legal_moves() self.status = "RUNNING" def play_move(self, move): start_pos, end_pos = extract_move(move) if move in self.legal_moves: self[end_pos] = self[start_pos] self[start_pos] = "." self.current_turn = not self.current_turn self.legal_moves = self.generate_legal_moves() self.update_status() else: print(f"Invalid move {move}...") def update_status(self): if self.is_checkmate(): self.status = "GAMEOVER"
{ "domain": "codereview.stackexchange", "id": 44267, "lm_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, game, console, chess", "url": null }
python, python-3.x, game, console, chess def update_status(self): if self.is_checkmate(): self.status = "GAMEOVER" def play_moves(self, moves: str): for move in moves.split(): print(self) self.play_move(move)
{ "domain": "codereview.stackexchange", "id": 44267, "lm_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, game, console, chess", "url": null }
python, python-3.x, game, console, chess def is_valid(self, move: str) -> bool: start_pos, end_pos = extract_move(move) largest = max(start_pos.y, start_pos.x, end_pos.y, end_pos.x) smallest = min(start_pos.y, start_pos.x, end_pos.y, end_pos.x) # Check if coordinates are out of bound if smallest < 0 or largest > 7: return False if start_pos == end_pos: return False piece = self[start_pos] if is_empty(piece): return False to_capture_piece = self[end_pos] if not is_empty(to_capture_piece) and not is_same_color(to_capture_piece, piece): return False delta = end_pos - start_pos if is_pawn(piece): if abs(delta.y) == 1: # 1 step forward if delta.x == 0 and is_empty(self[end_pos]): # No capture return True elif abs(delta.x) == 1 and not is_empty(self[end_pos]): # Capture return True if (abs(delta.y) == 2 and start_pos.y in (1, 6) and is_empty(self[end_pos]) and is_empty(self[end_pos - Position(sign(delta.y), 0)]) ): # 2 step forward return True elif is_bishop(piece): if abs(delta.y) == abs(delta.x): increment = Position(sign(delta.y), sign(delta.x)) for i in range(1, abs(delta.y)): if not is_empty(self[start_pos + (increment * i)]): return False return True elif is_rook(piece): if delta.x == 0 or delta.y == 0: increment = Position(sign(delta.y), sign(delta.x)) for i in range(1, max(abs(delta.y), abs(delta.x))): if not is_empty(self[start_pos + (increment * i)]): return False return True elif is_knight(piece): if delta.abs() == Position(2, 1) or delta.abs() == Position(1, 2):
{ "domain": "codereview.stackexchange", "id": 44267, "lm_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, game, console, chess", "url": null }
python, python-3.x, game, console, chess if delta.abs() == Position(2, 1) or delta.abs() == Position(1, 2): return True elif is_queen(piece): # Rook validation if delta.x == 0 or delta.y == 0: increment = Position(sign(delta.y), sign(delta.x)) for i in range(1, max(abs(delta.y), abs(delta.x))): if not is_empty(self[start_pos + (increment * i)]): return False return True # Bishop validation if abs(delta.y) == abs(delta.x): increment = Position(sign(delta.y), sign(delta.x)) for i in range(1, abs(delta.y)): if not is_empty(self[start_pos + (increment * i)]): return False return True elif is_king(piece): if abs(delta.y) in (0, 1) and abs(delta.x) in (0, 1): return True
{ "domain": "codereview.stackexchange", "id": 44267, "lm_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, game, console, chess", "url": null }
python, python-3.x, game, console, chess return False def is_check(self, move) -> bool: new_game = deepcopy(self) start_pos, end_pos = extract_move(move) new_game[end_pos] = new_game[start_pos] new_game[start_pos] = "." king_pos = new_game.get_king_pos(new_game.current_turn) for pos in new_game.get_all_pieces_pos()[not new_game.current_turn]: if new_game.is_valid(str(pos) + str(king_pos)): return True return False def is_checkmate(self) -> bool: return len(self.legal_moves) == 0
{ "domain": "codereview.stackexchange", "id": 44267, "lm_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, game, console, chess", "url": null }
python, python-3.x, game, console, chess def generate_legal_moves(self) -> list[str]: legal_moves = [] candidate_moves = [] pieces_pos = self.get_all_pieces_pos()[self.current_turn] # print([str(pos) for pos in pieces_pos]) for pos in pieces_pos: piece = self[pos] # print("In for pos in pieces_pos:", piece, pos) if is_pawn(piece): if is_white(piece): deltas = [ Position(1, 0), Position(2, 0), Position(1, 1), Position(1, -1) ] else: deltas = [ Position(-1, 0), Position(-2, 0), Position(-1, 1), Position(-1, -1) ] for delta in deltas: try: move = str(pos) + str(pos + delta) candidate_moves.append(move) except KeyError: pass elif is_knight(piece): deltas = [ Position(2, 1), Position(1, 2), Position(-2, 1), Position(1, -2), Position(2, -1), Position(-1, 2), Position(-2, -1), Position(-1, -2) ] for delta in deltas: try: move = str(pos) + str(pos + delta) candidate_moves.append(move) except KeyError: pass elif is_bishop(piece): deltas = [ Position(1, 1), Position(-1, -1), Position(1, -1), Position(-1, 1) ] for delta in deltas: for i in range(1, 8): try: move = str(pos) + str(pos + delta * i) candidate_moves.append(move) except KeyError:
{ "domain": "codereview.stackexchange", "id": 44267, "lm_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, game, console, chess", "url": null }
python, python-3.x, game, console, chess candidate_moves.append(move) except KeyError: pass elif is_rook(piece): deltas = [ Position(1, 0), Position(0, 1), Position(-1, 0), Position(0, -1) ] for delta in deltas: for i in range(1, 8): try: move = str(pos) + str(pos + delta * i) candidate_moves.append(move) except KeyError: pass elif is_king(piece): deltas = [ Position(1, 0), Position(0, 1), Position(-1, 0), Position(0, -1), Position(1, 1), Position(-1, -1), Position(1, -1), Position(-1, 1) ] for delta in deltas: try: move = str(pos) + str(pos + delta) candidate_moves.append(move) except KeyError: pass elif is_queen(piece): deltas = [ # Bishop Position(1, 1), Position(-1, -1), Position(1, -1), Position(-1, 1), # Rook Position(1, 0), Position(0, 1), Position(-1, 0), Position(0, -1) ] for delta in deltas: for i in range(1, 8): try: move = str(pos) + str(pos + delta * i) candidate_moves.append(move) except KeyError: pass
{ "domain": "codereview.stackexchange", "id": 44267, "lm_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, game, console, chess", "url": null }
python, python-3.x, game, console, chess for move in candidate_moves: try: # print(move, self.is_valid(move), not self.is_check(move)) if self.is_valid(move) and not self.is_check(move): legal_moves.append(move) except ValueError: pass return legal_moves def get_all_pieces_pos(self) -> dict[bool, list[Position]]: pieces_pos = {WHITE: [], BLACK: []} for y in range(8): for x in range(8): piece = self.board[y][x] if not is_empty(piece): pieces_pos[is_white(piece)].append(Position(y, x)) return pieces_pos def get_king_pos(self, color: bool) -> Position: for y in range(8): for x in range(8): if is_king(self.board[y][x]) and is_white(self.board[y][x]) == color: return Position(y, x) def __getitem__(self, pos: Position) -> str: return self.board[pos.y][pos.x] def __setitem__(self, pos: Position, piece: str) -> None: self.board[pos.y][pos.x] = piece def __repr__(self) -> str: return "\n".join( [" ".join(rank + [str(8 - i)]) for i, rank in enumerate(self.board[::-1])] + [" ".join(RANK.keys())] ) game = Board(start_position) def play(): while True: print(game) if game.status == "GAMEOVER": print(player, "wins!!") break player = "WHITE" if game.current_turn == WHITE else "BLACK" # print([str(move) for move in game.generate_legal_moves()]) move = input(f"{player}, please enter your move:").lower().strip() game.play_move(move) play() Thank you for your time!!
{ "domain": "codereview.stackexchange", "id": 44267, "lm_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, game, console, chess", "url": null }
python, python-3.x, game, console, chess play() Thank you for your time!! Answer: Bug play() gets a move string from the user, and calls game.play_move(move). which in turn calls extract_move(move), which can raise a ValueError, but that is not caught by any of the proceeding functions. Confusing Code try: move = str(pos) + str(pos + delta) candidate_moves.append(move) except KeyError: pass Nothing about the above code looks like it can generate a KeyError. The only possibility looks to be the pos + delta, but Position.__add__ only does some math and calls the constructor which just stores the results. append on a vanilla list shouldn't fail. The only other possibility is str(...), which should always succeed: def __str__(self) -> str: flipped_rank = {v: k for k, v in RANK.items()} return f"{flipped_rank[self.x]}{self.y + 1}" And here is where we find the exception: it is possible to construct an invalid Position, which cannot be stringified. This code shows two other issues: Only some invalid positions raise an exception. If the y is out of legal range, it can be stringified without issue. Only a that falls out of the valid x-range will raise an exception and be prevented from being added to candidate.moves. flipped_rank is recomputed on every stringification, despite depending only upon the RANK constant. It should be computed once: FLIPPED_RANK = {v: k for k, v in RANK.items()} class Position: def __init__(self, y: int, x: int): if x not in range(8) or y not in range(8): raise ValueError("Illegal position coordinate") self.y = y self.x = x def __str__(self) -> str: return f"{FLIPPED_RANK[self.x]}{self.y + 1}"
{ "domain": "codereview.stackexchange", "id": 44267, "lm_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, game, console, chess", "url": null }
python, python-3.x, game, console, chess def __str__(self) -> str: return f"{FLIPPED_RANK[self.x]}{self.y + 1}" PEP 8 Constants start_position is a constant. As such, PEP 8: The Style Guide for Python Code recommends using UPPER_CASE for the identifier's name. It terms of names, it isn't really just one position. It is the starting position of all the pieces (plural), so perhaps STARTING_POSITIONS would be better? Or maybe even STARTING_BOARD, since it gets assigned to the .board member? Blank Space is_valid(...) and generate_legal_moves(...) are LONG functions. They could use additional blank lines to break the code into logical sections ... or be separated into more functions. Type Hints You've added type hints in many places, but omitted them in several. Eg, Position.abs() needs a return type, In Board, the __init__(), play_move(), lacks parameter type hints, and many methods could be declared to return -> None. def is_same_color(*pieces: list[str]) -> bool means the function accepts a variable number of lists of strings. I'm certain you just want the function to accept a variable number of strings, which would be written as: *pieces: str. Types def get_king_pos(self, color: bool) is an indication you need some better types, since a colour is not a boolean. You have two sides/players. They are not the True player and the False player. Let's create an enumeration for the the player: from enum import Enum class Player(Enum): WHITE = "White" BLACK = "Black"
{ "domain": "codereview.stackexchange", "id": 44267, "lm_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, game, console, chess", "url": null }
python, python-3.x, game, console, chess class Player(Enum): WHITE = "White" BLACK = "Black" You can use Player as a type. If the player variable holds the current player, you can now write f"{player.value}, please enter your move:" to create the input() prompt. Separate Logic and I/O You have a game system where "K" represents the white king, and "r" represents the black rook. Unicode characters can convey this information much more directly: ♜♞♝♛♚♟︎ ♖♘♗♕♔♙. You could change the implementation to use these characters instead of upper & lower case letters, but if you wanted to build a graphical version of the game, or a 3d animated battle-chess game, you'd again find the unicode chess piece characters annoying to work with. Really, what you want is for the game logic to use an "abstract" internal representation, and have the UI layer convert to the appropriate user representation. So maybe an enumeration for piece types: class PieceType: PAWN = 1 ROOK = 2 BISHOP = 3 KNIGHT = 4 QUEEN = 5 KING = 6 Now the black king could be represented as (PieceType.KING, Player.BLACK), and a dictionary could map that value to 'k', and later changing that to use '♚' would be a trivial modification. But that still leaves a long string of if is_pawn(piece) type tests. It would be even better to have a type hierarchy which represents the chess pieces, and the specific types would know how they can move: class ChessPiece: ... class Pawn(ChessPiece): ... class Rook(ChessPiece): ... ... class King(ChessPiece): ... With appropriate member functions, you could ask the piece which side it belongs to, where it is on the board, and what its valid moves are.
{ "domain": "codereview.stackexchange", "id": 44267, "lm_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, game, console, chess", "url": null }
c, recursion, file-system Title: Find the 10 largest files in a directory tree Question: I've recently finished a small project intended to better understand C. The program will output the ten largest files found (recursively in the event of subdirectories) in a specified directory. I've just improved my code to use dynamic memory allocation instead of allocating (statically) a massive array. Please critique not only my use of dynamic memory allocation, but any additional anomalies or smells in terms of C conventions. The program compiles, runs, and outputs identical findings compared to the same program I implemented using Rust. #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <sys/stat.h> #include <string.h> #include "fs_info.h" /* A struct to contain the name of a filesystem entry and its size in bytes. An array of this type will be used to catalog all filesystem entries for the directory specified as command line argument. */ struct FS_Info { char name[1024]; int size; }; // initial size of array used to contain filesystem entries int N = 100; // number of largest entries to output const int num_entries = 10; // global pointer to current FS_Info array // will be updated as the array is resized using dynamic memory allocation struct FS_Info *curr_fs_info_ptr; // determine the size of the info struct, used for qsort const int info_size = sizeof(struct FS_Info); // used to sort fs_entries array descending in terms of entry size int compare(const void *a, const void *b) { struct FS_Info *entryA = (struct FS_Info *)a; struct FS_Info *entryB = (struct FS_Info *)b; return (entryB->size - entryA->size); } void get_size(char *path) { static int items_added = 0; struct stat st; if (stat(path, &st) == 0) { if (items_added < N) // if array capacity will not be exceeded { strcpy(curr_fs_info_ptr[items_added].name, path); curr_fs_info_ptr[items_added].size = st.st_size;
{ "domain": "codereview.stackexchange", "id": 44268, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, recursion, file-system", "url": null }
c, recursion, file-system items_added++; } else // double the size of the containing array { // puts("Re-allocating array to fit additional fs_entries"); N *= 2; struct FS_Info *resized_fs_entries = realloc(curr_fs_info_ptr, N * sizeof(*curr_fs_info_ptr)); if (resized_fs_entries) { curr_fs_info_ptr = resized_fs_entries; strcpy(curr_fs_info_ptr[items_added].name, path); curr_fs_info_ptr[items_added].size = st.st_size; items_added++; } else { puts("An error occurred when attempting to resize the array!"); exit(-1); } } } else { printf("Error getting stat for entry %s: %d\n", path, stat(path, &st)); } } void walk(const char *currDir) { DIR *dir = opendir(currDir); struct dirent *entry; if (dir == NULL) // directory could not be opened { return; } while ((entry = readdir(dir)) != NULL) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) // if directory is current dir or parent dir { continue; } char path_to_entry[1024]; snprintf(path_to_entry, sizeof(path_to_entry), "%s/%s", currDir, entry->d_name); // use path_to_entry to call stats on the entry get_size(path_to_entry); // fs_entries will only be used on first call if (entry->d_type == DT_DIR) { // recursively visit subdirectories walk(path_to_entry); } } closedir(dir); } int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: %s <target directory>\n", argv[0]); } const char *target_dir = argv[1]; printf("Finding %d largest files in: %s\n", num_entries, target_dir);
{ "domain": "codereview.stackexchange", "id": 44268, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, recursion, file-system", "url": null }
c, recursion, file-system printf("Finding %d largest files in: %s\n", num_entries, target_dir); /* Create a pointer to the start of the FS_Info array and set the global variable curr_fs_info_ptr to this memory address */ struct FS_Info *fs_entries = malloc(N * sizeof(struct FS_Info)); curr_fs_info_ptr = fs_entries; // recursively visit all entries in the specified directory walk(target_dir); // sort the entries descending by file size qsort(curr_fs_info_ptr, N, info_size, compare); // output ten largest files found for (int i = 0; i < num_entries; i++) { printf("%s\t%d\n", curr_fs_info_ptr[i].name, curr_fs_info_ptr[i].size); } free(curr_fs_info_ptr); // good practice, but program is over and OS will reclaim anyways return 0; }
{ "domain": "codereview.stackexchange", "id": 44268, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, recursion, file-system", "url": null }
c, recursion, file-system return 0; } Answer: General Observations Good job checking all possible compiler errors and warnings. It appears that the contents of fs_info.h are already included, so that include should be removed. In the future include those include files that you have written. The code isn't completely portable because the header file dirent.h does not exist on Windows 10 systems using Visual Studio 2022. It does compile fine when the include for fs_info.h is removed on Linux systems (Ubuntu in my case). Rather than return 0; at the end of the program the use of EXIT_SUCCESS will make the code more readable, in the examples below I use EXIT_FAILURE in the cases where the program should exit due to a problem. These symbolic constants are defined in stdlib.h for the C programming language and cstdlib for C++. Error Handling There is insufficient error handling, at least in the case where the number of arguments is checked. The program should exit at this point if there is an error, due to the lack of error handling when a user doesn't provide a directory to search the code crashes. Errors should be reported to stderr rather than stdout so instead of using printf() errors should be printed using fprintf(stderr, ERROR_MESSAGE); if (argc != 2) { printf("Usage: %s <target directory>\n", argv[0]); return EXIT_FAILURE; }
{ "domain": "codereview.stackexchange", "id": 44268, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, recursion, file-system", "url": null }
c, recursion, file-system Test for Possible Memory Allocation Errors In modern high-level languages such as C++, memory allocation errors throw an exception that the programmer can catch. This is not the case in the C programming language. While it is rare in modern computers because there is so much memory, memory allocation can fail, especially if the code is working in a limited memory application such as embedded control systems. In the C programming language when memory allocation fails, the functions malloc(), calloc() and realloc() return NULL. Referencing any memory address through a NULL pointer results in undefined behavior (UB). Possible unknown behavior in this case can be a memory page error (in Unix this would be call Segmentation Violation), corrupted data in the program and in very old computers it could even cause the computer to reboot (corruption of the stack pointer). To prevent this undefined behavior a best practice is to always follow the memory allocation statement with a test that the pointer that was returned is not null. /* Create a pointer to the start of the FS_Info array and set the global variable curr_fs_info_ptr to this memory address */ struct FS_Info* fs_entries = malloc(N * sizeof(struct FS_Info)); if (!fs_entries) { fprintf(stderr, "Malloc of fs_entries failed in main\n"); return EXIT_FAILURE; }
{ "domain": "codereview.stackexchange", "id": 44268, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, recursion, file-system", "url": null }
c, recursion, file-system Note Personally I would have used calloc( size_t num, size_t size ) rather than malloc() in the memory allocation above. One of the benefits of calloc() is that it initializes the memory allocated to null values. Convention When Using Memory Allocation in C When using malloc(), calloc() or realloc() in C a common convention is to use sizeof *PTR rather than sizeof(PTR_TYPE); this makes the code easier to maintain and less error prone, since less editing is required if the type of the pointer changes. struct FS_Info* fs_entries = malloc(N * sizeof(*fs_entries)); if (!fs_entries) { fprintf(stderr, "Malloc of fs_entries failed in main\n"); return EXIT_FAILURE; } In the code there is a constant called info_size for qsort(); it might be better to use qsort(curr_fs_info_ptr, N, sizeof(*curr_fs_info_ptr), compare); Avoid Global Variables It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The answers to this Stack Overflow question provide a fuller explanation. Variable Names There must be a more descriptive variable name than N for the number of items in the array. The function name get_size() is misleading, since there is a call to realloc() in this function. It isn't just getting the size; it is changing the size. Which size is it supposed to get, the size of the file or the size of the allocated array?
{ "domain": "codereview.stackexchange", "id": 44268, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, recursion, file-system", "url": null }
c++, template, c++20, raii, constrained-templates Title: Implement scope_exit Question: I want to use the scope_exit class but my compiler/standard library (clang++-16 with libc++) don't support it. Until they do I wanted an implementation. I found a few on the Internet but they weren't quite what I wanted. So I made an attempt at implementing it. I used requires clauses on the constructor overloads to implement the forwarding behavior described on the cppreference.com pages. I came up with a brief suite of test objects (see test_scope_exit.cpp below) but it's paltry; what are more test cases where this should work? What are some examples of when it should not work so I can check if the compiler gives good diagnostic messages? How could the code be improved for clarity, idiosyncrasy, etc? scope_exit.hpp: #ifndef SCOPE_EXIT #define SCOPE_EXIT #include <type_traits> #include <utility> template <typename EF> class Scope_Exit { private: template <typename Fn> static inline constexpr bool noexcept_ctor = std::is_nothrow_constructible_v<EF, Fn> || std::is_nothrow_constructible_v<EF, Fn &>; static inline constexpr bool noexcept_move = std::is_nothrow_move_constructible_v<EF> || std::is_nothrow_copy_constructible_v<EF>; public: template <typename Fn> requires(!std::is_lvalue_reference_v<Fn> && std::is_nothrow_constructible_v<EF, Fn>) explicit Scope_Exit(Fn &&fn) noexcept(noexcept_ctor<Fn>) : exitfun(std::forward<Fn>(fn)) {} template <typename Fn> explicit Scope_Exit(Fn &&fn) noexcept(noexcept_ctor<Fn>) : exitfun(fn) {} Scope_Exit(Scope_Exit &&other) noexcept(noexcept_move) requires std::is_nothrow_move_constructible_v<EF> : active(other.active), exitfun(std::forward<EF>(other.exitfun)) { other.release(); } Scope_Exit(Scope_Exit &&other) noexcept(noexcept_move) : active(other.active), exitfun(other.exitfun) { other.release(); }
{ "domain": "codereview.stackexchange", "id": 44269, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template, c++20, raii, constrained-templates", "url": null }
c++, template, c++20, raii, constrained-templates Scope_Exit(const Scope_Exit &) = delete; Scope_Exit &operator=(Scope_Exit &&) = delete; Scope_Exit &operator=(const Scope_Exit &) = delete; ~Scope_Exit() noexcept { if (active) exitfun(); } void release() noexcept { active = false; } private: bool active = true; EF exitfun; }; template <class EF> Scope_Exit(EF) -> Scope_Exit<EF>; #endif // SCOPE_EXIT test_scope_exit.cpp: #include "../src/scope_exit.hpp" #include <iostream> #include <utility> #include <functional> void foo() { std::cout << "foo()" << std::endl; } void bar(int x) { std::cout << "bar() => " << x << std::endl; } class Baz { public: Baz() = default; Baz(const Baz &other) { std::cout << "copied Baz" << std::endl; } void operator()() { std::cout << "Baz::operator()" << std::endl; } }; int main() { Scope_Exit se1(foo); Scope_Exit se2(&foo); void (&foo_ref)() = foo; Scope_Exit se3(foo_ref); Scope_Exit se4([]{ std::cout << "lambda" << std::endl; }); Scope_Exit se5(std::bind(bar, 2)); int y = 5; Scope_Exit se6([&]{ std::cout << "capturing lambda => " << y << std::endl; }); Baz baz; Scope_Exit se7(baz); Baz &baz_ref = baz; Scope_Exit se8(baz_ref); Scope_Exit<Baz &> se9(baz_ref); // explicitly specifying a reference type prevents copy return 0; } result: copied Baz copied Baz Baz::operator() Baz::operator() Baz::operator() capturing lambda => 5 bar() => 2 lambda foo() foo() foo() Answer: Name it scope_exit If you want to have a drop-in replacement for std::experimental::scope_exit, give it the same name. You could put it in your own namespace if you want. This allows you to write code like: using mynamespace::scope_exit; ... scope_exit se(somefunc); And once scope_exit becomes available in the implementation of the standard library you are using, you can simply replace the first line by: using std::experimental::scope_exit; And no other code needs to be changed. Can exit functions throw? According to cppreference:
{ "domain": "codereview.stackexchange", "id": 44269, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template, c++20, raii, constrained-templates", "url": null }
c++, template, c++20, raii, constrained-templates And no other code needs to be changed. Can exit functions throw? According to cppreference: The behavior is undefined if calling fn() throws an exception or results in undefined behavior, even if fn has not been called. And std::experimental::exit_scope's destructor is unconditionally marked noexcept. However, I think that's a bit unsafe: it still allows you to pass a throwing function, and if it throws you cannot catch it. I think we can do better, but there are two options: Restrict EF to functions that are noexcept. You can do this by creating a suitable concept. Make the destructor noexcept only if EF is. Test cases I came up with a brief suite of test objects (see test_scope_exit.cpp below) but it's paltry; what are more test cases where this should work? You tested the copy constructor and various kinds of functions. However, you did not test that the exit functions are called in the reverse order that the exit scope were constructed. You only test normal scope exit, but std::experimental::exit_scope also calls the exit function when the scope exits abnormally, for example if an exception is thrown that is not caught inside the scope. You should test that as well. You never call release() in your test cases. You never test move constructing from an inactive scope. What are some examples of when it should not work so I can check if the compiler gives good diagnostic messages? Copy-constructing and assignment should not work. You can check this programmatically (for example, static_assert(!std::is_copy_constructible<…>)). Anything you check for using requires should be verified in the test suite. Of course, checking for a compile failure is harder.
{ "domain": "codereview.stackexchange", "id": 44269, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template, c++20, raii, constrained-templates", "url": null }
python Title: Efficiently solve unexplored maze in Python Question: I am trying to solve a maze in Python where parts of the maze are not explored, meaning in each step the player has to move toward an unexplored area and explore it until they discover the exit. I have a working solution, but it is quite inefficient. It takes approximately 2 seconds for a 100x100 pixel map. I'm looking for a more efficient solution. The maze itself is relatively simple. In the following image, I show the walls (white), the starting position (red) which is always in the center of the maze, and the unexplored area (blue). I'm looking for the purple line, i.e., the path that connects the starting point with the next unexplored area. Because the white walls are always closed, we can tell that the unexplored area starts where the white walls end (the walls don't end there, they are just not discovered yet). To solve this, I am choosing a random corner (here marked in green) and doing a breadth-first search. The resulting path is shown in the following image. Here is my code: import cv2 import numpy as np maze_image = cv2.imread("mypath/maze.png") maze = np.asarray(maze_image) # maze_image is the 100x100 black and white image of the maze start = (0, 0) # we start the search at the goal end = (int(maze.shape[1]/2), int(maze.shape[0]/2)) # this is the position of the player maze[start[0]][start[1]] = 1 maze[end[0]][end[1]] = 0 # breadth-first connecting start and goal def make_step(k): for i in range(len(maze)): for j in range(len(maze[i])): if maze[i][j] == k: if i>0 and maze[i-1][j] == 0: maze[i-1][j] = k + 1 if j>0 and maze[i][j-1] == 0: maze[i][j-1] = k + 1 if i<len(maze)-1 and maze[i+1][j] == 0: maze[i+1][j] = k + 1 if j<len(maze[i])-1 and maze[i][j+1] == 0: maze[i][j+1] = k + 1 k = 0 while maze[end[0]][end[1]] == 0: k += 1 make_step(k)
{ "domain": "codereview.stackexchange", "id": 44270, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python k = 0 while maze[end[0]][end[1]] == 0: k += 1 make_step(k) # finding the shortest path i, j = end k = maze[i][j] path = [(i,j)] while k > 1: if i > 0 and maze[i - 1][j] == k-1: i, j = i-1, j path.append((i, j)) k-=1 elif j > 0 and maze[i][j - 1] == k-1: i, j = i, j-1 path.append((i, j)) k-=1 elif i < len(maze) - 1 and maze[i + 1][j] == k-1: i, j = i+1, j path.append((i, j)) k-=1 elif j < len(maze[i]) - 1 and maze[i][j + 1] == k-1: i, j = i, j+1 path.append((i, j)) k -= 1 print(path) The code explained: We start at the goal and give its pixel the value 1. Then we check for any neighbor pixels that have the value 0 (0 = not a wall). These get the value 2. Any neighbors of them that are not walls get value 3, and so on until we reach the center of the maze. Once we have reached the center, we just connect pixels in reverse value until we reached the goal, which gives us the shortest path between the start and the goal. The algorithm works fine, but it takes around 2 seconds for the 100x100 pixel maze. To make it practical, I would need to go 10x faster. Any suggestions for improvement are very welcome. I have attached the original 100x100 maze below. The start position is the center of the maze. Answer: Code Style: There are a few minor issues: indentation should be 4 spaces, not 2, to be PEP-8 compliant the code can only run once; write a function to find the path from any arbitrary starting point to any arbitrary goal
{ "domain": "codereview.stackexchange", "id": 44270, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Algorithmic improvements This is where the biggest improvement could be found. You start by declaring a corner as a goal. Then you go over every single pixel in the entire image (so looping over 10,000 times) to determine that 2 spots are adjacent to that corner. Then you loop over every single pixel once more to find what is adjacent to those 2 spots. Then you loop again... The shortest possible path to the centre, which would assume zero obstacles, would require 100 steps. Each step requires 10,000 loops. Your best case solution is 1,000,000 loops. This is \$O(n^3)\$ for the best case scenario. \$O(n^3)\$ means a 200x200 image would take 8 times longer. What you want is to start by creating a list. The original list will just have the goal in it. Find every valid unexplored pixel adjacent to each element in the list: add those to a new list, and mark what step (k) you found it on. You now no longer need the original list, and can repeat on the new list. When repeating on the new list, you don't add previously added pixels, only new ones. What this would look like for the first few steps would be: just the corner [(0, 0)], then the 2 pixels adjacent [(1, 0), (0, 1)], then the 3 adjacent to that [(2, 0), (1, 1), (0, 2)] (the middle one only gets added once - when it gets looked at again it is already marked, just like the origin), then so on. When this method finds the goal, it can stop the loop. Your code already knows how to follow the marked path. This would at least mean the possibility space wouldn't creep up on you as quickly as it is currently. Thus, it would run faster not just here, but as you get larger and larger images the difference would be quite noticeable. Advanced
{ "domain": "codereview.stackexchange", "id": 44270, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Advanced Expand around both the goal & the origin simultaneously. The search area increases the further you get away from your starting position, so by searching in both directions at once, they are likely to overlap (and thus find you the solution) before the search gets as big as it would otherwise.
{ "domain": "codereview.stackexchange", "id": 44270, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python, pymongo Title: Object around user permissions dictionary Question: I want to expose permissions property on ORM User model: PERMISSIONS_MAP= { 'admin': ['can_delete'], } class DatabaseModel: pass class User(DatabaseModel): def __init__(self, role): self.role = role @property def permissions(self): return role_permissions.list(self.role) class RolePermissions: def __init__(self, permissions_map: dict = PERMISSIONS_MAP): self.permissions_map = permissions_map def list(self, role): print(f'listing permissions') return [p for p in self.permissions_map.get(role, [])] role_permissions = RolePermissions() admin = User('admin') assert admin.permissions == ['can_delete'] assert admin.permissions == ['can_delete'] # here the permissions will be recalculated, but ideally shouldn't guest = User('guest') assert guest.permissions == [] But I don't like 2 things: Return value of permissions property will be calculated each time the property is called: I can easily alleviate that by switching property with functools.cached_property decorator. However, I would like to instead improve the design. Would changing to RolePermissions(self.role).list() from role_permissions.list(self.role) be a move into a right direction? Where do I go from there to mitigate unwanted recalculations? User class is coupled to user_permissions. I could solve it through dependency injection, yet it feels cumbersome to make the permissions property accept UserPermissions object. Is there a better way to decouple this? Any other suggestions are of course welcome! Answer: PERMISSIONS_MAP should probably be a map of enums to enum sets, not strings to string lists. Stringly-typed data are not a good idea. Add PEP484 type hints to your function signatures. permissions being a property is fine. You're concerned about recalculation, but
{ "domain": "codereview.stackexchange", "id": 44271, "lm_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, pymongo", "url": null }
python, pymongo once this code is refactored and the list comprehension goes away, the amount of "recalculation" will be trivial, and whereas you could add an lru_cache, that is not called-for here. Do not use mutable structures like dictionaries for argument defaults. Usual workaround is to default to None and then fill in with a dictionary in function body. Do not call a method list since that's a built-in. Your list comprehension should go away. You can just delete the entire RolePermissions class, and in User, @property def permissions(self) -> set[Permission]: return PERMISSIONS_MAP[self.role] The get is problematic because it hides a situation where a user has an invalid role not present in PERMISSIONS_MAP, so don't do that.
{ "domain": "codereview.stackexchange", "id": 44271, "lm_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, pymongo", "url": null }
c++, homework, pointers, c++20 Title: Intrusive smart pointer implementation Question: I have homework in college to implement intrusive smart pointers. #include <atomic> #include <string_view> #include <string> #include <iostream> struct RefCount { inline void IncrementRefCount() const noexcept { refCount.fetch_add(1, std::memory_order_relaxed); } inline void DecrementRefCount() const noexcept { refCount.fetch_sub(1, std::memory_order_acq_rel); } [[nodiscard]] inline uint32_t getRefCount() const noexcept { return refCount; } private: mutable std::atomic_uint32_t refCount = 0; }; template<typename T> struct Ref { Ref() = default; Ref(std::nullptr_t) noexcept : data(nullptr) { } Ref(T* instance) noexcept : data(instance) { IncrementRef(); } template<typename T2> Ref(const Ref<T2>& other) noexcept { data = (T*)other.data; IncrementRef(); } template<typename T2> Ref(Ref<T2>&& other) noexcept { data = (T*)other.data; other.data = nullptr; } ~Ref() noexcept { DecrementRef(); } Ref(const Ref<T>& other) noexcept : data(other.data) { IncrementRef(); } [[nodiscard]] inline Ref& operator=(std::nullptr_t) noexcept { DecrementRef(); data = nullptr; return *this; } [[nodiscard]] inline Ref& operator=(const Ref<T>& other) noexcept { other.IncrementRef(); DecrementRef(); data = other.data; return *this; } template<typename T2> [[nodiscard]] inline Ref& operator=(const Ref<T2>& other) noexcept { other.IncrementRef(); DecrementRef(); data = other.data; return *this; } template<typename T2> [[nodiscard]] inline Ref& operator=(Ref<T2>&& other) noexcept { DecrementRef();
{ "domain": "codereview.stackexchange", "id": 44272, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, homework, pointers, c++20", "url": null }
c++, homework, pointers, c++20 data = other.data; other.data = nullptr; return *this; } [[nodiscard]] inline operator bool() noexcept { return data != nullptr; } [[nodiscard]] inline operator bool() const noexcept { return data != nullptr; } [[nodiscard]] inline bool operator==(const Ref<T>& other) const noexcept { return data == other.data; } [[nodiscard]] inline bool operator!=(const Ref<T>& other) const noexcept { return !(*this == other); } [[nodiscard]] inline T* operator->() noexcept { return data; } [[nodiscard]] inline const T* operator->() const noexcept { return data; } [[nodiscard]] inline T& operator*() noexcept { return *data; } [[nodiscard]] inline const T& operator*() const noexcept { return *data; } [[nodiscard]] inline T* get() noexcept { return data; } [[nodiscard]] inline const T* get() const noexcept { return data; } inline void Reset(T* instance = nullptr) noexcept { DecrementRef(); data = instance; } template<typename T2> [[nodiscard]] inline Ref<T2> as() const noexcept { return Ref<T2>(*this); } template<typename... Args> [[nodiscard]] inline static Ref<T> Create(Args&&... args) noexcept { return Ref<T>(new T(std::forward<Args>(args)...)); } private: inline void IncrementRef() const noexcept { if (data) { data->IncrementRefCount(); } } inline void DecrementRef() const noexcept { if (data) { data->DecrementRefCount(); if (data->getRefCount() == 0) { delete data; } } } template<typename T2> friend struct Ref; T* data = nullptr; }; template<typename T> class WeakRef { public: WeakRef() noexcept = default; WeakRef(Ref<T> ref) noexcept { data = ref.get(); } WeakRef(T* instance) noexcept : data(instance) { }
{ "domain": "codereview.stackexchange", "id": 44272, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, homework, pointers, c++20", "url": null }
c++, homework, pointers, c++20 WeakRef(T* instance) noexcept : data(instance) { } [[nodiscard]] inline Ref<T> lock() const noexcept { return Ref<T>(data); } [[nodiscard]] inline bool isValid() const noexcept { return data; } [[nodiscard]] inline operator bool() const noexcept { return isValid(); } private: T* data = nullptr; }; struct Leaf; struct Node : RefCount { virtual ~Node() noexcept = default; void PrintLeafName() noexcept const; Ref<Leaf> leaf = nullptr; std::string name; protected: Node(const std::string_view name) noexcept : name(name) { } }; struct ConcreteNode : Node { ConcreteNode(const std::string_view name, const std::string_view leafName) noexcept; ~ConcreteNode() noexcept override = default; }; struct Leaf : RefCount { virtual ~Leaf() noexcept = default; virtual void PrintName() const noexcept = 0; void PrintNodeName() const noexcept { std::cout << parent.lock()->name << "\n"; } protected: Leaf(WeakRef<Node> parent, const std::string_view name) noexcept : parent(std::move(parent)), name(name) { } WeakRef<Node> parent; std::string name; }; struct ConcreteLeaf : Leaf { ConcreteLeaf(WeakRef<Node> parent, const std::string_view name) noexcept : Leaf(std::move(parent), name) { } ~ConcreteLeaf() noexcept override = default; void PrintName() const noexcept { std::cout << name <<"\n"; } }; ConcreteNode::ConcreteNode(std::string_view name, std::string_view leafName) noexcept : Node(name) { leaf = Ref<ConcreteLeaf>::Create(this, leafName); } void Node::PrintLeafName() const noexcept { leaf->PrintName(); } int main() { Ref<Node> node = Ref<ConcreteNode>::Create("Concrete node", "Concrete leaf"); node->PrintLeafName(); node->leaf->PrintNodeName(); return 0; }
{ "domain": "codereview.stackexchange", "id": 44272, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, homework, pointers, c++20", "url": null }
c++, homework, pointers, c++20 node->PrintLeafName(); node->leaf->PrintNodeName(); return 0; } Could you review it please? I'm not sure if RefCount class needs a virtual destructor. Ref class deletes T, so I don't think it's needed, but I may be wrong. I'm also not sure of mutable std::atomic_uint32_t refCount, but it's required for RefCount::as() const https://godbolt.org/z/cvGzaqvqe
{ "domain": "codereview.stackexchange", "id": 44272, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, homework, pointers, c++20", "url": null }
c++, homework, pointers, c++20 Answer: Bugs: WeakRef is a big fat bug. Say you have your smart pointer Ref, create one WeakRef from it. Then clear Ref. Then use lock() function on WeakRef... voila a UB as you address deleted memory. std::shared_ptr and std::weak_ptr implement the whole thing by keeping control block separately. Once all shared_ptr are gone the object is deleted. And only once all weak_ptr are gone too, the control block is deleted too. Not sure how you should implement it but the managed object needs to be destroyed once all references are gone while the mechanism behind weak references needs to be kept alive as long as some weak references still exist. Do you really need weak references with intrusive smart pointers? For me it feels that the two don't mesh well together. The acquire_release memory order in DecrementRefCount() is overkill. You need only to call release regularly. While apply acquire fence only prior to destroying the object. Also the routine, DecrementRef() in Ref is buggy. You first decrease the value then read it. What if it is decreased simultaneously in two places and then it is read simultaneously in two places? You'll get double-delete. DecrementRefCount() should return the value given by fetch_sub and use it to judge whether to delete or not. Assignment operators: make sure operation like self-assignment (x = x; and x = std::move(x);) are safe. Currently they might behave weirdly or do unnecessary operations. While it doesn't normally happen people might accidentally trigger it in complicated calls. Operators like ->, *, and get() ought to be const and return the object without unnecessary const. Here constness means that the pointer is unchanged but the data is under users' responsibility not the smart pointer's. It is probably overkill for your homework assignment but the class should support T being a const object. std::shared_ptr<const double> is a thing.
{ "domain": "codereview.stackexchange", "id": 44272, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, homework, pointers, c++20", "url": null }
c++, homework, pointers, c++20 Clarification: Say you have a function foo(const Ref<A>& a). And bar() is not a const function of A. Then writing a->bar() is a compilation error because -> returns a const pointer. However, one can write Ref<A> a2 = a; and then call a2->bar(); which is absurd, right? So returning a const pointer via -> is illogical. The situation with * and get() is the same. RefCount's operations should be only accessible to Ref and WeakRef. Writing const std::string_view in function calls is superfluous. Write simply std::string_view. The class is inconvenient to use. Ref<int> and Ref<std::string> will not compile. It should be able to figure out on its own if the object does not have the control block mechanism and add it automatically while wrapping and unwrapping all the calls for the user's convenience. The class does not work with polymorphism. It is frequent that one first declares an Interface and then creates a Derived class. Normally users want to hold smart pointer to Interface, right? With this implementation it is impossible. You shouldn't put noexcept everywhere. There are places where it is much more reasonable to not have it. They are only important for move constructor and move assignment else STL algorithm won't work right with the classes.
{ "domain": "codereview.stackexchange", "id": 44272, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, homework, pointers, c++20", "url": null }
c++, homework, pointers, c++20 Regarding your questions: Self-Assignment: Ref<A> x; x = x; x = std::move(x); Well, nobody would ever write that, right? But imagine situation: bool DoStuff(Ref<A>& input, Ref<A>& output) { // lots of convoluted and branched code, some with early returns. output = std::move(input); return true; } And then someone decided to use it with DoStuff(x,x) for whatever reason. That'll cause a bug if self-assignment were not safe. That's being said, some STL classes do weird stuff on self-move-assignment, like std::vector that clears itself. The class does not work with polymorphism: Okey I didn't check it fully and just saw that you didn't implement any proper mechanisms. First, your template<typename T2> Ref(const Ref<T2>& other) noexcept { data = (T*)other.data; IncrementRef(); } Is extremely unsafe. With explicit pointer cast you can cast completely unrelated classes. For implicit conversion you ought to require T is a base of T2. When it is not the case, you ought to write external functions that perform dynamic casting and static casting. Like std::dynamic_pointer_cast and std::static_pointer_cast do for std::shared_ptr. Otherwise, you can easily cast cats into bananas. Also, as it is now, it is also buggy. Calling delete on pointer to an interface will cause UB. That's because the destructor is not virtual. RefCounter should declare its destructor virtual.
{ "domain": "codereview.stackexchange", "id": 44272, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, homework, pointers, c++20", "url": null }
python, numbers-to-words Title: Converting numbers to text Question: This code seems to work fine but I am sure this reads very amateurish. I would appreciate your comments as to how to make this code more "professional": def nToTxt(n): nums = {0:"", 1:'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',11: 'eleven', 12: 'twevlve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19 : 'ninteen'} tens = {2:'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninty'} if n < 21 : txt = f"{nums[n]}" elif n > 20 and n< 100: txt = f"{tens[int(n/10)]} {nums[n%10]}" else: txt = f"{nums[n//100]} hundred {tens[(int(n/10))%10]} {nums[n%10]}" return(txt) z=124326859660 x = f"{z:012}" # format number by padding with zeros to fit a 100 billion number (12 digits) billions = int(x[:3]) millions =int(x[3:6]) thousands = int (x[6:9]) digits = int(x[9:]) if billions > 0: print(f"{nToTxt(billions)} billion {nToTxt(millions)} million {nToTxt(thousands)} thousand {nToTxt(digits)}") elif millions > 0: print(f"{nToTxt(millions)} million {nToTxt(thousands)}thousand {nToTxt(digits)}") elif thousands > 0: print(f"{nToTxt(thousands)} thousand {nToTxt(digits)}") else: print(f"{nToTxt(digits)}") Answer: The "professional" approach would be using libraries that already exist. As agtoever mentioned, there's num2words. So you can do things like: >>> from num2words import num2words >>> num2words(42) forty-two >>> num2words(42, to='ordinal') forty-second >>> num2words(42, lang='fr') quarante-deux
{ "domain": "codereview.stackexchange", "id": 44273, "lm_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, numbers-to-words", "url": null }
python, numbers-to-words This library already supports thousand-separators, multiple languages, currencies and other neat stuff you hadn't even considered supporting yet. As BCdotWEB indicated in the comments, you should check your spelling (ninteen -> nineteen, ninty -> ninety) and write tests. Projects like these are perfect to familiarize yourself with Test Driven Development (TDD). TDD can very roughly be described as 'write tests first, keep writing code till tests pass, repeat`. Considering you already have the code, I'll cut away portions of it and use the base to somewhat illustrate TDD. We're already doing it the wrong way around (there's code first and tests later instead of vice versa), but I think it gets the message across: def nToTxt(n): nums = {0:"", 1:'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',11: 'eleven', 12: 'twevlve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19 : 'nineteen'} tens = {2:'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninety'} if n < 21 : txt = f"{nums[n]}" elif n > 20 and n< 100: txt = f"{tens[int(n/10)]} {nums[n%10]}" else: txt = f"{nums[n//100]} hundred {tens[(int(n/10))%10]} {nums[n%10]}" return(txt) assert nToTxt(1) == "one" assert nToTxt(2) == "two" assert nToTxt(7) == "seven" assert nToTxt(10) == "ten" assert nToTxt(19) == "nineteen" # assert nToTxt(20) == "twenty" assert nToTxt(21) == "twenty one" assert nToTxt(22) == "twenty two" assert nToTxt(24) == "twenty four" assert nToTxt(28) == "twenty eight" # assert nToTxt(30) == "thirty" assert nToTxt(49) == "forty nine" assert nToTxt(81) == "eighty one"
{ "domain": "codereview.stackexchange", "id": 44273, "lm_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, numbers-to-words", "url": null }
python, numbers-to-words This is not the best way to write such tests, but it is the easiest way. Especially if you've never written tests before. assert checks if the following statement is an expression and whether the expression resolves to True. Would I for example change the test for 49 to "fourty nine" instead of "forty nine", an AssertionError is raised. The tests for 20 and 30 are commented out. The other tests pass, but those do not. There's a problem in the core of your nToTxt function that fails to handle this case. There are multiple problems here. For starters: if n < 21 : Is still true for 20. It's handled the same way 10 is, but 20 is not in the same nums dictionary. So this will throw a KeyError, the program tells you it can not find the entry you're looking for. So, we'll change the program to: if n < 20 : txt = f"{nums[n]}" elif n >= 20 and n < 100: txt = f"{tens[int(n/10)]} {nums[n%10]}" This is still wrong. If there are no lookups for nums remaining, there will still be a trailing space. There are multiple ways to handle this. The two obvious ones are removing the trailing spaces or modifying the string in case n%10 is 0. First approach: if n < 20 : txt = f"{nums[n]}" elif n >= 20 and n < 100: txt = f"{tens[int(n/10)]} {nums[n%10]}" else: txt = f"{nums[n//100]} hundred {tens[(int(n/10))%10]} {nums[n%10]}" return(txt.rstrip(" ")) str.rstrip([chars]) will return a copy of the string with trailing characters removed. There's an lstrip too, in case you ever want to remove characters from the front of the string. I'll leave the second approach as an exercise, but you'll want to overhaul the remainder of the function either way. At the moment, nToTxt(0) is empty. Modifying the dictionary to have it contain zero will break the rest of your program. Add zero and modify the rest of your program to handle it properly with extra checks.
{ "domain": "codereview.stackexchange", "id": 44273, "lm_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, numbers-to-words", "url": null }
rust, fibonacci-sequence Title: Fibonacci calculator Question: I'm trying to learn Rust and for this reason I'm reading the Rust Book. It contains the following exercise: Generate the nth Fibonacci number. Here's my take. Note I'm only using material from chapters 1-3 of this book (since I've only read so far yet), with the exception of format! which I learned by Googling it and unreachable!, which I learned by asking other people. I think I needed both facilities to complete the task. use std::io; fn main() { let n = loop { println!("Enter n to get Fₙ:"); let mut n = String::new(); io::stdin() .read_line(&mut n) .expect("Failed to read line"); break match n.trim().parse() { Ok(n) => n, Err(_) => continue, } }; let subscript_n = subscript(n); let res = fib(n); println!("F{subscript_n} = {res}"); } fn fib(n: u32) -> u64 { match n { 0 => 0, n => { let mut fib_i = 1u64; let mut fib_i_minus_1 = 0u64; for _ in 1..n { (fib_i, fib_i_minus_1) = (fib_i.checked_add(fib_i_minus_1).expect("Result too large"), fib_i); } fib_i } } } fn subscript(n: u32) -> String { match n { 0 => format!("0"), mut n => { let mut res = String::new(); while n != 0 { let digit = match n % 10 { 0 => '₀', 1 => '₁', 2 => '₂', 3 => '₃', 4 => '₄', 5 => '₅', 6 => '₆', 7 => '₇', 8 => '₈', 9 => '₉', 10.. => unreachable!(), }; n /= 10; res = format!("{res}{digit}"); } res } } } Comments?
{ "domain": "codereview.stackexchange", "id": 44274, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, fibonacci-sequence", "url": null }
rust, fibonacci-sequence Comments? Answer: I would create the input string outside the loop and clear() it before each iteration, as this is more performant (no need to allocate twice). This code isn't performance sensitive, but still a good habit. break match is strange. I would rather use: match n.trim().parse() { Ok(n) => break n, Err(_) => continue, } I would rewrite subscript() as follows. This is subjective but I find it more readable (although perhaps less performant): fn subscript(n: u32) -> String { n.to_string() .chars() .map(|c| match c { '0' => '₀', '1' => '₁', '2' => '₂', '3' => '₃', '4' => '₄', '5' => '₅', '6' => '₆', '7' => '₇', '8' => '₈', '9' => '₉', _ => unreachable!(), }) .collect() } If you insist on using the old version, then format!("0") is rather unusual way to convert a string literal to a String - the commonly used ways are String::from("0"), "0".into() (where the compiler can infer the target type is String), "0".to_string() and "0".to_owned(). I personally prefer to_owned() as I think it reflects the intent the best - you want to go from a borrowed &str to an owned String. For pushing a char into a String we got String::push() - format!("{res}{digit}") is both unidiomatic and inefficient (as it creates a copy and use the formatting machinery which is pretty heavy). You can also use string literals ("₀", "₁") instead of chars then use push_str() - this may be a little more efficient as it doesn't need to determine the character length. Your subscript() function prints the subscript backwards (my version does it correctly) - you can fix that by changing format!("{res}{digit}") to format!("{digit}{res}") or insert(0, digit) instead of push(). The code after all changes: use std::io;
{ "domain": "codereview.stackexchange", "id": 44274, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, fibonacci-sequence", "url": null }
rust, fibonacci-sequence The code after all changes: use std::io; fn main() { let n = { let mut n = String::new(); loop { n.clear(); println!("Enter n to get Fₙ:"); io::stdin().read_line(&mut n).expect("Failed to read line"); match n.trim().parse() { Ok(n) => break n, Err(_) => continue, } } }; let subscript_n = subscript(n); let res = fib(n); println!("F{subscript_n} = {res}"); } fn fib(n: u32) -> u64 { match n { 0 => 0, n => { let mut fib_i = 1u64; let mut fib_i_minus_1 = 0u64; for _ in 1..n { (fib_i, fib_i_minus_1) = ( fib_i.checked_add(fib_i_minus_1).expect("Result too large"), fib_i, ); } fib_i } } } fn subscript(n: u32) -> String { n.to_string() .chars() .map(|c| match c { '0' => '₀', '1' => '₁', '2' => '₂', '3' => '₃', '4' => '₄', '5' => '₅', '6' => '₆', '7' => '₇', '8' => '₈', '9' => '₉', _ => unreachable!(), }) .collect() } ```
{ "domain": "codereview.stackexchange", "id": 44274, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, fibonacci-sequence", "url": null }
beginner, c, factors Title: A Simple C Program to Find Factors of any Integer Question: I have written a simple CLI app that finds factors in 3 different forms. I would like the code to be reviewed. Here's the code: #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <string.h> void eq(int num) { int factor_found = 0, factor = 2; printf("%d = " , num); while(factor_found==0) { if(num%factor==0 && num!=0) { printf("%d*" , factor); num = num/factor; } else if(num==-1 || num==0 || num==1) { printf("%d." , num); factor_found=1; } else { ++factor; } } } void n(int num) { int factor_found = 0, factor = 2; printf("Factors of %d are : ", num); if(num==1 || num==-1) { printf("%d,%d.", num, num*-1); } else if(num==0) { printf("Math Error."); } else { printf("1, -1, "); while(factor_found==0) { if(num%factor==0 && num!=factor && num!=factor*(-1)) { printf("%d, %d, ", factor, (factor*(-1))); ++factor; } else if(num==factor || num==factor*(-1)) { printf("%d, %d.", num, (num*(-1))); ++factor_found; } else { ++factor; } } } }
{ "domain": "codereview.stackexchange", "id": 44275, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, factors", "url": null }
beginner, c, factors void poc(int num) { int factor_found = 0, factor = 2, no_of_factors = 0, temp; if(num==1 || num==0 || num==-1) { printf("%d is nor prime nor composite.", num); } else { temp = num; num = abs(num); while(factor_found==0) { if(num%factor==0 && num!=factor) { ++no_of_factors; num=num/factor; } else if(num%factor==0 && (num==factor || factor==1)) { num=num/factor; } else if(num==1 || num==-1) { ++factor_found; } else { ++factor; } } if(no_of_factors==0) { printf("%d is a prime number.", temp); } else if(no_of_factors!=0) { printf("%d is a composite number.", temp); } } } void check(char mode[5], int num) { if(strcmp(mode, "-eq")==0 || strcmp(mode, "eq")==0) eq(num); else if(strcmp(mode, "-n")==0 || strcmp(mode, "n")==0) n(num); else if(strcmp(mode, "-poc")==0 || strcmp(mode, "poc")==0) poc(num); else if(strcmp(mode, "-all")==0 || strcmp(mode, "all")==0) { eq(num); printf("\n"); n(num); printf("\n"); poc(num); } else printf("Invalid Argument!"); } void main(int argc, char *argv[]) { int num = atoi(argv[1]); char mode[5]; if(argc==1) { printf("Enter the number : "); scanf("%d" , &num); printf("Enter the mode : "); scanf("%s" , mode); check(mode, num); } else if(argc==2) { printf("Enter the mode : "); scanf("%s" , mode); check(mode, num); } else check(argv[2], num); }
{ "domain": "codereview.stackexchange", "id": 44275, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, factors", "url": null }
beginner, c, factors Answer: conio is not a portable library so you should not rely on it. You should include stdbool.h and represent factor_found as a bool. However, in all cases, use of this flag is uncalled-for and you should simply break. In all cases, your use of while is better-represented by for. All of your functions other than main should be static. num==-1 || num==0 || num==1 should be reduced to two inequality comparisons. n as a function needs a better name. I don't know what that does unless I read the whole source. factor*(-1) should just be -factor. main should always return int. If the user does not pass any arguments, we expect atoi(argv[1]) to produce a memory fault. If it doesn't, that's entirely by coincidence: welcome to C. atoi is not a safe function because it cannot tell you whether user input is valid or not. Prefer instead something like strtol, and either bounds-check and cast back to an int, or (more easily) use long throughout. You should be compiling against the C17 standard, and using its features where appropriate, especially moving variable declaration away from the function start and closer to use. Whenever you print an error, you should usually print to stderr and not stdout. temp is not a good variable name. In this case, prefer something like orig_num. The responsibility for printing terminating newlines should be moved into your individual functions. Factors "%d, %d, ", factor, (factor*(-1))); have a slightly wobbly definition. See divisor; some definitions expect that only positive divisors are shown. check should not accept a char array, since it should work with any string length; instead accept const char *. Reduce repetition in main by only accepting the mode string once. Suggested I believe this to be equivalent but you should verify. This has been compiled with the following makefile: 282213: main.o gcc -o $@ $^ main.o: main.c gcc -o $@ $^ -c -Wall -std=c17 #include <stdio.h> #include <stdlib.h> #include <string.h>
{ "domain": "codereview.stackexchange", "id": 44275, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, factors", "url": null }
beginner, c, factors #include <stdio.h> #include <stdlib.h> #include <string.h> static void eq(long num) { printf("%ld = ", num); for (int factor = 2;;) { if (num >= -1 && num <= 1) { printf("%ld." , num); break; } if (num%factor==0) { printf("%d*", factor); num /= factor; } else ++factor; } putchar('\n'); } static void n(long num) { printf("Factors of %ld are: ", num); if (num==1 || num==-1) printf("%ld,%ld.", num, -num); else if (num==0) fprintf(stderr, "Math Error.\n"); else { printf("1, -1, "); for (long factor = 2;; ++factor) { if (num==factor || num==-factor) { printf("%ld, %ld.", num, -num); break; } if (num%factor==0) printf("%ld, %ld, ", factor, -factor); } } putchar('\n'); } static void poc(long num) { if (num >= -1 && num <= 1) { printf("%ld is nor prime nor composite.\n", num); return; } long orig_num = num; int no_of_factors = 0; num = labs(num); for (long factor = 2;;) { if (num%factor==0 && num!=factor) { ++no_of_factors; num /= factor; } else if (num%factor==0 && (num==factor || factor==1)) num /= factor; else if (num==1 || num==-1) break; else ++factor; } if (no_of_factors==0) printf("%ld is a prime number.\n", orig_num); else printf("%ld is a composite number.\n", orig_num); }
{ "domain": "codereview.stackexchange", "id": 44275, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, factors", "url": null }
beginner, c, factors static void check(const char *mode, long num) { if (!strcmp(mode, "-eq") || !strcmp(mode, "eq")) eq(num); else if(!strcmp(mode, "-n") || !strcmp(mode, "n")) n(num); else if(!strcmp(mode, "-poc") || !strcmp(mode, "poc")) poc(num); else if(!strcmp(mode, "-all") || !strcmp(mode, "all")) { eq(num); n(num); poc(num); } else fprintf(stderr, "Invalid mode\n"); } int main(int argc, const char **argv) { char mode_entry[5]; const char *mode; long num; if (argc < 2) { printf("Enter the number: "); if (scanf("%ld", &num) != 1) { fprintf(stderr, "Invalid number\n"); return 1; } } else { char *endptr = NULL; num = strtol(argv[1], &endptr, 10); if (endptr == argv[1]) { perror("Invalid number"); return 1; } } if (argc < 3) { printf("Enter the mode (eq|n|poc|all): "); if (scanf("%4s", mode_entry) != 1) { fprintf(stderr, "Invalid mode string\n"); return 2; } mode = mode_entry; } else mode = argv[2]; check(mode, num); }
{ "domain": "codereview.stackexchange", "id": 44275, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, factors", "url": null }
python-3.x, sorting, regex, io, to-do-list Title: Sort todo.txt items by due date in Python 3 Question: I am using the following format for my task management: https://github.com/todotxt/todo.txt Do some stuff +uni due:2022-12-31 Write some paper +uni due:2023-01-10 I am not using the syntax for priority. I know there is a command-line tool one can install to manage items but I just needed a sort function and decided to write it myself. I am not very experienced in Python so I would like to have your insights #!/usr/bin/env python3 import re from datetime import datetime, time import argparse DATE_PATTERN = re.compile(r"due:(\d{4}-\d{2}-\d{2})") def get_due_date(item): match = DATE_PATTERN.search(item) if not match: return time.max date_str = match.group(1) return datetime.strptime(date_str, "%Y-%m-%d").date() def sort_todos(filepath): with open(filepath, "r") as fh: lines = fh.readlines() lines.sort(key=get_due_date) with open(filepath, "w") as fh: fh.write("".join(lines)) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("filepath", help="Path to the file with todo items") args = parser.parse_args() sort_todos(args.filepath) Answer: It's a short script/utility, but it's very clear and well written. There's honestly not much to give feedback on. Some (very) minor improvements: use pathlib.Path and define this as the type for the filepath arg; that way you can just use Path.read_text() and Path.write_text and not have to use the context handlers sort your imports alphabetically, use type hints, and increase the spacing (PEP8 recommends 2 empty lines between global functions) turn get_due_date() into an internal/local function - it's only used by sort_todos() anyway store the date format in a variable (you could even have this as an argument to be more flexible with your todo-files) #!/usr/bin/env python3 import argparse from datetime import datetime, date, time from pathlib import Path import re
{ "domain": "codereview.stackexchange", "id": 44276, "lm_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-3.x, sorting, regex, io, to-do-list", "url": null }
python-3.x, sorting, regex, io, to-do-list import argparse from datetime import datetime, date, time from pathlib import Path import re DATE_PATTERN = re.compile(r"due:(\d{4}-\d{2}-\d{2})") DATE_FMT = "%Y-%m-%d" def sort_todos(filepath: Path) -> None: def get_due_date(item: str) -> date: match = DATE_PATTERN.search(item) if not match: return time.max date_str = match.group(1) return datetime.strptime(date_str, DATE_FMT).date() lines = filepath.read_text().split("\n") lines.sort(key=get_due_date) filepath.write_text("\n".join(lines)) if __name__ == "__main__": parser = argparse.ArgumentParser("Utility to sort todo-items in files") parser.add_argument("filepath", type=Path, help="File to sort") args = parser.parse_args() sort_todos(args.filepath) I wouldn't personally bother with docstrings for something this short and straight-forward, but they would be good to have if you're building something bigger---especially if it's a library to be used by others. But at that stage there would be other considerations too; packaging, tests, deployment, etc.
{ "domain": "codereview.stackexchange", "id": 44276, "lm_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-3.x, sorting, regex, io, to-do-list", "url": null }
c++, object-oriented, c++17, networking, web-services Title: Tiny Network Web Framework / Library in C++ Question: I recently wrote a tiny network library in C++17 called Turtle on Linux and wish to seek some improvement advice on how to further develop it. Any insights would be appreciated. Origin: As a student, I took a class in Computer Network this semester, during which I practised serveral network programming projects in C using TCP socket. I thought it would be a good idea to wrap the meticulously detailed socket operations into C++ classes for reusability. And here I go. Repo: GitHub Repo Link I've uploaded the little project to my github repo for reference. It is under the "Code-Review" branch that will stay static for a while to be reviewed. It contains a pretty detailed README. But I will illustrate more below anyway. Design Highlight: non-blocking socket and edge-trigger event handling mode thread pool to execute tasks in a FIFO queuing manner allow user custom server setup by only specifying 2 virtual callback functions System Architecture: the brain of the system is the Looper. It submits event-ready connection's callback function to ThreadPool to be executed, by doing epolling on the Poller. the system starts with an Acceptor, which contains one acceptor connection which is under monitor of the Poller. The acceptor connection builds connection for each new incoming client. the building block is Connection, which contains a Socket and a Buffer. Each client (as well as the listening acceptor) is essentially a Connection. The diagram below briefly explains the flow. ] Codes: There are quite a few helper classes. I will list them level by level up. Utils #ifndef SRC_INCLUDE_UTILS_H_ #define SRC_INCLUDE_UTILS_H_ #define NON_COPYABLE(class_name) \ class_name(const class_name &) = delete; \ class_name &operator=(const class_name &) = delete #define NON_MOVEABLE(class_name) \ class_name(class_name &&) = delete; \ class_name &operator=(class_name &&) = delete
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services #define NON_COPYABLE_AND_MOVEABLE(class_name) \ class_name(const class_name &) = delete; \ class_name &operator=(const class_name &) = delete; \ class_name(class_name &&) = delete; \ class_name &operator=(class_name &&) = delete #endif // SRC_INCLUDE_UTILS_H_ Buffer #ifndef SRC_INCLUDE_BUFFER_H_ #define SRC_INCLUDE_BUFFER_H_ #include <string> #include <vector> #define INITIAL_BUFFER_CAPACITY 1024 namespace TURTLE_SERVER { /** * This Buffer abstracts an underlying dynamic char array * that allows pushing in byte data from two ends * NOT thread-safe * */ class Buffer { friend class Connection; public: explicit Buffer(size_t initial_capacity = INITIAL_BUFFER_CAPACITY); ~Buffer() = default; void Append(const char *new_char_data, size_t data_size); void Append(const std::string &new_str_data); void AppendHead(const char *new_char_data, size_t data_size); void AppendHead(const std::string &new_str_data); auto Size() const -> size_t; auto ToCString() -> char *; auto ToString() const -> std::string; void Clear(); private: std::vector<char> buf_; }; Buffer::Buffer(size_t initial_capacity) { buf_.reserve(initial_capacity); } void Buffer::Append(const char *new_char_data, size_t data_size) { buf_.insert(buf_.end(), new_char_data, new_char_data + data_size); } void Buffer::Append(const std::string &new_str_data) { Append(new_str_data.c_str(), new_str_data.size()); } void Buffer::AppendHead(const char *new_char_data, size_t data_size) { buf_.insert(buf_.begin(), new_char_data, new_char_data + data_size); } void Buffer::AppendHead(const std::string &new_str_data) { AppendHead(new_str_data.c_str(), new_str_data.size()); } auto Buffer::Size() const -> size_t { return buf_.size(); } auto Buffer::ToCString() -> char * { return reinterpret_cast<char *>(buf_.data()); } auto Buffer::ToString() const -> std::string { return {buf_.begin(), buf_.end()}; }
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services auto Buffer::ToString() const -> std::string { return {buf_.begin(), buf_.end()}; } void Buffer::Clear() { buf_.clear(); } } // namespace TURTLE_SERVER #endif // SRC_INCLUDE_BUFFER_H_ NetAddress #ifndef SRC_INCLUDE_NET_ADDRESS_H_ #define SRC_INCLUDE_NET_ADDRESS_H_ #include <arpa/inet.h> #include <cstring> #include <iostream> #include <string> namespace TURTLE_SERVER { /** * This NetAddress class encapsulates the unique identifier of a network host * in the form of "IP Address + Port" * This class is compatible with both IPv4 and IPv6 * */ class NetAddress { public: explicit NetAddress(bool is_ipv4 = true); NetAddress(const char *ip, uint16_t port, bool is_ipv4 = true); ~NetAddress() = default; auto IsIpv4() const -> bool { return is_ipv4_; } auto YieldAddr() -> struct sockaddr * { return &addr_; }; auto YieldAddrLen() -> socklen_t * { return &addr_len_; }; auto GetIp() const -> std::string; auto GetPort() const -> uint16_t; auto ToString() const -> std::string; friend std::ostream &operator<<(std::ostream &os, const NetAddress &address); private: const bool is_ipv4_; mutable struct sockaddr addr_ {}; socklen_t addr_len_; }; NetAddress::NetAddress(bool is_ipv4) : is_ipv4_(is_ipv4) { memset(&addr_, 0, sizeof(addr_)); addr_len_ = sizeof(addr_); } NetAddress::NetAddress(const char *ip, uint16_t port, bool is_ipv4) : is_ipv4_(is_ipv4) { memset(&addr_, 0, sizeof(addr_)); addr_len_ = sizeof(addr_); if (is_ipv4) { auto addr_ipv4 = reinterpret_cast<struct sockaddr_in *>(&addr_); addr_ipv4->sin_family = AF_INET; inet_pton(AF_INET, ip, &addr_ipv4->sin_addr.s_addr); addr_ipv4->sin_port = htons(port); } else { auto addr_ipv6 = reinterpret_cast<struct sockaddr_in6 *>(&addr_); addr_ipv6->sin6_family = AF_INET6; inet_pton(AF_INET6, ip, &addr_ipv6->sin6_addr.s6_addr); addr_ipv6->sin6_port = htons(port); } }
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services auto NetAddress::GetIp() const -> std::string { char ip_address[INET6_ADDRSTRLEN]; // long enough for both Ipv4 and Ipv6 if (is_ipv4_) { auto addr_ipv4 = reinterpret_cast<struct sockaddr_in *>(&addr_); inet_ntop(AF_INET, &addr_ipv4->sin_addr, ip_address, INET_ADDRSTRLEN); } else { auto addr_ipv6 = reinterpret_cast<struct sockaddr_in6 *>(&addr_); inet_ntop(AF_INET6, &addr_ipv6->sin6_addr, ip_address, INET6_ADDRSTRLEN); } return ip_address; } auto NetAddress::GetPort() const -> uint16_t { uint16_t port; if (is_ipv4_) { auto addr_ipv4 = reinterpret_cast<struct sockaddr_in *>(&addr_); port = ntohs(addr_ipv4->sin_port); } else { auto addr_ipv6 = reinterpret_cast<struct sockaddr_in6 *>(&addr_); port = ntohs(addr_ipv6->sin6_port); } return port; } auto NetAddress::ToString() const -> std::string { return GetIp() + std::string(" @ ") + std::to_string(GetPort()); } std::ostream &operator<<(std::ostream &os, const NetAddress &address) { os << address.ToString(); return os; } } // namespace TURTLE_SERVER #endif // SRC_INCLUDE_NET_ADDRESS_H_ Socket #ifndef SRC_INCLUDE_SOCKET_H_ #define SRC_INCLUDE_SOCKET_H_ #include <fcntl.h> #include <sys/socket.h> #include <unistd.h> #include <cassert> #include <cerrno> #include "net_address.h" #include "utils.h" namespace TURTLE_SERVER { /** * This Socket class encapsulates a socket descriptor * which can act as either listener or client * This class is compatible with both IPv4 and IPv6 * */ class Socket { public: explicit Socket(bool is_ipv4 = true); explicit Socket(int fd); NON_COPYABLE(Socket); Socket(Socket &&other) noexcept; Socket &operator=(Socket &&other) noexcept; ~Socket(); auto GetFd() const -> int; /* for client, one step: directly connect */ void Connect(NetAddress &server_address); // NOLINT /* for server, three steps: bind + listen + accept */ void Bind(NetAddress &server_address); // NOLINT void Listen();
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services void Listen(); auto Accept(NetAddress &client_address) -> int; // NOLINT void SetReusable(); void SetNonBlocking(); private: int fd_{-1}; }; Socket::Socket(bool is_ipv4) : fd_(-1) { if (is_ipv4) { fd_ = socket(AF_INET, SOCK_STREAM, 0); } else { fd_ = socket(AF_INET6, SOCK_STREAM, 0); } if (fd_ == -1) { perror("Socket: socket() error"); exit(EXIT_FAILURE); } } Socket::Socket(int fd) : fd_(fd) {} Socket::Socket(Socket &&other) noexcept { fd_ = other.fd_; other.fd_ = -1; } Socket &Socket::operator=(Socket &&other) noexcept { if (fd_ != -1) { close(fd_); } fd_ = other.fd_; other.fd_ = -1; return *this; } Socket::~Socket() { if (fd_ != -1) { close(fd_); fd_ = -1; } } auto Socket::GetFd() const -> int { return fd_; } void Socket::Connect(NetAddress &server_address) { assert(fd_ != -1 && "cannot Connect() with an invalid fd"); if (connect(fd_, server_address.YieldAddr(), *server_address.YieldAddrLen()) == -1) { perror("Socket: Connect() error"); exit(EXIT_FAILURE); } } void Socket::Bind(NetAddress &server_address) { assert(fd_ != -1 && "cannot Bind() with an invalid fd"); if (bind(fd_, server_address.YieldAddr(), *server_address.YieldAddrLen()) == -1) { perror("Socket: Bind() error"); exit(EXIT_FAILURE); } } void Socket::Listen() { assert(fd_ != -1 && "cannot Listen() with an invalid fd"); if (listen(fd_, BACK_LOG) == -1) { perror("Socket: Listen() error"); exit(EXIT_FAILURE); } } auto Socket::Accept(NetAddress &client_address) -> int { assert(fd_ != -1 && "cannot Accept() with an invalid fd"); int client_fd = -1; if ((client_fd = accept(fd_, client_address.YieldAddr(), client_address.YieldAddrLen())) == -1) { perror("Socket: Accept() error"); exit(EXIT_FAILURE); } return client_fd; }
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services void Socket::SetReusable() { assert(fd_ != -1 && "cannot SetReusable() with an invalid fd"); int yes = 1; if (setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) == -1 || setsockopt(fd_, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof yes) == -1) { perror("Socket: SetReusable() error"); exit(EXIT_FAILURE); } } void Socket::SetNonBlocking() { assert(fd_ != -1 && "cannot SetNonBlocking() with an invalid fd"); if (fcntl(fd_, F_SETFL, fcntl(fd_, F_GETFL) | O_NONBLOCK) == -1) { perror("Socket: SetNonBlocking() error"); exit(EXIT_FAILURE); } } } // namespace TURTLE_SERVER #endif // SRC_INCLUDE_SOCKET_H_ Connnetion #ifndef SRC_INCLUDE_CONNECTION_H_ #define SRC_INCLUDE_CONNECTION_H_ #include <functional> #include <memory> #include <string> #include <utility> #include "buffer.h" #include "socket.h" #include "utils.h" #define TEMP_BUF_SIZE 2048 namespace TURTLE_SERVER { // forward declaration class Looper; /** * This Connection class encapsulates a TCP client connection * It could be set a custom callback function when new messages arrive * and it contains information about the monitoring events and return events * so that Poller could manipulate and epoll based on this Connection class * */ class Connection { public: explicit Connection(Looper *looper, std::unique_ptr<Socket> socket); ~Connection() = default; NON_COPYABLE(Connection); auto GetFd() const -> int; auto GetSocket() -> Socket *; /* for Poller */ void SetEvents(uint32_t events); auto GetEvents() const -> uint32_t; void SetRevents(uint32_t revents); auto GetRevents() const -> uint32_t; void SetInPoller(bool in_poller); auto InPoller() const -> bool; void SetCallback(const std::function<void(Connection *)> &callback); auto GetCallback() -> std::function<void()>; auto GetLooper() -> Looper *;
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services auto GetLooper() -> Looper *; /* for Buffer */ auto GetReadBuffer() -> Buffer *; auto GetWriteBuffer() -> Buffer *; auto GetReadBufferSize() -> size_t; auto GetWriteBufferSize() -> size_t; void WriteToReadBuffer(const char *buf, size_t size); void WriteToWriteBuffer(const char *buf, size_t size); void WriteToReadBuffer(const std::string &str); void WriteToWriteBuffer(const std::string &str); auto Read() -> const char *; auto ReadAsString() const -> std::string; /* return std::pair<How many bytes read, whether the client exits> */ auto Recv() -> std::pair<ssize_t, bool>; void Send(); void ClearReadBuffer(); void ClearWriteBuffer(); private: std::unique_ptr<Buffer> read_buffer_; std::unique_ptr<Buffer> write_buffer_; std::unique_ptr<Socket> socket_; Looper *looper_; bool in_poller_{false}; uint32_t events_{}; uint32_t revents_{}; std::function<void()> callback_{nullptr}; }; Connection::Connection(Looper *looper, std::unique_ptr<Socket> socket) : looper_(looper), socket_(std::move(socket)), read_buffer_(std::make_unique<Buffer>()), write_buffer_(std::make_unique<Buffer>()), events_(0), revents_(0) {} auto Connection::GetFd() const -> int { return socket_->GetFd(); } auto Connection::GetSocket() -> Socket * { return socket_.get(); } void Connection::SetEvents(uint32_t events) { events_ = events; } auto Connection::GetEvents() const -> uint32_t { return events_; } void Connection::SetRevents(uint32_t revents) { revents_ = revents; } auto Connection::GetRevents() const -> uint32_t { return revents_; } void Connection::SetInPoller(bool in_poller) { in_poller_ = in_poller; } auto Connection::InPoller() const -> bool { return in_poller_; } void Connection::SetCallback( const std::function<void(Connection *)> &callback) { callback_ = [callback, this] { return callback(this); }; } auto Connection::GetCallback() -> std::function<void()> { return callback_; }
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services auto Connection::GetCallback() -> std::function<void()> { return callback_; } auto Connection::GetLooper() -> Looper * { return looper_; } auto Connection::GetReadBuffer() -> Buffer * { return read_buffer_.get(); } auto Connection::GetWriteBuffer() -> Buffer * { return write_buffer_.get(); } auto Connection::GetReadBufferSize() -> size_t { return read_buffer_->Size(); } auto Connection::GetWriteBufferSize() -> size_t { return write_buffer_->Size(); } void Connection::WriteToReadBuffer(const char *buf, size_t size) { read_buffer_->Append(buf, size); } void Connection::WriteToWriteBuffer(const char *buf, size_t size) { write_buffer_->Append(buf, size); } void Connection::WriteToReadBuffer(const std::string &str) { read_buffer_->Append(str); } void Connection::WriteToWriteBuffer(const std::string &str) { write_buffer_->Append(str); } auto Connection::Read() -> const char * { return read_buffer_->buf_.data(); } auto Connection::ReadAsString() const -> std::string { return read_buffer_->ToString(); } auto Connection::Recv() -> std::pair<ssize_t, bool> { // read all available bytes, since Edge-trigger int from_fd = GetFd(); ssize_t read = 0; char buf[TEMP_BUF_SIZE + 1]; memset(buf, 0, sizeof(buf)); while (true) { ssize_t curr_read = recv(from_fd, buf, TEMP_BUF_SIZE, 0); if (curr_read > 0) { read += curr_read; WriteToReadBuffer(buf, curr_read); memset(buf, 0, sizeof(buf)); } else if (curr_read == 0) { // the client has exit std::cout << "Client exits: " << from_fd << std::endl; return {read, true}; } else if (curr_read == -1 && errno == EINTR) { // normal interrupt continue; } else if (curr_read == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { // all data read break; } else { perror("HandleConnection: recv() error"); exit(EXIT_FAILURE); } } return {read, false}; }
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services void Connection::Send() { // robust write size_t curr_write = 0; size_t write; const size_t to_write = GetWriteBufferSize(); const char *buf = write_buffer_->buf_.data(); while (curr_write < to_write) { if ((write = send(GetFd(), buf + curr_write, to_write - curr_write, 0)) <= 0) { if (errno != EINTR) { perror("Send(): send error and error is not EINTR"); exit(EXIT_FAILURE); } write = 0; } curr_write += write; } ClearWriteBuffer(); } void Connection::ClearReadBuffer() { read_buffer_->Clear(); } void Connection::ClearWriteBuffer() { write_buffer_->Clear(); } } // namespace TURTLE_SERVER #endif // SRC_INCLUDE_CONNECTION_H_ Poller #ifndef SRC_INCLUDE_POLLER_H_ #define SRC_INCLUDE_POLLER_H_ #include <sys/epoll.h> #include <memory> #include <vector> #include "connection.h" #include "utils.h" /* the default maximum number of events to be listed on epoll tree */ #define DEFAULT_EVENTS_LISTENED 1024 namespace TURTLE_SERVER { /** * This Poller acts at the socket monitor that actively polling on connections * */ class Poller { public: explicit Poller(uint64_t poll_size = DEFAULT_EVENTS_LISTENED); ~Poller(); NON_COPYABLE(Poller); void AddConnection(Connection *conn); auto Poll(int timeout = -1) -> std::vector<Connection *>; auto GetPollSize() const -> uint64_t; private: int poll_fd_; struct epoll_event *poll_events_{nullptr}; uint64_t poll_size_; }; Poller::Poller(uint64_t poll_size) : poll_size_(poll_size) { poll_fd_ = epoll_create1(0); if (poll_fd_ == -1) { perror("Poller: epoll_create1() error"); exit(EXIT_FAILURE); } poll_events_ = new struct epoll_event[poll_size]; memset(poll_events_, 0, poll_size_ * sizeof(struct epoll_event)); } Poller::~Poller() { if (poll_fd_ != -1) { close(poll_fd_); delete[] poll_events_; poll_fd_ = -1; } }
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services void Poller::AddConnection(Connection *conn) { assert(conn->GetFd() != -1 && "cannot AddConnection() with an invalid fd"); struct epoll_event event; memset(&event, 0, sizeof(struct epoll_event)); event.data.ptr = conn; event.events = conn->GetEvents(); int ret_val = epoll_ctl(poll_fd_, EPOLL_CTL_ADD, conn->GetFd(), &event); if (ret_val == -1) { perror("Poller: epoll_ctl add error"); exit(EXIT_FAILURE); } conn->SetInPoller(true); } auto Poller::Poll(int timeout) -> std::vector<Connection *> { std::vector<Connection *> events_happen; int ready = epoll_wait(poll_fd_, poll_events_, poll_size_, timeout); if (ready == -1) { perror("Poller: Poll() error"); exit(EXIT_FAILURE); } for (int i = 0; i < ready; i++) { Connection *ready_connection = reinterpret_cast<Connection *>(poll_events_[i].data.ptr); ready_connection->SetRevents(poll_events_[i].events); events_happen.emplace_back(ready_connection); } return events_happen; } auto Poller::GetPollSize() const -> uint64_t { return poll_size_; } } // namespace TURTLE_SERVER #endif // SRC_INCLUDE_POLLER_H_ Looper #ifndef SRC_INCLUDE_LOOPER_H_ #define SRC_INCLUDE_LOOPER_H_ #include <atomic> #include <functional> #include <future> // NOLINT #include <map> #include <memory> #include <mutex> // NOLINT #include "acceptor.h" #include "connection.h" #include "poller.h" #include "thread_pool.h" #include "utils.h" /* the epoll_wait time in milliseconds */ #define TIMEOUT 3000 namespace TURTLE_SERVER { class Acceptor; /** * This Looper acts as the central coordinator between executor (ThreadPool) and * event polling (Poller) * */ class Looper { public: explicit Looper(ThreadPool *pool); ~Looper() = default; NON_COPYABLE(Looper); void Loop(); void AddAcceptor(std::unique_ptr<Acceptor> acceptor); void AddConnection(std::unique_ptr<Connection> new_conn); auto DeleteConnection(int fd) -> bool;
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services auto DeleteConnection(int fd) -> bool; auto DispatchTask(const std::function<void()> &task) -> std::future<void>; auto GetAcceptor() -> Acceptor *; void Exit(); private: ThreadPool *pool_; std::unique_ptr<Poller> poller_; std::mutex mtx_; std::unique_ptr<Acceptor> acceptor_{nullptr}; std::map<int, std::unique_ptr<Connection>> connections_; std::atomic<bool> exit_{false}; }; Looper::Looper(ThreadPool *pool) : poller_(std::make_unique<Poller>()), pool_(pool) {} void Looper::Loop() { if (!acceptor_) { throw std::runtime_error( "Looper: Loop() called before setting up acceptor"); } while (!exit_) { auto ready_connections = poller_->Poll(TIMEOUT); for (auto &conn : ready_connections) { auto fut = DispatchTask(conn->GetCallback()); } } } void Looper::AddAcceptor(std::unique_ptr<Acceptor> acceptor) { acceptor_ = std::move(acceptor); std::unique_lock<std::mutex> lock(mtx_); poller_->AddConnection(acceptor_->GetAcceptorConnection()); } void Looper::AddConnection(std::unique_ptr<Connection> new_conn) { std::unique_lock<std::mutex> lock(mtx_); poller_->AddConnection(new_conn.get()); int fd = new_conn->GetFd(); connections_.insert({fd, std::move(new_conn)}); } auto Looper::DeleteConnection(int fd) -> bool { std::unique_lock<std::mutex> lock(mtx_); auto it = connections_.find(fd); if (it == connections_.end()) { return false; } connections_.erase(it); return true; } auto Looper::DispatchTask(const std::function<void()> &task) -> std::future<void> { return pool_->SubmitTask(task); } auto Looper::GetAcceptor() -> Acceptor * { return acceptor_.get(); } void Looper::Exit() { exit_ = true; } } // namespace TURTLE_SERVER #endif // SRC_INCLUDE_LOOPER_H_ Acceptor #ifndef SRC_INCLUDE_ACCEPTOR_H_ #define SRC_INCLUDE_ACCEPTOR_H_ #include <functional> #include <memory> #include "connection.h" #include "looper.h" #include "net_address.h" #include "utils.h"
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services #include "connection.h" #include "looper.h" #include "net_address.h" #include "utils.h" namespace TURTLE_SERVER { /** * This Acceptor comes with basic functionality for accepting new client * connections and add its into the Poller More custom handling could be added * as well * */ class Acceptor { public: explicit Acceptor(Looper *looper, NetAddress server_address); ~Acceptor() = default; NON_COPYABLE(Acceptor); void BaseAcceptCallback(Connection *server_conn); void SetCustomAcceptCallback( std::function<void(Connection *)> custom_accept_callback); void SetCustomHandleCallback( std::function<void(Connection *)> custom_handle_callback); auto GetCustomAcceptCallback() -> std::function<void(Connection *)>; auto GetCustomHandleCallback() -> std::function<void(Connection *)>; auto GetAcceptorConnection() -> Connection *; private: Looper *looper_; std::unique_ptr<Connection> acceptor_conn; std::function<void(Connection *)> custom_accept_callback_{}; std::function<void(Connection *)> custom_handle_callback_{}; }; Acceptor::Acceptor(Looper *looper, NetAddress server_address) : looper_(looper) { auto acceptor_sock = std::make_unique<Socket>(); acceptor_sock->SetReusable(); acceptor_sock->Bind(server_address); acceptor_sock->Listen(); acceptor_conn = std::make_unique<Connection>(looper_, std::move(acceptor_sock)); acceptor_conn->SetEvents(EPOLLIN); // not edge-trigger for listener SetCustomAcceptCallback({}); SetCustomHandleCallback({}); }
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services /* * basic functionality for accepting new connection * provided to the acceptor by default */ void Acceptor::BaseAcceptCallback(Connection *server_conn) { NetAddress client_address; int accept_fd = server_conn->GetSocket()->Accept(client_address); std::cout << "New client joins: " << accept_fd << std::endl; auto client_sock = std::make_unique<Socket>(accept_fd); client_sock->SetNonBlocking(); auto client_connection = std::make_unique<Connection>( server_conn->GetLooper(), std::move(client_sock)); client_connection->SetEvents(EPOLLIN | EPOLLET); // edge-trigger for client client_connection->SetCallback(GetCustomHandleCallback()); server_conn->GetLooper()->AddConnection(std::move(client_connection)); } void Acceptor::SetCustomAcceptCallback( std::function<void(Connection *)> custom_accept_callback) { custom_accept_callback_ = std::move(custom_accept_callback); acceptor_conn->SetCallback([this](auto &&PH1) { BaseAcceptCallback(std::forward<decltype(PH1)>(PH1)); GetCustomAcceptCallback()(std::forward<decltype(PH1)>(PH1)); }); } void Acceptor::SetCustomHandleCallback( std::function<void(Connection *)> custom_handle_callback) { custom_handle_callback_ = std::move(custom_handle_callback); } auto Acceptor::GetCustomAcceptCallback() -> std::function<void(Connection *)> { return custom_accept_callback_; } auto Acceptor::GetCustomHandleCallback() -> std::function<void(Connection *)> { return custom_handle_callback_; } auto Acceptor::GetAcceptorConnection() -> Connection * { return acceptor_conn.get(); } } // namespace TURTLE_SERVER #endif // SRC_INCLUDE_ACCEPTOR_H_ ThreadPool #include <algorithm> #include <atomic> #include <condition_variable> // NOLINT #include <functional> #include <future> // NOLINT #include <memory> #include <mutex> // NOLINT #include <queue> #include <thread> // NOLINT #include <utility> #include <vector>
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services #include "utils.h" #ifndef SRC_INCLUDE_THREAD_POOL_H_ #define SRC_INCLUDE_THREAD_POOL_H_ /* The minimum number of threads to exist in the threadpool */ #define MIN_NUM_THREADS_IN_POOL 2 namespace TURTLE_SERVER { /** * This ThreadPool manages the thread resources and acts as the executor for * client requests upon submitting a task, it gives back a future to be waited * for * */ class ThreadPool { public: explicit ThreadPool(int size = std::thread::hardware_concurrency()); ~ThreadPool(); NON_COPYABLE(ThreadPool); template <typename F, typename... Args> decltype(auto) SubmitTask(F &&new_task, Args &&...args); void Exit(); private: std::vector<std::thread> threads_; std::queue<std::function<void()>> tasks_; std::mutex mtx_; std::condition_variable cv_; std::atomic<bool> exit_{false}; }; template <typename F, typename... Args> decltype(auto) ThreadPool::SubmitTask(F &&new_task, Args &&...args) { using return_type = std::invoke_result_t<F, Args...>; if (exit_) { throw std::runtime_error( "ThreadPool: SubmitTask() called while already exit_ being true"); } auto packaged_new_task = std::make_shared<std::packaged_task<return_type()>>( std::bind(std::forward<F>(new_task), std::forward<Args>(args)...)); auto fut = packaged_new_task->get_future(); { // submit in form of std::function to the Thread Pool task queue std::unique_lock<std::mutex> lock(mtx_); tasks_.emplace([packaged_new_task]() { (*packaged_new_task)(); }); } cv_.notify_one(); return fut; }
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services ThreadPool::ThreadPool(int size) { /* std::thread::hardware_concurrency() might return 0 if sys info not * available */ size = std::max(size, MIN_NUM_THREADS_IN_POOL); for (auto i = 0; i < size; i++) { threads_.emplace_back([this]() { while (true) { std::function<void()> next_task; { std::unique_lock<std::mutex> lock(mtx_); cv_.wait(lock, [this]() { return exit_ || !tasks_.empty(); }); if (exit_ && tasks_.empty()) { return; // thread life ends } next_task = tasks_.front(); tasks_.pop(); } next_task(); } }); } } ThreadPool::~ThreadPool() { Exit(); for (auto &worker : threads_) { if (worker.joinable()) { worker.join(); } } } void ThreadPool::Exit() { exit_ = true; cv_.notify_all(); } } // namespace TURTLE_SERVER #endif // SRC_INCLUDE_THREAD_POOL_H_ TurtleServer base class interface #include <memory> #include <utility> #include "acceptor.h" #include "connection.h" #include "looper.h" #include "net_address.h" #include "poller.h" #include "socket.h" #include "thread_pool.h" #include "utils.h" #ifndef SRC_INCLUDE_TURTLE_SERVER_H_ #define SRC_INCLUDE_TURTLE_SERVER_H_ namespace TURTLE_SERVER {
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services #ifndef SRC_INCLUDE_TURTLE_SERVER_H_ #define SRC_INCLUDE_TURTLE_SERVER_H_ namespace TURTLE_SERVER { /** * The base class for setting up a web server using the Turtle framework * User should design a class that inherits from the TurtleServer base class * and implements the two virtual function 'OnHandle' and 'OnAccept' * The rest is already taken care of and in most cases users don't need to touch * upon * * OnAccept(): Given the acceptor connection, when the Poller tells us there is * new incoming client connection basic step of socket accept and build * connection and add into the Poller are already taken care of in the * Acceptor::BaseAcceptCallback. This OnAccept() functionality is appended to * that base BaseAcceptCallback and called after that base, to support any * custom business logic upon receiving new client connection * * OnHandle(): No base version exists. Users should implement this function to * achieve the expected behavior */ class TurtleServer { public: explicit TurtleServer(NetAddress server_address) : pool_(std::make_unique<ThreadPool>()), looper_(std::make_unique<Looper>(pool_.get())) { auto acceptor = std::make_unique<Acceptor>(looper_.get(), server_address); acceptor->SetCustomHandleCallback( [this](auto &&PH1) { OnHandle(std::forward<decltype(PH1)>(PH1)); }); acceptor->SetCustomAcceptCallback( [this](auto &&PH1) { OnAccept(std::forward<decltype(PH1)>(PH1)); }); looper_->AddAcceptor(std::move(acceptor)); } virtual ~TurtleServer() = default; /* Not Edge trigger */ virtual void OnAccept(Connection *acceptor_conn) = 0; /* Edge trigger! Read all bytes please */ virtual void OnHandle(Connection *client_conn) = 0; virtual void Begin() { looper_->Loop(); } auto GetPool() -> ThreadPool * { return pool_.get(); } auto GetLooper() -> Looper * { return looper_.get(); }
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services private: std::unique_ptr<ThreadPool> pool_; std::unique_ptr<Looper> looper_; }; } // namespace TURTLE_SERVER #endif // SRC_INCLUDE_TURTLE_SERVER_H_ Demo A demo echo server could be setup fairly easy in less than 30 lines of real code: #include "turtle_server.h" namespace TURTLE_SERVER { class EchoServer : public TurtleServer { public: explicit EchoServer(NetAddress server_address) : TurtleServer(server_address) {} void OnAccept(Connection *server_conn) final {} void OnHandle(Connection *client_conn) final { int from_fd = client_conn->GetFd(); auto [read, exit] = client_conn->Recv(); if (exit) { client_conn->GetLooper()->DeleteConnection(from_fd); // client_conn ptr is destoryed and invalid below here, do not touch it // again return; } if (read) { client_conn->WriteToWriteBuffer(client_conn->ReadAsString()); client_conn->Send(); client_conn->ClearReadBuffer(); } } }; } // namespace TURTLE_SERVER int main() { TURTLE_SERVER::NetAddress local_address("0.0.0.0", 20080); TURTLE_SERVER::EchoServer echo_server(local_address); echo_server.Begin(); return 0; } Next Step Ideas I am thinking about what to do for the next step to further improve my library. A few things pop up my mind: Support HTTP Request parsing and responding (maybe just GET method first) Add a Cache layer after able to server HTTP GET Request Add performance test benchmark like web bench Add Timer to kill long-time inactive client connections Don't be lazy and add comprehensive Unit Test Any critique/advice/suggestions would be appreciated either on my current implementation or future next-step plans! I am pretty inexperienced in Networking and C++ language. There must be a lot of places I could learn to do more and do better!
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services Edit: I've started to reflect and revise according to the kind suggestions I receive in another branch code-review-revision for people's reference. I have just improved upon suggestions by rioki. And will continue to do so w.r.t to suggestions by pacmaninbw. Since I recently drafted out an additional basic HTTP-GET only component of my framework, I think a lot of lessons I learned here could be applied to that component as well. I will try to do so. Answer: #ifndef SRC_INCLUDE_UTILS_H_ #define SRC_INCLUDE_UTILS_H_ #define NON_COPYABLE(class_name) \ class_name(const class_name &) = delete; \ class_name &operator=(const class_name &) = delete #define NON_MOVEABLE(class_name) \ class_name(class_name &&) = delete; \ class_name &operator=(class_name &&) = delete #define NON_COPYABLE_AND_MOVEABLE(class_name) \ class_name(const class_name &) = delete; \ class_name &operator=(const class_name &) = delete; \ class_name(class_name &&) = delete; \ class_name &operator=(class_name &&) = delete #endif // SRC_INCLUDE_UTILS_H_ You should try to avoid using macros. If you really can't write a deleted copy constructor and assignment operator, you should look into something like boost::noncpyable, it's really simple, you can put one in your code and it's proper C++. The NON_MOVEABLE is actually useless, since classes that are non copyable are automatically non movable. If you want default move, you need to add explicit defaults. Even through NON_COPYABLE_AND_MOVEABLE with an obsolete NON_MOVEABLE making NON_COPYABLE_AND_MOVEABLE obsolete; following the DRY principle, you should call lNON_COPYABLE and NON_MOVEABLE from NON_COPYABLE_AND_MOVEABLE. #ifndef SRC_INCLUDE_BUFFER_H_ #define SRC_INCLUDE_BUFFER_H_
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services #ifndef SRC_INCLUDE_BUFFER_H_ #define SRC_INCLUDE_BUFFER_H_ If you are using macro include guards, you should probably name them something unique. Adding the name of your library is a good idea, such as _TURTLE_BUFFER_H_. The chance is to high that SRC_INCLUDE_BUFFER_H_ is used by some other library. #define INITIAL_BUFFER_CAPACITY 1024 Consider using constexpr for defaults and put them in your namespace. namespace TURTLE_SERVER { This namespace would drive me crazy. I prefer stating the namespace on every object. For example std::vector, glm::mat4 or c9y::sync. You notice how the namespaces are really short? I think turtle::Server is about as much as I could muster. class Buffer { friend class Connection; public: // a few functions private: std::vector<char> buf_; }; Why does Connection need access to Buffer's private parts. I think in the sense of logical modularization, connections use buffers, but are certainly not part of a common API. class Buffer { public: explicit Buffer(size_t initial_capacity = INITIAL_BUFFER_CAPACITY); ~Buffer() = default; }; I would add two constructors, one with the value and the other as default constructor. I find adding default values, which live in the calling code, hinder making small changes without ABI breaks. Also if the constructor is copyable, I would add defaulted copy constructor and assignment operator, following the rule of five. class Buffer { public: void Append(const char *new_char_data, size_t data_size); private: std::vector<char> buf_; }; Since Buffer is almost certainly not handling text, consider using std::byte instead of char. auto Buffer::ToCString() -> char * { return reinterpret_cast<char *>(buf_.data()); } auto Buffer::ToString() const -> std::string { return {buf_.begin(), buf_.end()}; }
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services auto Buffer::ToString() const -> std::string { return {buf_.begin(), buf_.end()}; } (Not a fan of trailing return type, but that's fine.) You probably should also provide a const version of the function ToCString for read only access. If you are interpreting the contents of the buffer as strings, consider providing a view as a string_view to prevent copying the data. class NetAddress Think of the name in context, what other type of address exists in a networking library? Consider turtle::Address. (If you write the namesapce, you do not need namespace like bits in the name of objects.) class NetAddress { public: explicit NetAddress(bool is_ipv4 = true); NetAddress(const char *ip, uint16_t port, bool is_ipv4 = true); }; You probably should defined an enum named Protocol with the values IP4 and IP6. This makes the code simpler to understand at the call site, since NetAddress(true) is not explicit, compared to NetAddress(Protocol::IP4). Also, why do calls need to specify the protocol at the default construction of the NetAddress? std::ostream &operator<<(std::ostream &os, const NetAddress &address) { os << address.ToString(); return os; } Since you already have a ToString function, consider defining the stream operator as standalone. class Socket { public: explicit Socket(bool is_ipv4 = true); void Connect(NetAddress &server_address); void Bind(NetAddress &server_address); }; Consider delaying the creation of the socket so that you can derive the protocol form the NetAddress. Socket::Socket(bool is_ipv4) : fd_(-1) { if (is_ipv4) { fd_ = socket(AF_INET, SOCK_STREAM, 0); } else { fd_ = socket(AF_INET6, SOCK_STREAM, 0); } if (fd_ == -1) { perror("Socket: socket() error"); exit(EXIT_FAILURE); } }
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services This is C++, you probably should throw an exception here. You can later still to the perror and exit. But the client code of Socket may not agree with your error handling strategy here. (Applies to all other instance error handling.) Socket &Socket::operator=(Socket &&other) noexcept { if (fd_ != -1) { close(fd_); } fd_ = other.fd_; other.fd_ = -1; return *this; } Properly implementing move is hard. There are different theories what is correct. But in this case I think swapping the fd_ and letting the destructor of the rvalue handle cleanup would be a viable strategy that reduces code duplication. auto Socket::GetFd() const -> int { return fd_; } This probably should be noexcept. You probably should have WAY more noexcept. Any function that has no sane way to throw an exception should have noexcept; your optimizer will thank you. class Connection { public: explicit Connection(Looper *looper, std::unique_ptr<Socket> socket); }; You put so much effort into making Socket movable and now you are using a unique_ptr? Both are viable strategies, but you should decide wich aproach you want to take. I would prefer unique_ptr, a tad more expensive, but at least you can't mess up any move semantics. The lopper object is not used by the Connection, you probably should remove it. class Connection { public: auto GetReadBuffer() -> Buffer *; auto GetWriteBuffer() -> Buffer *; auto GetReadBufferSize() -> size_t; auto GetWriteBufferSize() -> size_t; void WriteToReadBuffer(const char *buf, size_t size); void WriteToWriteBuffer(const char *buf, size_t size); void WriteToReadBuffer(const std::string &str); void WriteToWriteBuffer(const std::string &str); };
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services Not sure if these function should be public. You should have a send / receive API that know nothing of buffers or the buffers are the bits moving though your system. For example, either: class Connection { public: void Send(const std::string& value); void Send(const unsigned int value); void Send(const float value); std::string ReciveString(); unsigned int ReciveUint(const value); float ReciveFloat(); }; or: class Connection { public: void Send(const Buffer& message); Buffer Recive(); }; Here an elegant way to build and decode a buffer may be of use. class TurtleServer { public: explicit TurtleServer(NetAddress server_address) : pool_(std::make_unique<ThreadPool>()), looper_(std::make_unique<Looper>(pool_.get())) { auto acceptor = std::make_unique<Acceptor>(looper_.get(), server_address); acceptor->SetCustomHandleCallback( [this](auto &&PH1) { OnHandle(std::forward<decltype(PH1)>(PH1)); }); acceptor->SetCustomAcceptCallback( [this](auto &&PH1) { OnAccept(std::forward<decltype(PH1)>(PH1)); }); looper_->AddAcceptor(std::move(acceptor)); } Why the inline constructor. This feels like is a super expensive operation. class TurtleServer { public: auto GetPool() -> ThreadPool * { return pool_.get(); } auto GetLooper() -> Looper * { return looper_.get(); } }; You have many accessor functions like there. I ask my self does client code really need to look this much into the guts of these classes? Consider if you can remove implementation details from the API. class EchoServer : public TurtleServer { public: explicit EchoServer(NetAddress server_address) : TurtleServer(server_address) {} void OnAccept(Connection *server_conn) final {}
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
c++, object-oriented, c++17, networking, web-services void OnAccept(Connection *server_conn) final {} void OnHandle(Connection *client_conn) final { int from_fd = client_conn->GetFd(); auto [read, exit] = client_conn->Recv(); if (exit) { client_conn->GetLooper()->DeleteConnection(from_fd); // client_conn ptr is destoryed and invalid below here, do not touch it // again return; } if (read) { client_conn->WriteToWriteBuffer(client_conn->ReadAsString()); client_conn->Send(); client_conn->ClearReadBuffer(); } } }; This feels very old school OO. Consider providing an API with callbacks. Consider the following: int main() { auto server = turtle::Server(turtle::Address("0.0.0.0", 20080)); server.onHandle([&] (turtle::Connection& conn) { auto [read, exit] = conn.Recv(); if (exit) { server.Close(conn); return; } if (read) { conn.Send(conn.ReadAsString()); } }); }
{ "domain": "codereview.stackexchange", "id": 44277, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, c++17, networking, web-services", "url": null }
rust Title: The Twelve Days of Christmas Question: I'm trying to learn Rust and for this reason I'm reading the Rust Book. It contains the following exercise: Print the lyrics to the Christmas carol “The Twelve Days of Christmas,” taking advantage of the repetition in the song. Here's my take. Note I'm only using material from chapters 1-3 of this book (since I've only read so far yet), with the exception of unreachable, which I nonetheless think needed to solve this exercise. Sorry for managing the letter case in such an ugly way. Unfortunately, my Googling revealed that letter case in Rust is somewhat complicated and probably uses stuff from later chapters of the book, so I thought I'd "cheat" my way out of this problem like I did in this code: use std::cmp::Ordering;
{ "domain": "codereview.stackexchange", "id": 44278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }