/src/opendnp3/cpp/lib/src/link/ShiftableBuffer.cpp
Line | Count | Source |
1 | | /* |
2 | | * Copyright 2013-2022 Step Function I/O, LLC |
3 | | * |
4 | | * Licensed to Green Energy Corp (www.greenenergycorp.com) and Step Function I/O |
5 | | * LLC (https://stepfunc.io) under one or more contributor license agreements. |
6 | | * See the NOTICE file distributed with this work for additional information |
7 | | * regarding copyright ownership. Green Energy Corp and Step Function I/O LLC license |
8 | | * this file to you under the Apache License, Version 2.0 (the "License"); you |
9 | | * may not use this file except in compliance with the License. You may obtain |
10 | | * a copy of the License at: |
11 | | * |
12 | | * http://www.apache.org/licenses/LICENSE-2.0 |
13 | | * |
14 | | * Unless required by applicable law or agreed to in writing, software |
15 | | * distributed under the License is distributed on an "AS IS" BASIS, |
16 | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
17 | | * See the License for the specific language governing permissions and |
18 | | * limitations under the License. |
19 | | */ |
20 | | #include "ShiftableBuffer.h" |
21 | | |
22 | | #include <cassert> |
23 | | #include <cstring> |
24 | | #include <iostream> |
25 | | |
26 | | namespace opendnp3 |
27 | | { |
28 | | |
29 | | ShiftableBuffer::ShiftableBuffer(uint8_t* pBuffer_, size_t size) |
30 | 7.49k | : pBuffer(pBuffer_), M_SIZE(size), writePos(0), readPos(0) |
31 | 7.49k | { |
32 | 7.49k | } |
33 | | |
34 | | void ShiftableBuffer::Shift() |
35 | 12.0k | { |
36 | 12.0k | auto numRead = this->NumBytesRead(); |
37 | | |
38 | | // copy all unread data to the front of the buffer |
39 | 12.0k | memmove(pBuffer, pBuffer + readPos, numRead); |
40 | | |
41 | 12.0k | readPos = 0; |
42 | 12.0k | writePos = numRead; |
43 | 12.0k | } |
44 | | |
45 | | void ShiftableBuffer::Reset() |
46 | 0 | { |
47 | 0 | writePos = 0; |
48 | 0 | readPos = 0; |
49 | 0 | } |
50 | | |
51 | | void ShiftableBuffer::AdvanceRead(size_t numBytes) |
52 | 72.5k | { |
53 | 72.5k | assert(numBytes <= this->NumBytesRead()); |
54 | 72.5k | readPos += numBytes; |
55 | 72.5k | } |
56 | | |
57 | | void ShiftableBuffer::AdvanceWrite(size_t aNumBytes) |
58 | 12.0k | { |
59 | 12.0k | assert(aNumBytes <= this->NumWriteBytes()); |
60 | 12.0k | writePos += aNumBytes; |
61 | 12.0k | } |
62 | | |
63 | | bool ShiftableBuffer::Sync(size_t& skipCount) |
64 | 44.5k | { |
65 | 72.6k | while (this->NumBytesRead() > 1) // at least 2 bytes |
66 | 72.5k | { |
67 | 72.5k | if (this->ReadBuffer()[0] == 0x05 && this->ReadBuffer()[1] == 0x64) |
68 | 44.4k | { |
69 | 44.4k | return true; |
70 | 44.4k | } |
71 | | |
72 | 28.0k | this->AdvanceRead(1); // skip the first byte |
73 | 28.0k | ++skipCount; |
74 | 28.0k | } |
75 | | |
76 | 66 | return false; |
77 | 44.5k | } |
78 | | |
79 | | } // namespace opendnp3 |