First, for simplicity:
to = from + len - 1
I think it could be broken into 3 equations, for each "section". That is:
- A:
0
to 0xD800 - 1
- B:
0xD800
to 0xDFFF
- C:
0xDFFF + 1
to infinity
Section A and C are "worth" 2, and B is worth 1. Unless I have misinterpreted your code -- is there only 2 sections?
So multiply each section value by the length of the range that falls within it:
A: if (from < 0xD800) size += 2 * min((0xD800 - 1) - from + 1, len)
Assuming min
is a function that returns the lesser of its arguments: The range is "from
to the end of the section, or len
, whichever is shorter". Range is (end - start + 1).
B: if (to > 0xD800) size += 1 * min(0xDFFF - 0xD800 + 1, to - D800 + 1)
The logic is similar here: "the full section, or the beginning of the section to to
, whichever is shorter".
C: if (to > 0xDFFF + 1) size += 2 * (to - (0xDFFF + 1) + 1)
This is simpler because there is no end point: just count from the beginning to to
.
I have no idea if this would be more efficient for a computer. It's definitely less efficient for my brain, though.