@@ -201,4 +201,43 @@ describe("ExtensionCodec", () => {
201201 ] ) ;
202202 } ) ;
203203 } ) ;
204+
205+ context ( "custom extensions with alignment" , ( ) => {
206+ const extensionCodec = new ExtensionCodec ( ) ;
207+
208+ extensionCodec . register ( {
209+ type : 0x01 ,
210+ encode : ( object : unknown ) => {
211+ if ( object instanceof Float32Array ) {
212+ return ( pos : number ) => {
213+ const bpe = Float32Array . BYTES_PER_ELEMENT ;
214+ const padding = 1 + ( ( bpe - ( ( pos + 1 ) % bpe ) ) % bpe ) ;
215+ const data = new Uint8Array ( object . buffer ) ;
216+ const result = new Uint8Array ( padding + data . length ) ;
217+ result [ 0 ] = padding ;
218+ result . set ( data , padding ) ;
219+ return result ;
220+ } ;
221+ }
222+ return null ;
223+ } ,
224+ decode : ( data : Uint8Array ) => {
225+ const padding = data [ 0 ] ! ;
226+ const bpe = Float32Array . BYTES_PER_ELEMENT ;
227+ const offset = data . byteOffset + padding ;
228+ const length = data . byteLength - padding ;
229+ return new Float32Array ( data . buffer , offset , length / bpe ) ;
230+ } ,
231+ } ) ;
232+
233+ it ( "encodes and decodes Float32Array type with zero-copy" , ( ) => {
234+ const data = {
235+ position : new Float32Array ( [ 1.1 , 2.2 , 3.3 , 4.4 , 5.5 ] ) ,
236+ } ;
237+ const encoded = encode ( data , { extensionCodec } ) ;
238+ const decoded = decode ( encoded , { extensionCodec } ) ;
239+ assert . deepStrictEqual ( decoded , data ) ;
240+ assert . strictEqual ( decoded . position . buffer , encoded . buffer ) ;
241+ } ) ;
242+ } ) ;
204243} ) ;
0 commit comments