Example #1
0
func ExampleIsPrint() {
	c := strconv.IsPrint('\u263a')
	fmt.Println(c)

	bel := strconv.IsPrint('\007')
	fmt.Println(bel)

	// Output:
	// true
	// false
}
Example #2
0
func appendQuoted(buf []byte, s string) []byte {
	var runeTmp [utf8.UTFMax]byte
	for width := 0; len(s) > 0; s = s[width:] {
		r := rune(s[0])
		width = 1
		if r >= utf8.RuneSelf {
			r, width = utf8.DecodeRuneInString(s)
		}
		if width == 1 && r == utf8.RuneError {
			buf = append(buf, `\x`...)
			buf = append(buf, lowerhex[s[0]>>4])
			buf = append(buf, lowerhex[s[0]&0xF])
			continue
		}
		if r == rune('"') || r == '\\' { // always backslashed
			buf = append(buf, '\\')
			buf = append(buf, byte(r))
			continue
		}
		if strconv.IsPrint(r) {
			n := utf8.EncodeRune(runeTmp[:], r)
			buf = append(buf, runeTmp[:n]...)
			continue
		}
		buf = appendRune(buf, s, r)
	}
	return buf
}
Example #3
0
func (s sliceExpr) ProgString() string {
	var b bytes.Buffer
	// If it's all Char, we can do a prettier job.
	if s.allChars() {
		b.WriteRune('\'')
		for _, v := range s {
			c := rune(v.(value.Char))
			esc := charEscape[c]
			if esc != "" {
				b.WriteString(esc)
				continue
			}
			if !strconv.IsPrint(c) {
				if c <= 0xFFFF {
					fmt.Fprintf(&b, "\\u%04x", c)
				} else {
					fmt.Fprintf(&b, "\\U%08x", c)
				}
				continue
			}
			b.WriteRune(c)
		}
		b.WriteRune('\'')
	} else {
		for i, v := range s {
			if i > 0 {
				b.WriteRune(' ')
			}
			b.WriteString(v.ProgString())
		}
	}
	return b.String()
}
func (this *Handler) HandleRegister(login string, password string) string {
	result := map[string]string{"result": "ok"}
	salt := time.Now().Unix()
	fmt.Println("register salt: ", salt)
	hash := GetMD5Hash(password + strconv.Itoa(int(salt)))
	passHasInvalidChars := false
	for i := 0; i < len(password); i++ {
		if strconv.IsPrint(rune(password[i])) == false {
			passHasInvalidChars = true
			break
		}
	}
	isExist, _, _, _ := IsExist(login)
	if isExist == true {
		result["result"] = "loginExists"
	} else if !MatchRegexp("^[a-zA-Z0-9]{2,36}$", login) {
		result["result"] = "badLogin"
	} else if !MatchRegexp("^.{6,36}$", password) && !passHasInvalidChars {
		result["result"] = "badPassword"
	} else {
		db := connect.DBConnect()
		query := connect.DBInsert("users", []string{"login", "password", "salt"})
		stmt, err := db.Prepare(query)
		utils.HandleErr("[HandleRegister] Prepare error :", err)
		defer stmt.Close()
		_, err = stmt.Exec(login, hash, salt)
		utils.HandleErr("[HandleRegister] Query error :", err)
	}
	response, err := json.Marshal(result)
	utils.HandleErr("[HandleRegister] json.Marshal: ", err)
	return string(response)
}
func (this *RegistrationController) Register(login, password, email, role string) (result string, regId int) {
	result = "ok"
	salt := strconv.Itoa(int(time.Now().Unix()))
	pass := utils.GetMD5Hash(password + salt)

	passHasInvalidChars := false
	for i := 0; i < len(password); i++ {
		if strconv.IsPrint(rune(password[i])) == false {
			passHasInvalidChars = true
			break
		}
	}

	if db.IsExists("users", []string{"login"}, []interface{}{login}) == true {
		result = "loginExists"

	} else if !utils.MatchRegexp("^[a-zA-Z0-9]{2,36}$", login) {
		result = "badLogin"

	} else if !utils.MatchRegexp("^.{6,36}$", password) || passHasInvalidChars {
		result = "badPassword"

		// } else if bad email {

	} else {
		token := utils.GetRandSeq(HASH_SIZE)

		if !mailer.SendConfirmEmail(login, email, token) {
			return "badEmail", -1
		}

		var userId int
		this.GetModel("users").
			LoadModelData(map[string]interface{}{
				"login":   login,
				"pass":    pass,
				"salt":    salt,
				"role":    role,
				"token":   token,
				"enabled": false}).
			QueryInsert("RETURNING id").
			Scan(&userId)

		var faceId int
		this.GetModel("faces").
			LoadModelData(map[string]interface{}{"user_id": userId}).
			QueryInsert("RETURNING id").
			Scan(&faceId)

		this.GetModel("registrations").
			LoadModelData(map[string]interface{}{"face_id": faceId, "event_id": 1, "status": false}).
			QueryInsert("RETURNING id").
			Scan(&regId)

		return result, regId
	}

	return result, -1
}
Example #6
0
//  cprotect returns its argument if printable, else a backslash form.
func cprotect(r rune) string {
	if strconv.IsPrint(r) {
		return string(r)
	} else {
		s := strconv.QuoteRune(r)
		return s[1 : len(s)-1]
	}
}
/*
Returns true when the string is entirely made of printable runes, false otherwise.
*/
func isPrintableString(str string) bool {
	for _, runeValue := range str {
		if !strconv.IsPrint(runeValue) {
			return false
		}
	}
	return true
}
Example #8
0
func (v *OctetString) String() string {
	for _, c := range v.Value {
		if !strconv.IsPrint(rune(c)) {
			return toHexStr(v.Value, ":")
		}
	}
	return string(v.Value)
}
Example #9
0
func isValueBinary(value []byte) bool {
	for _, r := range value {
		if strconv.IsPrint(rune(r)) == false {
			return true
		}
	}
	return false
}
Example #10
0
func isPrint(s string) bool {
	for _, c := range s {
		if !strconv.IsPrint(c) {
			return false
		}
	}

	return true
}
Example #11
0
// fmt_unicode formats a uint64 as "U+0078" or with f.sharp set as "U+0078 'x'".
func (f *fmt) fmt_unicode(u uint64) {
	buf := f.intbuf[0:]

	// With default precision set the maximum needed buf length is 18
	// for formatting -1 with %#U ("U+FFFFFFFFFFFFFFFF") which fits
	// into the already allocated intbuf with a capacity of 68 bytes.
	prec := 4
	if f.precPresent && f.prec > 4 {
		prec = f.prec
		// Compute space needed for "U+" , number, " '", character, "'".
		width := 2 + prec + 2 + utf8.UTFMax + 1
		if width > len(buf) {
			buf = make([]byte, width)
		}
	}

	// Format into buf, ending at buf[i]. Formatting numbers is easier right-to-left.
	i := len(buf)

	// For %#U we want to add a space and a quoted character at the end of the buffer.
	if f.sharp && u <= utf8.MaxRune && strconv.IsPrint(rune(u)) {
		i--
		buf[i] = '\''
		i -= utf8.RuneLen(rune(u))
		utf8.EncodeRune(buf[i:], rune(u))
		i--
		buf[i] = '\''
		i--
		buf[i] = ' '
	}
	// Format the Unicode code point u as a hexadecimal number.
	for u >= 16 {
		i--
		buf[i] = udigits[u&0xF]
		prec--
		u >>= 4
	}
	i--
	buf[i] = udigits[u]
	prec--
	// Add zeros in front of the number until requested precision is reached.
	for prec > 0 {
		i--
		buf[i] = '0'
		prec--
	}
	// Add a leading "U+".
	i--
	buf[i] = '+'
	i--
	buf[i] = 'U'

	oldZero := f.zero
	f.zero = false
	f.pad(buf[i:])
	f.zero = oldZero
}
Example #12
0
func (v *SnmpOctetString) IsPrintable() bool {
	isPrintable := true
	for _, c := range []byte(*v) {
		if !strconv.IsPrint(rune(c)) {
			isPrintable = false
			break
		}
	}
	return isPrintable
}
Example #13
0
File: dump.go Project: h12w/dfa
func quote(b byte) string {
	switch b {
	case '\'', '"', '`':
		return string(rune(b))
	}
	if b < utf8.RuneSelf && strconv.IsPrint(rune(b)) {
		return strconv.QuoteRune(rune(b))
	}
	return fmt.Sprintf(`%.2x`, b)
}
Example #14
0
// _isPrint() returns true if str is printable
//
// @private method
func _isPrint(str string) bool {
	for _, c := range str {

		if !strconv.IsPrint(rune(c)) {
			return false
		}
	}

	return true
}
Example #15
0
func (c *asciiChunk) prepareBuf() {
	for i := 0; i < len(c.buf); i++ {
		for {
			c.nextAscii = (c.nextAscii + 1) % 128
			if strconv.IsPrint(rune(c.nextAscii)) && c.nextAscii != '\n' {
				break
			}
		}
		c.buf[i] = c.nextAscii
	}
}
Example #16
0
File: nex.go Project: infogulch/nex
// Print a graph in DOT format given the start node.
//
//  $ dot -Tps input.dot -o output.ps
func writeDotGraph(outf *os.File, start *node, id string) {
	done := make(map[*node]bool)
	var show func(*node)
	show = func(u *node) {
		if u.accept {
			fmt.Fprintf(outf, "  %v[style=filled,color=green];\n", u.n)
		}
		done[u] = true
		for _, e := range u.e {
			// We use -1 to denote the dead end node in DFAs.
			if e.dst.n == -1 {
				continue
			}
			label := ""
			runeToDot := func(r rune) string {
				if strconv.IsPrint(r) {
					return fmt.Sprintf("%v", string(r))
				}
				return fmt.Sprintf("U+%X", int(r))
			}
			switch e.kind {
			case kRune:
				label = fmt.Sprintf("[label=%q]", runeToDot(e.r))
			case kWild:
				label = "[color=blue]"
			case kClass:
				label = "[label=\"["
				if e.negate {
					label += "^"
				}
				for i := 0; i < len(e.lim); i += 2 {
					label += runeToDot(e.lim[i])
					if e.lim[i] != e.lim[i+1] {
						label += "-" + runeToDot(e.lim[i+1])
					}
				}
				label += "]\"]"
			}
			fmt.Fprintf(outf, "  %v -> %v%v;\n", u.n, e.dst.n, label)
		}
		for _, e := range u.e {
			if !done[e.dst] {
				show(e.dst)
			}
		}
	}
	fmt.Fprintf(outf, "digraph %v {\n  0[shape=box];\n", id)
	show(start)
	fmt.Fprintln(outf, "}")
}
Example #17
0
// Returns an escaped version of rune. Escaping letters that produce control
// codes (n => \n) will produce undesirable results.
//
// Modified version of strconv/quote.go:quoteWith
func escape(r rune) string {
	if r == utf8.RuneError {
		return `\uFFFD`
	}
	if strconv.IsPrint(r) {
		// Printable characters just a get a backslash prepended. Lowercase ascii characters that are used when escaping control codes
		return `\` + string(r)
	}
	switch r {
	case '\a':
		return `\a`
	case '\b':
		return `\b`
	case '\f':
		return `\f`
	case '\n':
		return `\n`
	case '\r':
		return `\r`
	case '\t':
		return `\t`
	case '\v':
		return `\v`
	default:
		switch {
		case r < ' ':
			buf := make([]byte, 0, 4)
			buf = append(buf, `\x`...)
			buf = append(buf, lowerhex[r>>4])
			buf = append(buf, lowerhex[r&0xF])
			return string(buf)
		case r > utf8.MaxRune:
			return string(utf8.RuneError)
		case r < 0x10000:
			buf := make([]byte, 0, 6)
			buf = append(buf, `\u`...)
			for s := 12; s >= 0; s -= 4 {
				buf = append(buf, lowerhex[r>>uint(s)&0xF])
			}
			return string(buf)
		default:
			buf := make([]byte, 0, 10)
			buf = append(buf, `\U`...)
			for s := 28; s >= 0; s -= 4 {
				buf = append(buf, lowerhex[r>>uint(s)&0xF])
			}
			return string(buf)
		}
	}
}
Example #18
0
// rewrite rewrites a subname to having only printable characters and no white
// space.
func rewrite(s string) string {
	b := []byte{}
	for _, r := range s {
		switch {
		case isSpace(r):
			b = append(b, '_')
		case !strconv.IsPrint(r):
			s := strconv.QuoteRune(r)
			b = append(b, s[1:len(s)-1]...)
		default:
			b = append(b, string(r)...)
		}
	}
	return string(b)
}
Example #19
0
// Escape stdout/stderr so the Jenkins YAMLish parser doesn't barf on
// it. This escaping is crude (it masks all colons as something humans
// will hopefully see as a colon, for instance), but it should get the
// job done without pulling in a whole YAML package.
func escapeOutput(s string) (out string) {
	for _, r := range s {
		switch {
		case r == '\n':
			out += string(r)
		case !strconv.IsPrint(r):
			out += " "
		case r == ':':
			out += "\ua789" // "꞉", modifier letter colon
		default:
			out += string(r)
		}
	}
	return
}
Example #20
0
// Currency in computer parsable form
func (c Currency) Machine() string {
	switch c.Type() {
	case CT_XRP:
		return "XRP"
	case CT_STANDARD:
		// Check for unprintable characters
		for _, r := range string(c[12:15]) {
			if !strconv.IsPrint(r) {
				return string(b2h(c[:]))
			}
		}
		return string(c[12:15])
	default:
		return string(b2h(c[:]))
	}
}
Example #21
0
func main() {
	c := strconv.IsPrint('\u263a')
	fmt.Println(c)

	bel := strconv.IsPrint('\007')
	fmt.Println(bel)

	fmt.Println(strconv.IsPrint(' '))
	fmt.Println(strconv.IsPrint('\t'))
	fmt.Println(strconv.IsPrint('\n'))
	fmt.Println(strconv.IsPrint('\r'))
}
Example #22
0
File: ini.go Project: calmh/mole
// Write writes the sections and options to the io.Writer in INI format.
func (c *Config) Write(out io.Writer) error {
	for _, cmt := range c.comments {
		fmt.Fprintln(out, "; "+cmt)
	}
	if len(c.comments) > 0 {
		fmt.Fprintln(out)
	}

	for _, sect := range c.sections {
		fmt.Fprintf(out, "[%s]\n", sect.name)
		for _, cmt := range sect.comments {
			fmt.Fprintln(out, "; "+cmt)
		}
		for _, opt := range sect.options {
			val := opt.value
			if len(val) == 0 {
				continue
			}

			// Quote the string if it begins or ends with space
			needsQuoting := val[0] == ' ' || val[len(val)-1] == ' '

			if !needsQuoting {
				// Quote the string if it contains any unprintable characters
				for _, r := range val {
					if !strconv.IsPrint(r) {
						needsQuoting = true
						break
					}
				}
			}

			if needsQuoting {
				val = strconv.Quote(val)
			}

			fmt.Fprintf(out, "%s=%s\n", opt.name, val)
		}
		fmt.Fprintln(out)
	}
	return nil
}
Example #23
0
func main() {
	log.SetFlags(0)

	args := os.Args[1:]
	if len(args) < 2 {
		log.Fatal("usage: roxor <file> <crib>")
	}

	filename := args[0]
	crib := []byte(args[1])

	if len(crib) < 2 {
		log.Fatal("error: crib too short")
	}

	ciphertext, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Fatal(err)
	}

	if len(ciphertext) < len(crib) {
		log.Fatal("error: ciphertext too short")
	}

	attackCipher(ciphertext, crib, func(m Match) {
		fmt.Printf("Found text at 0x%x (XOR key 0x%02x)\n", m.offset, m.key)
		fmt.Printf("  preview: ")

		for i, ch := range ciphertext[m.offset:] {
			if i >= PreviewSize {
				break
			}
			ch ^= m.key
			if !strconv.IsPrint(rune(ch)) {
				ch = '.'
			}
			fmt.Printf("%c", ch)
		}

		fmt.Println()
	})
}
Example #24
0
// return ui8v field as a string
func union_ui8v_string(cbytes [8]byte, value_len _Ctype_gsize) (result string) {
	var ptr uint64
	var err error
	buf := bytes.NewBuffer(cbytes[:])
	if err = binary.Read(buf, binary.LittleEndian, &ptr); err != nil { // read bytes as uint64
		return
	}
	up := (unsafe.Pointer(uintptr(ptr))) // convert the uint64 into a pointer

	length := (_Ctype_int)(value_len)
	gobytes := C.GoBytes(up, length)
	for i := 0; i < int(length); i++ {
		if !strconv.IsPrint(rune(gobytes[i])) {
			// can't pass gobytes & length to union_ui8v_hexstring() -
			// it's also used for TYPE_OPAQUE
			return union_ui8v_hexstring(cbytes, value_len)
		}
	}

	return string(gobytes)
}
Example #25
0
// bodyRepr returns representation of body depending on content type.
// It may be indented, shortened or returned as is.
// It returns nil for empty body.
func bodyRepr(contentType string, body []byte) []byte {
	if len(body) == 0 {
		return nil
	}

	switch {
	case strings.Contains(contentType, "json"):
		return []byte(jsons.ParseBytes(body).Indent())

	default:
		for _, r := range string(body) {
			switch {
			case r == '\n':
				continue
			case strconv.IsPrint(r):
				continue
			default:
				return []byte(fmt.Sprintf("[%d bytes data]", len(body)))
			}
		}
		return body
	}
}
Example #26
0
func appendQuoted(buf []byte, s string) []byte {
	var runeTmp [utf8.UTFMax]byte
	for width := 0; len(s) > 0; s = s[width:] {
		r := rune(s[0])
		width = 1
		if r >= utf8.RuneSelf {
			r, width = utf8.DecodeRuneInString(s)
		}
		if width == 1 && r == utf8.RuneError {
			buf = append(buf, `\x`...)
			buf = append(buf, lowerhex[s[0]>>4])
			buf = append(buf, lowerhex[s[0]&0xF])
			continue
		}
		if r == rune('"') || r == '\\' { // always backslashed
			buf = append(buf, '\\')
			buf = append(buf, byte(r))
			continue
		}
		if strconv.IsPrint(r) {
			n := utf8.EncodeRune(runeTmp[:], r)
			buf = append(buf, runeTmp[:n]...)
			continue
		}
		switch r {
		case '\a':
			buf = append(buf, `\a`...)
		case '\b':
			buf = append(buf, `\b`...)
		case '\f':
			buf = append(buf, `\f`...)
		case '\n':
			buf = append(buf, `\n`...)
		case '\r':
			buf = append(buf, `\r`...)
		case '\t':
			buf = append(buf, `\t`...)
		case '\v':
			buf = append(buf, `\v`...)
		default:
			switch {
			case r < ' ':
				buf = append(buf, `\x`...)
				buf = append(buf, lowerhex[s[0]>>4])
				buf = append(buf, lowerhex[s[0]&0xF])
			case r > utf8.MaxRune:
				r = 0xFFFD
				fallthrough
			case r < 0x10000:
				buf = append(buf, `\u`...)
				for s := 12; s >= 0; s -= 4 {
					buf = append(buf, lowerhex[r>>uint(s)&0xF])
				}
			default:
				buf = append(buf, `\U`...)
				for s := 28; s >= 0; s -= 4 {
					buf = append(buf, lowerhex[r>>uint(s)&0xF])
				}
			}
		}
	}
	return buf

}
Example #27
0
// integer; interprets prec but not wid. Once formatted, result is sent to pad()
// and then flags are cleared.
func (f *fmt) integer(a int64, base uint64, signedness bool, digits string) {
	// precision of 0 and value of 0 means "print nothing"
	if f.precPresent && f.prec == 0 && a == 0 {
		return
	}

	negative := signedness == signed && a < 0
	if negative {
		a = -a
	}

	var buf []byte = f.intbuf[0:]
	if f.widPresent || f.precPresent || f.plus || f.space {
		width := f.wid + f.prec // Only one will be set, both are positive; this provides the maximum.
		if base == 16 && f.sharp {
			// Also adds "0x".
			width += 2
		}
		if f.unicode {
			// Also adds "U+".
			width += 2
			if f.uniQuote {
				// Also adds " 'x'".
				width += 1 + 1 + utf8.UTFMax + 1
			}
		}
		if negative || f.plus || f.space {
			width++
		}
		if width > nByte {
			// We're going to need a bigger boat.
			buf = make([]byte, width)
		}
	}

	// two ways to ask for extra leading zero digits: %.3d or %03d.
	// apparently the first cancels the second.
	prec := 0
	if f.precPresent {
		prec = f.prec
		f.zero = false
	} else if f.zero && f.widPresent && !f.minus && f.wid > 0 {
		prec = f.wid
		if negative || f.plus || f.space {
			prec-- // leave room for sign
		}
	}

	// format a into buf, ending at buf[i].  (printing is easier right-to-left.)
	// a is made into unsigned ua.  we could make things
	// marginally faster by splitting the 32-bit case out into a separate
	// block but it's not worth the duplication, so ua has 64 bits.
	i := len(buf)
	ua := uint64(a)
	// use constants for the division and modulo for more efficient code.
	// switch cases ordered by popularity.
	switch base {
	case 10:
		for ua >= 10 {
			i--
			next := ua / 10
			buf[i] = byte('0' + ua - next*10)
			ua = next
		}
	case 16:
		for ua >= 16 {
			i--
			buf[i] = digits[ua&0xF]
			ua >>= 4
		}
	case 8:
		for ua >= 8 {
			i--
			buf[i] = byte('0' + ua&7)
			ua >>= 3
		}
	case 2:
		for ua >= 2 {
			i--
			buf[i] = byte('0' + ua&1)
			ua >>= 1
		}
	default:
		panic("fmt: unknown base; can't happen")
	}
	i--
	buf[i] = digits[ua]
	for i > 0 && prec > len(buf)-i {
		i--
		buf[i] = '0'
	}

	// Various prefixes: 0x, -, etc.
	if f.sharp {
		switch base {
		case 8:
			if buf[i] != '0' {
				i--
				buf[i] = '0'
			}
		case 16:
			// Add a leading 0x or 0X.
			i--
			buf[i] = digits[16]
			i--
			buf[i] = '0'
		}
	}
	if f.unicode {
		i--
		buf[i] = '+'
		i--
		buf[i] = 'U'
	}

	if negative {
		i--
		buf[i] = '-'
	} else if f.plus {
		i--
		buf[i] = '+'
	} else if f.space {
		i--
		buf[i] = ' '
	}

	// If we want a quoted char for %#U, move the data up to make room.
	if f.unicode && f.uniQuote && a >= 0 && a <= utf8.MaxRune && strconv.IsPrint(rune(a)) {
		runeWidth := utf8.RuneLen(rune(a))
		width := 1 + 1 + runeWidth + 1 // space, quote, rune, quote
		copy(buf[i-width:], buf[i:])   // guaranteed to have enough room.
		i -= width
		// Now put " 'x'" at the end.
		j := len(buf) - width
		buf[j] = ' '
		j++
		buf[j] = '\''
		j++
		utf8.EncodeRune(buf[j:], rune(a))
		j += runeWidth
		buf[j] = '\''
	}

	f.pad(buf[i:])
}
Example #28
0
// integer; interprets prec but not wid.  Once formatted, result is sent to pad()
// and then flags are cleared.
func (f *fmt) integer(a int64, base uint64, signedness bool, digits string) {
	// precision of 0 and value of 0 means "print nothing"
	if f.precPresent && f.prec == 0 && a == 0 {
		return
	}

	var buf []byte = f.intbuf[0:]
	negative := signedness == signed && a < 0
	if negative {
		a = -a
	}

	// two ways to ask for extra leading zero digits: %.3d or %03d.
	// apparently the first cancels the second.
	prec := 0
	if f.precPresent {
		prec = f.prec
		f.zero = false
	} else if f.zero && f.widPresent && !f.minus && f.wid > 0 {
		prec = f.wid
		if negative || f.plus || f.space {
			prec-- // leave room for sign
		}
	}

	// format a into buf, ending at buf[i].  (printing is easier right-to-left.)
	// a is made into unsigned ua.  we could make things
	// marginally faster by splitting the 32-bit case out into a separate
	// block but it's not worth the duplication, so ua has 64 bits.
	i := len(f.intbuf)
	ua := uint64(a)
	for ua >= base {
		i--
		buf[i] = digits[ua%base]
		ua /= base
	}
	i--
	buf[i] = digits[ua]
	for i > 0 && prec > nByte-i {
		i--
		buf[i] = '0'
	}

	// Various prefixes: 0x, -, etc.
	if f.sharp {
		switch base {
		case 8:
			if buf[i] != '0' {
				i--
				buf[i] = '0'
			}
		case 16:
			i--
			buf[i] = 'x' + digits[10] - 'a'
			i--
			buf[i] = '0'
		}
	}
	if f.unicode {
		i--
		buf[i] = '+'
		i--
		buf[i] = 'U'
	}

	if negative {
		i--
		buf[i] = '-'
	} else if f.plus {
		i--
		buf[i] = '+'
	} else if f.space {
		i--
		buf[i] = ' '
	}

	// If we want a quoted char for %#U, move the data up to make room.
	if f.unicode && f.uniQuote && a >= 0 && a <= utf8.MaxRune && strconv.IsPrint(rune(a)) {
		runeWidth := utf8.RuneLen(rune(a))
		width := 1 + 1 + runeWidth + 1 // space, quote, rune, quote
		copy(buf[i-width:], buf[i:])   // guaranteed to have enough room.
		i -= width
		// Now put " 'x'" at the end.
		j := len(buf) - width
		buf[j] = ' '
		j++
		buf[j] = '\''
		j++
		utf8.EncodeRune(buf[j:], rune(a))
		j += runeWidth
		buf[j] = '\''
	}

	f.pad(buf[i:])
}
Example #29
0
func printMsg(msg *mangos.Message) {
	if printFormat == "no" {
		return
	}
	bw := bufio.NewWriter(os.Stdout)
	switch printFormat {
	case "raw":
		bw.Write(msg.Body)
	case "ascii":
		for i := 0; i < len(msg.Body); i++ {
			if strconv.IsPrint(rune(msg.Body[i])) {
				bw.WriteByte(msg.Body[i])
			} else {
				bw.WriteByte('.')
			}
		}
		bw.WriteString("\n")
	case "quoted":
		for i := 0; i < len(msg.Body); i++ {
			switch msg.Body[i] {
			case '\n':
				bw.WriteString("\\n")
			case '\r':
				bw.WriteString("\\r")
			case '\\':
				bw.WriteString("\\\\")
			case '"':
				bw.WriteString("\\\"")
			default:
				if strconv.IsPrint(rune(msg.Body[i])) {
					bw.WriteByte(msg.Body[i])
				} else {
					bw.WriteString(fmt.Sprintf("\\x%02x",
						msg.Body[i]))
				}
			}
		}
		bw.WriteString("\n")

	case "msgpack":
		enc := make([]byte, 5)
		switch {
		case len(msg.Body) < 256:
			enc = enc[:2]
			enc[0] = 0xc4
			enc[1] = byte(len(msg.Body))

		case len(msg.Body) < 65536:
			enc = enc[:3]
			enc[0] = 0xc5
			binary.BigEndian.PutUint16(enc[1:], uint16(len(msg.Body)))
		default:
			enc = enc[:5]
			enc[0] = 0xc6
			binary.BigEndian.PutUint32(enc[1:], uint32(len(msg.Body)))
		}
		bw.Write(enc)
		bw.Write(msg.Body)
	}
	bw.Flush()
}
Example #30
0
func quoteWith(s string, quote byte) string {
	var runeTmp [utf8.UTFMax]byte
	buf := make([]byte, 0, 3*len(s)/2) // Try to avoid more allocations.
	buf = append(buf, quote)
	for width := 0; len(s) > 0; s = s[width:] {
		r := rune(s[0])
		width = 1
		if r >= utf8.RuneSelf {
			r, width = utf8.DecodeRuneInString(s)
		}
		if width == 1 && r == utf8.RuneError {
			buf = append(buf, `\x`...)
			buf = append(buf, lowerhex[s[0]>>4])
			buf = append(buf, lowerhex[s[0]&0xF])
			continue
		}
		if r == rune(quote) {
			buf = append(buf, byte(r))
			buf = append(buf, byte(r))
			continue
		}
		if r == '\\' { // always backslashed
			buf = append(buf, '\\')
			buf = append(buf, byte(r))
			continue
		}
		if strconv.IsPrint(r) {
			n := utf8.EncodeRune(runeTmp[:], r)
			buf = append(buf, runeTmp[:n]...)
			continue
		}
		switch r {
		case '\a':
			buf = append(buf, `\a`...)
		case '\b':
			buf = append(buf, `\b`...)
		case '\f':
			buf = append(buf, `\f`...)
		case '\n':
			buf = append(buf, `\n`...)
		case '\r':
			buf = append(buf, `\r`...)
		case '\t':
			buf = append(buf, `\t`...)
		case '\v':
			buf = append(buf, `\v`...)
		default:
			switch {
			case r < ' ':
				buf = append(buf, `\x`...)
				buf = append(buf, lowerhex[s[0]>>4])
				buf = append(buf, lowerhex[s[0]&0xF])
			case r > utf8.MaxRune:
				r = 0xFFFD
				fallthrough
			case r < 0x10000:
				buf = append(buf, `\u`...)
				for s := 12; s >= 0; s -= 4 {
					buf = append(buf, lowerhex[r>>uint(s)&0xF])
				}
			default:
				buf = append(buf, `\U`...)
				for s := 28; s >= 0; s -= 4 {
					buf = append(buf, lowerhex[r>>uint(s)&0xF])
				}
			}
		}
	}
	buf = append(buf, quote)
	return string(buf)

}