Menu

#1589 Code simplify 202607

Committed
accepted
5
3 hours ago
1 day ago
Zufu Liu
No

Range::Length() and SelectionRange::Length() can be simplified to use std::abs() on the distance.

1 Attachments

Discussion

  • Zufu Liu

    Zufu Liu - 1 day ago

    Range::ContainsCharacter() and SelectionRange::ContainsCharacter(Sci::Position posCharacter) can be simplified to unreadable ((pos - start) * (pos - end)) < 0 or ((pos - start) ^ (pos - end)) < 0.

     
    • Neil Hodgson

      Neil Hodgson - 13 hours ago

      Not worth the weirdness. The multiply version may overflow on huge documents.

       
      • Zufu Liu

        Zufu Liu - 3 hours ago

        Yeah, both may introduce new UB when either number is PTRDIFF_MIN, https://alive2.llvm.org/ce/z/4eA5gv

         
  • Neil Hodgson

    Neil Hodgson - 13 hours ago
    • status: open --> accepted
    • Group: Initial --> Committed
     
  • Neil Hodgson

    Neil Hodgson - 13 hours ago

    Committed with [dea670] and [230a0b].

     

    Related

    Commit: [230a0b]
    Commit: [dea670]

  • Zufu Liu

    Zufu Liu - 3 hours ago

    It might worth to bring back old manually expanded code for SelectionPosition::operator <= and operator >= (used by Contains() and ContainsCharacter()), Clang and MSVC seems honor other == *this and think that's the likely case, then do a literal compile, result in four comparisons instead of just two, see https://godbolt.org/z/qnvePMaYh

    direct expansion with virtualSpace comparison merged:

    bool SelectionPosition::operator <=(const SelectionPosition &other) const noexcept {
        if (position == other.position) {
            return virtualSpace <= other.virtualSpace;
        }
        return position < other.position;
    }
    
    bool SelectionPosition::operator >=(const SelectionPosition &other) const noexcept {
        if (position == other.position) {
            return virtualSpace >= other.virtualSpace;
        }
        return position > other.position;
    }
    

    or equivalents that MSVC generate small code. also looks close to operator < and operator > with just compare operator replaced.

    bool SelectionPosition::operator <=(const SelectionPosition &other) const noexcept {
        if (position == other.position) {
            return virtualSpace <= other.virtualSpace;
        }
        return position <= other.position;
    }
    
    bool SelectionPosition::operator >=(const SelectionPosition &other) const noexcept {
        if (position == other.position) {
            return virtualSpace >= other.virtualSpace;
        }
        return position >= other.position;
    }
    

    SelectionRange::Contains(Sci::Position pos) and SelectionRange::ContainsCharacter(Sci::Position posCharacter) seems can be simplified to if (anchor.Position() > caret.Position()) as virtualSpace isn't used for further comparison.

     

Log in to post a comment.

Auth0 Logo