Esempio n. 1
0
 public int TryWrite(LibuvFunctions.uv_buf_t buf)
 {
     return(_uv.try_write(this, new[] { buf }, 1));
 }
Esempio n. 2
0
        private unsafe void Write(
            UvStreamHandle handle,
            ReadOnlySequence <byte> buffer,
            Action <UvWriteReq, int, UvException, object> callback,
            object state)
        {
            try
            {
                var nBuffers = 0;
                if (buffer.IsSingleSegment)
                {
                    nBuffers = 1;
                }
                else
                {
                    foreach (var _ in buffer)
                    {
                        nBuffers++;
                    }
                }

                var pBuffers = (LibuvFunctions.uv_buf_t *)_bufs;
                if (nBuffers > BUFFER_COUNT)
                {
                    // create and pin buffer array when it's larger than the pre-allocated one
                    var bufArray = new LibuvFunctions.uv_buf_t[nBuffers];
                    var gcHandle = GCHandle.Alloc(bufArray, GCHandleType.Pinned);
                    _pins.Add(gcHandle);
                    pBuffers = (LibuvFunctions.uv_buf_t *)gcHandle.AddrOfPinnedObject();
                }

                if (nBuffers == 1)
                {
                    var memory       = buffer.First;
                    var memoryHandle = memory.Pin();
                    _handles.Add(memoryHandle);

                    // Fast path for single buffer
                    pBuffers[0] = Libuv.buf_init(
                        (IntPtr)memoryHandle.Pointer,
                        memory.Length);
                }
                else
                {
                    var index = 0;
                    foreach (var memory in buffer)
                    {
                        // This won't actually pin the buffer since we're already using pinned memory
                        var memoryHandle = memory.Pin();
                        _handles.Add(memoryHandle);

                        // create and pin each segment being written
                        pBuffers[index] = Libuv.buf_init(
                            (IntPtr)memoryHandle.Pointer,
                            memory.Length);
                        index++;
                    }
                }

                _callback = callback;
                _state    = state;
                _uv.write(this, handle, pBuffers, nBuffers, _uv_write_cb);
            }
            catch
            {
                _callback = null;
                _state    = null;
                UnpinGcHandles();
                throw;
            }
        }