1 | /******************************************************************** |
2 | * Copyright (c) 2013 - 2014, Pivotal Inc. |
3 | * All rights reserved. |
4 | * |
5 | * Author: Zhanwei Wang |
6 | ********************************************************************/ |
7 | /******************************************************************** |
8 | * 2014 - |
9 | * open source under Apache License Version 2.0 |
10 | ********************************************************************/ |
11 | /** |
12 | * Licensed to the Apache Software Foundation (ASF) under one |
13 | * or more contributor license agreements. See the NOTICE file |
14 | * distributed with this work for additional information |
15 | * regarding copyright ownership. The ASF licenses this file |
16 | * to you under the Apache License, Version 2.0 (the |
17 | * "License"); you may not use this file except in compliance |
18 | * with the License. You may obtain a copy of the License at |
19 | * |
20 | * http://www.apache.org/licenses/LICENSE-2.0 |
21 | * |
22 | * Unless required by applicable law or agreed to in writing, software |
23 | * distributed under the License is distributed on an "AS IS" BASIS, |
24 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
25 | * See the License for the specific language governing permissions and |
26 | * limitations under the License. |
27 | */ |
28 | #include "WriteBuffer.h" |
29 | |
30 | #include <google/protobuf/io/coded_stream.h> |
31 | |
32 | using namespace google::protobuf::io; |
33 | using google::protobuf::uint8; |
34 | |
35 | namespace Hdfs { |
36 | namespace Internal { |
37 | |
38 | #define WRITEBUFFER_INIT_SIZE 64 |
39 | |
40 | WriteBuffer::WriteBuffer() : |
41 | size(0), buffer(WRITEBUFFER_INIT_SIZE) { |
42 | } |
43 | |
44 | WriteBuffer::~WriteBuffer() { |
45 | } |
46 | |
47 | void WriteBuffer::writeVarint32(int32_t value, size_t pos) { |
48 | char buffer[5]; |
49 | uint8 * end = CodedOutputStream::WriteVarint32ToArray(value, |
50 | reinterpret_cast<uint8 *>(buffer)); |
51 | write(buffer, reinterpret_cast<char *>(end) - buffer, pos); |
52 | } |
53 | |
54 | char * WriteBuffer::alloc(size_t offset, size_t s) { |
55 | assert(offset <= size && size <= buffer.size()); |
56 | |
57 | if (offset > size) { |
58 | return NULL; |
59 | } |
60 | |
61 | size_t target = offset + s; |
62 | |
63 | if (target >= buffer.size()) { |
64 | target = target > 2 * buffer.size() ? target : 2 * buffer.size(); |
65 | buffer.resize(target); |
66 | } |
67 | |
68 | size = offset + s; |
69 | return &buffer[offset]; |
70 | } |
71 | |
72 | void WriteBuffer::write(const void * bytes, size_t s, size_t pos) { |
73 | assert(NULL != bytes); |
74 | assert(pos <= size && pos < buffer.size()); |
75 | char * p = alloc(size, s); |
76 | memcpy(p, bytes, s); |
77 | } |
78 | |
79 | } |
80 | } |
81 | |