Пример #1
0
func ParseVirtualDJTracklist(bufReader *bufio.Reader) []Track {
	var list []Track

	for line, _, err := bufReader.ReadLine(); err != io.EOF; line, _, err = bufReader.ReadLine() {
		data := strings.SplitN(string(line), " : ", 2)
		trackdata := strings.SplitN(data[1], " - ", 2)
		if len(trackdata) != 2 {
			term.OutputError("Error parsing track " + string(data[1]))
			term.OutputMessage("Please enter an artist for this track: ")
			artist, err := term.STD_IN.ReadString('\n')
			if err != nil {
				term.OutputError("Incorrect artist entry.")
				os.Exit(2)
			}
			term.OutputMessage("Please enter a name for this track: ")
			track, err := term.STD_IN.ReadString('\n')
			if err != nil {
				term.OutputError("Incorrect track name entry.")
				os.Exit(2)
			}

			trackdata = []string{artist, track}
		}

		thistrack := new(Track)
		thistrack.Artist = trackdata[0]
		thistrack.Song = trackdata[1]

		list = append(list, *thistrack)
	}

	return list
}
Пример #2
0
func Grep(arg *GrepArg) {
	var f []byte
	var path = ""
	var ok bool
	var stdin *bufio.Reader

	if path, ok = arg.input.(string); ok {
		if fi, err := os.Stat(path); err == nil && fi.Size() == 0 {
			return
		}
		mf, err := mmap.Open(path)
		if err != nil {
			errorline(err.Error() + ": " + path)
			return
		}
		defer mf.Close()
		f = mf.Data()
		doGrep(path, f, arg)
	} else if in, ok := arg.input.(io.Reader); ok {
		stdin = bufio.NewReader(in)
		for {
			f, _, err := stdin.ReadLine()
			doGrep("stdin", f, arg)
			if err != nil {
				break
			}
		}
	}
}
Пример #3
0
func getBoardAndPrincess(reader *bufio.Reader) (Board, Princess) {
	board := Board{}
	princess := Princess{}

	y := 0

	for {
		line, isPrefix, err := reader.ReadLine()

		if err == io.EOF {
			break
		}

		handleError(err)
		handleLongLines(isPrefix)

		x := bytes.Index(line, []byte("p"))

		if x > -1 {
			// Found the princess!
			princess.X = x
			princess.Y = y
		}

		y++

		board = append(board, line)
	}

	return board, princess
}
Пример #4
0
func parseOrders(r *bufio.Reader) ([]*order, error) {
	lineno := 0
	var keys, actions []byte
	var o []*order
	var err error
	for err == nil {
		l, _, err := r.ReadLine()
		if err != nil {
			break
		}
		lineno++
		if len(l) == 0 || l[0] == COMMENT {
			continue
		}
		for l[len(l)-1] == LINECONTINUE {
			nl, _, err := r.ReadLine()
			if err != nil {
				return nil, ParseError(fmt.Sprintf("line %d -- %s", lineno, err.Error()))
			}
			l = append(l, bytes.TrimFunc(nl, unicode.IsSpace)...)
		}
		if l[0] != SPACE {
			keys = bytes.Join(bytes.Split(l, []byte{SPACE}), []byte(""))
		} else {
			actions = bytes.TrimFunc(l, unicode.IsSpace)
		}
		if keys != nil && actions != nil {
			o = append(o, neworder(keys, actions))
			keys = nil
			actions = nil
		}
	}
	return o, nil
}
Пример #5
0
//ReadBufferedLine is a function which wraps around the bufio.ReadLine method to
//return a full line of data. bufio.ReadLine might return an incomplete line
//(requiring multiple calls to bufio.ReadLine), while this function ensures that
//it will return the complete line. In case the provided buffer is not large
//enough, it will grow
func ReadBufferedLine(r *bufio.Reader, p *[]byte) (bool, error) {
	//declare variables used in next loop, initialize isPrefix as true
	var line []byte
	var isPrefix bool = true
	var err error

	for isPrefix {
		//read (partial) data
		line, isPrefix, err = r.ReadLine()

		if err != nil {
			//check if it the error is EOF
			if err == io.EOF {
				//store last data
				*p = append(*p, line...)
				return true, nil
			}

			return true, err
		}

		//append line to buffer
		*p = append(*p, line...)
	}

	return false, nil
}
Пример #6
0
// Streams the tokens within a text file.
func TokensFromFile(filename string, lowerCase bool, returnChars bool) (tokens []string) {
	var (
		bfr *bufio.Reader
		tks []string
	)
	tokens = make([]string, 0)
	// Open the file for reading.
	fh, err := os.Open(filename)
	if err != nil {
		log.Fatal(err)
	}
	defer fh.Close()
	// Read the lines of the file one at a time.
	bfr = bufio.NewReaderSize(fh, 1024*16)
	for line, isprefix, err := bfr.ReadLine(); err != io.EOF; {
		// Error handling.
		if err != nil {
			log.Fatal(err)
		}
		if isprefix {
			log.Fatal("Line too long for buffered reader.")
		}
		// Convert the bytes in the line to nice tokens.
		tks = TokenizeLine(string(line), lowerCase, returnChars)
		for _, tk := range tks {
			tokens = append(tokens, tk)
		}
		// Read from the file for the next iteration.
		line, isprefix, err = bfr.ReadLine()
	}
	return
}
Пример #7
0
func (h *Harvester) readline(reader *bufio.Reader) (*string, error) {
	var buffer bytes.Buffer
	for {
		segment, is_partial, err := reader.ReadLine()
		if err != nil {
			// TODO(sissel): Handle the error, check io.EOF?
			// TODO(sissel): if eof and line_complete is false, don't check rotation unless a very long time has passed
			if err == io.EOF {
				time.Sleep(1 * time.Second)
				continue
			} else {
				fmt.Println(err)
				return nil, err // TODO(sissel): don't do this
			}

			// TODO(sissel): At EOF, check rotation
			// TODO(sissel): if nothing to do, sleep
		}

		// TODO(sissel): if buffer exceeds a certain length, maybe report an error condition? chop it?
		buffer.Write(segment)

		if !is_partial {
			str := new(string)
			*str = buffer.String()
			return str, nil
		}
	} /* forever read chunks */

	return nil, nil
}
Пример #8
0
func genDataFromGenFile(ctx context.Context, genFile *bufio.Reader, evStore evstore.Connection) {
	chanInput := make(chan string, 1)
	for {
		s, _, err := genFile.ReadLine()
		if err == io.EOF {
			log.Println("EOF")
			break
		}
		if err != nil {
			log.Panicln(err)
		}
		go genData(ctx, string(s), chanInput)
	}
	log.Println("Waiting for Ctrl-C")
Loop:
	for {
		select {
		case <-ctx.Done():
			break Loop
		case msg := <-chanInput:
			log.Println(msg)
			evStore.Committer().SubmitEvent("", "scalar", msg)
		}
	}
}
Пример #9
0
//for write command
func write(filename string, numBytes int, seconds int, reader *bufio.Reader) string {
	buffer := ""
	total := 0
	//Case when user presses enters while entering file content
	for total < numBytes {
		curBytes, _, _ := reader.ReadLine()
		total += len(curBytes) + 2
		buffer += string(curBytes)
		buffer += "\r\n"
	}
	if len(buffer) >= 2 {
		buffer = buffer[0 : len(buffer)-2]
	}
	if len(buffer) != numBytes {
		return "ERR_CMD_ERR\r\n"
	}
	lock.Lock()
	contentMap[filename] = buffer
	if versionMap[filename] == 0 {
		//version starts from 1
		versionMap[filename] = 1
	} else {
		versionMap[filename] += 1
	}
	fileTimeMap[filename] = time.Now()
	//Assuming when user enters 0 as exptime, not to expire file
	if seconds == -1 || seconds == 0 {
		expiryMap[filename] = infiTime
	} else {
		expiryMap[filename] = time.Second * time.Duration(seconds)
	}
	version := strconv.Itoa(versionMap[filename])
	lock.Unlock()
	return "OK " + version + "\r\n"
}
Пример #10
0
//将socket请求内容 解析为一个MCRequest对象
func (req *MCRequest) Receive(r *bufio.Reader) error {
	line, _, err := r.ReadLine()
	if err != nil || len(line) == 0 {
		return io.EOF
	}

	params := strings.Fields(string(line))
	command := CommandCode(params[0])

	switch command {

	case SET, ADD, REPLACE:
		req.Opcode = command
		req.Key = params[1]
		req.Length, _ = strconv.Atoi(params[4])

		value := make([]byte, req.Length+2)
		io.ReadFull(r, value)

		req.Value = make([]byte, req.Length)
		copy(req.Value, value)
	case GET:
		req.Opcode = command
		req.Key = params[1]
		RunStats["cmd_get"].(*CounterStat).Increment(1)
	case STATS:
		req.Opcode = command
		req.Key = ""
	case DELETE:
		req.Opcode = command
		req.Key = params[1]
	}
	return err
}
Пример #11
0
Файл: parse.go Проект: evmar/hp
func mustReadLine(r *bufio.Reader) ([]byte, error) {
	line, prefix, err := r.ReadLine()
	if prefix {
		panic("prefix")
	}
	return line, err
}
Пример #12
0
func ReadLines_FromReader(reader *bufio.Reader) (lines []string, err error) {
	var (
		part   []byte
		prefix bool
	)
	buffer := bytes.NewBuffer(make([]byte, 0))
	//Read line from file and append the line to the List
	for {
		if part, prefix, err = reader.ReadLine(); err != nil {
			break
		}

		buffer.Write(part)
		if !prefix {
			lines = append(lines, buffer.String())
			buffer.Reset()
		}
	}

	if err == io.EOF {
		err = nil
	}

	return
}
Пример #13
0
func Readln(r *bufio.Reader) (string, error) {
	// http://stackoverflow.com/a/12206584
	// http://stackoverflow.com/a/21124415
	// http://stackoverflow.com/a/16615559
	//
	// Example:
	//
	// ```
	// reader := bufio.NewReaderSize(fp, 128 * 1024)  // 128KB
	//
	// line, err := Readln(reader)
	// for err == nil {
	//     fmt.Println(line)
	//     line, err = Readln(reader)
	// }
	// ```

	var (
		isPrefix         bool  = true
		err              error = nil
		line, ln         []byte
		num_buffer_count = 0
	)
	for isPrefix && err == nil {
		line, isPrefix, err = r.ReadLine()
		ln = append(ln, line...)

		num_buffer_count += 1
		if num_buffer_count > 10 {
			err = errors.New("too long line")
			break
		}
	}
	return string(ln), err
}
Пример #14
0
func readLine(r *bufio.Reader) string {
	line, _, err := r.ReadLine()
	if err != nil {
		return ""
	}
	return string(line)
}
Пример #15
0
// Format the input and return the formatted data.
// If any error is encountered, no data will be returned.
func Format(in io.Reader) ([]byte, error) {
	var src *bufio.Reader
	var ok bool
	src, ok = in.(*bufio.Reader)
	if !ok {
		src = bufio.NewReader(in)
	}
	dst := &bytes.Buffer{}
	state := fstate{out: dst, defines: make(map[string]struct{})}
	for {
		data, _, err := src.ReadLine()
		if err == io.EOF {
			state.flush()
			break
		}
		if err != nil {
			return nil, err
		}
		err = state.addLine(data)
		if err != nil {
			return nil, err
		}
	}
	return dst.Bytes(), nil
}
Пример #16
0
func ReadInputStrings() (string, string) {
	var r *bufio.Reader

	if *input == "" || *input == "-" {
		r = bufio.NewReader(os.Stdin)
	} else {
		f, e := os.Open(*input)
		if e != nil {
			panic("Could not open input file")
		}
		defer f.Close()
		r = bufio.NewReader(f)
	}
	var matrixstring, suffix []byte
	var err error
	for isPrefix := true; isPrefix; {
		suffix, isPrefix, err = r.ReadLine()
		if err != nil {
			panic("Could not read matrix line")
		}
		matrixstring = append(matrixstring, suffix...)
	}

	irreversiblestring, prefix, e := r.ReadLine()
	if e != nil || prefix {
		panic("Could not read reaction line")
	}
	return string(matrixstring), string(irreversiblestring)
}
Пример #17
0
func ReadFullOutput(rdr *bufio.Reader) []string {
	retval := make([]string, 0)
	timeout := make(chan bool)

	go func() {
		time.Sleep(5 * time.Second)
		timeout <- true
	}()

	msg := make(chan string)

	for {
		go func(rdr *bufio.Reader) {
			message, _, _ := rdr.ReadLine()
			msg <- string(message)
		}(rdr)

		select {
		case <-timeout:
			return retval
		case message := <-msg:
			retval = append(retval, message)
		}
	}
	return retval
}
Пример #18
0
func (s Store) parse(reader *bufio.Reader, filename string) (err error) {
	lineno := 0
	section := ""
	for err == nil {
		l, _, err := reader.ReadLine()
		if err != nil {
			break
		}
		lineno++
		if len(l) == 0 {
			continue
		}
		line := strings.TrimFunc(string(l), unicode.IsSpace)
		for line[len(line)-1] == '\\' {
			line = line[:len(line)-1]
			l, _, err := reader.ReadLine()
			if err != nil {
				return err
			}
			line += strings.TrimFunc(string(l), unicode.IsSpace)
		}
		section, err = s.parseLine(section, line)
		if err != nil {
			return StoreParseError(filename, lineno)
		}
	}
	return err
}
func getBoardAndPrincess(reader *bufio.Reader) ([][]byte, Pos) {
	var board [][]byte
	princess := Pos{}

	y := 0

	for {
		line, _, err := reader.ReadLine()
		if err == io.EOF {
			break
		}

		x := bytes.Index(line, []byte("p"))

		if x > -1 {
			princess.X = x
			princess.Y = y
		}

		board = append(board, line)

		y++
	}

	return board, princess
}
Пример #20
0
func readLine(r *bufio.Reader) (fname string, types []string, data string, err error) {
	var line []byte
	for len(line) == 0 {
		var short bool
		line, short, err = r.ReadLine()
		if short {
			err = fmt.Errorf("line too long")
			return
		}
		if err != nil {
			return
		}
		line = bytes.TrimSpace(line)
	}

	b, err := r.ReadByte()
	if err == io.EOF || b != ' ' {
		r.UnreadByte()
		return parseLine(string(line))
	}
	for b == ' ' && err != io.EOF {
		r.UnreadByte()
		stub, short, err := r.ReadLine()
		if !short {
			err = fmt.Errorf("line too long")
			return fname, types, data, err
		}
		line = append(line, bytes.TrimSpace(stub)...)
		b, err = r.ReadByte()
	}
	r.UnreadByte()
	return parseLine(string(line))
}
Пример #21
0
func promptName(c net.Conn, bufc *bufio.Reader) string {
	io.WriteString(c, LOGO)
	io.WriteString(c, "Welcome, stranger!\n")
	io.WriteString(c, "INPUT NAME: ")
	name, _, _ := bufc.ReadLine()
	return string(name)
}
Пример #22
0
func receiveMessage(in bufio.Reader, out io.Writer) (string, error) {
	// HACK: Here we should negotiate with the SMTP
	// client and tell it what capabilities we have.
	// But we instead skip the whole EHLO and HELO thing
	// and hope for the best!
	fmt.Fprint(out, "220 voicemail ESMTP voicemail\r\n")
	fmt.Fprint(out, "250-voicemail\r\n")
	fmt.Fprint(out, "250 DSN\r\n")

	for {
		line, _, err := in.ReadLine()
		if err != nil {
			return "", err
		}

		cmd := strings.Split(string(line), " ")
		switch cmd[0] {
		case "MAIL", "RCPT":
			fmt.Fprint(out, "250 2.1.0 Ok\r\n")
		case "DATA":
			return handleData(in, out), nil
		case "QUIT":
			return "", errors.New("No message received!")
		}
	}
}
Пример #23
0
Файл: ihex.go Проект: iand/go
// Function ReadIHex reads an Intel Hex file from `reader` and returns it.
func ReadIHex(reader *bufio.Reader) (ix *IHex, err error) {
	ix = NewIHex()

	for {
		line, _, err := reader.ReadLine()
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, err
		}

		sline := strings.Trim(string(line), " \t")
		if len(sline) == 0 {
			continue
		}

		t, addr, data, err := parseLine(sline)
		if err != nil {
			return nil, err
		}

		switch t {
		case 0x00:
			ix.InsertData(addr, data)
		}
	}

	return ix, nil
}
Пример #24
0
func loadProjectionViewPoint(proj *Projection, input *bufio.Reader) (err error) {
	num := 0

	// Loop until we get some number of values read.
	for num == 0 {
		var next []byte
		line, prefix, err := input.ReadLine()

		for prefix && err != nil {
			next, prefix, err = input.ReadLine()
			line = append(line, next...)
		}

		if err != nil {
			return err
		}

		num, err = fmt.Sscanf(string(line), "%f %f %f", &(*proj).Viewpoint.X,
			&(*proj).Viewpoint.Y, &(*proj).Viewpoint.Z)
	}

	if num != 3 && err == nil {
		err = fmt.Errorf("Tried to read 3 values, read %d instead.", num)
	}

	return err
}
Пример #25
0
Файл: ini.go Проект: tpot/goini
func LoadReader(reader *bufio.Reader) (dict Dict, err error) {
	dict = make(map[string]map[string]string)
	lineno := 0
	section := ""
	dict[section] = make(map[string]string)

	for err == nil {
		l, _, err := reader.ReadLine()
		if err != nil {
			break
		}
		lineno++
		if len(l) == 0 {
			continue
		}
		line := strings.TrimFunc(string(l), unicode.IsSpace)

		for line[len(line)-1] == '\\' {
			line = line[:len(line)-1]
			l, _, err := reader.ReadLine()
			if err != nil {
				return nil, err
			}
			line += strings.TrimFunc(string(l), unicode.IsSpace)
		}

		section, err = dict.parseLine(section, line)
		if err != nil {
			return nil, newError(
				err.Error() + fmt.Sprintf("':%d'.", lineno))
		}
	}

	return
}
Пример #26
0
func loadProjectionWorld(proj *Projection, input *bufio.Reader) (err error) {
	num := 0

	// Loop until we get some number of values read.
	for num == 0 {
		line, prefix, err := input.ReadLine()
		var next []byte

		for prefix && err != nil {
			next, prefix, err = input.ReadLine()
			line = append(line, next...)
		}

		if err != nil {
			return err
		}

		num, err = fmt.Sscanf(string(line), "%f %f", &(*proj).World.Width,
			&(*proj).World.Height)
	}

	if num != 2 && err == nil {
		err = fmt.Errorf("Tried to read 2 values, read %d instead.", num)
	}

	return err
}
Пример #27
0
func (h *Harvester) readline(reader *bufio.Reader, eof_timeout time.Duration) (*string, error) {
	var buffer bytes.Buffer
	start_time := time.Now()
	for {
		segment, is_partial, err := reader.ReadLine()

		if err != nil {
			if err == io.EOF {
				time.Sleep(1 * time.Second) // TODO(sissel): Implement backoff

				// Give up waiting for data after a certain amount of time.
				// If we time out, return the error (eof)
				if time.Since(start_time) > eof_timeout {
					return nil, err
				}
				continue
			} else {
				log.Println(err)
				return nil, err // TODO(sissel): don't do this?
			}
		}

		// TODO(sissel): if buffer exceeds a certain length, maybe report an error condition? chop it?
		buffer.Write(segment)

		if !is_partial {
			// If we got a full line, return the whole line.
			str := new(string)
			*str = buffer.String()
			return str, nil
		}
	} /* forever read chunks */

	return nil, nil
}
Пример #28
0
func ReadLines(path string) (lines []string, err error) {
	var file *os.File
	if file, err = os.OpenFile(path, os.O_RDONLY, 0644); err != nil {
		return
	}
	defer file.Close()

	var reader *bufio.Reader = bufio.NewReader(file)
	var buffer *bytes.Buffer = bytes.NewBuffer(make([]byte, 0))
	var line []byte
	var isPrefix bool
	for {
		if line, isPrefix, err = reader.ReadLine(); err != nil {
			break
		}
		buffer.Write(line)
		if !isPrefix {
			lines = append(lines, buffer.String())
			buffer.Reset()
		}
	}
	if err == io.EOF {
		err = nil
	}
	return
}
Пример #29
0
func nextLine(reader *bufio.Reader) []byte {
	line, _, err := reader.ReadLine()

	handleError(err)

	return line
}
Пример #30
0
Файл: decode.go Проект: nf/ics
func decodeLine(r *bufio.Reader) (key, value string, err error) {
	var buf bytes.Buffer
	for {
		// get full line
		b, isPrefix, err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				err = io.ErrUnexpectedEOF
			}
			return "", "", err
		}
		if isPrefix {
			return "", "", errors.New("unexpected long line")
		}
		if len(b) == 0 {
			return "", "", errors.New("unexpected blank line")
		}
		if b[0] == ' ' {
			b = b[1:]
		}
		buf.Write(b)

		b, err = r.Peek(1)
		if err != nil || b[0] != ' ' {
			break
		}
	}
	p := strings.SplitN(buf.String(), ":", 2)
	if len(p) != 2 {
		return "", "", errors.New("bad line, couldn't find key:value")
	}
	return p[0], p[1], nil
}