truncate_front
API for VecDeque
that is O(1) for trivial drop types
#533
Labels
ACP-accepted
API Change Proposal is accepted (seconded with no objections)
api-change-proposal
A proposal to add or alter unstable APIs in the standard libraries
T-libs-api
Proposal
Problem statement
VecDeque
is designed as a symmetric data structure with API available for operations on both ends of a double-ended queue.Currently,
VecDeque
supports thetruncate()
method that can be used to reduce the size of a container by dropping elements at its end and provides a O(1) guarantee for trivial drop types, but does not provide a counterpart for doing the same by dropping elements at the beginning.Motivating examples or use cases
Today, it is possible to implement a O(log N) solution for a sorted
VecDeque<u32>
that drops all elements larger thanx
by combiningbinary_search()
andtruncate()
functions. However, it is not possible to do so to drop all elements smaller thanx
except by popping then one-by-one which is O(N):Implementing
truncate_front()
API with same runtime guarantees astruncate()
would close this gap and maintain consistency inVecDeque
symmetric programming interface.Solution sketch
The implementation can look very similar to
truncate()
but operate on slices in the opposite order:The common code for safely dropping the
drop_back
slice in the second branch is the same as intruncate()
and can be factored out into a separate helper.Alternatives
drain()
to get an iterator over elements that need to be dropped in the front and drop it instantly:This seems to accomplish the goal but is arguably less intuitive and more complex internally.
VecDeque
can be split in two withsplit_off()
:but that would incur an extra allocation,
VecDeque
can be rotated withrotate_left()
and then truncated withtruncate()
:but that still has linear complexity: O(min(n, len() - n))
Links and related work
The need for
truncate_front()
has been expressed by a number of Rust developers and discussed in the following GitHub issues:rust-lang/rust#62408
rust-lang/rust#92547
What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
Second, if there's a concrete solution:
The text was updated successfully, but these errors were encountered: