ergo/irc/strings.go

81 lines
1.8 KiB
Go
Raw Normal View History

// Copyright (c) 2012-2014 Jeremy Latt
// Copyright (c) 2014-2015 Edmund Huber
2017-03-27 14:15:02 +02:00
// Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
2014-03-09 21:45:36 +01:00
package irc
import (
"errors"
2014-03-09 21:45:36 +01:00
"strings"
"golang.org/x/text/secure/precis"
2014-03-09 21:45:36 +01:00
)
const (
casemappingName = "rfc7613"
)
2014-03-09 21:45:36 +01:00
var (
errInvalidCharacter = errors.New("Invalid character")
2017-01-22 03:44:05 +01:00
errEmpty = errors.New("String is empty")
2014-03-09 21:45:36 +01:00
)
// Casefold returns a casefolded string, without doing any name or channel character checks.
func Casefold(str string) (string, error) {
return precis.UsernameCaseMapped.CompareKey(str)
2014-03-09 21:45:36 +01:00
}
// CasefoldChannel returns a casefolded version of a channel name.
func CasefoldChannel(name string) (string, error) {
lowered, err := Casefold(name)
2014-03-09 21:45:36 +01:00
if err != nil {
return "", err
2017-01-22 03:44:05 +01:00
} else if len(lowered) == 0 {
return "", errEmpty
}
2014-03-09 21:45:36 +01:00
if lowered[0] != '#' {
return "", errInvalidCharacter
}
2014-03-09 21:45:36 +01:00
// space can't be used
// , is used as a separator
// * is used in mask matching
// ? is used in mask matching
if strings.ContainsAny(lowered, " ,*?") {
return "", errInvalidCharacter
}
2014-03-09 21:45:36 +01:00
return lowered, err
2014-03-09 21:45:36 +01:00
}
// CasefoldName returns a casefolded version of a nick/user name.
func CasefoldName(name string) (string, error) {
lowered, err := Casefold(name)
2014-03-09 21:45:36 +01:00
if err != nil {
return "", err
2017-01-22 03:44:05 +01:00
} else if len(lowered) == 0 {
return "", errEmpty
}
2014-03-09 21:45:36 +01:00
// space can't be used
// , is used as a separator
// * is used in mask matching
// ? is used in mask matching
// . denotes a server name
// ! separates nickname from username
// @ separates username from hostname
// : means trailing
// # is a channel prefix
// ~&@%+ are channel membership prefixes
// - I feel like disallowing
if strings.ContainsAny(lowered, " ,*?.!@:") || strings.ContainsAny(string(lowered[0]), "#~&@%+-") {
return "", errInvalidCharacter
}
2014-03-09 21:45:36 +01:00
return lowered, err
2014-03-09 21:45:36 +01:00
}