From ba7937390841c1e4859eec8c70d00b6e302fa955 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=9B=BD=E4=BC=9F?= <366193849@qq.com> Date: Fri, 14 Oct 2022 11:44:11 +0800 Subject: [PATCH] =?UTF-8?q?=E5=85=AC=E5=BC=80GetSpan=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- WindivertDotnet/WinDivertPacket.cs | 80 ++++++------------------------ 1 file changed, 15 insertions(+), 65 deletions(-) diff --git a/WindivertDotnet/WinDivertPacket.cs b/WindivertDotnet/WinDivertPacket.cs index cd9eee9..cf9d85c 100644 --- a/WindivertDotnet/WinDivertPacket.cs +++ b/WindivertDotnet/WinDivertPacket.cs @@ -1,6 +1,5 @@ using Microsoft.Win32.SafeHandles; using System; -using System.Buffers; using System.ComponentModel; using System.Diagnostics; using System.Net.Sockets; @@ -56,58 +55,47 @@ public WinDivertPacket(int capacity = 0xFFFF + 40) { this.Capacity = capacity; this.handle = Marshal.AllocHGlobal(capacity); - this.Clear(); - } - - /// - /// 清除数据 - /// - public void Clear() - { this.GetSpan(0, this.Capacity).Clear(); } /// - /// 创建缓冲区写入对象 + /// 释放本机句柄 /// - /// 缓冲区偏移量 - /// /// - public IBufferWriter CreateBufferWriter(int offset = 0) + protected override bool ReleaseHandle() { - return new BufferWriter(this, offset); + Marshal.FreeHGlobal(this.handle); + return true; } /// - /// 释放本机句柄 + /// 将有效数据清0 /// - /// - protected override bool ReleaseHandle() + public void Clear() { - Marshal.FreeHGlobal(this.handle); - return true; + this.Span.Clear(); } /// - /// 获取span + /// 获取缓冲区的Span /// - /// - /// + /// 偏移量 + /// 字节数 /// - private unsafe Span GetSpan(int offset, int sizeHint) + public unsafe Span GetSpan(int offset, int count) { - if (offset > this.Capacity) + if (offset < 0 || offset > this.Capacity) { throw new ArgumentOutOfRangeException(nameof(offset)); } - if (this.Capacity - offset < sizeHint) + if (count < 0 || this.Capacity - offset < count) { - throw new ArgumentOutOfRangeException(nameof(sizeHint)); + throw new ArgumentOutOfRangeException(nameof(count)); } var pointer = (byte*)this.handle.ToPointer() + offset; - return new Span(pointer, sizeHint); + return new Span(pointer, count); } /// @@ -203,43 +191,5 @@ public unsafe WinDivertParseResult GetParseResult() NextLength = nextLength }; } - - - private class BufferWriter : IBufferWriter - { - private int index; - private readonly WinDivertPacket packet; - - public BufferWriter(WinDivertPacket packet, int offset) - { - if (offset >= packet.Capacity) - { - throw new ArgumentOutOfRangeException(nameof(offset)); - } - - this.index = offset; - this.packet = packet; - } - - public void Advance(int count) - { - this.index += count; - this.packet.Length = this.index; - } - - public Span GetSpan(int sizeHint = 0) - { - if (sizeHint == 0) - { - sizeHint = this.packet.Capacity - this.index; - } - return this.packet.GetSpan(this.index, sizeHint); - } - - public Memory GetMemory(int sizeHint = 0) - { - throw new NotSupportedException(); - } - } } }