1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright 2022 Datafuse Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt::Display;
use std::fmt::Formatter;
use std::ops::Range;
use std::ops::RangeInclusive;
use std::str::FromStr;

use crate::raw::*;
use crate::Error;
use crate::ErrorKind;
use crate::Result;

/// BytesContentRange is the content range of bytes.
///
/// `<unit>` should always be `bytes`.
///
/// ```text
/// Content-Range: bytes <range-start>-<range-end>/<size>
/// Content-Range: bytes <range-start>-<range-end>/*
/// Content-Range: bytes */<size>
/// ```
///
/// # Notes
///
/// ## Usage of the default.
///
/// `BytesContentRange::default` is not a valid content range.
/// Please make sure their comes up with `with_range` or `with_size` call.
///
/// ## Allow clippy::len_without_is_empty
///
/// BytesContentRange implements `len()` but not `is_empty()` because it's useless.
/// - When BytesContentRange's range is known, it must be non-empty.
/// - When BytesContentRange's range is no known, we don't know whether it's empty.
#[allow(clippy::len_without_is_empty)]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct BytesContentRange(
    /// Start position of the range. `None` means unknown.
    Option<u64>,
    /// End position of the range. `None` means unknown.
    Option<u64>,
    /// Size of the whole content. `None` means unknown.
    Option<u64>,
);

impl BytesContentRange {
    /// Update BytesContentRange with range.
    ///
    /// The range is inclusive: `[start..=end]` as described in `content-range`.
    pub fn with_range(mut self, start: u64, end: u64) -> Self {
        self.0 = Some(start);
        self.1 = Some(end);
        self
    }

    /// Update BytesContentRange with size.
    pub fn with_size(mut self, size: u64) -> Self {
        self.2 = Some(size);
        self
    }

    /// Get the length that specified by this BytesContentRange, return `None` if range is not known.
    pub fn len(&self) -> Option<u64> {
        if let (Some(start), Some(end)) = (self.0, self.1) {
            Some(end - start + 1)
        } else {
            None
        }
    }

    /// Get the size of this BytesContentRange, return `None` if size is not known.
    pub fn size(&self) -> Option<u64> {
        self.2
    }

    /// Get the range inclusive of this BytesContentRange, return `None` if range is not known.
    pub fn range(&self) -> Option<Range<u64>> {
        if let (Some(start), Some(end)) = (self.0, self.1) {
            Some(start..end + 1)
        } else {
            None
        }
    }

    /// Get the range inclusive of this BytesContentRange, return `None` if range is not known.
    pub fn range_inclusive(&self) -> Option<RangeInclusive<u64>> {
        if let (Some(start), Some(end)) = (self.0, self.1) {
            Some(start..=end)
        } else {
            None
        }
    }

    /// Convert bytes content range into Content-Range header.
    pub fn to_header(&self) -> String {
        format!("bytes {self}")
    }

    /// Calculate bytes content range from size and specified range.
    pub fn from_bytes_range(total_size: u64, range: BytesRange) -> Self {
        let (start, end) = match (range.offset(), range.size()) {
            (Some(offset), Some(size)) => (offset, offset + size - 1),
            (Some(offset), None) => (offset, total_size - 1),
            (None, Some(size)) => (total_size - size, total_size - 1),
            (None, None) => (0, total_size - 1),
        };

        Self(Some(start), Some(end), Some(total_size))
    }

    /// Calculate bytes range from bytes content range.
    pub fn to_bytes_range(self) -> Option<BytesRange> {
        match (self.0, self.1, self.2) {
            (Some(start), Some(end), _) => Some(BytesRange::from(start..=end)),
            (None, None, Some(_)) => None,
            _ => unreachable!("invalid bytes range: {:?}", self),
        }
    }
}

impl Display for BytesContentRange {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match (self.0, self.1, self.2) {
            (Some(start), Some(end), Some(size)) => write!(f, "{start}-{end}/{size}"),
            (Some(start), Some(end), None) => write!(f, "{start}-{end}/*"),
            (None, None, Some(size)) => write!(f, "*/{size}"),
            _ => unreachable!("invalid bytes range: {:?}", self),
        }
    }
}

impl FromStr for BytesContentRange {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        let s = value.strip_prefix("bytes ").ok_or_else(|| {
            Error::new(ErrorKind::Unexpected, "header content range is invalid")
                .with_operation("BytesContentRange::from_str")
                .with_context("value", value)
        })?;

        let parse_int_error = |e: std::num::ParseIntError| {
            Error::new(ErrorKind::Unexpected, "header content range is invalid")
                .with_operation("BytesContentRange::from_str")
                .with_context("value", value)
                .set_source(e)
        };

        if let Some(size) = s.strip_prefix("*/") {
            return Ok(
                BytesContentRange::default().with_size(size.parse().map_err(parse_int_error)?)
            );
        }

        let s: Vec<_> = s.split('/').collect();
        if s.len() != 2 {
            return Err(
                Error::new(ErrorKind::Unexpected, "header content range is invalid")
                    .with_operation("BytesContentRange::from_str")
                    .with_context("value", value),
            );
        }

        let v: Vec<_> = s[0].split('-').collect();
        if v.len() != 2 {
            return Err(
                Error::new(ErrorKind::Unexpected, "header content range is invalid")
                    .with_operation("BytesContentRange::from_str")
                    .with_context("value", value),
            );
        }
        let start: u64 = v[0].parse().map_err(parse_int_error)?;
        let end: u64 = v[1].parse().map_err(parse_int_error)?;
        let mut bcr = BytesContentRange::default().with_range(start, end);

        // Handle size part first.
        if s[1] != "*" {
            bcr = bcr.with_size(s[1].parse().map_err(parse_int_error)?)
        };

        Ok(bcr)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bytes_content_range_from_str() -> Result<()> {
        let cases = vec![
            (
                "range start with unknown size",
                "bytes 123-123/*",
                BytesContentRange::default().with_range(123, 123),
            ),
            (
                "range start with known size",
                "bytes 123-123/1024",
                BytesContentRange::default()
                    .with_range(123, 123)
                    .with_size(1024),
            ),
            (
                "only have size",
                "bytes */1024",
                BytesContentRange::default().with_size(1024),
            ),
        ];

        for (name, input, expected) in cases {
            let actual = input.parse()?;

            assert_eq!(expected, actual, "{name}")
        }

        Ok(())
    }

    #[test]
    fn test_from_bytes_range() {
        let cases = vec![
            (
                "offset only",
                BytesRange::new(Some(1024), None),
                2048,
                BytesContentRange::default()
                    .with_size(2048)
                    .with_range(1024, 2047),
            ),
            (
                "size only",
                BytesRange::new(None, Some(1024)),
                2048,
                BytesContentRange::default()
                    .with_size(2048)
                    .with_range(1024, 2047),
            ),
            (
                "offset zero",
                BytesRange::new(Some(0), Some(1024)),
                2048,
                BytesContentRange::default()
                    .with_size(2048)
                    .with_range(0, 1023),
            ),
            (
                "part of data",
                BytesRange::new(Some(1024), Some(1)),
                4096,
                BytesContentRange::default()
                    .with_size(4096)
                    .with_range(1024, 1024),
            ),
        ];

        for (name, input, input_size, expected) in cases {
            let actual = BytesContentRange::from_bytes_range(input_size, input);

            assert_eq!(expected, actual, "{name}")
        }
    }

    #[test]
    fn test_bytes_content_range_to_string() {
        let h = BytesContentRange::default().with_size(1024);
        assert_eq!(h.to_string(), "*/1024");

        let h = BytesContentRange::default().with_range(0, 1023);
        assert_eq!(h.to_string(), "0-1023/*");

        let h = BytesContentRange::default()
            .with_range(0, 1023)
            .with_size(1024);
        assert_eq!(h.to_string(), "0-1023/1024");
    }

    #[test]
    fn test_bytes_content_range_to_header() {
        let h = BytesContentRange::default().with_size(1024);
        assert_eq!(h.to_header(), "bytes */1024");

        let h = BytesContentRange::default().with_range(0, 1023);
        assert_eq!(h.to_header(), "bytes 0-1023/*");

        let h = BytesContentRange::default()
            .with_range(0, 1023)
            .with_size(1024);
        assert_eq!(h.to_header(), "bytes 0-1023/1024");
    }
}