jshin@chromium.org | 6f31ac3 | 2014-03-26 22:15:14 +0000 | [diff] [blame^] | 1 | // Copyright (C) 2009-2011, International Business Machines |
| 2 | // Corporation and others. All Rights Reserved. |
| 3 | // |
| 4 | // Copyright 2007 Google Inc. All Rights Reserved. |
| 5 | // Author: sanjay@google.com (Sanjay Ghemawat) |
| 6 | |
| 7 | #include "unicode/utypes.h" |
| 8 | #include "unicode/bytestream.h" |
| 9 | #include "cmemory.h" |
| 10 | |
| 11 | U_NAMESPACE_BEGIN |
| 12 | |
| 13 | ByteSink::~ByteSink() {} |
| 14 | |
| 15 | char* ByteSink::GetAppendBuffer(int32_t min_capacity, |
| 16 | int32_t /*desired_capacity_hint*/, |
| 17 | char* scratch, int32_t scratch_capacity, |
| 18 | int32_t* result_capacity) { |
| 19 | if (min_capacity < 1 || scratch_capacity < min_capacity) { |
| 20 | *result_capacity = 0; |
| 21 | return NULL; |
| 22 | } |
| 23 | *result_capacity = scratch_capacity; |
| 24 | return scratch; |
| 25 | } |
| 26 | |
| 27 | void ByteSink::Flush() {} |
| 28 | |
| 29 | CheckedArrayByteSink::CheckedArrayByteSink(char* outbuf, int32_t capacity) |
| 30 | : outbuf_(outbuf), capacity_(capacity < 0 ? 0 : capacity), |
| 31 | size_(0), appended_(0), overflowed_(FALSE) { |
| 32 | } |
| 33 | |
| 34 | CheckedArrayByteSink::~CheckedArrayByteSink() {} |
| 35 | |
| 36 | CheckedArrayByteSink& CheckedArrayByteSink::Reset() { |
| 37 | size_ = appended_ = 0; |
| 38 | overflowed_ = FALSE; |
| 39 | return *this; |
| 40 | } |
| 41 | |
| 42 | void CheckedArrayByteSink::Append(const char* bytes, int32_t n) { |
| 43 | if (n <= 0) { |
| 44 | return; |
| 45 | } |
| 46 | appended_ += n; |
| 47 | int32_t available = capacity_ - size_; |
| 48 | if (n > available) { |
| 49 | n = available; |
| 50 | overflowed_ = TRUE; |
| 51 | } |
| 52 | if (n > 0 && bytes != (outbuf_ + size_)) { |
| 53 | uprv_memcpy(outbuf_ + size_, bytes, n); |
| 54 | } |
| 55 | size_ += n; |
| 56 | } |
| 57 | |
| 58 | char* CheckedArrayByteSink::GetAppendBuffer(int32_t min_capacity, |
| 59 | int32_t /*desired_capacity_hint*/, |
| 60 | char* scratch, |
| 61 | int32_t scratch_capacity, |
| 62 | int32_t* result_capacity) { |
| 63 | if (min_capacity < 1 || scratch_capacity < min_capacity) { |
| 64 | *result_capacity = 0; |
| 65 | return NULL; |
| 66 | } |
| 67 | int32_t available = capacity_ - size_; |
| 68 | if (available >= min_capacity) { |
| 69 | *result_capacity = available; |
| 70 | return outbuf_ + size_; |
| 71 | } else { |
| 72 | *result_capacity = scratch_capacity; |
| 73 | return scratch; |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | U_NAMESPACE_END |