Skip to content

Commit

Permalink
Fix shared views breaking ABI contract
Browse files Browse the repository at this point in the history
As outlined in #209, the TypeScript runtime utilizes a shared buffer for encoding which can lead to subtle bugs when decoding multiple types. For example:
```typescript
    // should be the data of 'CreateUser'
    const createUserBuffer = CreateUser.encode({ email: "hi@andrew.im" });
    // encode another type
    CreateOk.encode({ now: 1 })
    // fails to decode as the data of 'createUserBuffer' is now the data of 'CreateOk.encode'
    const user = CreateUser.decode(createUserBuffer);
```

This change ensures we create and return a new buffer from 'toArray()'; yes, it allocates additional data, but it means users don't need to think about what happens when encoding multiple types when they might still need the data buffer.
  • Loading branch information
andrewmd5 committed Apr 7, 2023
1 parent c5c2d00 commit 368eb35
Showing 1 changed file with 2 additions and 1 deletion.
3 changes: 2 additions & 1 deletion Runtime/TypeScript/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ export class BebopView {
}

toArray(): Uint8Array {
return this.buffer.subarray(0, this.length);
// allocate a new space in memory and copy the items from the original array between the start and end indices
return this.buffer.slice(0, this.length);
}

readByte(): number { return this.buffer[this.index++]; }
Expand Down

0 comments on commit 368eb35

Please sign in to comment.