azure_storage_blob 1.0.0

Microsoft Azure Blob Storage client library for Rust
Documentation
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

use azure_core::error::{Error, ErrorKind, ResultExt};
use azure_core::http::headers::{Header, HeaderName, HeaderValue};
use std::fmt;
use std::ops::{Range, RangeFrom, RangeInclusive, RangeTo, RangeToInclusive};
use std::str::FromStr;

const PREFIX: &str = "bytes ";
const WILDCARD: &str = "*";
const CONTENT_RANGE_ID: HeaderName = HeaderName::from_static("content-range");

type Result<T> = azure_core::Result<T>;

/// Represents the `Content-Range` HTTP response header.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) struct ContentRange {
    /// Inclusive start and exclusive end of the range.
    pub range: Option<(usize, usize)>,
    /// Total length of the remote resource.
    pub total_len: Option<usize>,
}

impl Header for ContentRange {
    fn name(&self) -> azure_core::http::headers::HeaderName {
        CONTENT_RANGE_ID
    }

    fn value(&self) -> azure_core::http::headers::HeaderValue {
        let range_str = match self.range {
            Some(range) => format!("{}-{}", range.0, range.1),
            None => WILDCARD.to_string(),
        };
        let len_str = match self.total_len {
            Some(len) => len.to_string(),
            None => WILDCARD.to_string(),
        };
        format!("{}{}/{}", PREFIX, range_str, len_str).into()
    }
}

impl FromStr for ContentRange {
    type Err = Error;
    fn from_str(s: &str) -> Result<ContentRange> {
        let remaining = s.strip_prefix(PREFIX).ok_or_else(|| {
            Error::with_message_fn(ErrorKind::Other, || {
                format!(
                    "expected token \"{PREFIX}\" not found when parsing ContentRange from \"{s}\""
                )
            })
        })?;

        let mut split_at_slash = remaining.split('/');

        let range = parse_range(split_at_slash.next().ok_or_else(|| {
            Error::with_message(ErrorKind::Other, "Unexpected end of Content-Range.")
        })?)?;

        let total_len = parse_total_length(split_at_slash.next().ok_or_else(|| {
            Error::with_message_fn(ErrorKind::Other, || {
                format!(
                    "expected token \"{}\" not found when parsing ContentRange from \"{}\"",
                    "/", s
                )
            })
        })?)?;

        Ok(ContentRange { range, total_len })
    }
}

/// Parses the range portion of the Content-Range header: `<unit> <range>/<size>`.
/// The range portion can be of the format `<start>-<end>` or a wildcard `*`.
/// `start` and `end` are both serialized as inclusive values, but we return a
/// half-open range (inclusive start, exclusive end).
fn parse_range(s: &str) -> Result<Option<(usize, usize)>> {
    let s = s.trim();
    if s == WILDCARD {
        return Ok(None);
    }

    let mut split_at_dash = s.split('-');
    let start = split_at_dash
        .next()
        .ok_or_else(|| Error::with_message(ErrorKind::Other, "Unexpected end of Content-Range."))?
        .parse::<usize>()
        .with_kind(ErrorKind::DataConversion)?;
    let end = split_at_dash
        .next()
        .ok_or_else(|| {
            Error::with_message_fn(ErrorKind::Other, || {
                format!(
                    "expected token \"{}\" not found when parsing ContentRange from \"{}\"",
                    "-", s
                )
            })
        })?
        .parse::<usize>()
        .with_kind(ErrorKind::DataConversion)?;

    Ok(Some((start, end + 1)))
}

fn parse_total_length(s: &str) -> Result<Option<usize>> {
    let s = s.trim();
    if s == WILDCARD {
        return Ok(None);
    }
    Ok(Some(s.parse().with_kind(ErrorKind::DataConversion)?))
}

impl fmt::Display for ContentRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}{}/{}",
            PREFIX,
            self.range
                .map(|range| format!("{}-{}", range.0, range.1 - 1))
                .unwrap_or(WILDCARD.into()),
            self.total_len
                .map(|len| len.to_string())
                .unwrap_or(WILDCARD.into()),
        )
    }
}

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

    #[test]
    fn parse() {
        let range = "bytes 172032-172489/172490"
            .parse::<ContentRange>()
            .unwrap();

        assert_eq!(range.range.unwrap().0, 172032);
        assert_eq!(range.range.unwrap().1, 172490);
        assert_eq!(range.total_len.unwrap(), 172490);
    }

    #[test]
    fn parse_no_starting_token() {
        "something else".parse::<ContentRange>().unwrap_err();
    }

    #[test]
    fn parse_no_dash() {
        "bytes 100".parse::<ContentRange>().unwrap_err();
    }

    #[test]
    fn parse_no_slash() {
        "bytes 100-500".parse::<ContentRange>().unwrap_err();
    }

    #[test]
    fn display() {
        let range = ContentRange {
            range: Some((100, 500)),
            total_len: Some(5000),
        };

        let txt = format!("{range}");

        assert_eq!(txt, "bytes 100-499/5000");
    }
}

/// Represents an HTTP Range header value for blob operations.
///
/// Defines a range of bytes within an HTTP resource, starting at an offset and
/// ending at `offset + length - 1` inclusively. This matches the semantics of .NET's
/// `Azure.HttpRange`.
///
/// # Examples
///
/// Range of 512 bytes starting at offset 0:
///
/// ```
/// use azure_storage_blob::models::HttpRange;
///
/// let range = HttpRange::new(0, 512);
/// assert_eq!(range.to_string(), "bytes=0-511");
/// ```
///
/// Open-ended range starting at offset 255:
///
/// ```
/// use azure_storage_blob::models::HttpRange;
///
/// let range = HttpRange::from_offset(255);
/// assert_eq!(range.to_string(), "bytes=255-");
/// ```
///
/// Convert from standard Rust range types:
///
/// ```
/// use azure_storage_blob::models::HttpRange;
///
/// let range: HttpRange = (0u64..100).into();
/// assert_eq!(range.to_string(), "bytes=0-99");
///
/// let range: HttpRange = (100u64..).into();
/// assert_eq!(range.to_string(), "bytes=100-");
///
/// let range: HttpRange = (0u64..=99).into();
/// assert_eq!(range.to_string(), "bytes=0-99");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpRange {
    /// The starting byte offset.
    offset: u64,
    /// The length of the range. If `None`, the range extends to the end of the resource.
    length: Option<u64>,
}

impl HttpRange {
    /// Creates a new `HttpRange` with the specified offset and length.
    ///
    /// The range will cover bytes from `offset` to `offset + length - 1` inclusive.
    ///
    /// # Arguments
    ///
    /// * `offset` - The starting byte offset.
    /// * `length` - The number of bytes in the range.
    pub fn new(offset: u64, length: u64) -> Self {
        Self {
            offset,
            length: Some(length),
        }
    }

    /// Creates a new `HttpRange` that starts at the specified offset and extends to the end.
    ///
    /// # Arguments
    ///
    /// * `offset` - The starting byte offset.
    pub fn from_offset(offset: u64) -> Self {
        Self {
            offset,
            length: None,
        }
    }

    pub(crate) fn offset(&self) -> u64 {
        self.offset
    }

    pub(crate) fn length(&self) -> Option<u64> {
        self.length
    }
}

impl fmt::Display for HttpRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.length {
            Some(length) => write!(
                f,
                "bytes={}-{}",
                self.offset,
                self.offset.saturating_add(length).saturating_sub(1)
            ),
            None => write!(f, "bytes={}-", self.offset),
        }
    }
}

impl From<HttpRange> for HeaderValue {
    fn from(range: HttpRange) -> Self {
        HeaderValue::from(range.to_string())
    }
}

// From<Range*<u64>> impls

impl From<Range<u64>> for HttpRange {
    fn from(range: Range<u64>) -> Self {
        Self::new(range.start, range.end - range.start)
    }
}

impl From<RangeFrom<u64>> for HttpRange {
    fn from(range: RangeFrom<u64>) -> Self {
        Self::from_offset(range.start)
    }
}

impl From<RangeInclusive<u64>> for HttpRange {
    fn from(range: RangeInclusive<u64>) -> Self {
        Self::new(*range.start(), range.end() - range.start() + 1)
    }
}

impl From<RangeTo<u64>> for HttpRange {
    fn from(range: RangeTo<u64>) -> Self {
        Self::new(0, range.end)
    }
}

impl From<RangeToInclusive<u64>> for HttpRange {
    fn from(range: RangeToInclusive<u64>) -> Self {
        Self::new(0, range.end + 1)
    }
}

// From<Range*<usize>> impls

impl From<Range<usize>> for HttpRange {
    fn from(range: Range<usize>) -> Self {
        Self::new(range.start as u64, (range.end - range.start) as u64)
    }
}

impl From<RangeFrom<usize>> for HttpRange {
    fn from(range: RangeFrom<usize>) -> Self {
        Self::from_offset(range.start as u64)
    }
}

impl From<RangeInclusive<usize>> for HttpRange {
    fn from(range: RangeInclusive<usize>) -> Self {
        Self::new(
            *range.start() as u64,
            (range.end() - range.start() + 1) as u64,
        )
    }
}

impl From<RangeTo<usize>> for HttpRange {
    fn from(range: RangeTo<usize>) -> Self {
        Self::new(0, range.end as u64)
    }
}

impl From<RangeToInclusive<usize>> for HttpRange {
    fn from(range: RangeToInclusive<usize>) -> Self {
        Self::new(0, (range.end + 1) as u64)
    }
}

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

    #[test]
    fn new_creates_bounded_range() {
        let range = HttpRange::new(0, 512);
        assert_eq!(range.to_string(), "bytes=0-511");
    }

    #[test]
    fn from_offset_creates_open_ended_range() {
        let range = HttpRange::from_offset(255);
        assert_eq!(range.to_string(), "bytes=255-");
    }

    #[test]
    fn display_bounded_range() {
        let range = HttpRange::new(0, 512);
        assert_eq!(range.to_string(), "bytes=0-511");
    }

    #[test]
    fn display_open_ended_range() {
        let range = HttpRange::from_offset(255);
        assert_eq!(range.to_string(), "bytes=255-");
    }

    #[test]
    fn to_string_bounded_range() {
        let range = HttpRange::new(100, 101);
        assert_eq!(range.to_string(), "bytes=100-200");
    }

    #[test]
    fn into_header_value() {
        let range = HttpRange::new(0, 512);
        let header_value: HeaderValue = range.into();
        assert_eq!(header_value.as_str(), "bytes=0-511");
    }

    #[test]
    fn display_zero_length_does_not_panic() {
        // length == 0 would underflow without saturating arithmetic; must not panic
        let range = HttpRange::new(0, 0);
        // saturating_add(0).saturating_sub(1) on offset 0 saturates to 0
        let _ = range.to_string();
    }

    #[test]
    fn display_overflow_does_not_panic() {
        // offset + length would overflow u64 without saturating arithmetic; must not panic
        let range = HttpRange::new(u64::MAX, u64::MAX);
        let _ = range.to_string();
    }

    // From<Range*<u64>> tests

    #[test]
    fn from_range_u64() {
        let range: HttpRange = (0u64..100).into();
        assert_eq!(range.to_string(), "bytes=0-99");
    }

    #[test]
    fn from_range_from_u64() {
        let range: HttpRange = (100u64..).into();
        assert_eq!(range.to_string(), "bytes=100-");
    }

    #[test]
    fn from_range_inclusive_u64() {
        let range: HttpRange = (0u64..=99).into();
        assert_eq!(range.to_string(), "bytes=0-99");
    }

    #[test]
    fn from_range_to_u64() {
        let range: HttpRange = (..100u64).into();
        assert_eq!(range.to_string(), "bytes=0-99");
    }

    #[test]
    fn from_range_to_inclusive_u64() {
        let range: HttpRange = (..=99u64).into();
        assert_eq!(range.to_string(), "bytes=0-99");
    }

    // From<Range*<usize>> tests

    #[test]
    fn from_range_usize() {
        let range: HttpRange = (0usize..100).into();
        assert_eq!(range.to_string(), "bytes=0-99");
    }

    #[test]
    fn from_range_from_usize() {
        let range: HttpRange = (100usize..).into();
        assert_eq!(range.to_string(), "bytes=100-");
    }

    #[test]
    fn from_range_inclusive_usize() {
        let range: HttpRange = (0usize..=99).into();
        assert_eq!(range.to_string(), "bytes=0-99");
    }

    #[test]
    fn from_range_to_usize() {
        let range: HttpRange = (..100usize).into();
        assert_eq!(range.to_string(), "bytes=0-99");
    }

    #[test]
    fn from_range_to_inclusive_usize() {
        let range: HttpRange = (..=99usize).into();
        assert_eq!(range.to_string(), "bytes=0-99");
    }

    #[test]
    fn from_range_nonzero_offset() {
        // Verify no off-by-one when start != 0
        let exclusive: HttpRange = (50u64..150).into();
        let inclusive: HttpRange = (50u64..=149).into();
        assert_eq!(exclusive.to_string(), "bytes=50-149");
        assert_eq!(inclusive.to_string(), "bytes=50-149");
        assert_eq!(exclusive, inclusive);
    }

    #[test]
    fn from_range_single_byte() {
        // A 1-byte range must not produce an off-by-one
        let exclusive: HttpRange = (42u64..43).into();
        let inclusive: HttpRange = (42u64..=42).into();
        assert_eq!(exclusive.to_string(), "bytes=42-42");
        assert_eq!(inclusive.to_string(), "bytes=42-42");
        assert_eq!(exclusive, inclusive);
    }
}