gitee.com/mysnapcore/mysnapd@v0.1.0/strutil/limbuffer.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2018 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package strutil
    21  
    22  type LimitedBuffer struct {
    23  	buffer   []byte
    24  	maxLines int
    25  	maxBytes int
    26  }
    27  
    28  func NewLimitedBuffer(maxLines, maxBytes int) *LimitedBuffer {
    29  	return &LimitedBuffer{
    30  		maxLines: maxLines,
    31  		maxBytes: maxBytes,
    32  	}
    33  }
    34  
    35  func (lb *LimitedBuffer) Write(data []byte) (int, error) {
    36  	drop := len(lb.buffer) + len(data) - lb.maxBytes
    37  	switch {
    38  	case drop < 0:
    39  		lb.buffer = append(lb.buffer, data...)
    40  	case drop > len(lb.buffer):
    41  		lb.buffer = append(lb.buffer[:0], data[drop-len(lb.buffer):]...)
    42  	default:
    43  		keep := copy(lb.buffer, lb.buffer[drop:])
    44  		lb.buffer = append(lb.buffer[:keep], data...)
    45  	}
    46  	return len(data), nil
    47  }
    48  
    49  func (lb *LimitedBuffer) Bytes() []byte {
    50  	return TruncateOutput(lb.buffer, lb.maxLines, lb.maxBytes)
    51  }