本文整理汇总了Golang中unicode/utf8.RuneCountInString函数的典型用法代码示例。如果您正苦于以下问题:Golang RuneCountInString函数的具体用法?Golang RuneCountInString怎么用?Golang RuneCountInString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了RuneCountInString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: NewLabel
// NewLabel returns a new label whos name consists of a prefix followed by
// some digits which make it unique.
//
// Only the first length characters of the prefix are used, and the prefix must
// not end with a digit. If no prefix is given, then the default is used.
//
// Label is initially not initally placed.
func NewLabel(prefix string) *Label {
l := &Label{
count: count,
length: 5,
prefix: "label",
}
if utf8.RuneCountInString(prefix) > utf8.RuneCountInString(l.prefix) {
l.prefix = prefix[:utf8.RuneCountInString(prefix)-1]
}
lastRune, _ := utf8.DecodeLastRuneInString(l.prefix)
if prefix == "main" {
l.name = "main"
return l
}
if unicode.IsDigit(lastRune) {
log.Fatal("label ended with a digit")
}
l.name = l.prefix + strconv.Itoa(l.count)
count++
return l
}
示例2: Event
func (c *Client) Event(title string, text string, eo *EventOpts) error {
var b bytes.Buffer
fmt.Fprintf(&b, "_e{%d,%d}:%s|%s|t:%s", utf8.RuneCountInString(title),
utf8.RuneCountInString(text), title, text, eo.AlertType)
if eo.SourceTypeName != "" {
fmt.Fprintf(&b, "|s:%s", eo.SourceTypeName)
}
if !eo.DateHappened.IsZero() {
fmt.Fprintf(&b, "|d:%d", eo.DateHappened.Unix())
}
if eo.Priority != "" {
fmt.Fprintf(&b, "|p:%s", eo.Priority)
}
if eo.Host != "" {
fmt.Fprintf(&b, "|h:%s", eo.Host)
}
if eo.AggregationKey != "" {
fmt.Fprintf(&b, "|k:%s", eo.AggregationKey)
}
tags := append(c.Tags, eo.Tags...)
format := "|#%s"
for _, t := range tags {
fmt.Fprintf(&b, format, t)
format = ",%s"
}
bytes := b.Bytes()
if len(bytes) > maxEventBytes {
return fmt.Errorf("Event '%s' payload is too big (more that 8KB), event discarded", title)
}
_, err := c.conn.Write(bytes)
return err
}
示例3: DiffToDelta
// DiffToDelta crushes the diff into an encoded string which describes the
// operations required to transform text1 into text2.
// E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
// Operations are tab-separated. Inserted text is escaped using %xx
// notation.
func DiffToDelta(diffs []Diff) string {
var buf bytes.Buffer
for _, d := range diffs {
switch d.Type {
case DiffInsert:
buf.WriteString("+")
buf.WriteString(
strings.Replace(url.QueryEscape(d.Text), "+", " ", -1),
)
buf.WriteString("\t")
break
case DiffDelete:
buf.WriteString("-")
buf.WriteString(strconv.Itoa(utf8.RuneCountInString(d.Text)))
buf.WriteString("\t")
break
case DiffEqual:
buf.WriteString("=")
buf.WriteString(strconv.Itoa(utf8.RuneCountInString(d.Text)))
buf.WriteString("\t")
break
}
}
delta := buf.String()
if len(delta) != 0 {
// Strip off trailing tab character.
delta = delta[0 : utf8.RuneCountInString(delta)-1]
delta = unescaper.Replace(delta)
}
return delta
}
示例4: checkTrim
func checkTrim(t string) bool {
diff := ((utf8.RuneCountInString(t) - len(t)) / 2)
if utf8.RuneCountInString(t) > (titleCount + diff) {
return true
}
return false
}
示例5: ZipStrByGoroutine
func ZipStrByGoroutine(s1, s2 string) string {
zippedLength := utf8.RuneCountInString(s1) + utf8.RuneCountInString(s2)
zipped := make([]rune, zippedLength)
recvCh := make(chan rune)
switchCh1 := make(chan struct{})
switchCh2 := make(chan struct{})
go func() {
for _, r := range s1 {
<-switchCh1
recvCh <- r
switchCh2 <- struct{}{}
}
}()
go func() {
for _, r := range s2 {
<-switchCh2
recvCh <- r
switchCh1 <- struct{}{}
}
}()
i := 0
switchCh1 <- struct{}{}
for r := range recvCh {
zipped[i] = r
i++
if i == zippedLength {
break
}
}
return string(zipped)
}
示例6: ValidateLengthOf
func ValidateLengthOf(resource Resource, attribute string, rule string, chars int) {
value := reflect.ValueOf(resource).Elem()
value = reflect.Indirect(value).FieldByName(attribute)
switch rule {
case "at least":
if utf8.RuneCountInString(value.String()) < chars {
message := fmt.Sprintf("length can't be less than %d characters", chars)
resource.Errors().Add(attribute, message)
}
case "at most":
if utf8.RuneCountInString(value.String()) > chars {
message := fmt.Sprintf("length can't be more than %d characters", chars)
resource.Errors().Add(attribute, message)
}
case "exactly":
if utf8.RuneCountInString(value.String()) != chars {
message := fmt.Sprintf("length must equal %d characters", chars)
resource.Errors().Add(attribute, message)
}
}
}
示例7: saveConfig
func saveConfig(w io.Writer, obsKeys map[string]string) {
// find flags pointing to the same variable. We will only write the longest
// named flag to the config file, the shorthand version is ignored.
deduped := make(map[flag.Value]flag.Flag)
flag.VisitAll(func(f *flag.Flag) {
if cur, ok := deduped[f.Value]; !ok || utf8.RuneCountInString(f.Name) > utf8.RuneCountInString(cur.Name) {
deduped[f.Value] = *f
}
})
flag.VisitAll(func(f *flag.Flag) {
if cur, ok := deduped[f.Value]; ok && cur.Name == f.Name {
_, usage := flag.UnquoteUsage(f)
usage = strings.Replace(usage, "\n \t", "\n# ", -1)
fmt.Fprintf(w, "\n# %s (default %v)\n", usage, f.DefValue)
fmt.Fprintf(w, "%s=%v\n", f.Name, f.Value.String())
}
})
// if we have obsolete keys left from the old config, preserve them in an
// additional section at the end of the file
if obsKeys != nil && len(obsKeys) > 0 {
fmt.Fprintln(w, "\n\n# The following options are probably deprecated and not used currently!")
for key, val := range obsKeys {
fmt.Fprintf(w, "%v=%v\n", key, val)
}
}
}
示例8: DrawLabel
func DrawLabel(s *svg.SVG, bs string) *BrailleCanvas {
var c BrailleCanvas
// TODO: they hard coded
c.dotSize = 12
c.pageMarginTop = 3
c.pageMarginBottom = 3
c.pageMarginLeft = 3
c.pageMarginRight = 3
c.gapCell = 3
c.canvasW = c.pageMarginLeft + c.pageMarginRight
c.canvasW += c.dotSize * 2 * utf8.RuneCountInString(bs)
c.canvasW += c.gapCell*utf8.RuneCountInString(bs) - 1
c.canvasH = c.pageMarginTop + c.pageMarginBottom
c.canvasH += c.dotSize * 3
s.Start(c.canvasW, c.canvasH)
x := c.pageMarginLeft
y := c.pageMarginTop
for _, b := range bs {
if b&0x2800 != 0x2800 {
log.Printf("0x%x is not a braille character!\n", b)
continue
}
Draw(s, b, x, y, c.dotSize)
x += (c.dotSize * 2) + c.gapCell
}
return &c
}
示例9: DiffToDelta
// DiffToDelta crushes the diff into an encoded string which describes the operations required to transform text1 into text2.
// E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated. Inserted text is escaped using %xx notation.
func (dmp *DiffMatchPatch) DiffToDelta(diffs []Diff) string {
var text bytes.Buffer
for _, aDiff := range diffs {
switch aDiff.Type {
case DiffInsert:
_, _ = text.WriteString("+")
_, _ = text.WriteString(strings.Replace(url.QueryEscape(aDiff.Text), "+", " ", -1))
_, _ = text.WriteString("\t")
break
case DiffDelete:
_, _ = text.WriteString("-")
_, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text)))
_, _ = text.WriteString("\t")
break
case DiffEqual:
_, _ = text.WriteString("=")
_, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text)))
_, _ = text.WriteString("\t")
break
}
}
delta := text.String()
if len(delta) != 0 {
// Strip off trailing tab character.
delta = delta[0 : utf8.RuneCountInString(delta)-1]
delta = unescaper.Replace(delta)
}
return delta
}
示例10: AreOneEditAway
func AreOneEditAway(input1, input2 string) bool {
len1 := utf8.RuneCountInString(input1)
len2 := utf8.RuneCountInString(input2)
if len1 != len2 && len1-1 != len2 && len2-1 != len1 {
return false
}
if len1 == len2 { // must be one replacement
var width1, width2 int
var r1, r2 rune
diffSeen := false
for i, j := 0, 0; i < len1 || j < len2; i, j = i+width1, j+width2 {
r1, width1 = utf8.DecodeRuneInString(input1[i:])
r2, width2 = utf8.DecodeRuneInString(input2[j:])
if r1 != r2 {
if diffSeen {
return false
} else {
diffSeen = true
}
}
}
return true
} else if len1-1 == len2 { // input1 must be a removal from input2
return oneRemovalAway(input2, input1)
} else { //if len2-1 == len1 { // input2 must be a removal from input1
return oneRemovalAway(input1, input2)
}
}
示例11: cellValue
func (t *PrintableTable) cellValue(col int, value string) string {
padding := ""
if col < len(t.headers)-1 {
var count int
if utf8.RuneCountInString(value) == len(value) {
if t.maxRuneCountLengths[col] == t.maxStringLengths[col] {
count = t.maxRuneCountLengths[col] - utf8.RuneCountInString(Decolorize(value))
} else {
count = t.maxRuneCountLengths[col] - len(Decolorize(value))
}
} else {
if t.maxRuneCountLengths[col] == t.maxStringLengths[col] {
count = t.maxRuneCountLengths[col] - len(Decolorize(value)) + utf8.RuneCountInString(Decolorize(value))
} else {
count = t.maxStringLengths[col] - len(Decolorize(value))
}
}
padding = strings.Repeat(" ", count)
}
return fmt.Sprintf("%s%s ", value, padding)
}
示例12: Worlds
// слово
func (l *Lorem) Worlds(num int) string {
if num == 0 {
return ""
}
var worlds []string
result := ""
k := 0
for i := 0; i < num; i++ {
if len(worlds) == 0 || k >= len(worlds) {
speech := l.Speech(1)
worlds = strings.Split(speech[:utf8.RuneCountInString(speech)-1], " ")
k = 0
}
result += worlds[k]
if i < num-1 {
result += " "
}
k++
}
if result[utf8.RuneCountInString(result)-1:] == "," {
result = result[:utf8.RuneCountInString(result)-1]
}
return result + ". "
}
示例13: resetPassword
func resetPassword(app *Application, answer *model.SecurityAnswer, token *model.Token, r *http.Request) error {
ans := r.FormValue("answer")
pass := r.FormValue("password")
pass2 := r.FormValue("password2")
if len(pass) < viper.GetInt("min_passwd_len") || len(pass2) < viper.GetInt("min_passwd_len") {
return errors.New(fmt.Sprintf("Please set a password at least %d characters in length.", viper.GetInt("min_passwd_len")))
}
if pass != pass2 {
return errors.New("Password do not match. Please confirm your password.")
}
if utf8.RuneCountInString(ans) < 2 || utf8.RuneCountInString(ans) > 100 {
return errors.New("Invalid answer. Must be between 2 and 100 characters long.")
}
err := bcrypt.CompareHashAndPassword([]byte(answer.Answer), []byte(ans))
if err != nil {
return errors.New("The security answer you provided does not match. Please check that you are entering the correct answer.")
}
// Setup password in FreeIPA
err = setPassword(token.UserName, "", pass)
if err != nil {
if ierr, ok := err.(*ipa.ErrPasswordPolicy); ok {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": ierr.Error(),
}).Error("password does not conform to policy")
return errors.New("Your password is too weak. Please ensure your password includes a number and lower/upper case character")
}
if ierr, ok := err.(*ipa.ErrInvalidPassword); ok {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": ierr.Error(),
}).Error("invalid password from FreeIPA")
return errors.New("Invalid password.")
}
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": err.Error(),
}).Error("failed to set user password in FreeIPA")
return errors.New("Fatal system error")
}
// Destroy token
err = model.DestroyToken(app.db, token.Token)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": err.Error(),
}).Error("failed to remove token from database")
return errors.New("Fatal system error")
}
return nil
}
示例14: Valid
func (nv *stringValidater) Valid(source string, opt *FieldOption) (vr *ValidResult) {
source, vr = nv.baseValidater.Valid(source, opt)
if vr.IsValid || vr.ErrorMsg != "" {
return vr
}
if opt.Range[0] > 0 && utf8.RuneCountInString(source) < opt.Range[0] {
if opt.Range[1] > 0 {
vr.ErrorMsg = strings.Replace(
getOrDefault(opt.ErrorMsgs, "range", MST_RANGE_LENGTH),
"{0}", strconv.Itoa(opt.Range[0]), -1)
vr.ErrorMsg = strings.Replace(vr.ErrorMsg, "{1}", strconv.Itoa(opt.Range[1]), -1)
} else {
vr.ErrorMsg = strings.Replace(
getOrDefault(opt.ErrorMsgs, "min", MSG_MIN_LENGTH), "{0}", strconv.Itoa(opt.Range[0]), -1)
}
return vr
}
if opt.Range[1] > 0 && utf8.RuneCountInString(source) > opt.Range[1] {
if opt.Range[0] > 0 {
vr.ErrorMsg = strings.Replace(
getOrDefault(opt.ErrorMsgs, "range", MST_RANGE_LENGTH), "{0}", strconv.Itoa(opt.Range[0]), -1)
vr.ErrorMsg = strings.Replace(vr.ErrorMsg, "{1}", strconv.Itoa(opt.Range[1]), -1)
} else {
vr.ErrorMsg = strings.Replace(
getOrDefault(opt.ErrorMsgs, "max", MSG_MAX_LENGTH), "{0}", strconv.Itoa(opt.Range[1]), -1)
}
return vr
}
vr.IsValid = true
vr.CleanValue = source
return vr
}
示例15: IsValid
// IsValid validates the user and returns an error if it isn't configured
// correctly.
func (u *User) IsValid() *AppError {
if len(u.Id) != 26 {
return NewLocAppError("User.IsValid", "model.user.is_valid.id.app_error", nil, "")
}
if u.CreateAt == 0 {
return NewLocAppError("User.IsValid", "model.user.is_valid.create_at.app_error", nil, "user_id="+u.Id)
}
if u.UpdateAt == 0 {
return NewLocAppError("User.IsValid", "model.user.is_valid.update_at.app_error", nil, "user_id="+u.Id)
}
if len(u.TeamId) != 26 {
return NewLocAppError("User.IsValid", "model.user.is_valid.team_id.app_error", nil, "")
}
if !IsValidUsername(u.Username) {
return NewLocAppError("User.IsValid", "model.user.is_valid.username.app_error", nil, "user_id="+u.Id)
}
if len(u.Email) > 128 || len(u.Email) == 0 {
return NewLocAppError("User.IsValid", "model.user.is_valid.email.app_error", nil, "user_id="+u.Id)
}
if utf8.RuneCountInString(u.Nickname) > 64 {
return NewLocAppError("User.IsValid", "model.user.is_valid.nickname.app_error", nil, "user_id="+u.Id)
}
if utf8.RuneCountInString(u.FirstName) > 64 {
return NewLocAppError("User.IsValid", "model.user.is_valid.first_name.app_error", nil, "user_id="+u.Id)
}
if utf8.RuneCountInString(u.LastName) > 64 {
return NewLocAppError("User.IsValid", "model.user.is_valid.last_name.app_error", nil, "user_id="+u.Id)
}
if len(u.Password) > 128 {
return NewLocAppError("User.IsValid", "model.user.is_valid.pwd.app_error", nil, "user_id="+u.Id)
}
if len(u.AuthData) > 128 {
return NewLocAppError("User.IsValid", "model.user.is_valid.auth_data.app_error", nil, "user_id="+u.Id)
}
if len(u.AuthData) > 0 && len(u.AuthService) == 0 {
return NewLocAppError("User.IsValid", "model.user.is_valid.auth_data_type.app_error", nil, "user_id="+u.Id)
}
if len(u.Password) > 0 && len(u.AuthData) > 0 {
return NewLocAppError("User.IsValid", "model.user.is_valid.auth_data_pwd.app_error", nil, "user_id="+u.Id)
}
if len(u.ThemeProps) > 2000 {
return NewLocAppError("User.IsValid", "model.user.is_valid.theme.app_error", nil, "user_id="+u.Id)
}
return nil
}