97e2d472ad6d0a6792f32b844b85583af198a623
[platform/core/security/key-manager.git] / src / manager / common / message-buffer.cpp
1 /*
2  *  Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *  Contact: Bumjin Im <bj.im@samsung.com>
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License
17  */
18 /*
19  * @file        message-buffer.cpp
20  * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
21  * @author      Zofia Abramowska (z.abramowska@samsung.com)
22  * @version     1.0
23  * @brief       Implementation of MessageBuffer.
24  */
25
26 #include <message-buffer.h>
27
28 #include <dpl/log/log.h>
29
30 namespace CKM {
31
32 void MessageBuffer::Push(const RawBuffer &data)
33 {
34         m_buffer.AppendCopy(&data[0], data.size());
35 }
36
37 RawBuffer MessageBuffer::Pop()
38 {
39         size_t size = m_buffer.Size();
40         RawBuffer buffer;
41         buffer.resize(size + sizeof(size_t));
42         memcpy(&buffer[0], &size, sizeof(size_t));
43         m_buffer.FlattenConsume(&buffer[sizeof(size_t)], size);
44         return buffer;
45 }
46
47 bool MessageBuffer::Ready()
48 {
49         CountBytesLeft();
50
51         if (m_bytesLeft == 0)
52                 return false;
53
54         if (m_bytesLeft > m_buffer.Size())
55                 return false;
56
57         return true;
58 }
59
60 void MessageBuffer::Read(size_t num, void *bytes)
61 {
62         CountBytesLeft();
63
64         if (num > m_bytesLeft) {
65                 LogDebug("Protocol broken. OutOfData. Asked for: " << num << " Ready: " <<
66                                  m_bytesLeft << " Buffer.size(): " << m_buffer.Size());
67                 Throw(Exception::OutOfData);
68         }
69
70         m_buffer.FlattenConsume(bytes, num);
71         m_bytesLeft -= num;
72 }
73
74 void MessageBuffer::Write(size_t num, const void *bytes)
75 {
76         m_buffer.AppendCopy(bytes, num);
77 }
78
79 } // namespace CKM
80