Rust-Based, Memory-Safe PNG Decoders "Vastly Outperform" C-Based PNG Libraries

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts
  • back2未來
    Phoronix Member
    • Oct 2023
    • 79

    Originally posted by sdack View Post
    *lol* Thanks for that. I hope it was meant as a joke! ... No null-pointer checks, no check whether size is 0, no memory check, ... and contents should have been char* per cURL docs. Lots of missed opportunities to write good code.
    [ sorry ( ) for the funny moment, but i had to reach out for the cpp expert (this version is only from his assistant) and that's the update available (for further amusement&delight):

    Code:
    #include <iostream>
    #include <curl/curl.h>
    #include <nlohmann/json.hpp>
    #include <functional>
    
    using json = nlohmann::json;
    Code:
    // Callback function to handle data received from libcurl
    size_t WriteCallback(char* contents, size_t size, size_t nmemb, std::string* out) {
     if (contents==nullptr || out==nullptr) {
      std::cerr << "Error: Null pointer passed to WriteCallback" << std::endl;
      return 0;
     }
    
      size_t totalSize = size * nmemb;
     if (totalSize == 0) {
      std::cerr << "Error: Received empty data (size=0)" << std::endl;
      return 0;
     }
    
     // Append data to the output buffer
     //out->append(data, totalSize);
     out->append(contents, totalSize);
      return totalSize;
    }
    
    void fetch(const std::string& url, const std::function<void(const json&)>& callback) {
     if (url.empty()) {
      std::cerr << "Error: Empty URL provided" << std::endl;
      return;
     }
     if (callback == nullptr) {
      std::cerr << "Error: Null callback function provided" << std::endl;
      return;
     }
    
     CURL* curl = nullptr;
     CURLcode res;
     std::string readBuffer;
    
     curl_global_init(CURL_GLOBAL_DEFAULT);
     curl = curl_easy_init();
     if (curl == nullptr) {
      std::cerr << "Error: Failed to initialize CURL" << std::endl;
      return;
     }
    
     curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
     curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
     curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
    
     res = curl_easy_perform(curl);
     if (res != CURLE_OK) {
      std::cerr << "Failed to fetch " << url << ": " << curl_easy_strerror(res) << std::endl;
     } else {
     // Check if readBuffer is empty (size 0) before attempting to parse
     if (readBuffer.empty()) {
      std::cerr << "Error: Received empty response body from " << url << std::endl;
     } else {
     try {
      json jsonData = json::parse(readBuffer);
      callback(jsonData);
     } catch (const json::parse_error& e) {
      std::cerr << "Failed to decode JSON from " << url << ": " << e.what() << std::endl;
     }
     }
     }
     curl_easy_cleanup(curl);
     curl_global_cleanup();
    }

    Code:
    int main() {
     fetch("http://worldtimeapi.org/api/ip", [](const json& data) {
     if (data.is_null()) {
     std::cerr << "Error: Received null JSON data" << std::endl;
     return;
     }
     std::cout << "Received data " << data.dump(4) << std::endl;
     });
     return 0;
    }
    edit_from_feedback: It is now ~83 lines (previous version: 48 lines), including comment lines, empty lines, formatting line forwards&carriage returns and descriptive error messages.
    A most compressed source code can be difficult to handle without also descriptive comments (and that's before the compiler&build system or at least the interpreter (~Perl or Python, byte-code or IL) translates to machine code)?

    (thx) ]
    Last edited by back2未來; 13 December 2024, 09:38 AM. Reason: code review

    Comment

    • TheMightyBuzzard
      Senior Member
      • Sep 2021
      • 416

      Originally posted by duby229 View Post

      That's not entirely true actually. Multithreading is built into the structure and syntax of rust. It's a fundamental part of rusts standard library. Coherency is built into rust at a fundamental level. But in C you have to literally do it all manually. Nowadays there are APIs you can use like a template, but you still have to do your own memory management. Coherency is really hard in C.
      You say that like it's something that isn't absolutely expected and dealt with to the point of becoming boring by C devs.

      Comment

      • TheMightyBuzzard
        Senior Member
        • Sep 2021
        • 416

        Originally posted by Mordrag View Post

        Tell me you haven't written Rust without telling me you haven't written Rust. Please go to crates io and lookup some popular crates. It is ridiculous how many are still not 1.0.0 with great documentation and dx overall. I've never seen that kind of quality control in any ecosystem except Rust's.
        That I have written Rust is precisely why I can say it with absolute certainty. I even contributed to a few crates back before they all started adopting CoCs. The second they did I stopped contributing to them.

        Comment

        • sdack
          Senior Member
          • Mar 2011
          • 1724

          Originally posted by back2未來 View Post

          [ sorry ( ) for the funny moment, but i had to reach out for the cpp expert (this version is only from his assistant) and that's the update available (for Your further amusement&delight):

          Code:
          ...
          // Callback function to handle data received from libcurl
          size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* out) {
          ...
          // Ensure contents is treated as a char*
          char* data = static_cast<char*>(contents);
          if (data == nullptr) {
          std::cerr << "Error: Invalid data received in callback" << std::endl;
          return 0;
          }
          ...
          It is now ~91 lines (previous version: 48 lines).

          (thx) ]
          What I meant with contents being char* is that its type is from the beginning char* and not void*. You can just write char *contents in the function declaration. See here:

          Comment

          • duby229
            Senior Member
            • Nov 2007
            • 7779

            Originally posted by TheMightyBuzzard View Post

            You say that like it's something that isn't absolutely expected and dealt with to the point of becoming boring by C devs.
            How could it be boring when your code corrupts itself and there is no possible way of figuring it out? I'd think frustrating would be a better term.

            Comment

            • smitty3268
              Senior Member
              • Oct 2008
              • 6954

              Originally posted by TheMightyBuzzard View Post

              How experienced are you? Because the answer is "any and all of them may be if you're dealing with a fresh graduate". But if you are a fresh graduate (or a fanboi to the point of self-delusion) you'll deny this.
              I'm a very experienced programmer (though not with Rust), and I'm well aware that the average new grad is useless. But this whole conversation was assuming at least some basic level of competence. Those types that are able to learn do exist, as long as you are doing proper screening during the job interviews.

              I mean, if you are just saying they're completely useless, then I'd actually argue more so that Rust is better than C because at least the compiler holds their hands a bit and works out a lot of the bugs up front. If a dev is mystified by Rust's error handling code, they're going to be equally mystified the first time they see a void * in c, and a lot more likely to submit something with runtime errors in it I have to debug for them.
              Last edited by smitty3268; 10 December 2024, 09:55 PM.

              Comment

              • ssokolow
                Senior Member
                • Nov 2013
                • 5095

                Originally posted by TheMightyBuzzard View Post
                I wish that were the case. Kids loooooooove using the Shiny New Thing They Just Learned even when it is of absolutely zero benefit. Like using futures in a library whose logic absolutely necessitates blocking at every step of its single thread, just because they wanted to play with futures. I've actually seen that done. I stopped using and contributing to that library on the grounds that its author was an idiot.
                Fair... though you'd be surprised how demotivating for that kind of behaviour "shiny new thing is a perfectionist nitpicker" can be.

                Comment

                • mobadboy
                  Senior Member
                  • Jul 2024
                  • 167

                  the classic "too stupid to learn rust" folks rearing their dumb ass heads yet again

                  bet u dont wear a seatbelt either because u r too good to crash

                  and before you say anything so dumb as fuck, the point is that it helps to protect u against others mistakes. one-person projects have one coding style, one understanding of the code. rust makes it much easier to scale contributors and have many people contribute to the same codebase without all of the same footguns, and without needing to completely understand every dumb ass macro some neckbeard wrote because they thought preprocessor macros weren't dumb as fuck.

                  only the most novice of programmers think the c and c++ approach to memory management etc is a good idea for end-user applications. at least c++ has smart pointers although they suck to write out (std::unique_ptr EW) and can still easily be fucked up if you dont check the var.
                  Last edited by mobadboy; 11 December 2024, 12:11 AM.

                  Comment

                  • hasnoidea
                    Junior Member
                    • Aug 2022
                    • 6

                    Originally posted by TheMightyBuzzard View Post
                    Oh, wait, are you a recent grad yourself and think you know everything? Or anything for that matter?
                    Nope. But bold of you to assume someone may know everything.

                    Comment

                    • back2未來
                      Phoronix Member
                      • Oct 2023
                      • 79

                      [ interested, if there are preferences for programming languages on gender, it appeared being (by far, still) a mainly male task, globally, year ~2022:
                      male ~91.9%, female ~5.2%, non-binary&genderqueer&gender_non-conforming ~1.7%, prefer_not_to_say&own_words ~1.6/0.7%

                      While it seems there's a discussion about binary efficiency and source code maintainability (and unique advantages for programming languages), there's few statistics about efficiency on programming structures being 'infrastructure/framework/ide' for the tasks, on the long run (but for sure empirical results, from individual experience, are recognizable).
                      "Programmed differently? Testing for gender differences in Python programming style and quality on GitHub"
                      generally elaborates on that, for maintenance issues on modern programming languages, with
                      "This study has argued that code is a form of communication in OSS. Code in OSS shares features with written text: It has authors and is read, understood, and shared. Contributing code is fundamental to open source, yet code interpretation is mediated by cultural norms and context that extend beyond the specifics of a particular programming task. Code is embedded in a system of communication, meaning that assessments of quality are intrinsically tied to the perceptions of the author. Gender and masculinity have been powerfully associated with quality in programming, suggesting that notions of gender difference have become widespread without empirical evidence."
                      and resumes
                      "The study concludes that gender differences in Python code are a matter of style, not quality."

                      Within this context also; is 'Rust' a modern, up-to date programming language, specialized or universal, more than, e.g. Cpp? (thx) ​]
                      Last edited by back2未來; 11 December 2024, 05:32 AM.

                      Comment

                      Working...
                      X