Implements the special common case of a finite range based on long start, end, and step, with no more than Integer.MAX_VALUE items.
| 20 | * with no more than Integer.MAX_VALUE items. |
| 21 | */ |
| 22 | public class LongRange extends ASeq implements Counted, IChunkedSeq, IReduce, IDrop { |
| 23 | |
| 24 | private static final long serialVersionUID = -1467242400566893909L; |
| 25 | |
| 26 | // Invariants guarantee this is never an empty or infinite seq |
| 27 | // assert(start != end && step != 0) |
| 28 | final long start; |
| 29 | final long end; |
| 30 | final long step; |
| 31 | final int count; |
| 32 | |
| 33 | private LongRange(long start, long end, long step, int count){ |
| 34 | this.start = start; |
| 35 | this.end = end; |
| 36 | this.step = step; |
| 37 | this.count = count; |
| 38 | } |
| 39 | |
| 40 | private LongRange(IPersistentMap meta, long start, long end, long step, int count){ |
| 41 | super(meta); |
| 42 | this.start = start; |
| 43 | this.end = end; |
| 44 | this.step = step; |
| 45 | this.count = count; |
| 46 | } |
| 47 | |
| 48 | // returns exact size of remaining items OR throws ArithmeticException for overflow case |
| 49 | static long rangeCount(long start, long end, long step) { |
| 50 | // (1) count = ceiling ( (end - start) / step ) |
| 51 | // (2) ceiling(a/b) = (a+b+o)/b where o=-1 for positive stepping and +1 for negative stepping |
| 52 | // thus: count = end - start + step + o / step |
| 53 | return Numbers.add(Numbers.add(Numbers.minus(end, start), step), step > 0 ? -1 : 1) / step; |
| 54 | } |
| 55 | |
| 56 | public static ISeq create(long end) { |
| 57 | if(end > 0) { |
| 58 | try { |
| 59 | return new LongRange(0L, end, 1L, Math.toIntExact(rangeCount(0L, end, 1L))); |
| 60 | } catch(ArithmeticException e) { |
| 61 | return Range.create(end); // count > Integer.MAX_VALUE |
| 62 | } |
| 63 | } else { |
| 64 | return PersistentList.EMPTY; |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | public static ISeq create(long start, long end) { |
| 69 | if(start >= end) { |
| 70 | return PersistentList.EMPTY; |
| 71 | } else { |
| 72 | try { |
| 73 | return new LongRange(start, end, 1L, Math.toIntExact(rangeCount(start, end, 1L))); |
| 74 | } catch(ArithmeticException e) { |
| 75 | return Range.create(start, end); |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 |
nothing calls this directly
no outgoing calls
no test coverage detected