237 points · by agluszak · 5y ago · 214 comments
pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
fn inner(path: &Path) -> io::Result<Vec<u8>> {
let mut file = File::open(path)?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes)?;
Ok(bytes)
}
inner(path.as_ref())
}
--Nobody seems to care, but there's a crate that does this for you https://github.com/llogiq/momo
But the Rust compiler should be doing this automatically :(
This will become a lot easier once the actual full const-generics implementation lands. Because then even your "non-generic" implementations will be enabled to depend on compile-time-defined features of the instantiated type (such as size, alignment, value bounds etc.) without any sort of duplicate code generation. Of course, these in turn should delegate to truly non-generic code when feasible to minimize bloat.
fn read(path: &Path) -> io::Result<Vec<u8>> {
let mut file = File::open(path)?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes)?;
Ok(bytes)
}
which I find readable. Comparing to another language...I haven't written Go in a while, but I think the rough equivalent would be: func Read(path *Path) ([]byte, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
slice, err := io.ReadAll(file)
if err != nil {
return nil, err
}
return slice, nil
}
(Maybe in this case you'd just return the io.ReadAll rather than doing an if, but I'm trying to use similar constructs. The ? is something you can use all throughout the function, not just at the end, so I tried to match that pattern.)[edited: I said there wasn't a io.ReadToEnd extracted from io.ReadFile in Go, but jatone pointed out it's called io.ReadAll.]
file.read_to_end(&mut bytes)?;
`bytes` is already mutable. `read_to_end` is already declared as taking a `&mut Vec<u8>`. So why force every caller to do a `&mut` un-necessarily ? fun read(path: &Path): io.Result[Vec[UInt8] {
var file = File.open(path).orReturnErr()
var bytes = Vec.new()
file.readToEnd(&mut bytes).orReturnErr()
Ok(bytes)
}
would be good enough for me, tbh. (defn Read [path]
(io/ReadToEnd (os/Open path)))
Now that's what I call readable!is the golang equivalent.
Compare:
def read(path):
What is path? Unknow. What it read? Unknow. What it return? Unknow pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
What is path? Anything that can become path on the file system.What it read? Anything that can be pointed with that PATH
What it return? Vec of bytes or a IO::Error
PLUS: This code is compiled tot he exact types that call it, Path not allocate, the result can be cloned, the errors are defined in IO, ....
--
Rust is very readable: Almost any line tell you what is happening and what expect.
Where it get messy is when it hide that crucial info. But is not many times it happens.
Your example is also less about Rust and more about type signatures.
pub fn read<P>(path: P) -> io::Result<Vec<u8>>
where
P: AsRef<Path>,
{
And of course if you were using a lot of u8 vec results, you might create a shorter alias for that. # Your big function has specific types
function my_function(x::UInt, y::UInt)
[ ... ]
end
# Wrapper function to minimize monomorph. cost
my_function(x::Integer, y::Integer) = my_function(UInt(x), UInt(y))Things<Like<This, That>, That> -- as in C++
Instead of a more legible (and very familiar to Rust authors)
Things (Like This That) That -- as in Haskell
Inherited from C++, we had also :: for namespacing (while a dot . could be perfectly be used for that), and tons of other stuff like <> for scoping generics.
Without some of that we could have:
pub fn read<P: AsRef Path>(path: P) -> io.Result (Vec u8) {
fn inner(path: &Path) -> io.Result (Vec u8) {
let mut file = File.open(path)?;
let mut bytes = Vec.new();
file.read_to_end(&mut bytes)?;
Ok(bytes)
}
inner(path.as_ref())
}
Perhaps it looks a little better? It looks for me, at least.For doing better than that we could drop C-like syntax perhaps?
The trouble is that languages have a weirdness budget - there's a finite amount of novel stuff a language can have until it becomes too weird for mainstream programmers. So language designers have to pick their weird features carefully. Spending it all in novel syntax is unwise.
I think that at the time the Rust pull was safety for low level code and, as Rust was targeted to replace some C++ components, following C++ syntax was seen as a good idea.
And that was a good decision. If it were too far from the C++ syntax, I would not have learned it, because as a mostly C++ guy at the time, some similarities with C++ helped me keep interest in Rust. Also, I was unable to parse Haskell's "type parameters as function applications" syntax, which was purely confusing. The Rust syntax is an abomination, that's true, but it is a necessary evil.
let x = Foo::new();
x.bar();
Foo::bar(x);Not saying it's good or bad, just how Rust ended up where it is.
This is so true, and so hard to convey to a lot of people, even in engineering. They like to abstract humans as machines that can just context switch at a whim, which is just not true.
It also models your source code in your build system (exposing libraries, binaries, etc).
I'd love to see a performance comparison with `rules_rust`.
There are also a number of other open source alternatives such as Buildbarn (https://github.com/buildbarn) and Buildfarm (https://github.com/bazelbuild/bazel-buildfarm) which you can host yourself.
Personally, I've found Buildbarn great to throw up in Kubernetes and build massive projects with.
I haven't really used Bazel much, but the features it brings are really huge: reliable pure compilation, so you can actually do globally cached and distributed builds reliably.
Maybe I should try it.
It's worth noting that there's a sort of uncanny valley in the amount of time something takes: when it's short, it's not too big a deal to wait for it. When it's fairly long (and predictably so), it's easy enough to context switch (I used to read a lot waiting for compiles to finish). It's the stuff in the 5–10 minute range that kills you.
What depresses me, is that while I can now do something else in a different window while a process runs, the issues with errors and requiring interaction still persist.
As a library author, I sometimes wonder if I should be introducing more feature flags into my crate to let people only use the bits that they want, in order to help compile times. The whole thing doesn't take very long to compile (~20 seconds), but maybe the added complexity of juggling feature flags might be worth it.
In particular, please for the love of god don't put the whole kitchen sink into the default feature. I'd even argue don't ever have a default feature at all. In practice, once a codebase gets above a specific size, it becomes completely impossible to exclude any features in a crate's default list because `default-features=false` only applies locally. Something 5 levels deep will bring those features in whether I like it or not just by not specifying anything.
Also, please don't do things like how slog uses a feature flag to control minimum log levels, or k8s-openapi uses it for version selection. These kinds of usages create extremely frustrating problems.
Honestly, features -- and especially the way default features work -- are the worst thing about cargo to me. I think they should be a lot more restricted than they currently are. If I had my way you'd only be able to use `#[cfg(feature = X)]` at module level to include or exclude code, never to select actual behaviour.
To me they're filling a hole that crates themselves should be filling. Certain language features aren't really rich enough to make really effective 'additive' crates though, unfortunately.
Curious, what that specific size approximately is? For rust-analyzer, getting all the deps to use features correctly is rather annoying, but isn’t particularly time-consuming.
If you depend on crates A and B, and B depends on A, and you specify `default-features=false` on A but B doesn't, you will always get A's default features included in your compile. There is no way to prevent this.
Your 20 second library is not too bad when it's used on its own, but add 5 or 6 libraries that all "only" take a few seconds and you're waiting a solid five minutes compiling other people's code and their dependencies.
Even simple Rust programs quickly end up compiling several versions of several libraries because of the dependency tree, some of which can include large libraries like Tokio and Serde. I love libraries that make use of feature flags, they massively cut down on my compile time.
This isn't really any library developers' fault, it's a problem with the entire ecosystem. Cargo is not dissimilar from NPM where you can quickly end up with an exploded dependency chain of hundreds of megabytes in supporting code before you even realize.
Some smaller libraries I've seen that just do some annoying-to-test but simple string manipulations have had similar compile times, mostly because they include specific versions of advanced logging or error reporting libraries for no obvious reason.
For example in the `procfs` crate, there's a dependency on `flate2` just in case a /boot/config.gz file exists (in order to see what options the kernel was built with). But if a consumer never needs to inspect the kernel options, this dependency (and related code) is just dead-weight.
The nice thing about rust is that this code will be removed from the final executable if it's unused, but maybe it's time to start thinking more carefully about compile times.
20 seconds once per machine per dependency version (i.e. there is no rebuild of the dependency until you change compiler flags or update the library) is OK.
Features are super neat, but it’s easy to see them overused. It’s also a bit hard to adequately test arbitrary combinations of features. It’s a different concern from a library, but we saw this with one of our applications. We had a situation where we were using features where we should have just been using env vars for feature flagging, and it caused a fair bit of hassle. We’ve since ripped out that usage, because we never in practice tested or deployed with anything other than “all features,” and even in the case where we want to use some functionality to upsell, enabling an env var and restarting is way easier than recompiling the project.
Personally, dynamically linking dependencies and using the `mold` linker has given me the most bang for my bucks. You can't dynamically compile all crates (actix_web, sqlx) unfortunately due to some assumptions macros make about crate paths (using Bevy scheme). And this exclusion extends to all crates pulled in as [dev-dependencies].
Consensus seemed to be that reqwest is the way to do this using rust, since the stdlib does not include an http client.
Adding the dependency on reqwest tried to pull in over 100 dependencies and after building for a while, it failed somewhere along the way because my rust version was too old. Now, maybe some of these were optional dependencies, but they all got pulled in automatically.
so, when TFA says
> Another obvious advice is to use fewer, smaller dependencies.
I just went back to go, which can do the crazy obscure task of making an http request without requiring 100 external dependencies.
Raw dependency counts can be shocking for those coming from other languages where pulling in a dependency is an uncommon operation, but it's not a bad thing. I'd rather have my HTTP client library re-use popular, tested packages for things like decoding JSON, handling TLS, working with IP addresses, and other common tasks. I don't think it would be better to have every package roll their own versions of all of those common pieces.
You can browse the dependencies of reqwest here: https://crates.io/crates/reqwest/0.11.4/dependencies
Notably, several of the big dependencies are maintained by the same person who maintains reqwest. It's a common practice with Rust crates to split a project into reusable parts. Reqwest uses hyper (http client), http, http-body, mime, url, and several other crates that are owned by the person who owns the reqwest crate.
If we instead mashed all of those dependencies together into a single crate it would appease the people who don't like seeing high dependency numbers, but it wouldn't really make the product any better. It would make it harder to re-use the individual pieces, though.
> I just went back to go, which can do the crazy obscure task of making an http request without requiring 100 external dependencies.
Go is famous for including HTTP utilities in the standard library. If I was building a simple app that made HTTP requests and little more, I'd probably pick Go as well. Or Python.
Or you could have searched for a minimal HTTP request crate ( https://github.com/algesten/ureq ) designed to be small instead of using the most full-featured crate.
Or you could have searched for Rust libcurl bindings ( https://github.com/alexcrichton/curl-rust ) to use an old standby.
If your goal is to reach for something quick and easy with batteries included and minimal external dependencies, Rust is not a good choice. Doesn't mean Rust is "bad", but it's not the right tool for every simple job. You also can't just pick the most popular crate and assume it's exactly what you want.
Precisely this. Rust is not the same as Go or Java or Python: it's still a fairly low-level language. Standard practice is to build lower-level components (like http parsing and url crates) that are abstracted over by more 'friendly' crates (like reqwest). It's jarring, and certainly different from a lot of other languages, but it's a testament to the language's flexibility in my eyes.
Seeing how they are different languages, there's not a single language feature that explains this dependency gluttony.
I'd like to open up the option that it is a necessary side-effect of large ecosystems: more devs using the language, more packages published, more quality in small packages. And then, when building a large-ish package, it only makes sense to use existing packages rather than reinventing the wheel.
And so, driven by nothing but good will and best practices, since you have a lot of prebuilt "assets" at your disposal ,your project ends up with 100s of deps and everybody complains.
Yes, for instance one of `reqwest`'s dependencies is `base64`. We can argue both that re-inventing base64 in every big library is pointless, and also that a language doesn't need base64 in its stdlib because C and C++ don't have it.
There's no right way to cut this cake - Many a language has included something in the standard library, and then struggled to fix a broken interface once everything depended on it. (Like JS picking UTF-16 for strings) Many a language has also failed to include something in the stdlib and caused every application to suffer and re-invent it. (Like C++ not really saying anything about Unicode strings, which means Qt and everyone else has their own little take on it.)
And the suffering is only bigger if you make dependencies artificially hard to add.
Rust's approach is more flexible, at the cost of building the universe from scratch every time you make a new workspace. Personally I don't mind it. At least it's not like the problems I've heard from Haskell land. Moving from futures to async in Rust was fairly smooth.
The question is whether that code is going to come from a monolithic Swiss Army Knife of a library (aka a standard library), a bunch of packages, or some code that everybody copies into their codebase. In which case the packages option doesn't seem so bad. At least they're explicitly versioned, tracked for vulnerabilities and can be updated at a granular level.
Doesn't seem hard to work out.
I don't follow this logic. If we just wanted to do everything the way C/C++ does it, we'd be using C/C++, and Rust wouldn't exist.
Other languages that don't face this, e.g. Python, have very large standard libraries which already include a dizzying array of features. E.g. take a look at some of the things you get with standard Python[0].
- sqlite3 (DB-API 2.0 interface for SQLite databases)
- bz2 (Support for bzip2 compression)
- sunau (Read and write Sun AU files)
- netrc (netrc file processing)
- curses (terminal handling for character-cell displays)
- mailbox (manipulate mailboxes in various formats)
https://leancrew.com/all-this/2012/04/where-modules-go-to-di...
HN discussion: https://news.ycombinator.com/item?id=3913182
The obvious compromise would be to let libraries bake as third-party projects for a good long while until there's a fair amount of consensus that they're the Right Thing To Do, then pull them into the standard library. Java's Joda-Time would be one example.
One recent build I did, a small library included a dependency to build its documentation. This was a full-fledged documentation project, which pulled in hundreds more dependencies.
It would be interesting to see a display of “cost” in projects indicating how much additional dead weight each individual dependency pulls in. This might lead to slight better decisions on dependencies to choose.
cargo-bloat is kind of along these lines, although it only measures the absolute size of each dependency (as opposed to "dead weight") and has some platform limitations.
It depends a lot.
Java has a huge ecosystem, but almost all of the core functionality is provided for you.
Like everything there's a 90/10 rule in that 90% of the 'things we need' really amount to only 10% of the total packages out there, so it actually makes sense that the people backing the platform provide for it.
Language, compiler, debugger, documentation, tutorials, standard libraries etc. - it's all part of the platform.
Looking at it that way, it becomes a little more obvious why even some cool languages don't quite breakthrough.
As another commenter pointed out, it may relate more to the size of the standard library than to the size of the ecosystem. Which your comment seems to emphasize as well.
What seems to be missing is standard library as constellation of well designed modules/packages. I decided to just do it for myself (and anybody who finds it interesting). I don't think it's going to fly high but if somebody is interested the link is here [0]. I'm adding modules every few days.
The aim is to have something worthwile to show around the time node v16 goes lts. I have some experience taking care of high stake business critical systems. This is fun side project as a hobby atm. Modules being dropped there are reflection of problems I'm facing during my day-to-day work.
You'll see there some non conventional code. Large parts are inspired by functional programming, ocalm and simplicitly in general. Personally I find it exciting how well this kind of approach fits into production projects.
The nice thing about this approach is that you can have niche leaf packages/modules as part of standard library (constellation) - if you don't want to use it, it doesn't matter, it wont incur any cost. For example order book module or exchange matching engine - those can simply live there, be useful to people who care and have zero impact to people who don't care at all. I find it to be an interesting difference from builtin, shipped library.
Large package ecosystem is a sign of popularity. With time libraries should converge onto shared approaches. Interestingly practice shows wide spread of duplication. I think more effort from big players with wide reach could reduce it. Ie. not me doing stuff but Microsoft or others picking up the ball.
That _is_ the tradeoff - Rust builds up from nothing and makes it friction-less to add a new dependency. Go starts at a higher level and the friction for adding new stuff is high. And some of the high-level stuff, like the GC, can't be removed.
Not really, it's just a 'go get'.
How often are folks writing applications that don’t need to connect to the web these days?
Maybe the lesson here is to update Rust if you haven't used it in a while?
For Go, perhaps rarely. For Rust, not needing to touch the web is extremely common.
Let's also keep in mind that Rust's stdlib does include IP, TCP, and UDP.
In Go? Rarely, I would expect. In Rust, I'd assume connecting to the web is the exception rather than the norm. Most Rust projects tend to be lower-level infrastructure & systems programming.
This probably explains, and in turn is explained by, their different choices re: http in stdlib. They have much different aims and target use-case.
Every day? I think the only one I've done that in Rust it was through the program I was wrapping anyway.
Or... `rustup update`...
Rust is a system language.
For example, one shock is that you can't print! or dbg! anything (without adding Debug/Display to each type).
The reasons?
Where it will print in a Airpod? yeah: Rust is made to work in places where NOT exist a place to print to. Or where NOT exist a filesystem, or HTTP because not exist TCP because not exist a network card.
So, in Rust all start in the deepest of the deepest bottom.
---
I have a good metric to select frameworks/libraries:
- If is too complex, NO except if is the only game on town
- If have crazy deps setup (ejem: OpenSSL, bastard mess of dep!) NOOOOO. (except if is the only game on town)
- If is too big, damm be good and solid (ej: PostgreSQL)
Whatever the lang, this have served me well, and when I have been lazy (I get a deps to OpenSSL and waste 1 week fixing CI builds with it then remember this and cut that mess) the pain quickly fix it.
So, next time you get a trouble like this (in Rust or whatever) ask what alternatives you can use instead!
Dude it's like one command to update.
They could at least package rustup, I have no idea why they don't.
Rust went for "evergreen" approach like Chrome. It focuses on making small gradual changes, quick and painless upgrades, and provides stability via backwards compatibility in the compiler. This allows everyone to only target one version: the current one.
Debian's philosophy is the polar opposite, so Debian's Rust version is doomed to be perpetually obsolete.
I'd say, first of all, that it does matter, because very few projects with hundreds of (transitive) dependencies are going to be able to take security sufficiently seriously. And because minimizing the number of other projects you rely on is good engineering (see: left-pad).
I don't think the other two explanations are much better. Compare C as an example. With C you can use libcurl which is well-maintained, actually supports far more protocols than simply http(s), and uses far fewer dependencies to do it. It also runs on an insane number of platforms, so portability isn't the issue here either.
I think it primarily comes down to cultural differences. Rust is a newer, "cooler" platform, and attracts a very different audience than C does. Because of that Rust's users will be more apt to follow common modern programming practices: using a language's built in package manager and so on. (This culture both contributes to the development of languages like Rust and is fed by them.)
Remember the XKCD "Python" comic? [1] Python is what I would consider an older language in terms of culture, but it captures the idea of being able to just import a library that can already magically do everything you want. "Programming is fun again", you don't have to write boilerplate or worry about managing dependencies any more. The problem begins when everyone has that attitude, including the people writing libraries that will be used by others. Importing a library that can instantly solve your problem is just one line in your Cargo.toml away - who cares that it's got 200 dependencies!
why not bash and curl?
I look forward when cargo offers that as an option, doesn't mean everyone has to offer their libraries that way, just having the possibility on crates.io would be nice.
I am also very thankful for what has been achieved thus far, so don't take this as thankless complaint rather as I would like Rust one day to be.
Yet another way is to just use bigger machines if you’re CPU bound. Github and Gitlab generally offer 1/2 core 3-8GB RAM instances, but SurplusCI[0] (a project I recently launched) has no such restriction. Up to 8 vcore 32GB RAM machines available.
Now, there are still ways to make the compiler choke: the mention of instantiations towards the end is a great example. But in my (non-professional) experience, the build times are pretty tolerable for what it's providing.
There are some alternate codegen backends that aim to fix this by compiling less-optimized debug builds more quickly.
Something I noticed since I've started timing builds is that codegen and linking usually takes less than 30% of the build time for an incremental build.
So in practice, switching to Cranelift and lld/mold will shave maybe 2 seconds off a 10-seconds build. Better, but still flow breaking.
If we want Go-like compile times, we're going to need some more fundamental improvements to the compiler.
I think this is probably right, and I think just about everyone "tolerates" the build times (that is, I see very few people stop developing in rust because of the build times).
But when, for example, I run `rustup update` to get a new nightly compiler and have to re-compile everything, it's annoying to have to wait 20 minutes. I'll tolerate it, and if a magic wand could make it instantaneous I would love that. But it's still annoying.
If you want to cut the CI run time even further. I'd recommend BuildJet for Github Action. We give you managed high-performance CI runners, which cuts both your CI time and price in half.
We plug right into Github Actions, so it's just one line change in your yaml file.