[swift-users] Why no unsafeRemainder(dividingBy: Self) in FixedWidthInteger?

Jens Persson jens at bitcycle.com
Tue Dec 5 14:52:49 CST 2017


What I actually want is the "true modulo", and it should not check for
overflow, as it needs to be as fast as possible.

infix operator &%%: MultiplicationPrecedence

extension FixedWidthInteger {
    func unsafeTrueModulo(_ v: Self) -> Self {
        let rem = self % v
        return rem >= 0 ? rem : rem &+ v
        // Or:
        //return (self % v &+ v) % v
    }
    static func &%%(lhs: Self, rhs: Self) -> Self {
        return lhs.unsafeTrueModulo(rhs)
    }
}

My concern is that if % is checking for overflow, and there is no &%, like
there is eg &+, then my &%% is not as fast as it could be.
(Making sure everything is unchecked in code that is heavily used can
sometimes make a huge difference.)

So, now I have two questions:

1. Why is there no &% (my original question), is % unchecked?
That is, FixedWidthInteger has:
func remainderReportingOverflow(dividingBy: Self)
but there is no:
func unsafeRemainder(dividingBy: Self)

2. Does anyone know a better way to implement the &%% above (to be as fast
as possible)?

/Jens


On Sun, Oct 29, 2017 at 9:13 AM, Jens Persson via swift-users <
swift-users at swift.org> wrote:

> I have some integer processing code that is called very intensively and
> need to be as fast as possible, I therefore use &+ &- &/ &* instead of + -
> / * which results in a significant speedup.
>
> However, I also need to use % and I noticed that there is no &% ...
>
> That is, FixedWidthInteger has:
> func remainderReportingOverflow(dividingBy: Self)
>
> but there is no:
> func unsafeRemainder(dividingBy: Self)
>
> which is different from the other …ReportingOverflow-unsafe…-pairs:
>
> func addingReportingOverflow(Self)
> func subtractingReportingOverflow(Self)
> func dividedReportingOverflow(by: Self)
> func multipliedReportingOverflow(by: Self)
>
> func unsafeAdding(Self)
> func unsafeSubtracting(Self)
> func unsafeMultiplied(by: Self)
> func unsafeDivided(by: Self)
>
> Is this intentional and if so why?
>
> /Jens
>
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171205/273f4a30/attachment.html>


More information about the swift-users mailing list