10b57cec5SDimitry Andric //===- circular_raw_ostream.cpp - Implement circular_raw_ostream ----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This implements support for circular buffered streams.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/Support/circular_raw_ostream.h"
140b57cec5SDimitry Andric #include <algorithm>
150b57cec5SDimitry Andric using namespace llvm;
160b57cec5SDimitry Andric 
write_impl(const char * Ptr,size_t Size)170b57cec5SDimitry Andric void circular_raw_ostream::write_impl(const char *Ptr, size_t Size) {
180b57cec5SDimitry Andric   if (BufferSize == 0) {
190b57cec5SDimitry Andric     TheStream->write(Ptr, Size);
200b57cec5SDimitry Andric     return;
210b57cec5SDimitry Andric   }
220b57cec5SDimitry Andric 
230b57cec5SDimitry Andric   // Write into the buffer, wrapping if necessary.
240b57cec5SDimitry Andric   while (Size != 0) {
250b57cec5SDimitry Andric     unsigned Bytes =
260b57cec5SDimitry Andric       std::min(unsigned(Size), unsigned(BufferSize - (Cur - BufferArray)));
270b57cec5SDimitry Andric     memcpy(Cur, Ptr, Bytes);
280b57cec5SDimitry Andric     Size -= Bytes;
290b57cec5SDimitry Andric     Cur += Bytes;
300b57cec5SDimitry Andric     if (Cur == BufferArray + BufferSize) {
310b57cec5SDimitry Andric       // Reset the output pointer to the start of the buffer.
320b57cec5SDimitry Andric       Cur = BufferArray;
330b57cec5SDimitry Andric       Filled = true;
340b57cec5SDimitry Andric     }
350b57cec5SDimitry Andric   }
360b57cec5SDimitry Andric }
370b57cec5SDimitry Andric 
flushBufferWithBanner()380b57cec5SDimitry Andric void circular_raw_ostream::flushBufferWithBanner() {
390b57cec5SDimitry Andric   if (BufferSize != 0) {
400b57cec5SDimitry Andric     // Write out the buffer
410b57cec5SDimitry Andric     TheStream->write(Banner, std::strlen(Banner));
420b57cec5SDimitry Andric     flushBuffer();
430b57cec5SDimitry Andric   }
440b57cec5SDimitry Andric }
45