有没有一种API可以从读取器中读取一行,但限制返回行的长度?

huangapple go评论87阅读模式
英文:

Is there a API to read a line from a reader, but to limit the length of returned line?

问题

原型将是:

 (reader *Reader) ReadLineWithMaxLength (delim byte, max int) (line []byte, err error)

当找到delim或达到max长度时,它会返回一行。

英文:

The prototype would be:

 (reader *Reader) ReadLineWithMaxLength (delim byte, max int) (line []byte, err error)

It returns a line when either the delim is found or max length is reached.

答案1

得分: 2

我不认为有一个直接的函数,但是使用io.LimitReader来实现一个函数是很简单的。

func ReadLimitedLine(r io.Reader, delim byte, max int64) ([]byte, error) {
    l, err := bufio.NewReader(io.LimitReader(r, max)).ReadBytes(delim)
    if err != nil && err != io.EOF {
        return nil, err
    }

    // ReadBytes函数会将分隔符包含在返回值中
    return bytes.TrimSuffix(l, []byte{delim}), nil
}
英文:

I don't think there is a direct function, but implementing one using io.LimitReader is straightforward.

func ReadLimitedLine(r io.Reader, delim byte, max int64) ([]byte, error) {
    l, err := bufio.NewReader(io.LimitReader(r, max)).ReadBytes(delim)
    if err != nil && err != io.EOF {
        return nil, err
    }

    // ReadBytes includes the delimiter in return value
    return bytes.TrimSuffix(l, []byte{delim}), nil
}

huangapple
  • 本文由 发表于 2015年9月20日 13:11:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/32676034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定