Exemple #1
1
// Format implements the NodeFormatter interface.
func (node IndexElem) Format(buf *bytes.Buffer, f FmtFlags) {
	FormatNode(buf, f, node.Column)
	if node.Direction != DefaultDirection {
		buf.WriteByte(' ')
		buf.WriteString(node.Direction.String())
	}
}
Exemple #2
0
func (c *aliasColumn) SerializeSqlForColumnList(out *bytes.Buffer) error {
	if !validIdentifierName(c.name) {
		return errors.Newf(
			"Invalid alias name `%s`.  Generated sql: %s",
			c.name,
			out.String())
	}
	if c.expression == nil {
		return errors.Newf(
			"Cannot alias a nil expression.  Generated sql: %s",
			out.String())
	}

	out.WriteByte('(')
	if c.expression == nil {
		return errors.Newf("nil alias clause.  Generate sql: %s", out.String())
	}
	if err := c.expression.SerializeSql(out); err != nil {
		return err
	}
	out.WriteString(") AS `")
	out.WriteString(c.name)
	out.WriteByte('`')
	return nil
}
Exemple #3
0
// parseMultivalueLine parses a line that includes several quoted values separated by whitespaces.
// Example: MachineMetadata="foo=bar" "baz=qux"
// If the provided line is not a multivalue string, the line is returned as the sole value.
func parseMultivalueLine(line string) (values []string) {
	if !strings.HasPrefix(line, `"`) || !strings.HasSuffix(line, `"`) {
		return []string{line}
	}

	var v bytes.Buffer
	w := false // check whether we're within quotes or not
	for _, e := range []byte(line) {
		// ignore quotes
		if e == '"' {
			w = !w
			continue
		}

		if e == ' ' {
			if !w { // between quoted values, keep the previous value and reset.
				values = append(values, v.String())
				v.Reset()
				continue
			}
		}

		v.WriteByte(e)
	}

	values = append(values, v.String())

	return
}
Exemple #4
0
// Encode encodes the values into ``URL encoded'' form
// ("acl&bar=baz&foo=quux") sorted by key.
func Encode(v url.Values) string {
	if v == nil {
		return ""
	}
	var buf bytes.Buffer
	keys := make([]string, 0, len(v))
	for k := range v {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		vs := v[k]
		prefix := url.QueryEscape(k)
		for _, v := range vs {
			if buf.Len() > 0 {
				buf.WriteByte('&')
			}
			buf.WriteString(prefix)
			if v != "" {
				buf.WriteString("=")
				buf.WriteString(url.QueryEscape(v))
			}
		}
	}
	return buf.String()
}
Exemple #5
0
// write2d prints the 2d matrix m into the buffer.
// value is a slice of already-printed values.
// The receiver provides only the shape of the matrix.
func (m Matrix) write2d(b *bytes.Buffer, value []string, width int) {
	nrows := int(m.shape[0].(Int))
	ncols := int(m.shape[1].(Int))
	for row := 0; row < nrows; row++ {
		if row > 0 {
			b.WriteByte('\n')
		}
		index := row * ncols
		for col := 0; col < ncols; col++ {
			if col > 0 {
				b.WriteByte(' ')
			}
			s := value[index]
			pad := width - len(s)
			for ; pad >= 10; pad -= 10 {
				b.WriteString("          ")
			}
			for ; pad > 0; pad-- {
				b.WriteString(" ")
			}
			b.WriteString(s)
			index++
		}
	}
}
Exemple #6
0
/**
 * Escape string
 */
func (mysql *MySQL) Escape(str string) (esc string) {
	if mysql.Logging {
		log.Print("Escape called")
	}

	var prev byte
	var b bytes.Buffer

	for i := 0; i < len(str); i++ {
		switch str[i] {
		case '\'', '"':
			if prev != '\\' {
				b.WriteString(str[:i])
				b.WriteByte('\\')
				str = str[i:]
				i = 0
			}
		}

		prev = str[i]
	}

	b.WriteString(str)
	return b.String()
}
Exemple #7
0
func readSlidesDat() (slides []string, err error) {
	f, err := os.Open("slides.dat")
	if err != nil {
		return
	}
	defer f.Close()
	var buf bytes.Buffer
	flush := func() {
		s := strings.TrimSpace(buf.String())
		if s != "" {
			slides = append(slides, s+"\n")
		}
		buf.Reset()
	}
	bs := bufio.NewScanner(f)
	for bs.Scan() {
		if bs.Text() == "--" {
			flush()
			continue
		}
		buf.WriteString(bs.Text())
		buf.WriteByte('\n')
	}
	flush()
	return slides, bs.Err()
}
Exemple #8
0
func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {

	b.WriteString(key)
	b.WriteByte('=')

	switch value := value.(type) {
	case string:
		if needsQuoting(value) {
			b.WriteString(value)
		} else {
			fmt.Fprintf(b, "%q", value)
		}
	case error:
		errmsg := value.Error()
		if needsQuoting(errmsg) {
			b.WriteString(errmsg)
		} else {
			fmt.Fprintf(b, "%q", value)
		}
	default:
		fmt.Fprint(b, value)
	}

	b.WriteByte(' ')
}
Exemple #9
0
func binExprFmtWithParen(buf *bytes.Buffer, f FmtFlags, e1 Expr, op string, e2 Expr) {
	exprFmtWithParen(buf, f, e1)
	buf.WriteByte(' ')
	buf.WriteString(op)
	buf.WriteByte(' ')
	exprFmtWithParen(buf, f, e2)
}
Exemple #10
0
func attrEscapeInCode(r Renderer, out *bytes.Buffer, src []byte) {
	var prev byte
	j := 0
	for i := 0; i < len(src); i++ {
		ch := src[i]
		if ch == '<' && prev != '\\' {
			if x := leftAngleCode(src[i:]); x > 0 {
				j++
				// Call the renderer's CalloutCode
				r.CalloutCode(out, strconv.Itoa(j), string(src[i:i+x+1]))
				i += x
				prev = ch
				continue
			}
		}
		if ch == '\\' && i < len(src)-1 && src[i+1] == '<' {
			// skip \\ here
			prev = ch
			continue
		}
		if entity, ok := escapeSingleChar(ch); ok {
			out.WriteString(entity)
			prev = ch
			continue
		}
		out.WriteByte(ch)
		prev = ch
	}
}
Exemple #11
0
func (options *html) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte, subfigure bool) {
	if options.flags&HTML_SKIP_IMAGES != 0 {
		return
	}
	s := options.inlineAttr().String()
	if subfigure {
		s += " role=\"group\""
	}
	out.WriteString("<figure" + s + ">")
	out.WriteString("<img src=\"")
	options.maybeWriteAbsolutePrefix(out, link)
	attrEscape(out, link)
	out.WriteString("\" alt=\"")
	if len(alt) > 0 {
		attrEscape(out, alt)
	}
	if len(title) > 0 {
		out.WriteString("\" title=\"")
		attrEscape(out, title)
	}
	out.WriteByte('"')
	out.WriteString(options.closeTag)
	if len(title) > 0 {
		out.WriteString("<figcaption>")
		out.Write(title)
		out.WriteString("</figcaption>")
	}
	out.WriteString("</figure>")
	return
}
func (h FrameHeader) String() string {
	var buf bytes.Buffer
	buf.WriteString("[FrameHeader ")
	buf.WriteString(h.Type.String())
	if h.Flags != 0 {
		buf.WriteString(" flags=")
		set := 0
		for i := uint8(0); i < 8; i++ {
			if h.Flags&(1<<i) == 0 {
				continue
			}
			set++
			if set > 1 {
				buf.WriteByte('|')
			}
			name := flagName[h.Type][Flags(1<<i)]
			if name != "" {
				buf.WriteString(name)
			} else {
				fmt.Fprintf(&buf, "0x%x", 1<<i)
			}
		}
	}
	if h.StreamID != 0 {
		fmt.Fprintf(&buf, " stream=%d", h.StreamID)
	}
	fmt.Fprintf(&buf, " len=%d]", h.Length)
	return buf.String()
}
Exemple #13
0
func writeParam(buf *bytes.Buffer, key, value string) {
	buf.Write([]byte("; "))
	buf.WriteString(key)
	buf.Write([]byte(`="`))
	buf.WriteString(value)
	buf.WriteByte('"')
}
Exemple #14
0
func (c *ConnectPacket) Write(w io.Writer) error {
	var body bytes.Buffer
	var err error

	body.Write(encodeString(c.ProtocolName))
	body.WriteByte(c.ProtocolVersion)
	body.WriteByte(boolToByte(c.CleanSession)<<1 | boolToByte(c.WillFlag)<<2 | c.WillQos<<3 | boolToByte(c.WillRetain)<<5 | boolToByte(c.PasswordFlag)<<6 | boolToByte(c.UsernameFlag)<<7)
	body.Write(encodeUint16(c.KeepaliveTimer))
	body.Write(encodeString(c.ClientIdentifier))
	if c.WillFlag {
		body.Write(encodeString(c.WillTopic))
		body.Write(encodeBytes(c.WillMessage))
	}
	if c.UsernameFlag {
		body.Write(encodeString(c.Username))
	}
	if c.PasswordFlag {
		body.Write(encodeBytes(c.Password))
	}
	c.FixedHeader.RemainingLength = body.Len()
	packet := c.FixedHeader.pack()
	packet.Write(body.Bytes())
	_, err = packet.WriteTo(w)

	return err
}
func TestBMP180DriverMeasurements(t *testing.T) {
	bmp180, adaptor := initTestBMP180DriverWithStubbedAdaptor()
	adaptor.i2cReadImpl = func() ([]byte, error) {
		buf := new(bytes.Buffer)
		// Values from the datasheet example.
		if adaptor.written[len(adaptor.written)-1] == bmp180RegisterAC1MSB {
			binary.Write(buf, binary.BigEndian, int16(408))
			binary.Write(buf, binary.BigEndian, int16(-72))
			binary.Write(buf, binary.BigEndian, int16(-14383))
			binary.Write(buf, binary.BigEndian, uint16(32741))
			binary.Write(buf, binary.BigEndian, uint16(32757))
			binary.Write(buf, binary.BigEndian, uint16(23153))
			binary.Write(buf, binary.BigEndian, int16(6190))
			binary.Write(buf, binary.BigEndian, int16(4))
			binary.Write(buf, binary.BigEndian, int16(-32768))
			binary.Write(buf, binary.BigEndian, int16(-8711))
			binary.Write(buf, binary.BigEndian, int16(2868))
		} else if adaptor.written[len(adaptor.written)-2] == bmp180CmdTemp && adaptor.written[len(adaptor.written)-1] == bmp180RegisterTempMSB {
			binary.Write(buf, binary.BigEndian, int16(27898))
		} else if adaptor.written[len(adaptor.written)-2] == bmp180CmdPressure && adaptor.written[len(adaptor.written)-1] == bmp180RegisterPressureMSB {
			binary.Write(buf, binary.BigEndian, int16(23843))
			// XLSB, not used in this test.
			buf.WriteByte(0)
		}
		return buf.Bytes(), nil
	}
	bmp180.Start()
	temp, err := bmp180.Temperature()
	gobottest.Assert(t, err, nil)
	gobottest.Assert(t, temp, float32(15.0))
	pressure, err := bmp180.Pressure(BMP180UltraLowPower)
	gobottest.Assert(t, err, nil)
	gobottest.Assert(t, pressure, float32(69964))
}
Exemple #16
0
// Format implements the NodeFormatter interface.
func (node *NullIfExpr) Format(buf *bytes.Buffer, f FmtFlags) {
	buf.WriteString("NULLIF(")
	FormatNode(buf, f, node.Expr1)
	buf.WriteString(", ")
	FormatNode(buf, f, node.Expr2)
	buf.WriteByte(')')
}
func wrap(text string, length int) string {
	var buf bytes.Buffer
	var last rune
	var lastNL bool
	var col int

	for _, c := range text {
		switch c {
		case '\r': // ignore this
			continue // and also don't track `last`
		case '\n': // ignore this too, but reset col
			if col >= length || last == '\n' {
				buf.WriteString("\n\n")
			}
			col = 0
		case ' ', '\t': // opportunity to split
			if col >= length {
				buf.WriteByte('\n')
				col = 0
			} else {
				if !lastNL {
					buf.WriteRune(c)
				}
				col++ // count column
			}
		default:
			buf.WriteRune(c)
			col++
		}
		lastNL = c == '\n'
		last = c
	}
	return buf.String()
}
func Decompress(dat []byte) ([]byte, error) {
	buf := new(bytes.Buffer)

	for i := 0; i < len(dat); i++ {
		if dat[i] == token {
			if i+1 < len(dat) {
				switch dat[i+1] {
				case emptyShaToken:
					buf.Write(empty)
				case emptyListShaToken:
					buf.Write(emptyList)
				case tokenToken:
					buf.WriteByte(token)
				default:
					buf.Write(make([]byte, int(dat[i+1]-2)))
				}
				i++
			} else {
				return nil, errors.New("error reading bytes. token encountered without proceeding bytes")
			}
		} else {
			buf.WriteByte(dat[i])
		}
	}

	return buf.Bytes(), nil
}
func randomString(r *rand.Rand, n int) []byte {
	b := new(bytes.Buffer)
	for i := 0; i < n; i++ {
		b.WriteByte(' ' + byte(r.Intn(95)))
	}
	return b.Bytes()
}
Exemple #20
0
func (d *WordDecoder) convert(buf *bytes.Buffer, charset string, content []byte) error {
	switch {
	case strings.EqualFold("utf-8", charset):
		buf.Write(content)
	case strings.EqualFold("iso-8859-1", charset):
		for _, c := range content {
			buf.WriteRune(rune(c))
		}
	case strings.EqualFold("us-ascii", charset):
		for _, c := range content {
			if c >= utf8.RuneSelf {
				buf.WriteRune(unicode.ReplacementChar)
			} else {
				buf.WriteByte(c)
			}
		}
	default:
		if d.CharsetReader == nil {
			return fmt.Errorf("mime: unhandled charset %q", charset)
		}
		r, err := d.CharsetReader(strings.ToLower(charset), bytes.NewReader(content))
		if err != nil {
			return err
		}
		if _, err = buf.ReadFrom(r); err != nil {
			return err
		}
	}
	return nil
}
Exemple #21
0
func (w *Walker) funcSigString(ft *ast.FuncType) string {
	var b bytes.Buffer
	b.WriteByte('(')
	if ft.Params != nil {
		for i, f := range ft.Params.List {
			if i > 0 {
				b.WriteString(", ")
			}
			b.WriteString(w.nodeString(w.namelessType(f.Type)))
		}
	}
	b.WriteByte(')')
	if ft.Results != nil {
		if nr := len(ft.Results.List); nr > 0 {
			b.WriteByte(' ')
			if nr > 1 {
				b.WriteByte('(')
			}
			for i, f := range ft.Results.List {
				if i > 0 {
					b.WriteString(", ")
				}
				b.WriteString(w.nodeString(w.namelessType(f.Type)))
			}
			if nr > 1 {
				b.WriteByte(')')
			}
		}
	}
	return b.String()
}
Exemple #22
0
// TODO gocui doesn't support color text:
// https://github.com/jroimartin/gocui/issues/9
func (f *GuiFormatter) Format(entry *log.Entry) ([]byte, error) {
	buf := new(bytes.Buffer)

	ts := entry.Time.Format("15:04:05")

	fmt.Fprintf(buf, "%s %s | ", ts, entry.Level.String())

	call, hasCall := entry.Data["call"].(string)
	if hasCall {
		fmt.Fprintf(buf, "%s ", call)
	}
	if entry.Message != "" {
		fmt.Fprintf(buf, "%s ", entry.Message)
	}

	for _, k := range []string{"call"} {
		delete(entry.Data, k)
	}

	if len(entry.Data) > 0 {
		fmt.Fprint(buf, "| ")
		writeMap(buf, entry.Data)
	}

	buf.WriteByte('\n')
	return buf.Bytes(), nil
}
Exemple #23
0
func newline(dst *bytes.Buffer, prefix, indent string, depth int) {
	dst.WriteByte('\n')
	dst.WriteString(prefix)
	for i := 0; i < depth; i++ {
		dst.WriteString(indent)
	}
}
Exemple #24
0
func twoDigits(b *bytes.Buffer, d int) {
	c2 := digits[d%10]
	d /= 10
	c1 := digits[d%10]
	b.WriteByte(c1)
	b.WriteByte(c2)
}
Exemple #25
0
// decorate prefixes the string with the file and line of the call site
// and inserts the final newline if needed and indentation tabs for formatting.
func decorate(s string) string {
	_, file, line, ok := runtime.Caller(3) // decorate + log + public function.
	if ok {
		// Truncate file name at last file name separator.
		if index := strings.LastIndex(file, "/"); index >= 0 {
			file = file[index+1:]
		} else if index = strings.LastIndex(file, "\\"); index >= 0 {
			file = file[index+1:]
		}
	} else {
		file = "???"
		line = 1
	}
	buf := new(bytes.Buffer)
	// Every line is indented at least one tab.
	buf.WriteByte('\t')
	fmt.Fprintf(buf, "%s:%d: ", file, line)
	lines := strings.Split(s, "\n")
	if l := len(lines); l > 1 && lines[l-1] == "" {
		lines = lines[:l-1]
	}
	for i, line := range lines {
		if i > 0 {
			// Second and subsequent lines are indented an extra tab.
			buf.WriteString("\n\t\t")
		}
		buf.WriteString(line)
	}
	buf.WriteByte('\n')
	return buf.String()
}
Exemple #26
0
// tracef is like fmt.Printf but it rewrites the format string
// to take care of indentation.
func (p *exporter) tracef(format string, args ...interface{}) {
	if strings.IndexAny(format, "<>\n") >= 0 {
		var buf bytes.Buffer
		for i := 0; i < len(format); i++ {
			// no need to deal with runes
			ch := format[i]
			switch ch {
			case '>':
				p.indent++
				continue
			case '<':
				p.indent--
				continue
			}
			buf.WriteByte(ch)
			if ch == '\n' {
				for j := p.indent; j > 0; j-- {
					buf.WriteString(".  ")
				}
			}
		}
		format = buf.String()
	}
	fmt.Printf(format, args...)
}
Exemple #27
0
// String reassembles the URL into a valid URL string.
func (u *URL) String() string {
	var buf bytes.Buffer
	if u.Scheme != "" {
		buf.WriteString(u.Scheme)
		buf.WriteByte(':')
	}
	if u.Opaque != "" {
		buf.WriteString(u.Opaque)
	} else {
		if u.Scheme != "" || u.Host != "" || u.User != nil {
			buf.WriteString("//")
			if ui := u.User; ui != nil {
				buf.WriteString(ui.String())
				buf.WriteByte('@')
			}
			if h := u.Host; h != "" {
				buf.WriteString(h)
			}
		}
		if u.Path != "" && u.Path[0] != '/' && u.Host != "" {
			buf.WriteByte('/')
		}
		buf.WriteString(escape(u.Path, encodePath))
	}
	if u.RawQuery != "" {
		buf.WriteByte('?')
		buf.WriteString(u.RawQuery)
	}
	if u.Fragment != "" {
		buf.WriteByte('#')
		buf.WriteString(escape(u.Fragment, encodeFragment))
	}
	return buf.String()
}
Exemple #28
0
func buildCallerPrefix(file string, line int, s string) string {
	buf := new(bytes.Buffer)
	// Every line is indented at least one tab.
	err := buf.WriteByte('\t')
	if err != nil {
		return "???:1"
	}
	fmt.Fprintf(buf, "%s:%d: ", file, line)
	lines := strings.Split(s, "\n")
	if l := len(lines); l > 1 && lines[l-1] == "" {
		lines = lines[:l-1]
	}
	for i, l := range lines {
		if i > 0 {
			// Second and subsequent lines are indented an extra tab.
			_, err = buf.WriteString("\n\t\t")
			if err != nil {
				return "???:1"
			}
		}
		_, err = buf.WriteString(l)
		if err != nil {
			return "???:1"
		}
	}
	err = buf.WriteByte('\n')
	if err != nil {
		return "???:1"
	}
	return buf.String()
}
Exemple #29
0
func (options *Html) BlockCode(out *bytes.Buffer, text []byte, lang string) {
	doubleSpace(out)

	// parse out the language names/classes
	count := 0
	for _, elt := range strings.Fields(lang) {
		if elt[0] == '.' {
			elt = elt[1:]
		}
		if len(elt) == 0 {
			continue
		}
		if count == 0 {
			out.WriteString("<pre><code class=\"language-")
		} else {
			out.WriteByte(' ')
		}
		attrEscape(out, []byte(elt))
		count++
	}

	if count == 0 {
		out.WriteString("<pre><code>")
	} else {
		out.WriteString("\">")
	}

	attrEscape(out, text)
	out.WriteString("</code></pre>\n")
}
Exemple #30
0
func exactInvertedPrefix(val []byte) []byte {
	var buf bytes.Buffer
	buf.Grow(len(val) + 1)
	buf.Write(val)
	buf.WriteByte(invertedKeySep)
	return buf.Bytes()
}