Rust Placeholder PNG Generator
Decided to try my hand at a little rust. Figured a simple CGI application that generates solid color placeholder PNG files as quickly as possible would be a reasonably interesting project.
It’s probably terribly written since I’ve never written Rust before, and it’s syntax is pretty arcane. Nevertheless, the source is available.
How it works: The CGI application reads width and height out of the PATH_INFO tacked onto the end of the URL. It’s pretty simple – just looks for numbers and makes sure they are between 10 and 4000. The first one encountered is used as the width and the height is the second. (I was going to add a color and border setting, but decided this was good enough as a learning exercise. It would not be hard to add either, however.)
A bunch of Vec:<u8> shennanigans ensue and the necessary headers and PNG contents are printed to STDOUT. Partly in an effort to learn, I build the PNG contents without the aid of a PNG library.
The resulting is indeed pretty fast. Once the connection is established, it can usually return even large PNGs in about 40-60 ms.
Some example URLs:
Some take-aways from my first dive into Rust:
- The compiler is very helpful and will tell you how to fix simple problems.
- I still don’t understand borrowing. Reading up on the tutorials and documentation involving ownership would probably have been a good idea. I squeaked by on the compiler’s messages.
- The standard library is pretty limited, by design from what I understand, so expect to be using some carts from Cargo for a lot of things.
- Binaries can get pretty big – Rust optimizes for speed by default, not size. There are guides online for optimizing rust binary sizes.
- (For Linux) Binaries are linked to the standard C library so if you’re deploying to another system consider using MUSL or just ensure whatever machine you’re building on is using an older version than the deployment target.