Overte C++ Documentation
ByteRange.h
1 //
2 // ByteRange.h
3 // libraries/networking/src
4 //
5 // Created by Stephen Birarda on 4/17/17.
6 // Copyright 2017 High Fidelity, Inc.
7 //
8 // Distributed under the Apache License, Version 2.0.
9 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
10 //
11 
12 #ifndef hifi_ByteRange_h
13 #define hifi_ByteRange_h
14 
15 struct ByteRange {
16  int64_t fromInclusive { 0 };
17  int64_t toExclusive { 0 };
18 
19  bool isSet() const { return fromInclusive < 0 || fromInclusive < toExclusive; }
20  int64_t size() const { return toExclusive - fromInclusive; }
21 
22  // byte ranges are invalid if:
23  // (1) the toExclusive of the range is negative
24  // (2) the toExclusive of the range is less than the fromInclusive, and isn't zero
25  // (3) the fromExclusive of the range is negative, and the toExclusive isn't zero
26  bool isValid() {
27  return toExclusive >= 0
28  && (toExclusive >= fromInclusive || toExclusive == 0)
29  && (fromInclusive >= 0 || toExclusive == 0);
30  }
31 
32  void fixupRange(int64_t fileSize) {
33  if (!isSet()) {
34  // if the byte range is not set, force it to be from 0 to the end of the file
35  fromInclusive = 0;
36  toExclusive = fileSize;
37  }
38 
39  if (fromInclusive > 0 && toExclusive == 0) {
40  // we have a left side of the range that is non-zero
41  // if the RHS of the range is zero, set it to the end of the file now
42  toExclusive = fileSize;
43  } else if (-fromInclusive >= fileSize) {
44  // we have a negative range that is equal or greater than the full size of the file
45  // so we just set this to be a range across the entire file, from 0
46  fromInclusive = 0;
47  toExclusive = fileSize;
48  }
49  }
50 };
51 
52 
53 #endif // hifi_ByteRange_h