The Android Open Source Project | 7c1b96a | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2008 The Android Open Source Project |
| 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 | #ifndef __UTILS_BUFFER_H__ |
| 18 | #define __UTILS_BUFFER_H__ 1 |
| 19 | |
| 20 | #include <stdio.h> |
| 21 | #include <stdlib.h> |
| 22 | #include <string.h> |
| 23 | |
| 24 | namespace android { |
| 25 | |
| 26 | class Buffer |
| 27 | { |
| 28 | private: |
| 29 | char *buf; |
| 30 | int bufsiz; |
| 31 | int used; |
| 32 | void ensureCapacity(int len); |
| 33 | |
| 34 | void |
| 35 | makeRoomFor(int len) |
| 36 | { |
| 37 | if (len + used >= bufsiz) { |
| 38 | bufsiz = (len + used) * 3/2 + 2; |
| 39 | char *blah = new char[bufsiz]; |
| 40 | |
| 41 | memcpy(blah, buf, used); |
| 42 | delete[] buf; |
| 43 | buf = blah; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | public: |
| 48 | Buffer() |
| 49 | { |
| 50 | bufsiz = 16; |
| 51 | buf = new char[bufsiz]; |
| 52 | clear(); |
| 53 | } |
| 54 | |
| 55 | ~Buffer() |
| 56 | { |
| 57 | delete[] buf; |
| 58 | } |
| 59 | |
| 60 | void |
| 61 | clear() |
| 62 | { |
| 63 | buf[0] = '\0'; |
| 64 | used = 0; |
| 65 | } |
| 66 | |
| 67 | int |
| 68 | length() |
| 69 | { |
| 70 | return used; |
| 71 | } |
| 72 | |
| 73 | void |
| 74 | append(const char c) |
| 75 | { |
| 76 | makeRoomFor(1); |
| 77 | buf[used] = c; |
| 78 | used++; |
| 79 | buf[used] = '\0'; |
| 80 | } |
| 81 | |
| 82 | void |
| 83 | append(const char *s, int len) |
| 84 | { |
| 85 | makeRoomFor(len); |
| 86 | |
| 87 | memcpy(buf + used, s, len); |
| 88 | used += len; |
| 89 | buf[used] = '\0'; |
| 90 | } |
| 91 | |
| 92 | void |
| 93 | append(const char *s) |
| 94 | { |
| 95 | append(s, strlen(s)); |
| 96 | } |
| 97 | |
| 98 | char * |
| 99 | getBytes() |
| 100 | { |
| 101 | return buf; |
| 102 | } |
| 103 | }; |
| 104 | |
| 105 | }; // namespace android |
| 106 | |
| 107 | #endif |