33
44ProtocolBuffer::ProtocolBuffer (std::size_t capacity)
55 : _writeIndex(0 ),
6- _readBuffer(capacity, 0 ),
6+ // _readBuffer(capacity, 0),
7+ _textProtocol(capacity, 0 ),
78 _contentLength(0 ),
8- _bodyStartIndex(0 )
9+ _bodyStartIndex(0 ),
10+ _normalCapacity(capacity)
911{
1012}
1113
1214char * ProtocolBuffer::GetWritableCursor ()
1315{
14- return _readBuffer .data ();
16+ return _textProtocol .data () + _writeIndex ;
1517}
1618
1719
1820std::size_t ProtocolBuffer::GetRestCapacity ()
1921{
20- return _readBuffer .size ();
22+ return _textProtocol .size () - _writeIndex ;
2123}
2224
23- void ProtocolBuffer::WriteBuff (std::size_t size)
25+ void ProtocolBuffer::SetWriteSize (std::size_t size)
2426{
25- if (_textProtocol.size () < _writeIndex + size)
26- {
27- if (_bodyStartIndex != 0 && _contentLength != 0 && _writeIndex < (_bodyStartIndex + _contentLength))
28- {
29- _textProtocol.resize (std::max (_writeIndex + size, _bodyStartIndex + _contentLength));
30- }
31- else
32- {
33- _textProtocol.resize (_writeIndex + size);
34- }
35- }
36-
37- std::copy_n (_readBuffer.begin (), size, _textProtocol.begin () + _writeIndex);
3827 _writeIndex += size;
3928}
4029
@@ -62,6 +51,15 @@ std::string_view ProtocolBuffer::ReadOneProtocol()
6251 return " " ;
6352}
6453
54+ void ProtocolBuffer::FitCapacity ()
55+ {
56+ auto oneProtocolCapacity = _contentLength + _bodyStartIndex;
57+ if (oneProtocolCapacity > _normalCapacity && oneProtocolCapacity > _textProtocol.size ())
58+ {
59+ _textProtocol.resize (oneProtocolCapacity);
60+ }
61+ }
62+
6563void ProtocolBuffer::Reset ()
6664{
6765 if (_writeIndex > _contentLength + _bodyStartIndex)
@@ -70,15 +68,25 @@ void ProtocolBuffer::Reset()
7068 std::copy_n (_textProtocol.data () + doneIndex, _writeIndex - doneIndex, _textProtocol.data ());
7169
7270 _writeIndex -= doneIndex;
73- _textProtocol.resize (std::max (_writeIndex, _readBuffer.size ()));
74- _textProtocol.shrink_to_fit ();
71+ if (_writeIndex > _normalCapacity)
72+ {
73+ _textProtocol.resize (_writeIndex);
74+ _textProtocol.shrink_to_fit ();
75+ }
76+ else
77+ {
78+ _textProtocol.resize (_normalCapacity);
79+ _textProtocol.shrink_to_fit ();
80+ }
7581 }
7682 else
7783 {
7884 _writeIndex = 0 ;
79- _textProtocol.clear ();
80- _textProtocol.resize (_readBuffer.size ());
81- _textProtocol.shrink_to_fit ();
85+ if (_textProtocol.size () > _normalCapacity)
86+ {
87+ _textProtocol.resize (_normalCapacity);
88+ _textProtocol.shrink_to_fit ();
89+ }
8290 }
8391
8492 _contentLength = 0 ;
@@ -121,8 +129,10 @@ bool ProtocolBuffer::TryParseHead()
121129 }
122130 auto lengthStr = text.substr (colonPosition + 1 , lineEndPosition - colonPosition - 1 );
123131 _contentLength = std::stoi (std::string (lengthStr));
132+
124133 }
125134 index = lineEndPosition + 2 ;
135+ _bodyStartIndex = index + 2 ;
126136 state = ParseState::CRLF;
127137 break ;
128138 }
0 commit comments