Refactor BinaryQueue and tests
[platform/core/security/key-manager.git] / src / manager / dpl / core / src / binary_queue.cpp
1 /*
2  * Copyright (c) 2011-2020 Samsung Electronics Co., Ltd. All rights reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16 /*
17  * @file        binary_queue.cpp
18  * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
19  * @version     1.0
20  * @brief       This file is the implementation file of binary queue
21  */
22 #include <dpl/binary_queue.h>
23 #include <cassert>
24 #include <algorithm>
25 #include <cstring>
26
27 namespace CKM {
28 BinaryQueue::BinaryQueue() :
29         m_size(0)
30 {}
31
32 void BinaryQueue::AppendCopy(const void *buffer, size_t bufferSize)
33 {
34         if (bufferSize == 0)
35                 return;
36
37         assert(buffer != NULL);
38
39         m_buckets.emplace_back(bufferSize);
40         memcpy(m_buckets.back().data(), buffer, bufferSize);
41         m_size += bufferSize;
42 }
43
44 size_t BinaryQueue::Size() const
45 {
46         return m_size;
47 }
48
49 void BinaryQueue::FlattenConsume(void *buffer, size_t bufferSize)
50 {
51         // Check parameters
52         if (bufferSize == 0)
53                 return;
54
55         assert(buffer != NULL);
56
57         if (bufferSize > m_size)
58                 Throw(Exception::OutOfData);
59
60         size_t bytesLeft = bufferSize;
61         void *ptr = buffer;
62         assert(!m_buckets.empty());
63
64         // Flatten data
65         do {
66                 auto& bucket = m_buckets.front();
67
68                 // Get consume size
69                 size_t bucketSize = bucket.size();
70                 size_t count = std::min(bytesLeft, bucketSize);
71
72                 // Copy data to user pointer
73                 memcpy(ptr, bucket.data(), count);
74
75                 // consume
76                 if (count == bucketSize) {
77                         m_buckets.pop_front();
78                 } else {
79                         bucket.erase(bucket.begin(), bucket.begin() + count);
80                         assert(count == bytesLeft);
81                         break;
82                 }
83
84                 bytesLeft -= count;
85                 ptr = static_cast<char *>(ptr) + count;
86         } while (bytesLeft);
87         m_size -= bufferSize;
88 }
89
90 } // namespace CKM