7 ms·
Pin
- j2kun 2y ago> As it happens, this little corner of Rust is my mess A nice surprise coming to this article with no context :)
- krukah 2y agoAnother great WithoutBoats writeup. Admittedly, this is one of those corners of Rust that I'm glad is abstracted away and buried in async runtime internals. That said, I'm curious if/when/why/how anyone uses Pin<T> outside of a custom Future implementation?
- ComputerGuru 2y agoFfi: you have a c api that exposes an item by ptr not by ref so it mustn't be moved. Interacting with system types that rely on their address. Eg I think std uses a pin equivalent for mutex/futex on some operating systems because the kernel docs say the userland lock object must not change its address after initialization (even when not locked, which is normally the only condition and doesn’t need Pin because you can’t move something that has a reference to it).
- etra0 2y agoI am curious about this as well. The way it's phrased it makes me understand a bit that it could be used within FFI, like if you get a pointer from a extern function that returns a *mut T, I could have better semantics by wrapping it with Pin<&mut T>, but then it says "Another fact about the pinned typestate is that for most types it is completely irrelevant. If the value of type can never contain any self-references, pinning it is useless" Mind you I'm very new at FFI but I'd like to understand what are the best ways to wrap them into safe Rust.
- vhvj 2y ago[dead]
- fallingsquirrel 2y agoThe problem as I see it is that having a &mut reference to something lets you move it via mem::swap/replace (and maybe a few others?) -- but actually needing to do so is rare. It seems to me that if that weren't allowed, taking a &mut reference to a self-referential value would be perfectly safe. Maybe there could have been a way to opt in to moving-via-reference for those rare cases when you need it. Or maybe this whole problem could have been avoided by making swap and replace unsafe? I'd love to see someone explore that design space.
- Sytten 2y agoThis just doesn't scale and it would have been a non starter because it would break so much exiting code. Mem swap is just one of the ways to move via mutable references, there are many many others. Option::take is one that I use quite often and it would be super weird if that was unsafe.
- withoutboats3 2y agoThis is true. When were working on the problem, the way Aaron Turon put it was that &mut is "too powerful." If &mut didn't give the power to move out of it, the whole design would be a lot simpler. I'll discuss this in my next post about this. Rust has to be backward compatible and already decided you can move out of an &mut, but there are definitely cleaner designs that can be, unburdened by what has been.
- o11c 2y agoPinning/!Move is useful for so many things outside of async/await. But because Rust fumbled it so badly, the usual answer is "rewrite your program in a language other than Rust." (aside: there are about 4 different ways to implement object moving, and an efficient language needs to be aware of several of them)
- n3t 2y ago> there are about 4 different ways to implement object moving What are they?
- o11c 2y ago0. no moves. This is very often needed for FFI callbacks, among others. 1. trivial copies. This is similar to 2, but means you do not have to do `swap`-like things in cases for non-destructive moves (which are, in fact, also important, they just shouldn't be the only kind of move. Note that supporting destructive moves likely implies supporting destructuring). 2. trivial moves. You can just use `memcpy`, `realloc`, etc. This is the only kind of move supported by Rust. C++ can introspect for it but with severe limitations. Note that "trivial" does NOT mean "cheap"; memory can be large. 3. moves with retroactive fixup (old address considered dead). What you do here is call `realloc` or whatever, then pass the old address (or the delta?) to a fixup function so that it (possibly with offset) can be replaced with the new address. Great caution is required to avoid UB by C's rules (the delta approach may be safer?). The compiler needs to be able to optimize this into the preceding when the fixup turns out to be empty (since generic wrapper classes may not know if their fields are trivially-movable or not). 4. full moves (both old and new address ranges are valid at the same time). C++ is the only language I know that supports this (though it is limited to non-destructive moves). One major use for this is maintaining "peer pointers" without forcing an extra allocation. Note that this can be simulated on top of "no moves" with some extra verbosity (C++98 anyone?). Related to this, it really is essential for allocators to provide a "reallocate in place if possible, else fail" function, to avoid unnecessary move-constructor calls. Unfortunately, real-world allocators do not actually avoid copies if you use `malloc_usable_size` + `realloc`. If emitting C, note that you must avoid `__attribute__((malloc))` etc. to avoid setting off the bug-laden-piece-of-crap that is `__builtin_dynamic_object_size`. Random reminder that "conditionally insert and move my object(s) into a container (usually a map), but keep my object alive if an equal one was already there" is important, and most languages do it pretty badly. Linear types are related but it's all Blub to me.
- alain_gilbert 2y agoShould add "rust" in the title, so that we know what the article is talking about. If you're one of the "rust/go in title" haters... please go rage somewhere else.
- qingcharles 2y agoThis is literally the worst post title I've ever seen on HN :D
- solarkraft 2y agoThe corresponding rule is worded so harshly that I’m not surprised the poster didn’t dare to change it ( https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html).
- lmm 2y agoNot merely worded but also enforced that way.
- latexr 2y agoThat’s not true. The moderators accept suggestions and changes titles to something other than the original time and again. It is a guideline after all, it depends on context. I have zero doubts a more descriptive title would be accepted in this instance, as long as it were accurate and not clickbait. https://hn.algolia.com/?query=by%3Adang%20change%20title&sort=byDate&type=comment https://hn.algolia.com/?query=by%3Adang%20change%20title&sor...
- lmm 2y agoI've seen many cases of useful descriptive titles being switched to uninformative ones (Stephen Hawking's thesis is one that immediately comes to mind). Every title edit that I've seen in realtime has looked like a robotic replacement with the page title. (Perhaps whatever moderators are active in my timezone are less flexible about their guidelines than dang is)
- jauntywundrkind 2y agoGreat seeing this backstory. WithoutBoats has had some super active discussions around very topical async iterators, poll, and pin topics already! https://news.ycombinator.com/from?site=without.boats https://news.ycombinator.com/from?site=without.boats It feels like there's very few communities that people going so in depth publically about the nitty gritty of their language, and it's so cool to see.
- Sytten 2y agoIts cool, but it also means the development of the language is very very slow. Async is still half backed and super complex, and I say that as a guy who has written rust code 40h/week for the past 3 years.
- tjf801 2y agoI fully agree. Sometimes it feels like so much effort is put into rust's async side that the rest of the language ends up taking a back seat and suffering for it.
- forrestthewoods 2y agoRust dev team cares too much about async and webdev imho. Yes I know the web is where 95% of programming jobs live now. But as a C++ systems programmer I simply could not care less about the web. Rust is a systems language trying to get its foot in the web door. I'd selfishly rather it focus on being a superior C/C++. Alas.
- ChrisSD 2y agoThe usual complaint is that there has been little progress on async and webdev in Rust itself since 2018 so it's odd to hear the reverse complaint. Though I would add that Rust's async is not just about webdev; it has had success in embedded contexts e.g. the popular https://github.com/embassy-rs/embassy?tab=readme-ov-file#embassy https://github.com/embassy-rs/embassy?tab=readme-ov-file#emb...
- 2y ago
- zengid 2y ago> The term “value identity” is not defined anywhere in this post, nor can I find it elsewhere in Mojo’s documentation, so I’m not clear on how Modular claims that Mojo solves the problem that Pin is meant to solve I don't claim to know the answer either, but it reminds me of a great talk from Dave Abrahams, who worked on the value semantics for Swift together with Chris Lattner (who started Mojo). The talk is "Value Semantics: Safety, Independence, Projection, & Future of Programming" [0] [0] https://www.youtube.com/watch?v=QthAU-t3PQ4 https://www.youtube.com/watch?v=QthAU-t3PQ4
- withoutboats3 2y agoIt's clear that Mojo is in some sense inheriting Swift's notion of "value semantics," but Rust also has "value semantics" in the same sense. Rust just also has references as first class types, whereas Swift (and as far as I can tell, Mojo) only allows references as a parameter passing mode; Mojo expands on Swift's inout parameters by having an immutable reference passing mode as well. Not being able to store references in objects does solve the problem of "self-referential structs" in that you just can't implement code like the code Rust compiles to, but that isn't at all what the quoted paragraph says about Mojo so I am quite lost as to what they mean.
- demurgos 2y agoMy understanding of _value identity_ refers to the `StableDeref`/yoke approach to self-regerential structs. The value is constructed at a stable address (usually some heap allocation) and you always access it through some pointer. The address is the value's identity. The pointer can move, but the value doesn't move.
- withoutboats3 2y agoCould you link to a source for this in Mojo's documentation? This would be a logical interpretation, but it would mean Mojo is planning to adopt a much worse implementation of async than Rust and the post is claiming that Mojo is both faster and easier than Rust.
- verdagon 2y agoI can imagine a Rust-like language where we have move-constructors (in TFA), and every generated Future subtype is opaque and also heap allocated for us. I think the need for Pin could then disappear, because the user would have no way to destroy it, since it's opaque and elsewhere on the heap, and therefore no way to move it (because having move-constructors implies that moving is conceptually destroying then recreating things).
- josephg 2y agoYeah. I can guess how disruptive it would be, but I really wish rust bit the bullet and added a Move trait to std, baked into the language at a similar level as Copy. Move defines a function which moves a value from one address in memory to another. Structs without impl Move cannot be moved. Almost all types would #[derive(Move)], which implements a trivial move function that copies the bytes. But this opens the door to self-referential types, futures, and lots of other things that need more complex move behaviour. (Actually, it might make more sense to define two traits, mirroring the difference between Copy and Clone. One is a marker trait which tells the compiler that the bytes can just be moved. The other allows custom "move constructor" implementation.) I want move because pin is so hard to understand. Its a complex idea wrapped in double- or sometimes triple negatives. fn<X: !Unpin>(...). Wat? I drop off at unsafe pin-projecting. When is that safe? When is it not? Blah I'm out. Moving from rust-without-move to rust-with-move would be inconvenient, because basically every struct anyone has written to date with rust needs #[derive(Move)] to be added. Including in std. And all types in existing editions that aren't pinned would need the compiler to infer a Move trait implementation. This should be possible to do mechanically. It would just be a lot of work. Async rust is horrible. Especially compared to futures / promises in almost any other language. At some point, someone will make a new rust-like systems language which has an improved version of rust's memory safety model, a Move trait, and better futures. I'd personally also love comptime instead of rust's macro system. I love rust. I love all the work the team has put into it over the years. But the language I’m really looking forward to is the language that comes after rust. Same idea, but something that has learned from rust’s mistakes. And it’s increasingly becoming clear what that better rust-like language might potentially look like. I can't wait.
- LegionMammal978 2y agoMy take on why users find Pin difficult: by itself, it has no meaning! This is different from every other wrapper in the language (except maybe AssertUnwindSafe<T>, which basically no one uses for its original purpose). Given a Pin<&mut InnerType>, there's nothing about Pin in the language or standard library that tells you what you can and can't do with it. (Unless the InnerType declares that it's Unpin, which implies that you can do anything you can do with an ordinary pointer.) Instead, it operates as more of a "bring your own meaning", where the provider of the InnerType further creates any number of (internally unsafe) methods and APIs to manipulate a pinned object soundly. The only purpose of Pin<P> itself is to provide a pointer with fewer "intrinsic capabilities" (e.g., swapping &muts, moving out of Boxes, etc.), so that the inner type can allow further capabilities on top of that. I suspect it's this nebulousness of meaning that confuses people the most. It certainly took me a fair while to figure it out. All the ideas about structural vs. non-structural fields are just to facilitate popular access patterns like "this one field is just plain old data, but this other field contains an object that itself wants to be pinned".
- withoutboats3 2y agoPin does have meaning: it means you cannot move the target of this pointer ever again (or invalidate its without running its destructor, which is what moving does that's the problem), unless the type of the target implements Unpin. This giving up of certain rights gives other rights (such as to store self-referential values), which are the reason you give it up. This is how contracts between components just work: similarly, giving up the right to mutate through a reference allows you to alias the reference at the same time. I'm always reminded of this line from Lincoln, about a very different and much graver subject: "If we submit to law, Alex, even submit to losing freedoms - the freedom to oppress for instance - we may discover other freedoms previously unknown to us." I do agree that the fact that you can't use those rights in safe code is an educational problem, because one can't easily demonstrate what you can do with a pinned reference except "call a poll method which the compiler has generated for you."
- LegionMammal978 2y ago> Pin does have meaning: it means you cannot move the target of this pointer ever again (or invalidate its without running its destructor, which is what moving does that's the problem), unless the type of the target implements Unpin. Sure you can: it's just that the target has to provide its own methods for it. It's perfectly valid (if pointless) to write struct PracticallyUnpin(..., PhantomPinned); impl PracticallyUnpin { fn unpin_mut(self: Pin<&mut Self>) -> &mut Self { // SAFETY: We're the ones writing the rules here unsafe { Pin::into_inner_unchecked(self) } } ... // (no other unsafe methods or impls) } and then the caller can do whatever they want with that reference, e.g., moving the value. Unpin isn't a magic word: it's just a generic way for the target to indicate that pinned pointers can safely regain full capabilities. Of course, putting a Pin around an object does further restrict what you can do with it generically in unsafe code. But I'd further count these under the umbrella of "intrinsic unsafe capabilities", which Pin removes, but which the target can later restore ad libitum. Compare the question of whether a fn replace_with(&mut T, impl FnOnce(T) -> T) (aborting on panic) is sound, which really comes down to the "unsafe capabilities" of a &mut reference. This is not to say, of course, that the target need not be very circumspect about which capabilities it restores! It has a responsibility not to create an unsound interface that might result in UB under permitted usage. E.g., if we have a type that owns a generic non-Unpin future, then that type must follow the strictest Pin invariants w.r.t. that future. But otherwise, it's entirely up to the target type which capabilities it wants to restore under which circumstances.
- School-Cotton 2y agoI’ve always thought Pin was difficult to understand because it’s not explained in a clear way in the official docs. In particular, lots of documentation claims things like “Pin ensures that an object is never moved”, which isn’t true! It’s only true if the object is not Unpin, but most normal objects are Unpin, so Pin usually does nothing. It took me a very long time to finally understand this. The set of types T for which Pin<T> does anything at all is very niche and weird and IMO this isn’t sufficiently highlighted by the documentation.
- withoutboats3 2y agoI think this is good feedback and it would be good for the docs to be clearer about this. Of course for the types that you're going to deal with pinned (futures and streams), they're a lot more likely to be those niche objects. I also do think the documentation has improved a lot over the years. I was surprised when I checked it while drafting this that it seemed to focus on the right things pretty well; circa 2019 I remember it being a lot more focused on specifying the contract in a way that really belongs in something like the Rust reference and not the std API docs.
- orf 2y agoI think “Pin” is a good example of a technically correct but hard to understand name. “Drop” has a much more familiar meaning because it’s a common action, whereas “pinning” isn’t so common and can mean different things in different contexts. Rather than “pin!(…)”, would “immovable!(…)” be any better? Probably not, and it’s difficult to think of a better one. So maybe a shorthand “colloquial” name doesn’t make sense, and something descriptive like “prevent_moving!(…)” and a PreventMove trait might be better?
- jollyllama 2y agoIt's a bad name for any application handling a Personal Identification Number of any kind.
- jackcviers3 2y agoI take it Pin is a fixpoint-type that allows for recursive reference?
- weavie 2y agoI've been programming Rust professionally for several years now and being totally honest I don't really understand Pin that well. I get the theory, but don't really have an intuitive understanding of when I should use it. My usage of pin essentially comes down to "I try something, and the compiler complains at me, so I pin stuff and then it compiles." It's never been such a hurdle in the day to day coding I need to do that I've been forced to sit down and truly grok it.
- 01HNNWZ0MV43FF 2y agoSame. It's one of my most common cases of "Just avoid unsafe and be glad some smart compiler folks already solved this all for me" Whereas in C++ I was regularly treading in the water of "stuff I don't know, but must use" and getting eaten by crocodiles
- api 2y agoSuch an insane amount of work to avoid fixing the real problem: the inefficiency of threads. All async code -- all of it -- is a hack to implement lightweight threads through a lot of syntactic sugar for state management. In a language like Rust it adds a ton of complexity that simply doesn't need to exist without it. Fixing the efficiency and scaling issues of threads would make all of this just go away. Poof. Gone. It's a bit like the trillion dollar mistake of "null" in languages like Java-- a ton of complexity that results from one design decision (or in this case lack thereof).
- simon_o 2y agoThis. The harmful decisions Rust made highlight its ingrained culture of doubling down on previous mistakes at all costs. There seems to be no reevaluation of the cost/benefit ratio once the "preferred approach" turns out to be non-viable. "We want to have feature X, consequences be damned" is rarely a winning move in language design.
- api 2y agoTrue but I didn't just mean Rust... I meant virtually all async coding as a pattern.
- simon_o 2y agoAgreed, it's just that in Rust async/await hurts more than in e. g. JavaScript where the browser gives you enough hooks to have a "fresh start with(out) async".
- withoutboats3 2y ago[flagged]
- CyberDildonics 2y agoIs it 'despicable' just because you don't like what it says? You didn't do anything to refute it.
- CyberDildonics 2y agoDo people like titles like this where there is no information about what the link is (and what little is there has basically nothing to do with the link) ? It seems like clickbait to me and the opposite purpose of having a site of headlines if they don't have any information.
- iknowstuff 2y agoWhen teaching, to make it clear that an "Unpin" item is unaffected by "Pin," I’d suggest analogies from real life where objects remain unaffected despite the use of something designed to hold them in place: 1. Velcro hooks do not stick to smooth surfaces: Pin -> Velcro, Unpin -> Smooth 2. Magnets do not affect non-magnetic materials: Pin -> Magnet, Unpin -> NonMagnetic/Glass/Brass 3. Glue does not adhere to non-stick surfaces: Pin -> Glue, Unpin -> NonStick This way, it becomes clear that a "Velcro" fixes an item in place, and if an item is "Smooth," it is unaffected by the "Velcro" mechanism. Given Rust’s ecosystem naming themes it would have been beautiful to rename the trait to something something magnet and non-magnetic :’)
- 01HNNWZ0MV43FF 2y agoBut a smooth object can't be velcroed, nor can wood hold up a magnet. Isn't it that `Unpin` means the object is always ready to be pinned? (I read the article last night and already forgot whether pinning requires a fixup step) So a `T: Pin + !Unpin` is like a sheet of paper that can only be fixed by stapling it, but a `T: Pin + Unpin` is like a painting with a hook which can be mounted on a nail and unmounted without damaging the hook
- iknowstuff 2y agoI think two things fuck with our brains here: - the double negative of „!Unpin” - Rust trait names are not adjectives Pin + Detach(-able) would be a less confusing name. That being said, you can velcro smooth objects all you want, but you'll still separate (Move) them easily :) or put a magnet to glass/brass objects. PS mind you that Pin is not a trait, only Unpin is, so Pin<T: Unpin> or Pin<T: !Unpin> is a more accurate way or writing what you described :)
- raggi 2y agoI think most people get a partial idea of what Pin is fairly quickly when they try, but that's part of the problem. They struggle a lot more with Unpin, and particularly the dynamics as code changes. This comes up more often than in probably should in an async context. (re. "should", the problem is it shows up because of closure changes most often, and the errors (last I was teaching) take the user to the wrong place, typically the just need to allocate, but there's no practicum on their error understanding path, see below). Users are integrating a change of some kind, get a compiler error and then struggle even further to really understand when and how the unpin marker exists, but a change, potentially at a fair distance from the code that they're editing, is now making compilation time demands that they both understand and address the issue. When those users enter the argument with rustc, they come to a page that starts with: Implementing the Unpin trait for T expresses the fact that T is pinning-agnostic: it shall not expose nor rely on any pinning guarantees. This, in turn, means that a Pin-wrapped pointer to such a type can feature a fully unrestricted API. In other words, if T: Unpin, a value of type T will not be bound by the invariants which pinning otherwise offers, even when “pinned” by a Pin<Ptr> pointing at it. When a value of type T is pointed at by a Pin<Ptr>, Pin will not restrict access to the pointee value like it normally would, thus allowing the user to do anything that they normally could with a non-Pin-wrapped Ptr to that value. Now this is reasonable documentation if you're in the thick of this universe, but to the average reader this is full of self-referential definition. When you have a weak understanding of Pin, then Unpin being defined in terms of Pin makes no sense, it's the same as Pin being defined in terms of Pin. All of this documentation needs to shift to a "systems engineering" or "in practice" basis first, and follow with theory. Most users give up with the docs before the second sentence they can't understand. All of the cleverness (reliance on a priori theory) in the docs for these core types needs to be moved out of the way for most readers - replaced by much simpler terminology and practicum suitable for the average knuckledragger. Normal people who end up here in practice are on average already at saturation point for working memory, they have "no stack space left" for trying to unpack language theory.
- withoutboats3 2y agoI agree that this definition of Unpin should be improved, but I'm confused about the scenario you're describing. When does a user encounter an error because of Unpin? Is it just that they use an API which requires Unpin? If so, what APIs do you encounter causing the issue most often?