Skip to content

Commit

Permalink
Add var int size methods
Browse files Browse the repository at this point in the history
  • Loading branch information
MatthewLM committed Nov 10, 2023
1 parent 8ff580a commit f43b890
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 15 deletions.
26 changes: 12 additions & 14 deletions coinlib/lib/src/common/serial.dart
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,17 @@ class BytesWriter extends _ReadWriteBase with Writer {
/// Measures the serialized size of data written to it without writing to a
/// Uint8List
class MeasureWriter with Writer {

int size = 0;

static int varIntSizeOf(BigInt i) {
if (i.compareTo(BigInt.from(0xfd)) < 0) return 1;
if (i.compareTo(BigInt.from(0xffff)) <= 0) return 3;
if (i.compareTo(BigInt.from(0xffffffff)) <= 0) return 5;
return 9;
}
static int varIntSizeOfInt(int i) => varIntSizeOf(BigInt.from(i));

@override
writeUInt8(int i) => size++;
@override
Expand All @@ -217,20 +227,8 @@ class MeasureWriter with Writer {
@override
writeSlice(Uint8List slice) => size += slice.length;
@override
writeVarInt(BigInt i) {
if (i.compareTo(BigInt.from(0xfd)) < 0) {
size++;
} else if (i.compareTo(BigInt.from(0xffff)) <= 0) {
// 16 bit
size += 3;
} else if (i.compareTo(BigInt.from(0xffffffff)) <= 0) {
// 32 bit
size += 5;
} else {
// 64 bit
size += 9;
}
}
writeVarInt(BigInt i) => size += varIntSizeOf(i);

}

/// Classes that use this mixin are serializable to a [Writer] via [write] and
Expand Down
2 changes: 1 addition & 1 deletion coinlib/lib/src/tx/inputs/p2sh_multisig_input.dart
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,6 @@ class P2SHMultisigInput extends LegacyInput {
int? get signedSize
=> 40 // Outpoint plus sequence
+ _signedScriptSize
+ (_signedScriptSize < 0xfd ? 1 : 3); // Varint size
+ MeasureWriter.varIntSizeOfInt(_signedScriptSize); // Varint size

}

0 comments on commit f43b890

Please sign in to comment.