1// Copyright 2014-2021 Ulrich Kunitz. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package lzma
6
7import (
8	"errors"
9	"io"
10)
11
12// ErrLimit indicates that the limit of the LimitedByteWriter has been
13// reached.
14var ErrLimit = errors.New("limit reached")
15
16// LimitedByteWriter provides a byte writer that can be written until a
17// limit is reached. The field N provides the number of remaining
18// bytes.
19type LimitedByteWriter struct {
20	BW io.ByteWriter
21	N  int64
22}
23
24// WriteByte writes a single byte to the limited byte writer. It returns
25// ErrLimit if the limit has been reached. If the byte is successfully
26// written the field N of the LimitedByteWriter will be decremented by
27// one.
28func (l *LimitedByteWriter) WriteByte(c byte) error {
29	if l.N <= 0 {
30		return ErrLimit
31	}
32	if err := l.BW.WriteByte(c); err != nil {
33		return err
34	}
35	l.N--
36	return nil
37}
38