调整缓冲区中的区域大小 [英] Resize an area in a buffer

查看:249
本文介绍了调整缓冲区中的区域大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我正在寻找一种有效的方法来调整缓冲区两侧的区域大​​小.基本缓冲区仅在必要时才可以重新分配.请看下面的示例源代码,让我知道您的解决方案.谢谢!

Hello all,
I looking for an efficent method to resize an area in a buffer at both sides. The base buffer should only reallocated if neseccary. Please take a look at the following sample source code and let me know your solutions. Thanks!

class BufferSampleClass
{
   // base buffer
   private Byte[] buffer = { 0, 0, 0, 0, 0, 8, 8, 1, 8, 8, 0, 0, 0, 0, 0 };

   // first valid index of the public accessible buffer area
   private Int32 firstIndex = 5;

   // current index in the public accessible buffer area
   private Int32 index = 7;

   // last valid index of the public accessible buffer area
   private Int32 lastIndex = 9;

   // length of the public accessible buffer area
   private Int32 length = 5;

   // resize the public accessible buffer at both sides
   public void Resize(Int32 frontSide, Int32 backSide)
   {
      Int32 newLength = frontSide + length + backSide;
      if (newLength < 0)
      {
         throw new ArgumentException();
      }
      Int32 newFirstIndex = firstIndex - frontSide;
      Int32 newLastIndex = lastIndex + backSide;

      // if newFirstIndex is lower than 0, move the current content
      // if newLastIndex is greater than buffer.Length, create a new buffer and copy the current content
      // combine both cases

      // update firstIndex and lastIndex
      throw new NotImplementedException();
   }

   // Read, Write, Seek, ... members to manipulate the content
}

推荐答案

我猜您正在尝试创建某种可调整大小的内存流,因为最后一行显示为:
I guess you are attempting to create some sort of resizable memory stream since your last line reads:
Read, Write, Seek, ... members to manipulate the content


尝试使用现有的 MemoryStream [


Try using the existing MemoryStream[^]. If that''s not good enough - try reimplementing the MemoryStream using a list of buffers. Depending on what you are doing this can be quite efficient since you will avoid copying and reallocation.

Regards
Espen Harlinn


我会说,

I would say,

byte[] newbuffer = new byte[newLength];
Array.Copy(buffer, newFirstIndex, newbuffer, 0, newLength);
buffer = newbuffer;



我认为这就是您所能做的;即使使用不安全的方法,也不能随意分配"尾部和前导部分.

—SA



I think that''s all you can do; you can''t arbitrarily "deallocate" trailing and leading parts, even using unsafe methods.

—SA


这篇关于调整缓冲区中的区域大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆