[swift-evolution] Marking sort and sorted with rethrows

Dave Abrahams dabrahams at apple.com
Sun Jun 5 18:18:18 CDT 2016

on Sun Jun 05 2016, Tim Vermeulen <swift-evolution at swift.org> wrote:

> Most standard library functions that take a closure allow that closure
> to throw (and those functions are subsequently marked with
> rethrows). sort and sorted are exceptions to this. I couldn’t find
> this documented anywhere, but I assume this is because sorting can
> happen in-place and it would be impossible to restore the array to its
> original state without giving up performance. Correct me if I’m wrong.

The guarantee that a function completes successfully or has no effect is
called the “strong guarantee.”  There's nothing wrong, however, with
operations that only give the “basic guarantee”—that invariants are
preserved—which would leave the collection in an indeterminate state.

> I’d like to propose that we let sort rethrow anyways, and leave the
> array in an intermediate state (where the elements are in an arbitrary
> order) when an error is thrown. As long as this is properly
> documented, this shouldn’t lead to any confusion. 

I have only one concern with this, which is that a completely
indeterminate state may not give us sufficient permission to detect and
prevent nonsense.  Should the compiler be allowed to refuse to compile
code that can be statically shown to use partially-modified state, and
the library allowed to mark any such state as unusable at runtime?

A cheap approximation of this kind of marking for Array might be to call
`clear(keepingCapacity: true)`, in debug builds only, when an error is
thrown through a mutating method.  That would (almost) ensure you had to
assign into or clear the array before doing anything with it.

When we first designed exception-safety for C++, details of the
standardization schedule made it important to reduce the model's
complexity to an absolute minimum, so we kept the idea of
unusable-until-reassigned state out of the picture.  But a simple model
that makes nonsense code legal is not really in keeping with Swift,
especially when we can detect the nonsense.

> Best of all, it would allow sorted to rethrow as well in which there
> is no room for confusion at all because it doesn’t mutate any of the
> user’s variables.

Yes, about sorted there is no question whatsoever because there is no mutation.


More information about the swift-evolution mailing list