Path: blob/master/thirdparty/icu4c/common/bytestream.cpp
9912 views
// © 2016 and later: Unicode, Inc. and others.1// License & terms of use: http://www.unicode.org/copyright.html2// Copyright (C) 2009-2011, International Business Machines3// Corporation and others. All Rights Reserved.4//5// Copyright 2007 Google Inc. All Rights Reserved.6// Author: [email protected] (Sanjay Ghemawat)78#include "unicode/utypes.h"9#include "unicode/bytestream.h"10#include "cmemory.h"1112U_NAMESPACE_BEGIN1314ByteSink::~ByteSink() {}1516char* ByteSink::GetAppendBuffer(int32_t min_capacity,17int32_t /*desired_capacity_hint*/,18char* scratch, int32_t scratch_capacity,19int32_t* result_capacity) {20if (min_capacity < 1 || scratch_capacity < min_capacity) {21*result_capacity = 0;22return nullptr;23}24*result_capacity = scratch_capacity;25return scratch;26}2728void ByteSink::Flush() {}2930CheckedArrayByteSink::CheckedArrayByteSink(char* outbuf, int32_t capacity)31: outbuf_(outbuf), capacity_(capacity < 0 ? 0 : capacity),32size_(0), appended_(0), overflowed_(false) {33}3435CheckedArrayByteSink::~CheckedArrayByteSink() {}3637CheckedArrayByteSink& CheckedArrayByteSink::Reset() {38size_ = appended_ = 0;39overflowed_ = false;40return *this;41}4243void CheckedArrayByteSink::Append(const char* bytes, int32_t n) {44if (n <= 0) {45return;46}47if (n > (INT32_MAX - appended_)) {48// TODO: Report as integer overflow, not merely buffer overflow.49appended_ = INT32_MAX;50overflowed_ = true;51return;52}53appended_ += n;54int32_t available = capacity_ - size_;55if (n > available) {56n = available;57overflowed_ = true;58}59if (n > 0 && bytes != (outbuf_ + size_)) {60uprv_memcpy(outbuf_ + size_, bytes, n);61}62size_ += n;63}6465char* CheckedArrayByteSink::GetAppendBuffer(int32_t min_capacity,66int32_t /*desired_capacity_hint*/,67char* scratch,68int32_t scratch_capacity,69int32_t* result_capacity) {70if (min_capacity < 1 || scratch_capacity < min_capacity) {71*result_capacity = 0;72return nullptr;73}74int32_t available = capacity_ - size_;75if (available >= min_capacity) {76*result_capacity = available;77return outbuf_ + size_;78} else {79*result_capacity = scratch_capacity;80return scratch;81}82}8384U_NAMESPACE_END858687