@@ -845,16 +845,21 @@ LUA_FUNCTION_STATIC(bf_write_WriteString)
845845}
846846
847847static constexpr int MAX_BUFFER_SIZE = 1 << 18 ;
848+ static constexpr int MIN_BUFFER_SIZE = 4 ;
849+ #define CLAMP_BF (val ) MAX(MIN(val + 1 , MAX_BUFFER_SIZE), MIN_BUFFER_SIZE)
850+
848851LUA_FUNCTION_STATIC (bitbuf_CopyReadBuffer)
849852{
850853 bf_read* pBf = Get_bf_read (1 , true );
851854
852855 int iSize = pBf->GetNumBytesRead () + pBf->GetNumBytesLeft ();
853- unsigned char * pData = new unsigned char [MIN (iSize + 1 , MAX_BUFFER_SIZE)];
856+ int iNewSize = CLAMP_BF (iSize);
857+
858+ unsigned char * pData = new unsigned char [iNewSize];
854859 memcpy (pData, pBf->GetBasePointer (), iSize);
855860
856861 bf_read* pNewBf = new bf_read;
857- pNewBf->StartReading (pData, iSize );
862+ pNewBf->StartReading (pData, iNewSize );
858863
859864 Push_bf_read (pNewBf);
860865
@@ -865,12 +870,13 @@ LUA_FUNCTION_STATIC(bitbuf_CreateReadBuffer)
865870{
866871 const char * pData = LUA->CheckString (1 );
867872 int iLength = LUA->ObjLen (1 );
873+ int iNewLength = CLAMP_BF (iLength);
868874
869- unsigned char * cData = new unsigned char [MIN (iLength + 1 , MAX_BUFFER_SIZE) ];
875+ unsigned char * cData = new unsigned char [iNewLength ];
870876 memcpy (cData, pData, iLength);
871877
872878 bf_read* pNewBf = new bf_read;
873- pNewBf->StartReading (cData, iLength );
879+ pNewBf->StartReading (cData, iNewLength );
874880
875881 Push_bf_read (pNewBf);
876882
@@ -881,8 +887,8 @@ LUA_FUNCTION_STATIC(bitbuf_CreateWriteBuffer)
881887{
882888 if (LUA->IsType (1 , GarrysMod::Lua::Type::Number))
883889 {
884- int iSize = ( int )LUA->CheckNumber (1 );
885- unsigned char * cData = new unsigned char [MIN ( iSize + 1 , MAX_BUFFER_SIZE) ];
890+ int iSize = CLAMP_BF (( int )LUA->CheckNumber (1 ) );
891+ unsigned char * cData = new unsigned char [iSize];
886892
887893 bf_write* pNewBf = new bf_write;
888894 pNewBf->StartWriting (cData, iSize);
@@ -891,12 +897,13 @@ LUA_FUNCTION_STATIC(bitbuf_CreateWriteBuffer)
891897 } else {
892898 const char * pData = LUA->CheckString (1 );
893899 int iLength = LUA->ObjLen (1 );
900+ int iNewLength = CLAMP_BF (iLength);
894901
895- unsigned char * cData = new unsigned char [MIN (iLength + 1 , MAX_BUFFER_SIZE) ];
902+ unsigned char * cData = new unsigned char [iNewLength ];
896903 memcpy (cData, pData, iLength);
897904
898905 bf_write* pNewBf = new bf_write;
899- pNewBf->StartWriting (cData, iLength );
906+ pNewBf->StartWriting (cData, iNewLength );
900907
901908 Push_bf_write (pNewBf);
902909 }
0 commit comments