fs: Adjust RangeOption.Decode to return -1 for read to end

A Range request can never request 0 bytes however this change was made
to make a clearer signal that the limit means read to the end.

Add test and more documentation and fixup uses
This commit is contained in:
Nick Craig-Wood
2018-01-27 14:31:29 +00:00
parent 9a73688e3a
commit fe52502f19
7 changed files with 42 additions and 14 deletions
+11 -3
View File
@@ -97,17 +97,25 @@ func (o *RangeOption) Mandatory() bool {
}
// Decode interprets the RangeOption into an offset and a limit
//
// The offset is the start of the stream and the limit is how many
// bytes should be read from it. If the limit is -1 then the stream
// should be read to the end.
func (o *RangeOption) Decode(size int64) (offset, limit int64) {
if o.Start >= 0 {
offset = o.Start
if o.End >= 0 {
limit = o.End - o.Start + 1
} else {
limit = 0
limit = -1
}
} else {
offset = size - o.End
limit = 0
if o.End >= 0 {
offset = size - o.End
} else {
offset = 0
}
limit = -1
}
return offset, limit
}
+21
View File
@@ -37,3 +37,24 @@ func TestParseRangeOption(t *testing.T) {
}
}
}
func TestRangeOptionDecode(t *testing.T) {
for _, test := range []struct {
in RangeOption
size int64
wantOffset int64
wantLimit int64
}{
{in: RangeOption{Start: 1, End: 10}, size: 100, wantOffset: 1, wantLimit: 10},
{in: RangeOption{Start: 10, End: 10}, size: 100, wantOffset: 10, wantLimit: 1},
{in: RangeOption{Start: 10, End: 9}, size: 100, wantOffset: 10, wantLimit: 0},
{in: RangeOption{Start: 1, End: -1}, size: 100, wantOffset: 1, wantLimit: -1},
{in: RangeOption{Start: -1, End: 90}, size: 100, wantOffset: 10, wantLimit: -1},
{in: RangeOption{Start: -1, End: -1}, size: 100, wantOffset: 0, wantLimit: -1},
} {
gotOffset, gotLimit := test.in.Decode(test.size)
what := fmt.Sprintf("%+v size=%d", test.in, test.size)
assert.Equal(t, test.wantOffset, gotOffset, "offset "+what)
assert.Equal(t, test.wantLimit, gotLimit, "limit "+what)
}
}