1
2/*
3* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4*
5* Licensed under the Apache License, Version 2.0 (the "License").
6* You may not use this file except in compliance with the License.
7* A copy of the License is located at
8*
9* http://aws.amazon.com/apache2.0
10*
11* or in the "license" file accompanying this file. This file is distributed
12* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
13* express or implied. See the License for the specific language governing
14* permissions and limitations under the License.
15*/
16
17#include <aws/core/utils/stream/PreallocatedStreamBuf.h>
18#include <cassert>
19
20namespace Aws
21{
22 namespace Utils
23 {
24 namespace Stream
25 {
26 PreallocatedStreamBuf::PreallocatedStreamBuf(unsigned char* buffer, std::size_t lengthToRead) :
27 m_underlyingBuffer(buffer), m_lengthToRead(lengthToRead)
28 {
29 char* end = reinterpret_cast<char*>(m_underlyingBuffer + m_lengthToRead);
30 char* begin = reinterpret_cast<char*>(m_underlyingBuffer);
31 setp(begin, end);
32 setg(begin, begin, end);
33 }
34
35 PreallocatedStreamBuf::pos_type PreallocatedStreamBuf::seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which)
36 {
37 if (dir == std::ios_base::beg)
38 {
39 return seekpos(off, which);
40 }
41 else if (dir == std::ios_base::end)
42 {
43 return seekpos(m_lengthToRead - off, which);
44 }
45 else if (dir == std::ios_base::cur)
46 {
47 if(which == std::ios_base::in)
48 {
49 return seekpos((gptr() - reinterpret_cast<char*>(m_underlyingBuffer)) + off, which);
50 }
51 else
52 {
53 return seekpos((pptr() - reinterpret_cast<char*>(m_underlyingBuffer)) + off, which);
54 }
55 }
56
57 return off_type(-1);
58 }
59
60 PreallocatedStreamBuf::pos_type PreallocatedStreamBuf::seekpos(pos_type pos, std::ios_base::openmode which)
61 {
62 assert(static_cast<size_t>(pos) <= m_lengthToRead);
63 if (static_cast<size_t>(pos) > m_lengthToRead)
64 {
65 return pos_type(off_type(-1));
66 }
67
68 char* end = reinterpret_cast<char*>(m_underlyingBuffer + m_lengthToRead);
69 char* begin = reinterpret_cast<char*>(m_underlyingBuffer);
70
71 if (which == std::ios_base::in)
72 {
73 setg(begin, begin + static_cast<size_t>(pos), end);
74 }
75
76 if (which == std::ios_base::out)
77 {
78 setp(begin + static_cast<size_t>(pos), end);
79 }
80
81 return pos;
82 }
83 }
84 }
85}
86