Exemplo n.º 1
0
Arquivo: sx.go Projeto: hlandau/sx
func writeQuotedString(s string, b *bufio.Writer, f *Format) {
  b.WriteRune('"')
  for i := range s {
    c := s[i] // don't decode as runes
    switch c {
    case '\r':
      b.WriteString(`\r`)
    case '\n':
      b.WriteString(`\n`)
    case '\t':
      b.WriteString(`\t`)
    case '"':
      b.WriteString(`\"`)
    case '\\':
      b.WriteString(`\\`)
    default:
      if c < 0x80 && unicode.IsPrint(rune(c)) {
        b.WriteRune(rune(c))
      } else {
        b.WriteString(`\x`)
        b.WriteRune(enchex((c >> 4) & 0x0F))
        b.WriteRune(enchex(c & 0x0F))
      }
    }
  }
  b.WriteRune('"')
}
Exemplo n.º 2
0
func CSVWriteVal(cw *bufio.Writer, i interface{}) {
	sVal := fmt.Sprintf("%v", i)
	if len(sVal) <= 0 {
		return
	}

	bQuot := strings.IndexRune(sVal, ',') >= 0 || strings.IndexAny(sVal, "\"\r\n") >= 0
	if !bQuot {
		cw.WriteString(sVal)
		return
	}

	cw.WriteByte('"')
	for _, r1 := range sVal {
		switch r1 {
		case '"':
			cw.WriteString(`""`)
		case '\r':
			cw.WriteByte('\r')
		case '\n':
			cw.WriteByte('\n')
		default:
			cw.WriteRune(r1)
		}
	}
	cw.WriteByte('"')
}
Exemplo n.º 3
0
Arquivo: sx.go Projeto: hlandau/sx
func writeBase64String(s string, b *bufio.Writer, f *Format) {
  b.WriteRune('|')
  w := base64.NewEncoder(base64.StdEncoding, b)
  w.Write([]byte(s))
  w.Close()
  b.WriteRune('|')
}
Exemplo n.º 4
0
func doWriteRune(w *bufio.Writer) {
	if written, err := w.WriteRune(rune('o')); err != nil {
		log.Fatalf("failed writing a rune: %s", err)
	} else {
		log.Printf("Wrote rune in %d bytes", written)
	}
}
Exemplo n.º 5
0
func (t *TcpPlayer) sendUpdates(w *bufio.Writer, wg *sync.WaitGroup) {
	defer wg.Done()

	enc := json.NewEncoder(w)

	lastTurnSent := -1
	for update := range t.update {
		t.stateL.Lock()
		t.state = update
		t.stateL.Unlock()

		if update.Turn == lastTurnSent {
			continue
		}

		if err := enc.Encode(update); err != nil {
			t.l.Errorf("[TCP] sending update to player, %v", err)
			return
		}

		if _, err := w.WriteRune('\n'); err != nil {
			t.l.Errorf("[TCP] sending EOL to player, %v", err)
			return
		}

		if err := w.Flush(); err != nil {
			t.l.Errorf("[TCP] flushing update to player, %v", err)
			return
		}
		lastTurnSent = update.Turn
	}
}
Exemplo n.º 6
0
Arquivo: sx.go Projeto: hlandau/sx
func (s *spacer) write(b *bufio.Writer, t rune) {
	if s.f.serializationMode == szModeCanonical {
		return
	}
	if s.prevType == 'i' || s.prevType == 's' {
		b.WriteRune(' ')
	}
	s.prevType = t
}
Exemplo n.º 7
0
// Prints a horizontal line for the table based on a row.
func (table Table) printHorizontalLine(w *bufio.Writer, r row) {
	if len(r) != 0 {
		w.WriteRune(table.CSeparator)
		for i, _ := range r {
			fmt.Fprintf(w, "%s%s", strings.Repeat(string(table.HSeparator), table.colWidth[i]+2), string(table.CSeparator))
		}
		w.WriteRune(newline)
	}
}
Exemplo n.º 8
0
func copyNext(in *scanner.Scanner, out *bufio.Writer) error {
	c := in.Next()
	if out != nil {
		if n, err := out.WriteRune(c); err == nil && n < 1 {
			return fmt.Errorf("Couldn't write: %c", c)
		} else if err != nil {
			return err
		}
	}
	return nil
}
Exemplo n.º 9
0
func (p *Parser) writeHelpOption(writer *bufio.Writer, option *Option, maxlen int, hasshort bool, termcol int) {
	if option.ShortName != 0 {
		writer.WriteString("  -")
		writer.WriteRune(option.ShortName)
	} else if hasshort {
		writer.WriteString("    ")
	}

	written := 0
	prelen := 4

	if option.LongName != "" {
		if option.ShortName != 0 {
			writer.WriteString(", ")
		} else {
			writer.WriteString("  ")
		}

		fmt.Fprintf(writer, "--%s", option.LongName)
		written = utf8.RuneCountInString(option.LongName)

		prelen += written + 4
	}

	if option.Description != "" {
		if written < maxlen {
			dw := maxlen - written

			writer.WriteString(strings.Repeat(" ", dw))
			prelen += dw
		}

		def := option.Default

		if def == "" && !option.isBool() {
			def = convertToString(option.Value, option.Field.Tag)
		}

		var desc string

		if def != "" {
			desc = fmt.Sprintf("%s (%v)", option.Description, def)
		} else {
			desc = option.Description
		}

		writer.WriteString(wrapText(desc,
			termcol-prelen,
			strings.Repeat(" ", prelen)))
	}

	writer.WriteString("\n")
}
Exemplo n.º 10
0
Arquivo: sx.go Projeto: hlandau/sx
func writeString(s string, b *bufio.Writer, f *Format) {
  if f.serializationMode == szModeAdvanced {
    if isBinary(s) {
      writeBase64String(s, b, f)
    } else if usesTokenCharset(s) {
      writeToken(s, b, f)
    } else {
      writeQuotedString(s, b, f)
    }
    return
  }

  writeUint(uint64(len(s)), b, f)
  b.WriteRune(':')
  b.WriteString(s)
}
Exemplo n.º 11
0
func outputLine(w *bufio.Writer, line string, suffix string, count int) (err error) {
	if count > 0 {
		if _, err = w.WriteRune('\t'); nil != err {
			return err
		}
	}
	if _, err = w.WriteString(line); nil != err {
		return err
	}
	if _, err = w.WriteString(suffix); nil != err {
		return err
	}
	if _, err = w.WriteRune('\n'); nil != err {
		return err
	}
	return nil
}
Exemplo n.º 12
0
// write writes a protocol buffer to the socketAPI socket.
func write(w *bufio.Writer, pb proto.Message) error {
	b, err := proto.Marshal(pb)
	if err != nil {
		return err
	}

	var buf bytes.Buffer
	buf.WriteString(strconv.Itoa(len(b)))
	buf.WriteString("\n")
	buf.Write(b)

	body := base64.StdEncoding.EncodeToString(buf.Bytes())

	w.WriteString(body)
	w.WriteRune('\n')
	return w.Flush()
}
Exemplo n.º 13
0
Arquivo: sx.go Projeto: hlandau/sx
func writeList(vs []interface{}, b *bufio.Writer, f *Format) error {
	spacer := spacer{f: f}
	for _, v := range vs {
		switch vv := v.(type) {
		case string:
			spacer.write(b, 's')
      writeString(vv, b, f)
		case []byte:
			spacer.write(b, 's')
      writeString(string(vv), b, f)
		case int:
			spacer.write(b, 'i')
			writeInt(int64(vv), b, f)
			if f.serializationMode == szModeCanonical {
				b.WriteRune(' ')
			}
		case int64:
			spacer.write(b, 'i')
			writeInt(vv, b, f)
			if f.serializationMode == szModeCanonical {
				b.WriteRune(' ')
			}
		case uint64:
			spacer.write(b, 'i')
			writeUint(vv, b, f)
			if f.serializationMode == szModeCanonical {
				b.WriteRune(' ')
			}
		case []interface{}:
			spacer.write(b, '(')
			b.WriteRune('(')
			if err := writeList(vv, b, f); err != nil {
				return err
			}
			b.WriteRune(')')
		default:
			return ErrUnsupportedType
		}
	}

	return nil
}
Exemplo n.º 14
0
func writeSanitized(buf *bufio.Writer, s string) error {
	prevUnderscore := false

	for _, c := range s {
		c = replaceInvalidRune(c)
		if c == '_' {
			if prevUnderscore {
				continue
			}
			prevUnderscore = true
		} else {
			prevUnderscore = false
		}
		if _, err := buf.WriteRune(c); err != nil {
			return err
		}
	}

	return nil
}
Exemplo n.º 15
0
// Prints the data that is contained inside the specified row.
func (table Table) printRowData(w *bufio.Writer, r row) {
	maxLines := r.maxLines()
	for i := 0; i < maxLines; i++ {
		w.WriteRune(table.VSeparator)
		for j := 0; j < len(r); j++ {
			var data string
			if i >= len(r[j]) {
				data = strings.Repeat(" ", table.colWidth[j])
			} else {
				data = r[j][i]
			}
			fmt.Fprintf(w, " %s ", table.Align.align(data, table.colWidth[j]))
			w.WriteRune(table.VSeparator)
		}
		w.WriteRune(newline)
	}
}
Exemplo n.º 16
0
func escapeProp(buf *bufio.Writer, s string, isKey bool) {
	for x, r := range s {
		if r > 61 && r < 127 {
			if r == '\\' {
				buf.WriteRune('\\')
				buf.WriteRune('\\')
				continue
			}
			buf.WriteRune(r)
			continue
		}

		switch {
		case r == ' ':
			if x == 0 || isKey {
				buf.WriteRune('\\')
			}
			buf.WriteRune(' ')
		case r == '\t':
			buf.WriteRune('\\')
			buf.WriteRune('t')
		case r == '\n':
			buf.WriteRune('\\')
			buf.WriteRune('n')
		case r == '\r':
			buf.WriteRune('\\')
			buf.WriteRune('r')
		case r == '\f':
			buf.WriteRune('\\')
			buf.WriteRune('f')
		case r == '=', r == ':', r == '#', r == '!':
			buf.WriteRune('\\')
			buf.WriteRune(r)
		case int32(r) < 0x20, int32(r) > 0x7e:
			buf.WriteRune('\\')
			buf.WriteRune('u')

			buf.WriteRune(rune(unhex[int32(r)>>12&0xF]))
			buf.WriteRune(rune(unhex[int32(r)>>8&0xF]))
			buf.WriteRune(rune(unhex[int32(r)>>4&0xF]))
			buf.WriteRune(rune(unhex[int32(r)&0xF]))
		default:
			buf.WriteRune(r)
		}
	}
}
Exemplo n.º 17
0
func LogKeeper(verbose bool) {
	var skip error
	var logw *bufio.Writer

	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Logger trace:", r)
		}
	}()

	logq = make(chan LogMessage, 1024)
	logf, skip := os.Create(cfg.ErrorLog)
	if skip == nil {
		logw = bufio.NewWriter(logf)
		fmt.Printf("Error log: %s\n", cfg.ErrorLog)
	} else {
		println("Can't create file for error log. Error logging to file skiped.")
	}

	for {
		timeout := make(chan bool, 1)
		go func() {
			time.Sleep(2 * time.Second)
			timeout <- true
		}()

		select {
		case msg := <-logq:
			if skip == nil {
				logw.WriteString(msg.Started.Format(TimeFormat))
				logw.WriteRune(' ')
				switch msg.Severity {
				case WARNING:
					logw.WriteString("warning")
				case ERROR:
					logw.WriteString("error")
				}
				logw.WriteString(": ")
				logw.WriteString(StreamErr2String(msg.Result.ErrType))
				logw.WriteRune(' ')
				logw.WriteString(strconv.Itoa(msg.HTTPCode))
				logw.WriteRune(' ')
				logw.WriteString(strconv.FormatInt(msg.ContentLength, 10))
				logw.WriteRune(' ')
				logw.WriteString(msg.Elapsed.String())
				logw.WriteRune(' ')
				logw.WriteString(msg.Group)
				logw.WriteString(": ")
				logw.WriteString(msg.Name)
				logw.WriteRune('\n')
			}
		case <-timeout:
			if skip == nil {
				_ = logw.Flush()
			}
		}
	}
}
Exemplo n.º 18
0
Arquivo: data.go Projeto: bfix/gospel
// Write internal data structure to stream writer.
func (d *Data) writeData(wrt *bufio.Writer, level int) {

	// emit name (if defined)
	if len(d.Name) > 0 {
		wrt.WriteString(d.Name)
		wrt.WriteRune('=')
	}
	// handle value..
	if d.Len() == 0 {
		// .. as direct value
		wrt.WriteRune('"')
		wrt.WriteString(d.Value)
		wrt.WriteRune('"')
	} else {
		// .. as list of data
		if level > 0 {
			wrt.WriteRune('{')
		}
		// handle all list elements...
		count := d.Len()
		for n := 0; n < count; n++ {
			// emit delimiter
			if n > 0 {
				wrt.WriteRune(',')
			}
			// recursively write list element
			s := d.At(n).(*Data)
			s.writeData(wrt, level+1)
		}
		if level > 0 {
			wrt.WriteRune('}')
		}
	}
}