zero_copy_stream_as_streambuf.h 1.76 KB
Newer Older
gejun's avatar
gejun committed
1
// Copyright (c) 2012 Baidu, Inc.
gejun's avatar
gejun committed
2 3 4 5 6 7 8 9 10 11 12 13
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
gejun's avatar
gejun committed
14 15 16 17

// Author: Ge,Jun (gejun@baidu.com)
// Date: Thu Nov 22 13:57:56 CST 2012

gejun's avatar
gejun committed
18 19
#ifndef BUTIL_ZERO_COPY_STREAM_AS_STREAMBUF_H
#define BUTIL_ZERO_COPY_STREAM_AS_STREAMBUF_H
gejun's avatar
gejun committed
20 21 22 23

#include <streambuf>
#include <google/protobuf/io/zero_copy_stream.h>

24
namespace butil {
gejun's avatar
gejun committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

// Wrap a ZeroCopyOutputStream into std::streambuf. Notice that before 
// destruction or shrink(), BackUp() of the stream are not called. In another
// word, if the stream is wrapped from IOBuf, the IOBuf may be larger than 
// appended data.
class ZeroCopyStreamAsStreamBuf : public std::streambuf {
public:
    ZeroCopyStreamAsStreamBuf(google::protobuf::io::ZeroCopyOutputStream* stream)
        : _zero_copy_stream(stream) {}
    virtual ~ZeroCopyStreamAsStreamBuf();

    // BackUp() unused bytes. Automatically called in destructor.
    void shrink();
    
protected:
    virtual int overflow(int ch);
    virtual int sync();
    std::streampos seekoff(std::streamoff off,
                           std::ios_base::seekdir way,
                           std::ios_base::openmode which);

private:
    google::protobuf::io::ZeroCopyOutputStream* _zero_copy_stream;
};

50
}  // namespace butil
gejun's avatar
gejun committed
51

gejun's avatar
gejun committed
52
#endif  // BUTIL_ZERO_COPY_STREAM_AS_STREAMBUF_H