github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/internal/saferio/io.go (about)

     1  // Copyright 2022 The Go Authors. 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  
     5  // Package saferio provides I/O functions that avoid allocating large
     6  // amounts of memory unnecessarily. This is intended for packages that
     7  // read data from an [io.Reader] where the size is part of the input
     8  // data but the input may be corrupt, or may be provided by an
     9  // untrustworthy attacker.
    10  package saferio
    11  
    12  import (
    13  	"github.com/shogo82148/std/io"
    14  )
    15  
    16  // ReadData reads n bytes from the input stream, but avoids allocating
    17  // all n bytes if n is large. This avoids crashing the program by
    18  // allocating all n bytes in cases where n is incorrect.
    19  //
    20  // The error is io.EOF only if no bytes were read.
    21  // If an io.EOF happens after reading some but not all the bytes,
    22  // ReadData returns io.ErrUnexpectedEOF.
    23  func ReadData(r io.Reader, n uint64) ([]byte, error)
    24  
    25  // ReadDataAt reads n bytes from the input stream at off, but avoids
    26  // allocating all n bytes if n is large. This avoids crashing the program
    27  // by allocating all n bytes in cases where n is incorrect.
    28  func ReadDataAt(r io.ReaderAt, n uint64, off int64) ([]byte, error)
    29  
    30  // SliceCapWithSize returns the capacity to use when allocating a slice.
    31  // After the slice is allocated with the capacity, it should be
    32  // built using append. This will avoid allocating too much memory
    33  // if the capacity is large and incorrect.
    34  //
    35  // A negative result means that the value is always too big.
    36  func SliceCapWithSize(size, c uint64) int
    37  
    38  // SliceCap is like SliceCapWithSize but using generics.
    39  func SliceCap[E any](c uint64) int