wit-bindgen-csharp 0.56.0

C# bindings generator for WIT and the component model, typically used through the `wit-bindgen-cli` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
/**
 * Helpers for the async support.
 */

public enum EventCode {
  None = 0,
  Subtask = 1,
  StreamRead = 2,
  StreamWrite = 3,
  FutureRead = 4,
  FutureWrite = 5,
  Cancel = 6,
}

public enum CallbackCode : uint
{
    Exit = 0,
    Yield = 1,
    Wait = 2,
    // TODO:
    //#define TEST_CALLBACK_CODE_WAIT(set) (2 | (set << 4))
}

public enum CancelCode : uint
{
    Completed = 0,
    Dropped = 1,
    Cancelled = 2,
}

// The context that we will create in unmanaged memory and pass to context_set.
// TODO: C has world specific types for these pointers, perhaps C# would benefit from those also.
[StructLayout(LayoutKind.Sequential)]
public struct ContextTask
{
    public int WaitableSetHandle;
    public int FutureHandle;
}

public static class AsyncSupport
{
    private static ConcurrentDictionary<int, ConcurrentDictionary<int, WaitableInfoState>> pendingTasks = new ();
    internal static class PollWasmInterop
    {
        [DllImport("wasi:io/poll@0.2.0", EntryPoint = "poll"), WasmImportLinkage]
        internal static extern void wasmImportPoll(nint p0, int p1, nint p2);
    }

    private static class Interop
    {
        [global::System.Runtime.InteropServices.DllImport("$root", EntryPoint = "[waitable-set-new]"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
        internal static extern int WaitableSetNew();

        [global::System.Runtime.InteropServices.DllImport("$root", EntryPoint = "[waitable-join]"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
        internal static extern void WaitableJoin(int waitable, int set);

        [global::System.Runtime.InteropServices.DllImport("$root", EntryPoint = "[waitable-set-wait]"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
        internal static unsafe extern int WaitableSetWait(int waitable, uint* waitableHandlePtr);

        [global::System.Runtime.InteropServices.DllImport("$root", EntryPoint = "[waitable-set-poll]"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
        internal static unsafe extern uint WaitableSetPoll(int waitable, uint* waitableHandlePtr);

        [global::System.Runtime.InteropServices.DllImport("$root", EntryPoint = "[waitable-set-drop]"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
        internal static extern void WaitableSetDrop(int waitable);

        [global::System.Runtime.InteropServices.DllImport("$root", EntryPoint = "[context-set-0]"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
        internal static unsafe extern void ContextSet(ContextTask* waitable);

        [global::System.Runtime.InteropServices.DllImport("$root", EntryPoint = "[context-get-0]"), global::System.Runtime.InteropServices.WasmImportLinkageAttribute]
        internal static unsafe extern ContextTask* ContextGet();
    }

    public static int WaitableSetNew() 
    {
        return Interop.WaitableSetNew();
    }

    // unsafe because we are using pointers.
    public static unsafe void WaitableSetPoll(int waitableHandle) 
    {
        var error  = Interop.WaitableSetPoll(waitableHandle, null);
        if(error != 0)
        {
            throw new Exception($"WaitableSetPoll failed with error code: {error}");
        }
    }

    internal static void Join(int readerWriterHandle, int waitableHandle, WaitableInfoState waitableInfoState) 
    {
        AddTaskToWaitables(waitableHandle, readerWriterHandle, waitableInfoState);
        Interop.WaitableJoin(readerWriterHandle, waitableHandle);
    }

    // TODO: Revisit this to see if we can remove it.
    // Only allow joining to a handle directly when there is no waitable.
    public static void Join(int handle) 
    {
        Interop.WaitableJoin(handle, 0);
    }

    private static void AddTaskToWaitables(int waitableSetHandle, int waitableHandle, WaitableInfoState waitableInfoState)
    {
        var waitableSetOfTasks = pendingTasks.GetOrAdd(waitableSetHandle, _ => new ConcurrentDictionary<int, WaitableInfoState>());
        waitableSetOfTasks[waitableHandle] = waitableInfoState;
    }

    // unsafe because we use a fixed size buffer.
    public static unsafe EventWaitable WaitableSetWait(int waitableSetHandle) 
    {
        uint* buffer = stackalloc uint[2];
        var eventCode = (EventCode)Interop.WaitableSetWait(waitableSetHandle, buffer);
        return new EventWaitable(eventCode, buffer[0], buffer[1]);
    }

    public static void WaitableSetDrop(int handle) 
    {
        Interop.WaitableSetDrop(handle);
    }

    // unsafe because we are using pointers.
    public static unsafe void ContextSet(ContextTask* contextTask)
    {
        Interop.ContextSet(contextTask);
    }

    // unsafe because we are using pointers.
    public static unsafe ContextTask* ContextGet()
    {
        return Interop.ContextGet();
    }

    // unsafe because we are using pointers.
    public static unsafe uint Callback(EventWaitable e, ContextTask* contextPtr)
    {
        ContextTask* contextTaskPtr = ContextGet();

        var waitables = pendingTasks[contextTaskPtr->WaitableSetHandle];
        var waitableInfoState = waitables[e.Waitable];

        if (e.IsDropped)
        {
            waitableInfoState.FutureStream.OtherSideDropped();
        }

        if (e.IsCompleted || e.IsDropped)
        {
            // The operation is complete so we can free the buffer and remove the waitable from our dicitonary
            waitables.Remove(e.Waitable, out _);
            if (e.IsSubtask)
            {
                // TODO: Handle/lift async function return values. 
                waitableInfoState.SetResult(0 /* not used */);
            }
            else
            {
                waitableInfoState.FutureStream.FreeBuffer();

                if (e.IsDropped)
                {
                    waitableInfoState.SetException(new StreamDroppedException());
                }
                else
                {
                    // This may add a new waitable to the set.
                    waitableInfoState.SetResult(e.WaitableCount);
                }
            }

            if (waitables.Count == 0)
            {
                ContextSet(null);
                Marshal.FreeHGlobal((IntPtr)contextTaskPtr);
                return (uint)CallbackCode.Exit;
            }

            return (uint)CallbackCode.Wait | (uint)(contextTaskPtr->WaitableSetHandle << 4);
        }

        throw new NotImplementedException($"WaitableStatus not implemented {e.WaitableStatus.State} in set {contextTaskPtr->WaitableSetHandle}");
    }

    // This method is unsafe because we are using unmanaged memory to store the context.
    internal static unsafe Task TaskFromStatus(uint status)
    {
        var subtaskStatus = new SubtaskStatus(status);
        status = status & 0xF;

        var tcs = new TaskCompletionSource<int>();
        if (subtaskStatus.IsSubtaskStarting || subtaskStatus.IsSubtaskStarted)
        {
            ContextTask* contextTaskPtr = ContextGet();
            if (contextTaskPtr == null)
            {
                contextTaskPtr = AllocateAndSetNewContext();
            }

            Join(subtaskStatus.Handle, contextTaskPtr->WaitableSetHandle, new WaitableInfoState(tcs));

            return tcs.Task;
        }
        else if (subtaskStatus.IsSubtaskReturned)
        {
            tcs.SetResult(0);
            return Task.CompletedTask;
        }
        else
        {
            throw new Exception($"unexpected subtask status: {status}");
        }
    }

    // unsafe because we are using pointers.
    public static unsafe Task<T> TaskFromStatus<T>(uint status, Func<T> liftFunc)
    {
        var subtaskStatus = new SubtaskStatus(status);

        if (subtaskStatus.IsSubtaskStarting || subtaskStatus.IsSubtaskStarted)
        {
            ContextTask* contextTaskPtr = ContextGet();
            if (contextTaskPtr == null) {
                contextTaskPtr = AllocateAndSetNewContext();
            }

            var intTaskCompletionSource = new TaskCompletionSource<int>();
            var tcs = new LiftingTaskCompletionSource<T>(intTaskCompletionSource, liftFunc);
            Join(subtaskStatus.Handle, contextTaskPtr->WaitableSetHandle, new WaitableInfoState(intTaskCompletionSource));

            return tcs.Task;
        }
        else if (subtaskStatus.IsSubtaskReturned)
        {
            var tcs = new TaskCompletionSource<T>();
            tcs.SetResult(liftFunc());
            return tcs.Task;
        }
        else 
        {
            throw new Exception($"unexpected subtask status: {status}");
        }
    }

    // Placeholder, TODO: Needs implementing for async functions that return values.
    internal class LiftingTaskCompletionSource<T> : TaskCompletionSource<T>
    {
        internal LiftingTaskCompletionSource(TaskCompletionSource<int> innerTaskCompletionSource, Func<T> _liftFunc)
        {
            innerTaskCompletionSource.Task.ContinueWith(t => {
                throw new NotImplementedException("lifting results from async functions not implemented yet");
            });
        }
    }

    // unsafe because we are working with native memory.
    internal static unsafe ContextTask* AllocateAndSetNewContext()
    {
        var contextTaskPtr = (ContextTask *)Marshal.AllocHGlobal(Marshal.SizeOf<ContextTask>());
        contextTaskPtr->WaitableSetHandle = WaitableSetNew();
        ContextSet(contextTaskPtr);
        return contextTaskPtr;
    }
}


/**
 * Future/Stream VTable delegate types.
 */
public delegate ulong New();
public delegate uint FutureRead(int handle, IntPtr buffer);
public delegate void DropReader(int handle);
public delegate void DropWriter(int handle);
public delegate uint FutureWrite(int handle, IntPtr buffer);

public delegate uint StreamWrite(int handle, IntPtr buffer, uint length);
public delegate uint StreamRead(int handle, IntPtr buffer, uint length);
public delegate void Lower(object payload, uint size);
public delegate uint CancelRead(int handle);
public delegate uint CancelWrite(int handle);

public interface ICancelableRead
{
    uint CancelRead(int handle);
}

public interface ICancelableWrite
{
    uint CancelWrite(int handle);
}

public interface ICancelable
{
    uint Cancel();
}

public class CancelableRead(ICancelableRead cancelableVTable, int handle) : ICancelable
{
    public uint Cancel()
    {
        return cancelableVTable.CancelRead(handle);        
    }
}

public class CancelableWrite(ICancelableWrite cancelableVTable, int handle) : ICancelable
{
    public uint Cancel()
    {
        return cancelableVTable.CancelWrite(handle);        
    }
}

public struct FutureVTable : ICancelableRead, ICancelableWrite
{
    internal New New;
    internal FutureRead Read;
    internal FutureWrite Write;
    internal DropReader DropReader;
    internal DropWriter DropWriter;
    internal Lower? Lower;
    internal CancelWrite CancelWriteDelegate;
    internal CancelRead CancelReadDelegate;

    public uint CancelRead(int handle)
    {
        return CancelReadDelegate(handle);
    }

    public uint CancelWrite(int handle)
    {
        return CancelWriteDelegate(handle);
    }
}

public struct StreamVTable : ICancelableRead, ICancelableWrite
{
    internal New New;
    internal StreamRead Read;
    internal StreamWrite Write;
    internal DropReader DropReader;
    internal DropWriter DropWriter;
    internal Lower? Lower;
    internal CancelWrite CancelWriteDelegate;
    internal CancelRead CancelReadDelegate;

    public uint CancelRead(int handle)
    {
        return CancelReadDelegate(handle);
    }

    public uint CancelWrite(int handle)
    {
        return CancelWriteDelegate(handle);
    }
}

internal interface IFutureStream : IDisposable
{
    void FreeBuffer();
    // Called when notified the other side is dropped.
    void OtherSideDropped();
}

public static class FutureHelpers
{
    /// Helper function to create a new read/write pair for a component model
    /// future.
    internal static (FutureReader, FutureWriter) RawFutureNew(FutureVTable vtable)
    {
        var packed = vtable.New();
        var readerHandle = (int)(packed & 0xFFFFFFFF);
        var writerHandle = (int)(packed >> 32);

        return (new FutureReader(readerHandle, vtable), new FutureWriter(writerHandle, vtable));
    }

    internal static (FutureReader<T>, FutureWriter<T>) RawFutureNew<T>(FutureVTable vtable)
    {
        var packed = vtable.New();
        var readerHandle = (int)(packed & 0xFFFFFFFF);
        var writerHandle = (int)(packed >> 32);

        return (new FutureReader<T>(readerHandle, vtable), new FutureWriter<T>(writerHandle, vtable));
    }

    /// Helper function to create a new read/write pair for a component model
    /// stream.
    internal static (StreamReader, StreamWriter) RawStreamNew(StreamVTable vtable)
    {
        var packed = vtable.New();
        var readerHandle = (int)(packed & 0xFFFFFFFF);
        var writerHandle = (int)(packed >> 32);

        return (new StreamReader(readerHandle, vtable), new StreamWriter(writerHandle, vtable));
    }

    internal static (StreamReader<T>, StreamWriter<T>) RawStreamNew<T>(StreamVTable vtable)
    {
        var packed = vtable.New();
        var readerHandle = (int)(packed & 0xFFFFFFFF);
        var writerHandle = (int)(packed >> 32);

        return (new StreamReader<T>(readerHandle, vtable), new StreamWriter<T>(writerHandle, vtable));
    }
}

public abstract class ReaderBase : IFutureStream
{
    private GCHandle? bufferHandle;
    private bool writerDropped;

    internal ReaderBase(int handle)
    {
        Handle = handle;
    }

    internal int Handle { get; private set; }

    internal int TakeHandle()
    {
        if (Handle == 0)
        {
            throw new InvalidOperationException("Handle already taken");
        }
        var handle = Handle;
        Handle = 0;
        return handle;
    }

    protected GCHandle LiftBuffer<T>(T[] buffer)
    {
        // For primitive, blittable types
        if (typeof(T).IsPrimitive || typeof(T).IsValueType)
        {
            return GCHandle.Alloc(buffer, GCHandleType.Pinned);
        }
        else
        {
            // TODO: create buffers for lowered stream types and then lift
            throw new NotImplementedException("reading from futures types that require lifting");
        }
    }

    internal abstract uint VTableRead(IntPtr bufferPtr, int length);

    // unsafe as we are working with pointers.
    internal unsafe ComponentTask<int> ReadInternal(Func<GCHandle?> liftBuffer, int length, ICancelableRead cancelableRead)
    {
        if (Handle == 0)
        {
            throw new InvalidOperationException("Handle already taken");
        }

        if (writerDropped)
        {
            throw new StreamDroppedException();    
        }

        bufferHandle = liftBuffer();
        var status = new WaitableStatus(VTableRead(bufferHandle == null ? IntPtr.Zero : bufferHandle.Value.AddrOfPinnedObject(), length));
        if (status.IsBlocked)
        {
            var task = new ComponentTask<int>(new CancelableRead(cancelableRead, Handle));
            ContextTask* contextTaskPtr = AsyncSupport.ContextGet();
            if(contextTaskPtr == null)
            {
                contextTaskPtr = AsyncSupport.AllocateAndSetNewContext();
            }

            AsyncSupport.Join(Handle, contextTaskPtr->WaitableSetHandle, new WaitableInfoState(task, this));
            return task;
        }
        if (status.IsCompleted)
        {
            return ComponentTask<int>.FromResult((int)status.Count);
        }

        throw new NotImplementedException(status.State.ToString());
    }

    void IFutureStream.FreeBuffer()
    {
        bufferHandle?.Free();
    }

    void IFutureStream.OtherSideDropped()
    {
        writerDropped = true;
    }

    internal abstract void VTableDrop();

    void Dispose(bool _disposing)
    {
        // Free unmanaged resources if any.
        if (Handle != 0)
        {
            VTableDrop();
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~ReaderBase()
    {
        Dispose(false);
    }
}

public class FutureReader : ReaderBase
{
    internal FutureReader(int handle, FutureVTable vTable) : base(handle)
    {
        VTable = vTable;
    }

    internal FutureVTable VTable { get; private set; }

    public ComponentTask Read()
    {
        return ReadInternal(() => null, 0, VTable);
    }

    internal override uint VTableRead(IntPtr ptr, int length)
    {
        return VTable.Read(Handle, ptr);
    }

    internal override void VTableDrop()
    {
        VTable.DropReader(Handle);
    }
}

public class FutureReader<T>(int handle, FutureVTable vTable) : ReaderBase(handle)
{
    public FutureVTable VTable { get; private set; } = vTable;

    public ComponentTask<T> Read()
    {
        T[] buf = new T[1];
        ComponentTask<int> internalTask = ReadInternal(() => LiftBuffer(buf), 1, VTable);

        // Wrap the task so we can return a T and not the number of Ts read
        ComponentTask<T> readTask = new(new DelegatingCancelable(internalTask));

        internalTask.ContinueWith(it =>
        {
            if (it.IsCompletedSuccessfully)
            {
                readTask.SetResult(buf[0]);
            }
            else if (!it.IsCanceled)
            {
                //TODO
                throw new NotImplementedException("faulted future read not implemented");
            }
        });
        return readTask;
    }

    class DelegatingCancelable : ICancelable
    {
        private ComponentTask innerTask;

        internal DelegatingCancelable(ComponentTask innerTask)
        {
            this.innerTask = innerTask;
        }

        uint ICancelable.Cancel()
        {
            var cancelVal = innerTask.Cancel();
            return (uint)cancelVal;
        }
    }

    internal override uint VTableRead(IntPtr ptr, int length)
    {
        return VTable.Read(Handle, ptr);
    }

    internal override void VTableDrop()
    {
        VTable.DropReader(Handle);
    }
}

public class StreamReader : ReaderBase
{
    public StreamReader(int handle, StreamVTable vTable) : base(handle)
    {
        VTable = vTable;
    }

    public StreamVTable VTable { get; private set; }

    public ComponentTask Read(int length)
    {
        return ReadInternal(() => null, length, VTable);
    }

    internal override uint VTableRead(IntPtr ptr, int length)
    {
        return VTable.Read(Handle, ptr, (uint)length);
    }

    internal override void VTableDrop()
    {
        VTable.DropReader(Handle);
    }
}

public class StreamReader<T>(int handle, StreamVTable vTable) :  ReaderBase(handle)
{
    public StreamVTable VTable { get; private set; } = vTable;

    public ComponentTask<int> Read(T[] buffer)
    {
        return ReadInternal(() => LiftBuffer(buffer), buffer.Length, VTable);
    }

    internal override uint VTableRead(IntPtr ptr, int length)
    {
        return VTable.Read(Handle, ptr, (uint)length);
    }

    internal override void VTableDrop()
    {
        VTable.DropReader(Handle);
    }
}

public abstract class WriterBase : IFutureStream
{
    private GCHandle? bufferHandle;
    private bool readerDropped;
    private bool canDrop;

    internal WriterBase(int handle)
    {
        Handle = handle;
    }

    internal int Handle { get; private set; }

    internal int TakeHandle()
    {
        if (Handle == 0)
        {
            throw new InvalidOperationException("Handle already taken");
        }
        var handle = Handle;
        Handle = 0;
        return handle;
    }

    internal abstract uint VTableWrite(IntPtr bufferPtr, int length);

    // unsafe as we are working with pointers.
    internal unsafe ComponentTask<int> WriteInternal(Func<GCHandle?> lowerPayload, int length, ICancelableWrite cancelable)
    {
        if (Handle == 0)
        {
            throw new InvalidOperationException("Handle already taken");
        }

        if (readerDropped)
        {
            throw new StreamDroppedException();    
        }
        bufferHandle = lowerPayload();

        var status = new WaitableStatus(VTableWrite(bufferHandle == null ? IntPtr.Zero : bufferHandle.Value.AddrOfPinnedObject(), length));
        canDrop = true;  // We can only call drop once something has been written.
        if (status.IsBlocked)
        {
            var tcs = new ComponentTask<int>(new CancelableWrite(cancelable, Handle));
            tcs.ContinueWith(t =>
            {
                if (t.IsCanceled)
                {
                    canDrop = false;
                }
            });

            ContextTask* contextTaskPtr = AsyncSupport.ContextGet();
            if(contextTaskPtr == null)
            {
                contextTaskPtr = AsyncSupport.AllocateAndSetNewContext();
            }
            AsyncSupport.Join(Handle, contextTaskPtr->WaitableSetHandle, new WaitableInfoState(tcs, this));
            return tcs;
        }

        if (status.IsCompleted)
        {
            bufferHandle?.Free();
            return ComponentTask<int>.FromResult((int)status.Count);
        }

        throw new NotImplementedException($"Unsupported write status {status.State}");
    }

    void IFutureStream.FreeBuffer()
    {
        bufferHandle?.Free();
    }

    void IFutureStream.OtherSideDropped()
    {
        readerDropped = true;
    }

    internal abstract void VTableDrop();

    void Dispose(bool _disposing)
    {
        // Free unmanaged resources if any.
        if (Handle != 0 && canDrop)
        {
            VTableDrop();
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~WriterBase()
    {
        Dispose(false);
    }
}

public class FutureWriter(int handle, FutureVTable vTable) : WriterBase(handle)
{
    public FutureVTable VTable { get; private set; } = vTable;

    public ComponentTask<int> Write()
    {
        return WriteInternal(() => null, 0, VTable);
    }

    internal override uint VTableWrite(IntPtr bufferPtr, int length)
    {
        return VTable.Write(Handle, bufferPtr);
    }

    internal override void VTableDrop()
    {
        VTable.DropWriter(Handle);
    }
}

public class FutureWriter<T>(int handle, FutureVTable vTable) : WriterBase(handle)
{
    public FutureVTable VTable { get; private set; } = vTable;

    private GCHandle LowerPayload(T[] payload)
    {
        if (VTable.Lower == null)
        {
            return GCHandle.Alloc(payload, GCHandleType.Pinned);
        }
        else
        {
            // Lower the payload
            throw new NotSupportedException("StreamWriter Write where the payload must be lowered.");
            // var loweredPayload = VTable.Lower(payload);
        }
    }

    public ComponentTask<int> Write(T payload)
    {
        return WriteInternal(() => LowerPayload([payload]), 1, VTable);
    }

    internal override uint VTableWrite(IntPtr bufferPtr, int length)
    {
        return VTable.Write(Handle, bufferPtr);
    }

    internal override void VTableDrop()
    {
        VTable.DropWriter(Handle);
    }
}

public class StreamWriter(int handle, StreamVTable vTable) : WriterBase(handle)
{
    public StreamVTable VTable { get; private set; } = vTable;

    public ComponentTask<int> Write()
    {
        return WriteInternal(() => null, 0, VTable);
    }

    internal override uint VTableWrite(IntPtr bufferPtr, int length)
    {
        return VTable.Write(Handle, bufferPtr, (uint)length);
    }

    internal override void VTableDrop()
    {
        VTable.DropWriter(Handle);
    }
}

public class StreamWriter<T>(int handle, StreamVTable vTable) : WriterBase(handle)
{
    private GCHandle bufferHandle;
    public StreamVTable VTable { get; private set; } = vTable;

    private GCHandle LowerPayload(T[] payload)
    {
        if (VTable.Lower == null)
        {
            return GCHandle.Alloc(payload, GCHandleType.Pinned);
        }
        else
        {
            // Lower the payload
            throw new NotSupportedException("StreamWriter Write where the payload must be lowered.");
            // var loweredPayload = VTable.Lower(payload);
        }
    }

    public ComponentTask<int> Write(T[] payload)
    {
        return WriteInternal(() => LowerPayload(payload), payload.Length, VTable);
    }

    internal override uint VTableWrite(IntPtr bufferPtr, int length)
    {
        return VTable.Write(Handle, bufferPtr, (uint)length);
    }

    internal override void VTableDrop()
    {
        VTable.DropWriter(Handle);
    }
}

internal struct WaitableInfoState
{
    internal WaitableInfoState(ComponentTask<int> componentTaskInt, IFutureStream futureStream)
    {
        this.componentTaskInt = componentTaskInt;
        FutureStream = futureStream;        
    }

    internal WaitableInfoState(TaskCompletionSource<int> taskCompletionSource)
    {
        this.taskCompletionSource = taskCompletionSource;
    }

    internal void SetResult(int count)
    {
        if (taskCompletionSource != null)
        {
            taskCompletionSource.SetResult(count);
        }
        else if (componentTask != null)
        {
            componentTask.SetResult();
        }
        else if (componentTaskInt != null)
        {
            componentTaskInt.SetResult(count);
        }
        else
        {
            throw new InvalidOperationException("No component task associated with this WaitableInfoState.");
        }
    }

    internal void SetException(Exception e)
    {
        if (componentTask != null)
        {
            componentTask.SetException(e);
        }
        else
        {
            componentTaskInt.SetException(e);
        }
    }

    // We have a taskCompletionSource for an async function, a ComponentTask for a future or stream.
    private TaskCompletionSource<int>? taskCompletionSource;
    private ComponentTask? componentTask;
    private ComponentTask<int>? componentTaskInt;
    internal IFutureStream? FutureStream;
}

public class StreamDroppedException : Exception
{
    public StreamDroppedException() : base()
    {
    }

    public StreamDroppedException(string message) : base(message)
    {
    }
}

public abstract class ComponentTask
{
    protected readonly ICancelable cancelableVTable;
    private bool canCancel = true;

    internal ComponentTask(ICancelable? cancelableVTable = null)
    {
        this.cancelableVTable = cancelableVTable;
    }

    public abstract Task Task { get; }

    public abstract bool IsCompleted { get; }

    public CancelCode Cancel()
    {
        if(!canCancel)
        {
            return CancelCode.Completed;
        }

        if(cancelableVTable == null)
        {
            throw new InvalidOperationException("Cannot cancel a task that was created as completed with a result.");
        }

        uint cancelReturn = cancelableVTable.Cancel();
        SetCanceled();
        return (CancelCode)cancelReturn;
    }

    public abstract void SetCanceled();

    public virtual void SetResult()
    {
        canCancel = false;
    }

    public abstract void SetException(Exception e);

    public static ComponentTask FromResult()
    {
        var task = new ComponentTask<int>();
        task.SetResult(0);
        return task;
    }

    /// <summary>
    /// Makes the class directly awaitable.
    /// </summary>
    public TaskAwaiter GetAwaiter()
    {
        return Task.GetAwaiter();
    }
}

public class ComponentTask<T> : ComponentTask
{
    private readonly TaskCompletionSource<T> tcs;

    internal ComponentTask(ICancelable? cancelableVTable = null) : base(cancelableVTable)
    {
        tcs = new TaskCompletionSource<T>();
    }

    public override Task Task => tcs.Task;

    public override bool IsCompleted => tcs.Task.IsCompleted;

    public Task ContinueWith(Action<Task<T>> continuationAction)
    {
        return tcs.Task.ContinueWith(continuationAction, TaskContinuationOptions.ExecuteSynchronously);
    }

    public void SetResult(T result) 
    {
        SetResult();
        tcs.SetResult(result);
    }

    public static ComponentTask<T> FromResult<T>(T result)
    {
        var task = new ComponentTask<T>();
        task.tcs.SetResult(result);
        return task;
    }

    public override void SetCanceled()
    {
        tcs.SetCanceled();
    }

    public override void SetException(Exception e)
    {
        tcs.SetException(e);
    }

    /// <summary>
    /// Makes the class directly awaitable.
    /// </summary>
    public new TaskAwaiter<T> GetAwaiter()
    {
        return tcs.Task.GetAwaiter();
    }
            
    public T Result => tcs.Task.Result;
}