github.com/la5nta/wl2k-go@v0.11.8/fbb/helpers.go (about)

     1  // Copyright 2015 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
     2  // Use of this source code is governed by the MIT-license that can be
     3  // found in the LICENSE file.
     4  
     5  package fbb
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"io"
    11  	"strings"
    12  )
    13  
    14  type ByDate []*Message
    15  
    16  func (d ByDate) Len() int           { return len(d) }
    17  func (d ByDate) Swap(i, j int)      { d[i], d[j] = d[j], d[i] }
    18  func (d ByDate) Less(i, j int) bool { return d[i].Date().Before(d[j].Date()) }
    19  
    20  func ReadLine(rd io.Reader) (string, error) {
    21  	var lineBuffer bytes.Buffer
    22  
    23  	for {
    24  		buf := make([]byte, 1)
    25  		n, err := rd.Read(buf)
    26  		if err != nil {
    27  			return ``, err
    28  		} else if n < 1 {
    29  			continue
    30  		}
    31  
    32  		if buf[0] == '\n' || buf[0] == '\r' {
    33  			if lineBuffer.Len() > 0 {
    34  				return cleanString(string(lineBuffer.Bytes())), nil
    35  			}
    36  			continue
    37  		} else {
    38  			lineBuffer.WriteByte(buf[0])
    39  		}
    40  	}
    41  }
    42  
    43  func (s *Session) nextLineRemoteErr(parseErr bool) (string, error) {
    44  	line, err := s.rd.ReadString('\r')
    45  	if err != nil {
    46  		return line, err
    47  	}
    48  
    49  	line = cleanString(line)
    50  	s.pLog.Println(line)
    51  
    52  	if err := errLine(line); parseErr && err != nil {
    53  		return "", err
    54  	} else {
    55  		return line, nil
    56  	}
    57  }
    58  
    59  func (s *Session) nextLine() (string, error) {
    60  	return s.nextLineRemoteErr(true)
    61  }
    62  
    63  func errLine(str string) error {
    64  	if len(str) == 0 || str[0] != '*' {
    65  		return nil
    66  	}
    67  
    68  	idx := strings.LastIndex(str, "*")
    69  	if idx+1 >= len(str) {
    70  		return nil
    71  	}
    72  
    73  	return fmt.Errorf(strings.TrimSpace(str[idx+1:]))
    74  }
    75  
    76  func cleanString(str string) string {
    77  	str = strings.TrimSpace(str)
    78  	if len(str) < 1 {
    79  		return str
    80  	}
    81  	if str[0] == byte(0) {
    82  		str = str[1:]
    83  	}
    84  	if str[len(str)-1] == byte(0) {
    85  		str = str[0 : len(str)-2]
    86  	}
    87  	return str
    88  }