Do not allow SubString to grow

proposal

#1

Consider the following code

x = "123\n"
y = chomp(x)
display(SubString(y, 1, 10)) # "123\n"

We see that means that we allow SubString to grow beyond its end.
Is it a planned feature?
I would expect that it should not be allowed. To fix this the following line https://github.com/JuliaLang/julia/blob/master/base/strings/types.jl#L30 should be replaced by:

SubString(s::SubString, i::Int, j::Int) = SubString(s.string, s.offset+i, s.offset+min(endof(s), j))

#2

This seems like a bug, and a PR would be welcome.


#3

git blame points to me :wink: but that’s just because I reorganized the string support in Base back for v0.4.
I just checked, the SubArray constructor has the same behavior (at least in v0.6.0), is that also a bug, or intended behavior for array views (personally, I’d count it as a bug, but not being a mathematician, not sure if there isn’t some LinAlg reason)


#4

I will make a PR for SubString.
With SubArray I am pretty convinced it is a bug:

x = ones(10);
y = SubArray(x, (-10:20,))

and you get garbage in y. But I would recommend someone having more experience with SubArrays to fix it.


#5

PR for SubString #22511.


#6

This may be significant, as you can modify memory outside the data structure:

julia> y[1] = 5.0
5.0

julia> y[2] = 5.0
5.0

julia> y
31-element SubArray{Float64,1,Array{Float64,1},Tuple{UnitRange{Int64}},true}:
 5.0
 5.0
 2.18291e-314
 2.21477e-314
...

#7

It was by design, but that design has evolved over time and we’re much more strict with string indexing than we originally were. A PR to changing this to raise an error would be welcomed (with tests to verify that an error is raised, of course).


#8

It is proposed in #22511, but I am waiting with finishing it till #22572 is merged as it is an underlying issue.