Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix several bugs in reverse(::UTF8String), add full coverage tests #12646

Merged
merged 1 commit into from Aug 21, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
44 changes: 38 additions & 6 deletions base/unicode/utf8.jl
Expand Up @@ -192,16 +192,48 @@ function string(a::Union{ByteString,Char}...)
UTF8String(s)
end

"""
Reverses a UTF-8 encoded string

### Returns:
* `UTF8String`

### Throws:
* `UnicodeError`
"""
function reverse(s::UTF8String)
out = similar(s.data)
if ccall(:u8_reverse, Cint, (Ptr{UInt8}, Ptr{UInt8}, Csize_t),
out, s.data, length(out)) == 1
throw(UnicodeError(UTF_ERR_INVALID_8,0,0))
dat = s.data
n = length(dat)
n <= 1 && return s
buf = Vector{UInt8}(n)
out = n
pos = 1
@inbounds while out > 0
ch = dat[pos]
if ch > 0xdf
if ch < 0xf0
(out -= 3) < 0 && throw(UnicodeError(UTF_ERR_SHORT, pos, ch))
buf[out + 1], buf[out + 2], buf[out + 3] = ch, dat[pos + 1], dat[pos + 2]
pos += 3
else
(out -= 4) < 0 && throw(UnicodeError(UTF_ERR_SHORT, pos, ch))
buf[out+1], buf[out+2], buf[out+3], buf[out+4] = ch, dat[pos+1], dat[pos+2], dat[pos+3]
pos += 4
end
elseif ch > 0x7f
(out -= 2) < 0 && throw(UnicodeError(UTF_ERR_SHORT, pos, ch))
buf[out + 1], buf[out + 2] = ch, dat[pos + 1]
pos += 2
else
buf[out] = ch
out -= 1
pos += 1
end
end
UTF8String(out)
UTF8String(buf)
end

## outputing UTF-8 strings ##
## outputting UTF-8 strings ##

write(io::IO, s::UTF8String) = write(io, s.data)

Expand Down
11 changes: 11 additions & 0 deletions test/unicode/utf8.jl
Expand Up @@ -11,6 +11,7 @@ let ch = 0x10000
end
end


let str = UTF8String(b"this is a test\xed\x80")
@test next(str, 15) == ('\ufffd', 16)
@test_throws BoundsError getindex(str, 0:3)
Expand All @@ -24,3 +25,13 @@ let str = UTF8String(b"this is a test\xed\x80")
@test s8 == "This is a sill"
@test convert(UTF8String, b"this is a test\xed\x80\x80") == "this is a test\ud000"
end

## Reverse of UTF8String
@test reverse(UTF8String("")) == ""
@test reverse(UTF8String("a")) == "a"
@test reverse(UTF8String("abc")) == "cba"
@test reverse(UTF8String("xyz\uff\u800\uffff\U10ffff")) == "\U10ffff\uffff\u800\uffzyx"
for str in (b"xyz\xc1", b"xyz\xd0", b"xyz\xe0", b"xyz\xed\x80", b"xyz\xf0", b"xyz\xf0\x80", b"xyz\xf0\x80\x80")
@test_throws UnicodeError reverse(UTF8String(str))
end