// bigIntToNetIPv6 is a helper function that correctly returns a net.IP with the // correctly padded values. func bigIntToNetIPv6(bi *big.Int) *net.IP { x := make(net.IP, IPv6len) ipv6Bytes := bi.Bytes() // It's possibe for ipv6Bytes to be less than IPv6len bytes in size. If // they are different sizes we to pad the size of response. if len(ipv6Bytes) < IPv6len { buf := new(bytes.Buffer) buf.Grow(IPv6len) for i := len(ipv6Bytes); i < IPv6len; i++ { if err := binary.Write(buf, binary.BigEndian, byte(0)); err != nil { panic(fmt.Sprintf("Unable to pad byte %d of input %v: %v", i, bi, err)) } } for _, b := range ipv6Bytes { if err := binary.Write(buf, binary.BigEndian, b); err != nil { panic(fmt.Sprintf("Unable to preserve endianness of input %v: %v", bi, err)) } } ipv6Bytes = buf.Bytes() } i := copy(x, ipv6Bytes) if i != IPv6len { panic("IPv6 wrong size") } return &x }
func quoteTo(buf *bytes.Buffer, s string) { buf.Grow(2 + len(s)) buf.WriteByte('"') for i, c := range s { switch { case unicode.IsControl(c): if s, ok := ctrlMap[c]; ok { buf.WriteString(s) } else { fmt.Fprintf(buf, "\\u%04x", c) } case c == '"', c == '\\', c == '\'': buf.WriteByte('\\') buf.WriteRune(c) case c <= unicode.MaxASCII: buf.WriteRune(c) case c == unicode.ReplacementChar: // In correctly-encoded UTF-8, we should never see a replacement // char. Some text in the wild has valid Unicode characters that // aren't UTF-8, and this case lets us be more forgiving of those. fmt.Fprintf(buf, "\\u%04x", s[i]) case c <= 0xffff: fmt.Fprintf(buf, "\\u%04x", c) default: fmt.Fprintf(buf, "\\U%08x", c) } } buf.WriteByte('"') }
func newRegex(p position, txt string, c *CommentNode) (*RegexNode, error) { // Remove leading and trailing quotes literal := txt[1 : len(txt)-1] // Unescape slashes '/' var buf bytes.Buffer buf.Grow(len(literal)) last := 0 for i := 0; i < len(literal)-1; i++ { if literal[i] == '\\' && literal[i+1] == '/' { buf.Write([]byte(literal[last:i])) i++ last = i } } buf.Write([]byte(literal[last:])) unescaped := buf.String() r, err := regexp.Compile(unescaped) if err != nil { return nil, err } return &RegexNode{ position: p, Regex: r, Literal: literal, Comment: c, }, nil }
func newString(p position, txt string, c *CommentNode) *StringNode { tripleQuotes := false // Remove leading and trailing quotes var literal string if len(txt) >= 6 && txt[0:3] == "'''" { literal = txt[3 : len(txt)-3] tripleQuotes = true } else { literal = txt[1 : len(txt)-1] quote := txt[0] // Unescape quotes var buf bytes.Buffer buf.Grow(len(literal)) last := 0 for i := 0; i < len(literal)-1; i++ { if literal[i] == '\\' && literal[i+1] == quote { buf.Write([]byte(literal[last:i])) i++ last = i } } buf.Write([]byte(literal[last:])) literal = buf.String() } return &StringNode{ position: p, Literal: literal, TripleQuotes: tripleQuotes, Comment: c, } }
// Bytes returns a slice of bytes representing an StartGameMessage // which can be sent through a connection func (ms *StartGameMessage) Bytes() []byte { var buf bytes.Buffer buf.Grow(10) buf.WriteByte(byte(ms.MessageType)) if ms.YourSide { buf.WriteByte(255) } else { buf.WriteByte(0) } twoByte := make([]byte, 2) binary.LittleEndian.PutUint16(twoByte, ms.YourPosition) buf.Write(twoByte) binary.LittleEndian.PutUint16(twoByte, ms.OtherPosition) buf.Write(twoByte) binary.LittleEndian.PutUint16(twoByte, ms.Ballx) buf.Write(twoByte) binary.LittleEndian.PutUint16(twoByte, ms.Bally) buf.Write(twoByte) buf.WriteString(ms.OtherAlias) buf.WriteByte(NullTerm) buf.WriteString(ms.GameID) buf.WriteByte(NullTerm) buf.WriteString(ms.GameName) buf.WriteByte(NullTerm) return buf.Bytes() }
func benchmarkWriter(b *testing.B, size int64) { b.SetBytes(size) expectedSize := int(size) + 2 if size+1 >= 0xff { expectedSize += 8 } var buf bytes.Buffer buf.Grow(expectedSize) w := newWriter(&buf) p := make([]byte, size) msg := newByteMessage([][]byte{p}) b.ResetTimer() for i := 0; i < b.N; i++ { buf.Reset() msg.rewind() if err := w.Write(msg); err != nil { b.Fatal(err) } else if buf.Len() != expectedSize { b.Fatal("size") } } }
func formatQuoted(text []byte) []byte { if bytes.Equal(text, noOutputOld) { return noOutputNew } nonZero := bytes.HasSuffix(text, nonZeroOld) if nonZero { text = text[:len(text)-len(nonZeroOld)] } var buf bytes.Buffer buf.Grow(512) fmt.Fprintf(&buf, "%q", text) if buf.Len() > maxTextLen { truncateMaxLen(&buf, 1) buf.Truncate(len(bytes.TrimRight(buf.Bytes(), "\\"))) buf.WriteString(`" + `) buf.WriteString(more) } if nonZero { buf.WriteString(split) buf.WriteString(nonZeroNew) } return buf.Bytes() }
func EncodePayload(pkts []*Packet, supportsBinary bool, callback EncodeCallback) { if supportsBinary { EncodePayloadAsBinary(pkts, callback) return } if len(pkts) == 0 { callback([]byte("0:")) return } buf := new(bytes.Buffer) estLen := 0 for _, pkt := range pkts { // sample encoded: 102:bxmessage // message is in base 64 estLen += 6 + len(pkt.Data)*2 } buf.Grow(estLen) for _, pkt := range pkts { EncodePacket(pkt, supportsBinary, func(data []byte) { buf.Write([]byte(strconv.FormatInt(int64(len(data)), 10))) buf.WriteByte(':') buf.Write(data) }) } callback(buf.Next(buf.Len())) }
func newString(p int, txt string) *StringNode { // Remove leading and trailing quotes var literal string if len(txt) >= 6 && txt[0:3] == "'''" { literal = txt[3 : len(txt)-3] } else { literal = txt[1 : len(txt)-1] quote := txt[0] // Unescape quotes var buf bytes.Buffer buf.Grow(len(literal)) last := 0 for i := 0; i < len(literal)-1; i++ { if literal[i] == '\\' && literal[i+1] == quote { buf.Write([]byte(literal[last:i])) i++ last = i } } buf.Write([]byte(literal[last:])) literal = buf.String() } return &StringNode{ pos: pos(p), Literal: literal, } }
func (g *grid) String() string { var buf bytes.Buffer // Don't really need to call Grow but it helps avoid multiple // reallocations if the size is large. buf.Grow((len(g.cell) + 2) * (len(g.cell[0]) + 3)) buf.WriteByte('+') for _ = range g.cell[0] { buf.WriteByte('-') } buf.WriteString("+\n") for y := range g.cell { buf.WriteByte('|') buf.Write(g.cell[y]) buf.WriteString("|\n") } buf.WriteByte('+') ly := len(g.cell) - 1 for x := range g.cell[ly] { if g.cell[ly][x] == used { buf.WriteByte(used) } else { buf.WriteByte('-') } } buf.WriteByte('+') return buf.String() }
// Port of php_escape_shell_arg // See https://github.com/php/php-src/blob/master/ext/standard/exec.c func escapeShellArg(arg string) string { var quotedArg bytes.Buffer quotedArg.Grow(len(arg)) if runtime.GOOS == "windows" { quotedArg.WriteString(`"`) } else { quotedArg.WriteString(`'`) } for _, runeVal := range arg { if runtime.GOOS == "windows" { if runeVal == '"' || runeVal == '%' { quotedArg.WriteRune(' ') continue } } else { if runeVal == '\'' { quotedArg.WriteString(`'\'`) } } quotedArg.WriteRune(runeVal) } if runtime.GOOS == "windows" { quotedArg.WriteString(`"`) } else { quotedArg.WriteString(`'`) } return quotedArg.String() }
func (p *ldapPlugin) formatEntries(results []ldap.Result) string { var buf bytes.Buffer buf.Grow(250) sizehint := 200 i := 0 for i < len(results) { result := &results[i] cn := result.Value("cn") nick := result.Value("mozillaNickname") maxsize := len(nick) + len(cn) + 6 if maxsize > sizehint && i+1 < len(results) { break } if i > 0 { buf.WriteString(", ") } if nick != "" { buf.WriteString(nick) buf.WriteString(" is ") buf.WriteString(cn) sizehint -= maxsize } else { buf.WriteString(cn) sizehint -= len(cn) } i++ } if i < len(results) { buf.WriteString(fmt.Sprintf(", plus %d more people.", len(results)-i)) } return buf.String() }
func (p *ldapPlugin) formatEntry(result *ldap.Result) string { var buf bytes.Buffer buf.Grow(250) cn := result.Value("cn") nick := result.Value("mozillaNickname") if nick != "" { buf.WriteString(nick) buf.WriteString(" is ") buf.WriteString(cn) } else { buf.WriteString(cn) } for _, item := range ldapFormat { for _, value := range result.Values(item.attr) { if value == "" { continue } if item.filter != nil { value = item.filter(value) } buf.WriteByte(' ') buf.WriteString(fmt.Sprintf(item.format, value)) } } return buf.String() }
func encodeV1(data []byte) []byte { buf := new(bytes.Buffer) buf.Grow(base64.StdEncoding.EncodedLen(len(data) + 1)) enc := base64.NewEncoder(base64.StdEncoding, buf) enc.Write(v1Header) enc.Write(data) enc.Close() flat := buf.Bytes() flatSize := len(flat) buf = new(bytes.Buffer) buf.Grow(flatSize + flatSize/maxEncodeLineLength + 1) off := 0 for { endOff := off + maxEncodeLineLength if endOff > flatSize { endOff = flatSize } buf.Write(flat[off:endOff]) off = endOff if off >= flatSize { break } buf.WriteByte('\n') } return buf.Bytes() }
// DecodeBinary decodes the given key-encoded byte slice, // returning the original BLOB value. (see documentation // for EncodeBinary for more details). func DecodeBinary(buf []byte) []byte { if buf[0] != orderedEncodingBinary { panic("doesn't begin with binary encoding byte") } var end int // Will panic if the terminator doesn't occur before end of the byte slice. for end = 1; (buf[end] & 0x80) != orderedEncodingTerminator; end++ { } end++ out := new(bytes.Buffer) out.Grow(end) s := uint(6) t := (buf[1] << 1) & 0xff for i := 2; i < end; i++ { if s == 7 { out.WriteByte(t | (buf[i] & 0x7f)) i++ } else { out.WriteByte(t | ((buf[i] & 0x7f) >> s)) } if i == end { break } t = (buf[i] << (8 - s)) & 0xff if s == 1 { s = 7 } else { s-- } } if t != 0 { panic("unexpected bits remaining after decoding blob") } return out.Bytes() }
func EncodePayloadAsBinary(pkts []*Packet, callback EncodeCallback) { if len(pkts) == 0 { callback([]byte{}) } buf := new(bytes.Buffer) estLen := 0 for _, pkt := range pkts { // Estimated length of buffer // 1(binary indicator) + 4(length bytes) + 1(255) + len(pkt.Data) estLen += 6 + len(pkt.Data) } buf.Grow(estLen) for _, pkt := range pkts { EncodePacket(pkt, true, func(data []byte) { buf.WriteByte(1) length := len(data) bitsBuf := make([]byte, 10) bits := 0 for length > 0 { bitsBuf[bits] = byte(length % 10) bits++ length = length / 10 } for i := bits - 1; i >= 0; i-- { buf.WriteByte(bitsBuf[i]) } buf.WriteByte(255) buf.Write(data) }) } callback(buf.Next(buf.Len())) }
func newRegex(p int, txt string) (*RegexNode, error) { // Remove leading and trailing quotes literal := txt[1 : len(txt)-1] // Unescape slashes '/' var buf bytes.Buffer buf.Grow(len(literal)) last := 0 for i := 0; i < len(literal)-1; i++ { if literal[i] == '\\' && literal[i+1] == '/' { buf.Write([]byte(literal[last:i])) i++ last = i } } buf.Write([]byte(literal[last:])) literal = buf.String() r, err := regexp.Compile(literal) if err != nil { return nil, err } return &RegexNode{ pos: pos(p), Regex: r, }, nil }
// StripColors returns a string by removing color-coding characters from the supplied string func StripColors(s string) string { var buf bytes.Buffer buf.Grow(len(s)) for i := 0; i < len(s); i++ { // Skip Color Code if s[i] == 0x1b { for i < len(s) && s[i] != 'm' { i++ } if i == len(s) { break } } // Add Byte if s[i] != 'm' { buf.WriteByte(s[i]) } } return buf.String() }
// readBlockHeader reads the block header. func readBlockHeader(r io.Reader) (h *blockHeader, n int, err error) { var buf bytes.Buffer buf.Grow(20) // block header size z, err := io.CopyN(&buf, r, 1) n = int(z) if err != nil { return nil, n, err } s := buf.Bytes()[0] if s == 0 { return nil, n, errIndexIndicator } // read complete header headerLen := (int(s) + 1) * 4 buf.Grow(headerLen - 1) z, err = io.CopyN(&buf, r, int64(headerLen-1)) n += int(z) if err != nil { return nil, n, err } // unmarshal block header h = new(blockHeader) if err = h.UnmarshalBinary(buf.Bytes()); err != nil { return nil, n, err } return h, n, nil }
func TestWriterBasics(t *testing.T) { b := new(bytes.Buffer) b.Grow(len(testCommon)) w := NewWriter(b) debian := &fileInfo{ name: "debian-binary", mtime: time.Unix(1385068169, 0), mode: os.FileMode(0100644) & os.ModePerm, size: 4, } if _, err := w.WriteFile(debian, strings.NewReader("2.0\n")); err != nil { t.Error(err) return } control := &fileInfo{ name: "control.tar.gz", mtime: time.Unix(1385068169, 0), mode: os.FileMode(0100644) & os.ModePerm, size: 0, } if _, err := w.WriteFile(control, strings.NewReader("")); err != nil { t.Error(err) return } if archive := b.String(); archive != testCommon { t.Errorf("got\n%q\nwant\n%q", archive, testCommon) } }
func handleRequestBody(r *http.Request, ctx *remote.ConnContext) ([]event.Event, error) { var rbuf bytes.Buffer var evs []event.Event var body io.Reader body = r.Body // if r.ContentLength <= 0 { // body = httputil.NewChunkedReader(body) // } reader := &helper.BufferChunkReader{body, nil} defer r.Body.Close() for { rbuf.Grow(8192) rbuf.ReadFrom(reader) ress, err := remote.HandleRequestBuffer(&rbuf, ctx) if nil != err { if err != event.EBNR { log.Printf("[ERROR]connection %s:%d error:%v", ctx.User, ctx.ConnIndex, err) return nil, err } } else { if len(ress) > 0 { evs = append(evs, ress...) } } if nil != reader.Err { break } } return evs, nil }
func (g *grid) String() string { var buf bytes.Buffer // Don't really need to call Grow but it helps avoid multiple // reallocations if the size is large. buf.Grow((len(g.cell) + 1) * len(g.cell[0]) * 7) for _ = range g.cell[0] { buf.WriteString("+") buf.WriteString(hopen[false]) } buf.WriteString("+\n") for y := range g.cell { buf.WriteString(vopen[false]) for x := range g.cell[y] { buf.WriteString(full[g.cell[y][x].full]) buf.WriteString(vopen[g.cell[y][x].right]) } buf.WriteByte('\n') for x := range g.cell[y] { buf.WriteString("+") buf.WriteString(hopen[g.cell[y][x].down]) } buf.WriteString("+\n") } ly := len(g.cell) - 1 for x := range g.cell[ly] { buf.WriteByte(' ') buf.WriteString(full[g.cell[ly][x].down && g.cell[ly][x].full]) } return buf.String() }
func benchmarkReader(b *testing.B, size int64) { b.SetBytes(size) sp := make([]byte, size+8) binary.BigEndian.PutUint64(sp[:], uint64(size)) spr := bytes.NewReader(sp) r := newReader(spr) var buf bytes.Buffer buf.Grow(int(size)) b.ResetTimer() for i := 0; i < b.N; i++ { spr.Seek(0, 0) buf.Reset() if msg, err := r.Read(); err != nil { b.Fatal(err) } else { frame, err := msg.Next() if err != nil { b.Fatal(err) } else if n, err := io.Copy(&buf, frame); err != nil { b.Fatal(err) } else if n != size { b.Fatal("size") } if msg.More() { b.Fatal("more") } } } }
func ReplaceVariableShorthands(text string, chr byte, name string) string { repl := fmt.Sprintf("$%s.", name) var buf bytes.Buffer buf.Grow(len(text)) cmd := false quoted := false runes := []rune(text) for ii, v := range runes { if byte(v) == chr && cmd && !quoted { buf.WriteString(repl) continue } if cmd && v == '}' { cmd = ii < len(runes)-1 && runes[ii+1] != '}' } else if !cmd && v == '{' { cmd = ii < len(runes)-1 && runes[ii+1] == '{' } if cmd { if v == '"' && (ii == 0 || runes[ii-1] != '\\') { quoted = !quoted } } buf.WriteRune(v) } return buf.String() }
// SerializeSCTList serializes the passed-in slice of SignedCertificateTimestamp into a // byte slice as a SignedCertificateTimestampList (see RFC6962 Section 3.3) func SerializeSCTList(scts []SignedCertificateTimestamp) ([]byte, error) { size, err := SCTListSerializedLength(scts) if err != nil { return nil, err } fullSize := 2 + size // 2 bytes for length + size of SCT list if fullSize > MaxSCTListLength { return nil, fmt.Errorf("SCT List too large to serialize: %d", fullSize) } buf := new(bytes.Buffer) buf.Grow(fullSize) if err = writeUint(buf, uint64(size), 2); err != nil { return nil, err } for _, sct := range scts { serialized, err := SerializeSCT(sct) if err != nil { return nil, err } if err = writeVarBytes(buf, serialized, 2); err != nil { return nil, err } } return asn1.Marshal(buf.Bytes()) // transform to Octet String }
func exactInvertedPrefix(val []byte) []byte { var buf bytes.Buffer buf.Grow(len(val) + 1) buf.Write(val) buf.WriteByte(invertedKeySep) return buf.Bytes() }
// Seal encrypts and authenticates plaintext, authenticates the // additional data and appends the result to dst, returning the updated // slice. opensslGCM supports any nonce size. func (be opensslGCM) Seal(dst, nonce, plaintext, data []byte) []byte { // Preallocate output buffer var cipherBuf bytes.Buffer cipherBuf.Grow(len(dst) + len(plaintext) + AUTH_TAG_LEN) // Output will be appended to dst cipherBuf.Write(dst) ectx, err := openssl.NewGCMEncryptionCipherCtx(KEY_LEN*8, nil, be.key, nonce) if err != nil { panic(err) } err = ectx.ExtraData(data) if err != nil { panic(err) } part, err := ectx.EncryptUpdate(plaintext) if err != nil { panic(err) } cipherBuf.Write(part) part, err = ectx.EncryptFinal() if err != nil { panic(err) } cipherBuf.Write(part) part, err = ectx.GetTag() if err != nil { panic(err) } cipherBuf.Write(part) return cipherBuf.Bytes() }
func (p *lpPlugin) formatNotes(bug *lpBug, tasks *lpBugTasks) string { var buf bytes.Buffer buf.Grow(256) for _, tag := range bug.Tags { buf.WriteString(" <") buf.WriteString(tag) buf.WriteString(">") } for _, entry := range tasks.Entries { buf.WriteString(" <") buf.WriteString(entry.Target) buf.WriteString(":") buf.WriteString(entry.Status) if i := strings.Index(entry.AssigneeLink, "~"); i > 0 { if entry.Status == "New" || entry.Status == "Confirmed" { buf.WriteString(" for ") } else { buf.WriteString(" by ") } buf.WriteString(entry.AssigneeLink[i+1:]) } buf.WriteString(">") } return buf.String() }
func invertedKey(key, val []byte) []byte { var buf bytes.Buffer buf.Grow(len(val) + 1 + len(key)) buf.Write(val) buf.WriteByte(invertedKeySep) buf.Write(key) return buf.Bytes() }
// MarshalJSON marshals the JSONLog. func (mj *JSONLog) MarshalJSON() ([]byte, error) { var buf bytes.Buffer buf.Grow(1024) if err := mj.MarshalJSONBuf(&buf); err != nil { return nil, err } return buf.Bytes(), nil }