Skip to content

Commit a51c23d

Browse files
committed
Replace type casts with orThrow
Casting is code smell
1 parent 05fe5d5 commit a51c23d

9 files changed

Lines changed: 54 additions & 48 deletions

File tree

packages/common/src/Buffer.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -116,10 +116,10 @@ export const createBuffer = (
116116
let value = arrayLike
117117
? new globalThis.Uint8Array(arrayLike)
118118
: new globalThis.Uint8Array(512);
119-
let length = (arrayLike ? arrayLike.length : 0) as NonNegativeInt;
119+
let length = NonNegativeInt.orThrow(arrayLike ? arrayLike.length : 0);
120120

121121
const buffer: Buffer = {
122-
getCapacity: () => value.length as NonNegativeInt,
122+
getCapacity: () => NonNegativeInt.orThrow(value.length),
123123

124124
getLength: () => length,
125125

@@ -132,7 +132,7 @@ export const createBuffer = (
132132
value.set(oldValue);
133133
}
134134
value.set(arg, length);
135-
length = (length + arg.length) as NonNegativeInt;
135+
length = NonNegativeInt.orThrow(length + arg.length);
136136
},
137137

138138
shift: () => {
@@ -142,7 +142,7 @@ export const createBuffer = (
142142
const first = value[0];
143143
value = value.subarray(1);
144144
length--;
145-
return first as NonNegativeInt;
145+
return NonNegativeInt.orThrow(first);
146146
},
147147

148148
shiftN: (n) => {
@@ -151,7 +151,7 @@ export const createBuffer = (
151151
}
152152
const subarray = value.subarray(0, n);
153153
value = value.subarray(n);
154-
length = (length - n) as NonNegativeInt;
154+
length = NonNegativeInt.orThrow(length - n);
155155
return subarray;
156156
},
157157

@@ -165,7 +165,7 @@ export const createBuffer = (
165165
},
166166

167167
reset: () => {
168-
length = 0 as NonNegativeInt;
168+
length = NonNegativeInt.orThrow(0);
169169
},
170170

171171
unwrap: () => value.subarray(0, length),

packages/common/src/Crypto.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -176,20 +176,20 @@ export const createSymmetricCrypto = (
176176
* https://bford.info/pub/sec/purb.pdf
177177
*/
178178
export const padmePaddedLength = (length: NonNegativeInt): NonNegativeInt => {
179-
if (length <= 0) return 0 as NonNegativeInt;
179+
if (length <= 0) return NonNegativeInt.orThrow(0);
180180
const e = 31 - Math.clz32(length >>> 0);
181181
const s = 32 - Math.clz32(e >>> 0);
182182
const z = Math.max(0, e - s);
183183
const mask = (1 << z) - 1;
184-
return ((length + mask) & ~mask) as NonNegativeInt;
184+
return NonNegativeInt.orThrow((length + mask) & ~mask);
185185
};
186186

187187
/**
188188
* Returns the PADMÉ padding length for a given input length. Uses
189189
* {@link padmePaddedLength}.
190190
*/
191191
export const padmePaddingLength = (length: NonNegativeInt): NonNegativeInt => {
192-
return (padmePaddedLength(length) - length) as NonNegativeInt;
192+
return NonNegativeInt.orThrow(padmePaddedLength(length) - length);
193193
};
194194

195195
/**

packages/common/src/Evolu/Owner.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ export const ownerIdToOwnerIdBytes = (ownerId: OwnerId): OwnerIdBytes =>
7373
export const ownerIdBytesToOwnerId = (ownerIdBytes: OwnerIdBytes): OwnerId =>
7474
idBytesToId(ownerIdBytes as IdBytes) as OwnerId;
7575

76-
export const ownerWriteKeyLength = 16 as NonNegativeInt;
76+
export const ownerWriteKeyLength = NonNegativeInt.orThrow(16);
7777

7878
export const OwnerEncryptionKey = brand("OwnerEncryptionKey", EncryptionKey);
7979
export type OwnerEncryptionKey = typeof OwnerEncryptionKey.Type;

packages/common/src/Evolu/Protocol.ts

Lines changed: 32 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ export const defaultProtocolMessageRangesMaxSize =
325325
export type ProtocolMessage = Uint8Array & Brand<"ProtocolMessage">;
326326

327327
/** Evolu Protocol version. */
328-
export const protocolVersion = 0 as NonNegativeInt;
328+
export const protocolVersion = NonNegativeInt.orThrow(0);
329329

330330
export const MessageType = {
331331
/** Request message from initiator (client) to non-initiator (relay). */
@@ -525,7 +525,7 @@ export const createProtocolMessageForSync =
525525

526526
splitRange(deps)(
527527
ownerIdBytes,
528-
0 as NonNegativeInt,
528+
NonNegativeInt.orThrow(0),
529529
size,
530530
InfiniteUpperBound,
531531
buffer,
@@ -628,7 +628,7 @@ export const createProtocolMessageBuffer = (
628628
const isWithinSizeLimits = () => getSize() <= totalMaxSize;
629629

630630
const getSize = () =>
631-
(getHeaderAndMessagesSize() + getRangesSize()) as PositiveInt;
631+
PositiveInt.orThrow(getHeaderAndMessagesSize() + getRangesSize());
632632

633633
const getHeaderAndMessagesSize = () =>
634634
buffers.header.getLength() +
@@ -726,7 +726,10 @@ export const createProtocolMessageBuffer = (
726726
buffers.ranges.timestamps.addInfinite();
727727
}
728728

729-
encodeNonNegativeInt(buffers.ranges.types, range.type as NonNegativeInt);
729+
encodeNonNegativeInt(
730+
buffers.ranges.types,
731+
NonNegativeInt.orThrow(range.type),
732+
);
730733

731734
switch (range.type) {
732735
case RangeType.Skip:
@@ -781,7 +784,7 @@ export interface TimestampsBuffer {
781784
}
782785

783786
export const createTimestampsBuffer = (): TimestampsBuffer => {
784-
let count = 0 as NonNegativeInt;
787+
let count = NonNegativeInt.orThrow(0);
785788
const countBuffer = createBuffer();
786789

787790
const syncCount = () => {
@@ -848,9 +851,9 @@ const createRunLengthEncoder = <T>(
848851
encodeValue: (buffer: Buffer, value: T) => void,
849852
): RunLengthEncoder<T> => {
850853
const buffer = createBuffer();
851-
let previousLength = 0 as NonNegativeInt;
854+
let previousLength = NonNegativeInt.orThrow(0);
852855
let previousValue = null as T | null;
853-
let runLength = 0 as NonNegativeInt;
856+
let runLength = NonNegativeInt.orThrow(0);
854857

855858
return {
856859
add: (value) => {
@@ -859,7 +862,7 @@ const createRunLengthEncoder = <T>(
859862
buffer.truncate(previousLength);
860863
} else {
861864
previousValue = value;
862-
runLength = 1 as NonNegativeInt;
865+
runLength = NonNegativeInt.orThrow(1);
863866
}
864867
previousLength = buffer.getLength();
865868
encodeValue(buffer, value);
@@ -1255,7 +1258,7 @@ const sync =
12551258
if (storageSize == null) return err(ProtocolErrorCode.SyncError);
12561259

12571260
let prevUpperBound: RangeUpperBound | null = null;
1258-
let prevIndex = 0 as NonNegativeInt;
1261+
let prevIndex = NonNegativeInt.orThrow(0);
12591262

12601263
let skip = false;
12611264
let nonSkipRangeAdded = false;
@@ -1458,7 +1461,7 @@ const splitRange =
14581461
upperBound: RangeUpperBound,
14591462
buffer: ProtocolMessageBuffer,
14601463
): void => {
1461-
const itemCount = (upper - lower) as NonNegativeInt;
1464+
const itemCount = NonNegativeInt.orThrow(upper - lower);
14621465
const buckets = computeBalancedBuckets(itemCount);
14631466

14641467
if (!buckets.ok) {
@@ -1470,7 +1473,7 @@ const splitRange =
14701473

14711474
deps.storage.iterate(
14721475
ownerId,
1473-
0 as NonNegativeInt,
1476+
NonNegativeInt.orThrow(0),
14741477
itemCount,
14751478
(timestamp) => {
14761479
range.timestamps.add(timestampBytesToTimestamp(timestamp));
@@ -1486,7 +1489,10 @@ const splitRange =
14861489
const fingerprintRangesBuckets =
14871490
lower === 0
14881491
? buckets.value
1489-
: [lower, ...buckets.value.map((b) => (b + lower) as NonNegativeInt)];
1492+
: [
1493+
lower,
1494+
...buckets.value.map((b) => NonNegativeInt.orThrow(b + lower)),
1495+
];
14901496

14911497
const fingerprintRanges = deps.storage.fingerprintRanges(
14921498
ownerId,
@@ -1510,7 +1516,7 @@ const decodeRanges = (buffer: Buffer): ReadonlyArray<Range> => {
15101516
const rangesCount = decodeNonNegativeInt(buffer);
15111517
if (rangesCount === 0) return [];
15121518

1513-
const timestampsCount = (rangesCount - 1) as NonNegativeInt;
1519+
const timestampsCount = NonNegativeInt.orThrow(rangesCount - 1);
15141520
const timestamps = decodeTimestamps(buffer, timestampsCount);
15151521
const rangeTypes: Array<RangeType> = [];
15161522

@@ -1845,7 +1851,7 @@ export const decodeNonNegativeInt = (buffer: Buffer): NonNegativeInt => {
18451851
};
18461852

18471853
export const encodeLength = (buffer: Buffer, value: ArrayLike<any>): void => {
1848-
encodeNonNegativeInt(buffer, value.length as NonNegativeInt);
1854+
encodeNonNegativeInt(buffer, NonNegativeInt.orThrow(value.length));
18491855
};
18501856

18511857
export const decodeLength = decodeNonNegativeInt;
@@ -1867,7 +1873,7 @@ export const encodeNodeId = (buffer: Buffer, nodeId: NodeId): void => {
18671873
};
18681874

18691875
export const decodeNodeId = (buffer: Buffer): NodeId => {
1870-
const bytes = buffer.shiftN(8 as NonNegativeInt);
1876+
const bytes = buffer.shiftN(NonNegativeInt.orThrow(8));
18711877
return bytesToHex(bytes) as NodeId;
18721878
};
18731879

@@ -1879,26 +1885,26 @@ export const ProtocolValueType = {
18791885
// 0-19 small ints
18801886

18811887
// SQLite types
1882-
String: 20 as NonNegativeInt,
1883-
Number: 21 as NonNegativeInt,
1884-
Null: 22 as NonNegativeInt,
1885-
Bytes: 23 as NonNegativeInt,
1888+
String: NonNegativeInt.orThrow(20),
1889+
Number: NonNegativeInt.orThrow(21),
1890+
Null: NonNegativeInt.orThrow(22),
1891+
Bytes: NonNegativeInt.orThrow(23),
18861892
// We can add more types for other DBs or anything else later.
18871893

18881894
// Optimized types
1889-
NonNegativeInt: 30 as NonNegativeInt,
1895+
NonNegativeInt: NonNegativeInt.orThrow(30),
18901896

18911897
// String optimizations
1892-
EmptyString: 31 as NonNegativeInt, // 1 byte vs 2 bytes (50% reduction)
1893-
Base64Url: 32 as NonNegativeInt,
1894-
Id: 33 as NonNegativeInt,
1895-
Json: 34 as NonNegativeInt,
1898+
EmptyString: NonNegativeInt.orThrow(31), // 1 byte vs 2 bytes (50% reduction)
1899+
Base64Url: NonNegativeInt.orThrow(32),
1900+
Id: NonNegativeInt.orThrow(33),
1901+
Json: NonNegativeInt.orThrow(34),
18961902

18971903
// new Date().toISOString() - 24 bytes
18981904
// encoded with fixed length - 8 bytes
18991905
// encode as NonNegativeInt - 6 bytes (additional 25% reduction)
1900-
DateIsoWithNonNegativeTime: 35 as NonNegativeInt,
1901-
DateIsoWithNegativeTime: 36 as NonNegativeInt, // 9 bytes
1906+
DateIsoWithNonNegativeTime: NonNegativeInt.orThrow(35),
1907+
DateIsoWithNegativeTime: NonNegativeInt.orThrow(36), // 9 bytes
19021908

19031909
// TODO: Operations (from 40)
19041910
// Increment, Decrement, Patch, whatever.

packages/common/src/Evolu/Storage.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ export interface StorageQuotaError extends BaseOwnerError {
183183
*/
184184
export type Fingerprint = Uint8Array & Brand<"Fingerprint">;
185185

186-
export const fingerprintSize = 12 as NonNegativeInt;
186+
export const fingerprintSize = NonNegativeInt.orThrow(12);
187187

188188
/** A fingerprint of an empty range. */
189189
export const zeroFingerprint = new Uint8Array(fingerprintSize) as Fingerprint;
@@ -425,7 +425,7 @@ export const createBaseSqliteStorage =
425425
}
426426

427427
for (let i = 0; i < result.value.rows.length; i++) {
428-
const index = (begin + 1 + i) as NonNegativeInt;
428+
const index = NonNegativeInt.orThrow(begin + 1 + i);
429429
if (!callback(result.value.rows[i].t, index)) return;
430430
}
431431
},
@@ -1153,7 +1153,7 @@ const randomSkiplistLevel = (deps: RandomDep): PositiveInt => {
11531153
) {
11541154
level += 1;
11551155
}
1156-
return level as PositiveInt;
1156+
return PositiveInt.orThrow(level);
11571157
};
11581158

11591159
/**
@@ -1294,7 +1294,7 @@ const findLowerBound =
12941294
if (!count.ok) return count;
12951295

12961296
// `decrement` converts a count to an index.
1297-
return ok(decrement(count.value) as NonNegativeInt);
1297+
return ok(NonNegativeInt.orThrow(decrement(count.value)));
12981298
};
12991299

13001300
const getTimestampCount =

packages/common/src/Number.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,15 +59,15 @@ export const computeBalancedBuckets = (
5959
numberOfItems: NonNegativeInt,
6060

6161
/** Default: 16 */
62-
numberOfBuckets = 16 as PositiveInt,
62+
numberOfBuckets = PositiveInt.orThrow(16),
6363

6464
/** Default: 2 */
65-
minNumberOfItemsPerBucket = 2 as PositiveInt,
65+
minNumberOfItemsPerBucket = PositiveInt.orThrow(2),
6666
): Result<NonEmptyReadonlyArray<PositiveInt>, PositiveInt> => {
6767
const minRequiredItems = numberOfBuckets * minNumberOfItemsPerBucket;
6868

6969
if (numberOfItems < minRequiredItems)
70-
return err(minRequiredItems as PositiveInt);
70+
return err(PositiveInt.orThrow(minRequiredItems));
7171

7272
const indexes: Array<PositiveInt> = [];
7373
const itemsPerBucket = Math.floor(numberOfItems / numberOfBuckets);
@@ -78,7 +78,7 @@ export const computeBalancedBuckets = (
7878
const hasExtraItem = i < extraItems;
7979
const itemsInThisBucket = itemsPerBucket + (hasExtraItem ? 1 : 0);
8080
bucketBoundary += itemsInThisBucket;
81-
indexes.push(bucketBoundary as PositiveInt);
81+
indexes.push(PositiveInt.orThrow(bucketBoundary));
8282
}
8383

8484
assertNonEmptyReadonlyArray(indexes);

packages/common/src/Skiplist.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ export const createSkiplistLevel =
2525
while (deps.random.next() <= probability && level < maxLevel) {
2626
level += 1;
2727
}
28-
return level as PositiveInt;
28+
return PositiveInt.orThrow(level);
2929
},
3030
};
3131
};

packages/common/src/Task.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -577,7 +577,7 @@ export const retry = <T, E>(
577577
}
578578

579579
// Wait before retry
580-
const delayResult = await wait(delay as NonNegativeInt)(context);
580+
const delayResult = await wait(NonNegativeInt.orThrow(delay))(context);
581581
if (!delayResult.ok) {
582582
// If delay was aborted, return AbortError (will be handled by toTask)
583583
return delayResult;
@@ -770,7 +770,7 @@ export interface Mutex extends Disposable {
770770
* ```
771771
*/
772772
export const createMutex = (): Mutex => {
773-
const mutex = createSemaphore(1 as PositiveInt);
773+
const mutex = createSemaphore(PositiveInt.orThrow(1));
774774

775775
return {
776776
withLock: mutex.withPermit,

packages/common/src/Time.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,5 +207,5 @@ export const durationToNonNegativeInt = (
207207
total += value * units[unit as keyof typeof units];
208208
}
209209

210-
return total as NonNegativeInt;
210+
return NonNegativeInt.orThrow(total);
211211
};

0 commit comments

Comments
 (0)