Skip to content
This repository has been archived by the owner on Dec 16, 2022. It is now read-only.

Commit

Permalink
Merge pull request JuliaLang#19445 from ScottPJones/spj/fixcmp
Browse files Browse the repository at this point in the history
Fix and improve cmp() on AbstractString
  • Loading branch information
nalimilan committed Dec 12, 2016
2 parents 579cfcb + 3262a29 commit 6d93bd9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
8 changes: 5 additions & 3 deletions base/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -139,15 +139,17 @@ function cmp(a::AbstractString, b::AbstractString)
end
i = start(a)
j = start(b)
while !done(a,i) && !done(b,i)
while !done(a,i)
if done(b,j)
return +1
end
c, i = next(a,i)
d, j = next(b,j)
if c != d
return c < d ? -1 : +1
end
end
done(a,i) && !done(b,j) ? -1 :
!done(a,i) && done(b,j) ? +1 : 0
done(b,j) ? 0 : -1
end

==(a::AbstractString, b::AbstractString) = cmp(a,b) == 0
Expand Down
20 changes: 20 additions & 0 deletions test/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -440,3 +440,23 @@ for s in ("Hello", "Σ", "こんにちは", "😊😁")
@test next(s, endof(s))[2] > endof(s.data)
@test nextind(s, endof(s)) > endof(s.data)
end

# Test cmp with AbstractStrings that don't index the same as UTF-8, which would include
# (LegacyString.)UTF16String and (LegacyString.)UTF32String, among others.

type CharStr <: AbstractString
chars::Vector{Char}
CharStr(x) = new(collect(x))
end
Base.start(x::CharStr) = start(x.chars)
Base.next(x::CharStr, i::Int) = next(x.chars, i)
Base.done(x::CharStr, i::Int) = done(x.chars, i)
Base.endof(x::CharStr) = endof(x.chars)

# Simple case, with just ANSI Latin 1 characters
@test "áB" != CharStr("áá") # returns false with bug
@test cmp("áB", CharStr("áá")) == -1 # returns 0 with bug

# Case with Unicode characters
@test cmp("\U1f596\U1f596", CharStr("\U1f596")) == 1 # Gives BoundsError with bug
@test cmp(CharStr("\U1f596"), "\U1f596\U1f596") == -1

0 comments on commit 6d93bd9

Please sign in to comment.