You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Tracking Issue for Extend::{extend_one,extend_reserve}Β #72631
This is a tracking issue for the trait methods Extend::extend_one and extend_reserve.
The feature gate for the issue is #![feature(extend_one)].
About tracking issues
Tracking issues are used to record the overall progress of implementation.
They are also uses as hubs connecting to other relevant issues, e.g., bugs or open design questions.
A tracking issue is however not meant for large scale discussion, questions, or bug reports about a feature.
Instead, open a dedicated issue for the specific matter and add the relevant feature gate label.
Reacted by WATANABE Yuki, Connor Slade, Ingvar Stepanyan, Js2xxx, marziply, dullbananas, orende, Ellen Emilia Anna Zscheile, orzogc, Jacob Pratt and 8 more
Reacted by Dave Halter and Arniu Tseng
Reacted by Kornel
Reacted by Eric Shimizu Karbstein, Brandon H. Gomes, museun and Matthijs Brobbel
Preserving a relevant concern from @βSimonSapin in #72162 (comment):
These methods look very out of place in the Extend trait, and the extend_ prefix in their name is apparently unrelated to the meaning of the name of the extend method.
From an API design perspective, this seems to be asking for new Push and Reserve traits. This might deserve to be part of a larger overall design for traits for generic collections. The standard library has mostly avoided doing this so far, if fact Extend is the odd one out and arguably should not have been a trait.
Reacted by Dave Halter, twilligon, Ibraheem Ahmed, Josh Triplett, Mihail Malo, Danny, Kornel, Andrew Banchich, Antti Korpi, Wang Weixuan and 5 more
reserve calls into allocation machinery. extend_one is not fallible, so it will also call into the allocation machinery in case not enough capacity has been reserved. This can lead to code bloat. Instead it should be something more along the lines of #84649
With arrays implementing the IntoIterator trait, I'm not sure extend_one is still pulling its weight? It seems the reasoning was that extend_one(v) is nicer than extend(Some(v))? To me at least, extend([v]) seems even nicer.
Reacted by Solomon Ucko, Chaoses-Ib, Nano and Techcable
It's not just how nice it looks, but also simpler implementation, like Vec is just a push. We call this repeatedly in unzip's own loop, so it's a benefit to keep that simple instead of adding an inner loop (even const 1).
Summarizing some real-time discussion from just now:
extend_one seems fine to me.
For extend_reserve, I'd prefer to at least see the default implementation be the one @dtolnay suggested: extend with a dummy iterator that has a size_hint of the appropriate size. We should also document the expected semantics: shouldextend_reserve panic if it can't allocate (like reserve methods), or is it a hint that should ignore failure?
(I'd still prefer to have it as a free function that can't be overridden, rather than a default method, but with the above documentation and default impl I'd just be -0 on it and wouldn't oppose adding it.)
Existing push and insert on eg Vec don't return a reference. Is this a bad legacy decision? I don't know.
Are push and try_push returning an immutable reference despite requiring a mutable reference to the container intentional? Are there containers in the wild that need this constraint?
Should they prescribe &Self::Item as a return? What about eg a HashSet that gets extended with (K, V) tuples? I imagine you'd want a push on that to return a &mut V.
Oh It was just a quite and dirty example, my main idea is I don't see why we can't have a trait for Push one item on alloc collection. Maybe split Push and TryPush is not need (same for extend). But I think Extend and Push should be two separate trait. My may issue with current design is you need to try_reserve THEN you can use extend. It's two step when it's should be one step for the user. Since we loose the battle in early Rust to have fallible allocation I would like to have trait where at least are nice to simple to use and not error prone. Having a trait TryPush and TryExtend will remove all user the burden to check at every call try_reserve().
yeah, I don't like to not have access to item I just pushed this is a thing I want to have almost everytime, one will say "call x.last()" but this require on unwrap() when push could just return it. Also this is probably cost free every function should return something expect few thing like drop. And even if this is not cost free I expect the compiler will optimize it away since it's very simple to optimize a not used reference (same argument is say about user to call vec::last that is optimize away after a Vec::push but again better optimize away the not used return value and this remove unwrap in user code). I give something to a function and it give me nothing back ? steal !
oh yeah sure nice catch
Maybe just don't implement Push on HashMap is a possibility too. We are not force to do it. But it a valid point, maybe have a second associate type like Output allowing HashMap to return a (&K, &V) instead of &(K, V) that will be not possible for several implementation of such. Problem of this it probably require Gats to compile.
So maybe:
pubtraitPush{typeItem;typeOutput;fnpush<'a>(&'amutself,item:Self::Item) -> Self::Output;}pubtraitTryPush{typeItem;typeOutput;// the error should return the item cause it didn't consume itfntry_push<'a>(&'amutself,item:Self::Item) -> Result<Self::Output,ErrorFoo<Self::Item>>;}
I don't know GaTs enough to know exactly but I often design thing where compiler tell me GATS as error. So if someone know better to make this trait compilable with or without gats. The idea is here, have traits to push and extend and return the item for push. Also, need to design the error type, should it be fixed or generic.
I'm writing something that uses size hint similar to iterators and was wondering how it works in std. I found some surprises related to this. As @qm3ster points out there's a question about use of reserve vs reserve_exact but there's also issue of upper bound of Iterator::size_hint() not being used.
I'm thinking about these scenarios:
iter.collect() or collection.extend(), then store the collection for a long time - best to avoid over-allocating
iter.collect() or collection.extend(), then push some new elements without iterator (is this ever reasonable? I couldn't find a good scenario useful for things coming from async and such)
maximum is known and reasonably likely
maximum is known and unlikely or unknown likelihood - this is the case of Iterator::take() which can have very high upper bound (typical scenario is DoS protection if the iterator is untrusted input)
I'm still unsure about the best solution but if there are people smarter than me interested I'd like to know what they are thinking.
@Kixunil I would like to note that repeatedly calling collection.extend() with small iterators is common. There's also cases when a collection is deserialized and extended immediately, or deserialized and then extended indefinitely (in the latter case, probably with some removals, so resizing may be amortized regardless).
@qm3ster I believe all such cases can be solved using Iterator::chain which also happens to be less tedious than manually calculating the right reserve size. If you have a situation that can not be converted I'm curious to learn!
Perhaps another solution is some kind of fn allocation_hint(&self) -> Option<usize>; method on iterators. That would fix the "lying about size_hint" problem, and you could get the functionality of extend_reserve with just .extend(itertools::allocation_hint(n)) or something. I've wanted this in the context of fallible iterators before, since for .collect::<Result<Vec<_>, _>>() the iterator constructed by try_process has a lower-bound size hint of 0, so the vec always uses an exponential allocation strategy, even though the iterator being collected from might have an exact size_hint.
For the record, I've just ran some simple benchmarks against vec.extend(Some(x)) and vec.extend_one(x) and the extend_some variant performed 20% faster on average. The main difference I can see from the codegen is the reserve call, and the order of the branching
My judgement from reading the raw_vec code is that extend_some, by using reserve which has allocation marked as #[cold], reorders the branching to be more helpful. Whereas the extend_one uses reserve_for_push which is not #[cold] and therefore suffers.
Activity
dtolnay commentedon May 28, 2020
Preserving a relevant concern from @βSimonSapin in #72162 (comment):
the8472 commentedon May 11, 2021
Additional concern:
reservecalls into allocation machinery.extend_oneis not fallible, so it will also call into the allocation machinery in case not enough capacity has been reserved. This can lead to code bloat. Instead it should be something more along the lines of #84649est31 commentedon Aug 5, 2021
With arrays implementing the IntoIterator trait, I'm not sure
extend_oneis still pulling its weight? It seems the reasoning was thatextend_one(v)is nicer thanextend(Some(v))? To me at least,extend([v])seems even nicer.cuviper commentedon Aug 5, 2021
It's not just how nice it looks, but also simpler implementation, like
Vecis just apush. We call this repeatedly inunzip's own loop, so it's a benefit to keep that simple instead of adding an inner loop (even const 1).est31 commentedon Aug 5, 2021
@cuviper can't this be also solved with specialization? Adding special code for
Option<T>,iter::Once<T>, and[T;1]?cuviper commentedon Aug 5, 2021
Yeah, I suppose specialization could do that too. Note that only
[T;1]is always one item though.est31 commentedon Aug 5, 2021
Good point!
[T;1]should be enough though.joshtriplett commentedon Sep 8, 2021
Summarizing some real-time discussion from just now:
extend_oneseems fine to me.For
extend_reserve, I'd prefer to at least see the default implementation be the one @dtolnay suggested:extendwith a dummy iterator that has a size_hint of the appropriate size. We should also document the expected semantics: shouldextend_reservepanic if it can't allocate (likereservemethods), or is it a hint that should ignore failure?(I'd still prefer to have it as a free function that can't be overridden, rather than a default method, but with the above documentation and default impl I'd just be -0 on it and wouldn't oppose adding it.)
5 remaining items
qm3ster commentedon Nov 16, 2021
@Stargateur:
pushandinserton egVecdon't return a reference. Is this a bad legacy decision? I don't know.pushandtry_pushreturning an immutable reference despite requiring a mutable reference to the container intentional? Are there containers in the wild that need this constraint?&Self::Itemas a return? What about eg aHashSetthat gets extended with(K, V)tuples? I imagine you'd want a push on that to return a&mut V.Stargateur commentedon Nov 16, 2021
@qm3ster
Oh It was just a quite and dirty example, my main idea is I don't see why we can't have a trait for Push one item on alloc collection. Maybe split
PushandTryPushis not need (same for extend). But I think Extend and Push should be two separate trait. My may issue with current design is you need totry_reserveTHEN you can use extend. It's two step when it's should be one step for the user. Since we loose the battle in early Rust to have fallible allocation I would like to have trait where at least are nice to simple to use and not error prone. Having a traitTryPushandTryExtendwill remove all user the burden to check at every calltry_reserve().unwrap()whenpushcould just return it. Also this is probably cost free every function should return something expect few thing likedrop. And even if this is not cost free I expect the compiler will optimize it away since it's very simple to optimize a not used reference (same argument is say about user to callvec::lastthat is optimize away after aVec::pushbut again better optimize away the not used return value and this remove unwrap in user code). I give something to a function and it give me nothing back ? steal !PushonHashMapis a possibility too. We are not force to do it. But it a valid point, maybe have a second associate type likeOutputallowingHashMapto return a(&K, &V)instead of&(K, V)that will be not possible for several implementation of such. Problem of this it probably requireGatsto compile.So maybe:
I don't know
GaTsenough to know exactly but I often design thing where compiler tell me GATS as error. So if someone know better to make this trait compilable with or without gats. The idea is here, have traits to push and extend and return the item for push. Also, need to design the error type, should it be fixed or generic.sugar700 commentedon Dec 13, 2021
A GAT API for pushing to
HashMapcould possibly look like this:Kixunil commentedon Jan 25, 2022
I'm writing something that uses size hint similar to iterators and was wondering how it works in
std. I found some surprises related to this. As @qm3ster points out there's a question about use ofreservevsreserve_exactbut there's also issue of upper bound ofIterator::size_hint()not being used.I'm thinking about these scenarios:
iter.collect()orcollection.extend(), then store the collection for a long time - best to avoid over-allocatingiter.collect()orcollection.extend(), then push some new elements without iterator (is this ever reasonable? I couldn't find a good scenariouseful for things coming fromasyncand such)Iterator::take()which can have very high upper bound (typical scenario is DoS protection if the iterator is untrusted input)I'm still unsure about the best solution but if there are people smarter than me interested I'd like to know what they are thinking.
qm3ster commentedon Jan 26, 2022
@Kixunil I would like to note that repeatedly calling
collection.extend()with small iterators is common. There's also cases when a collection is deserialized and extended immediately, or deserialized and then extended indefinitely (in the latter case, probably with some removals, so resizing may be amortized regardless).Kixunil commentedon Jan 26, 2022
@qm3ster I believe all such cases can be solved using
Iterator::chainwhich also happens to be less tedious than manually calculating the right reserve size. If you have a situation that can not be converted I'm curious to learn!qm3ster commentedon Jan 26, 2022
Of course!
I am talking about calling it at runtime, in an event/message-driven loop, not statically multiple times in a row in a block of code.
Kixunil commentedon Jan 26, 2022
Ah, finally a good case when it's needed!
coolreader18 commentedon Nov 3, 2022
Perhaps another solution is some kind of
fn allocation_hint(&self) -> Option<usize>;method on iterators. That would fix the "lying about size_hint" problem, and you could get the functionality of extend_reserve with just.extend(itertools::allocation_hint(n))or something. I've wanted this in the context of fallible iterators before, since for.collect::<Result<Vec<_>, _>>()the iterator constructed bytry_processhas a lower-bound size hint of 0, so the vec always uses an exponential allocation strategy, even though the iterator being collected from might have an exact size_hint.conradludgate commentedon Nov 21, 2022
For the record, I've just ran some simple benchmarks against
vec.extend(Some(x))andvec.extend_one(x)and theextend_somevariant performed 20% faster on average. The main difference I can see from the codegen is thereservecall, and the order of the branchingMy judgement from reading the raw_vec code is that
extend_some, by usingreservewhich has allocation marked as#[cold], reorders the branching to be more helpful. Whereas theextend_oneusesreserve_for_pushwhich is not#[cold]and therefore suffers.