| 1 |
// Copyright 2026 Bjørn Erik Pedersen |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
package golocales |
| 5 |
|
| 6 |
import ( |
| 7 |
"cmp" |
| 8 |
"fmt" |
| 9 |
"math" |
| 10 |
"slices" |
| 11 |
"strconv" |
| 12 |
"strings" |
| 13 |
"time" |
| 14 |
) |
| 15 |
|
| 16 |
// New returns a new Translator for the given locale, |
| 17 |
// or nil if the locale is not supported. |
| 18 |
func New(locale string) Translator { |
| 19 |
// Normalize locale. |
| 20 |
locale = strings.ToLower(locale) |
| 21 |
locale = strings.ReplaceAll(locale, "-", "_") |
| 22 |
|
| 23 |
i, ok := slices.BinarySearchFunc(_locales[:], locale, func(e localeEntry, target string) int { |
| 24 |
return cmp.Compare(e.name, target) |
| 25 |
}) |
| 26 |
if !ok { |
| 27 |
return nil |
| 28 |
} |
| 29 |
return &translatorImpl{data: &_locales[i]} |
| 30 |
} |
| 31 |
|
| 32 |
type Translator interface { |
| 33 |
// WeekdaysWide returns the full names of the week days, starting with Sunday. |
| 34 |
WeekdaysWide() []string |
| 35 |
// WeekdaysAbbreviated returns the abbreviated names of the week days, starting with Sunday. |
| 36 |
WeekdaysAbbreviated() []string |
| 37 |
|
| 38 |
// MonthsWide returns the full names of the months, starting with January. |
| 39 |
MonthsWide() []string |
| 40 |
// MonthsAbbreviated returns the abbreviated names of the months, starting with January. |
| 41 |
MonthsAbbreviated() []string |
| 42 |
|
| 43 |
// FormatDateFull formats the given time using the full date pattern for the locale. |
| 44 |
FormatDateFull(t time.Time) string |
| 45 |
// FormatDateLong formats the given time using the long date pattern for the locale. |
| 46 |
FormatDateLong(t time.Time) string |
| 47 |
// FormatDateMedium formats the given time using the medium date pattern for the locale. |
| 48 |
FormatDateMedium(t time.Time) string |
| 49 |
// FormatDateShort formats the given time using the short date pattern for the locale. |
| 50 |
FormatDateShort(t time.Time) string |
| 51 |
// FormatTimeFull formats the given time using the full time pattern for the locale. |
| 52 |
FormatTimeFull(t time.Time) string |
| 53 |
// FormatTimeLong formats the given time using the long time pattern for the locale. |
| 54 |
FormatTimeLong(t time.Time) string |
| 55 |
// FormatTimeMedium formats the given time using the medium time pattern for the locale. |
| 56 |
FormatTimeMedium(t time.Time) string |
| 57 |
// FormatTimeShort formats the given time using the short time pattern for the locale. |
| 58 |
FormatTimeShort(t time.Time) string |
| 59 |
|
| 60 |
// FormatNumber formats the given number with the specified number of decimal places. |
| 61 |
FormatNumber(num float64, p int) string |
| 62 |
// FormatAccounting formats the given number as an accounting value with the specified number of decimal places and currency. |
| 63 |
FormatAccounting(num float64, p int, currency string) string |
| 64 |
// FormatPercent formats the given number as a percentage with the specified number of decimal places. |
| 65 |
FormatPercent(num float64, p int) string |
| 66 |
// FormatCurrency formats the given number as a currency value with the specified number of decimal places and currency. |
| 67 |
FormatCurrency(num float64, p int, currency string) string |
| 68 |
} |
| 69 |
|
| 70 |
type translatorImpl struct { |
| 71 |
data *localeEntry |
| 72 |
} |
| 73 |
|
| 74 |
func (t *translatorImpl) WeekdaysWide() []string { |
| 75 |
d := _days[t.data.daysWide] |
| 76 |
return d[:] |
| 77 |
} |
| 78 |
|
| 79 |
func (t *translatorImpl) WeekdaysAbbreviated() []string { |
| 80 |
d := _days[t.data.daysAbbr] |
| 81 |
return d[:] |
| 82 |
} |
| 83 |
|
| 84 |
func (t *translatorImpl) MonthsWide() []string { |
| 85 |
m := _months[t.data.monthsWide] |
| 86 |
return m[:] |
| 87 |
} |
| 88 |
|
| 89 |
func (t *translatorImpl) MonthsAbbreviated() []string { |
| 90 |
m := _months[t.data.monthsAbbr] |
| 91 |
return m[:] |
| 92 |
} |
| 93 |
|
| 94 |
// Date/time formatting. |
| 95 |
|
| 96 |
func (t *translatorImpl) FormatDateFull(tm time.Time) string { |
| 97 |
return t.formatPattern(_strings[t.data.dateFull], tm) |
| 98 |
} |
| 99 |
|
| 100 |
func (t *translatorImpl) FormatDateLong(tm time.Time) string { |
| 101 |
return t.formatPattern(_strings[t.data.dateLong], tm) |
| 102 |
} |
| 103 |
|
| 104 |
func (t *translatorImpl) FormatDateMedium(tm time.Time) string { |
| 105 |
return t.formatPattern(_strings[t.data.dateMedium], tm) |
| 106 |
} |
| 107 |
|
| 108 |
func (t *translatorImpl) FormatDateShort(tm time.Time) string { |
| 109 |
return t.formatPattern(_strings[t.data.dateShort], tm) |
| 110 |
} |
| 111 |
|
| 112 |
func (t *translatorImpl) FormatTimeFull(tm time.Time) string { |
| 113 |
return t.formatPattern(_strings[t.data.timeFull], tm) |
| 114 |
} |
| 115 |
|
| 116 |
func (t *translatorImpl) FormatTimeLong(tm time.Time) string { |
| 117 |
return t.formatPattern(_strings[t.data.timeLong], tm) |
| 118 |
} |
| 119 |
|
| 120 |
func (t *translatorImpl) FormatTimeMedium(tm time.Time) string { |
| 121 |
return t.formatPattern(_strings[t.data.timeMedium], tm) |
| 122 |
} |
| 123 |
|
| 124 |
func (t *translatorImpl) FormatTimeShort(tm time.Time) string { |
| 125 |
return t.formatPattern(_strings[t.data.timeShort], tm) |
| 126 |
} |
| 127 |
|
| 128 |
// formatPattern interprets a CLDR date/time pattern and formats the given time. |
| 129 |
func (t *translatorImpl) formatPattern(pattern string, tm time.Time) string { |
| 130 |
var buf strings.Builder |
| 131 |
i := 0 |
| 132 |
for i < len(pattern) { |
| 133 |
c := pattern[i] |
| 134 |
|
| 135 |
// Quoted literal text. |
| 136 |
if c == '\'' { |
| 137 |
i++ |
| 138 |
if i < len(pattern) && pattern[i] == '\'' { |
| 139 |
buf.WriteByte('\'') |
| 140 |
i++ |
| 141 |
continue |
| 142 |
} |
| 143 |
for i < len(pattern) && pattern[i] != '\'' { |
| 144 |
buf.WriteByte(pattern[i]) |
| 145 |
i++ |
| 146 |
} |
| 147 |
if i < len(pattern) { |
| 148 |
i++ // skip closing quote |
| 149 |
} |
| 150 |
continue |
| 151 |
} |
| 152 |
|
| 153 |
// Pattern letter: consume run of same character. |
| 154 |
if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' { |
| 155 |
start := i |
| 156 |
for i < len(pattern) && pattern[i] == c { |
| 157 |
i++ |
| 158 |
} |
| 159 |
n := i - start |
| 160 |
t.formatField(&buf, c, n, tm) |
| 161 |
continue |
| 162 |
} |
| 163 |
|
| 164 |
// Literal character. |
| 165 |
buf.WriteByte(c) |
| 166 |
i++ |
| 167 |
} |
| 168 |
return buf.String() |
| 169 |
} |
| 170 |
|
| 171 |
func (t *translatorImpl) formatField(buf *strings.Builder, c byte, n int, tm time.Time) { |
| 172 |
switch c { |
| 173 |
case 'y': // year |
| 174 |
year := tm.Year() |
| 175 |
if n == 2 { |
| 176 |
fmt.Fprintf(buf, "%02d", year%100) |
| 177 |
} else { |
| 178 |
fmt.Fprintf(buf, "%d", year) |
| 179 |
} |
| 180 |
case 'M': // month |
| 181 |
month := tm.Month() |
| 182 |
switch { |
| 183 |
case n >= 4: // MMMM = wide month name |
| 184 |
m := _months[t.data.monthsWide] |
| 185 |
buf.WriteString(m[month-1]) |
| 186 |
case n == 3: // MMM = abbreviated month name |
| 187 |
m := _months[t.data.monthsAbbr] |
| 188 |
buf.WriteString(m[month-1]) |
| 189 |
case n == 2: // MM = zero-padded |
| 190 |
fmt.Fprintf(buf, "%02d", month) |
| 191 |
default: // M = no padding |
| 192 |
fmt.Fprintf(buf, "%d", month) |
| 193 |
} |
| 194 |
case 'd': // day of month |
| 195 |
day := tm.Day() |
| 196 |
if n >= 2 { |
| 197 |
fmt.Fprintf(buf, "%02d", day) |
| 198 |
} else { |
| 199 |
fmt.Fprintf(buf, "%d", day) |
| 200 |
} |
| 201 |
case 'E': // weekday |
| 202 |
wd := tm.Weekday() // Sunday=0 |
| 203 |
if n >= 4 { // EEEE = wide |
| 204 |
d := _days[t.data.daysWide] |
| 205 |
buf.WriteString(d[wd]) |
| 206 |
} else { // EEE = abbreviated |
| 207 |
d := _days[t.data.daysAbbr] |
| 208 |
buf.WriteString(d[wd]) |
| 209 |
} |
| 210 |
case 'H': // hour 24h |
| 211 |
hour := tm.Hour() |
| 212 |
if n >= 2 { |
| 213 |
fmt.Fprintf(buf, "%02d", hour) |
| 214 |
} else { |
| 215 |
fmt.Fprintf(buf, "%d", hour) |
| 216 |
} |
| 217 |
case 'h': // hour 12h |
| 218 |
hour := tm.Hour() % 12 |
| 219 |
if hour == 0 { |
| 220 |
hour = 12 |
| 221 |
} |
| 222 |
if n >= 2 { |
| 223 |
fmt.Fprintf(buf, "%02d", hour) |
| 224 |
} else { |
| 225 |
fmt.Fprintf(buf, "%d", hour) |
| 226 |
} |
| 227 |
case 'm': // minute |
| 228 |
min := tm.Minute() |
| 229 |
if n >= 2 { |
| 230 |
fmt.Fprintf(buf, "%02d", min) |
| 231 |
} else { |
| 232 |
fmt.Fprintf(buf, "%d", min) |
| 233 |
} |
| 234 |
case 's': // second |
| 235 |
sec := tm.Second() |
| 236 |
if n >= 2 { |
| 237 |
fmt.Fprintf(buf, "%02d", sec) |
| 238 |
} else { |
| 239 |
fmt.Fprintf(buf, "%d", sec) |
| 240 |
} |
| 241 |
case 'a': // AM/PM |
| 242 |
if tm.Hour() < 12 { |
| 243 |
// This is a choice based mostly on how Hugo's old library did it, |
| 244 |
// but this is a common convention in digital writing. |
| 245 |
buf.WriteString("am") |
| 246 |
} else { |
| 247 |
buf.WriteString("pm") |
| 248 |
} |
| 249 |
case 'z': // timezone |
| 250 |
if n >= 4 { // zzzz = long timezone name |
| 251 |
buf.WriteString(t.longTimezoneName(tm)) |
| 252 |
} else { // z = short timezone abbreviation |
| 253 |
name, _ := tm.Zone() |
| 254 |
buf.WriteString(name) |
| 255 |
} |
| 256 |
default: |
| 257 |
// Unknown pattern letter: output as-is. |
| 258 |
for range n { |
| 259 |
buf.WriteByte(c) |
| 260 |
} |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
func (t *translatorImpl) longTimezoneName(tm time.Time) string { |
| 265 |
loc := tm.Location().String() |
| 266 |
meta, ok := kvLookup(_metazones[:], loc) |
| 267 |
if !ok { |
| 268 |
name, _ := tm.Zone() |
| 269 |
return name |
| 270 |
} |
| 271 |
tzn := _tzNames[t.data.tzNames] |
| 272 |
idx := 0 |
| 273 |
if tm.IsDST() { |
| 274 |
idx = 1 |
| 275 |
} |
| 276 |
if name, ok := kvLookup(tzn[idx], meta); ok { |
| 277 |
return name |
| 278 |
} |
| 279 |
name, _ := tm.Zone() |
| 280 |
return name |
| 281 |
} |
| 282 |
|
| 283 |
func (t *translatorImpl) currencySymbol(code string) string { |
| 284 |
code = strings.ToUpper(code) |
| 285 |
overrides := _currencyOverrides[t.data.currencyOverrides] |
| 286 |
if s, ok := kvLookup(overrides, code); ok { |
| 287 |
return s |
| 288 |
} |
| 289 |
if s, ok := kvLookup(_currencyDefaults[:], code); ok { |
| 290 |
return s |
| 291 |
} |
| 292 |
return code |
| 293 |
} |
| 294 |
|
| 295 |
func (t *translatorImpl) FormatAccounting(num float64, p int, currency string) string { |
| 296 |
symbol := t.currencySymbol(currency) |
| 297 |
formatted := t.FormatNumber(num, p) |
| 298 |
|
| 299 |
pattern := _strings[t.data.stdCurrencyPattern] |
| 300 |
if pattern == "" { |
| 301 |
return formatted + " " + symbol |
| 302 |
} |
| 303 |
|
| 304 |
// Handle positive/negative subpatterns (separated by ";"). |
| 305 |
positive, _, _ := strings.Cut(pattern, ";") |
| 306 |
|
| 307 |
// Replace ¤ with symbol and number pattern with formatted number. |
| 308 |
result := strings.Replace(positive, "¤", symbol, 1) |
| 309 |
numPattern := strings.TrimSpace(strings.Replace(positive, "¤", "", 1)) |
| 310 |
result = strings.Replace(result, numPattern, formatted, 1) |
| 311 |
|
| 312 |
return result |
| 313 |
} |
| 314 |
|
| 315 |
func (t *translatorImpl) FormatPercent(num float64, p int) string { |
| 316 |
formatted := t.FormatNumber(num, p) |
| 317 |
pattern := _strings[t.data.percentPattern] |
| 318 |
if pattern == "" { |
| 319 |
return formatted + "%" |
| 320 |
} |
| 321 |
percentSym := _strings[t.data.percent] |
| 322 |
result := strings.Replace(pattern, "%", percentSym, 1) |
| 323 |
numPattern := strings.TrimSpace(strings.Replace(pattern, "%", "", 1)) |
| 324 |
result = strings.Replace(result, numPattern, formatted, 1) |
| 325 |
return result |
| 326 |
} |
| 327 |
|
| 328 |
func (t *translatorImpl) FormatCurrency(num float64, p int, currency string) string { |
| 329 |
symbol := t.currencySymbol(currency) |
| 330 |
formatted := t.FormatNumber(num, p) |
| 331 |
|
| 332 |
pattern := _strings[t.data.stdCurrencyPattern] |
| 333 |
if pattern == "" { |
| 334 |
return formatted + " " + symbol |
| 335 |
} |
| 336 |
|
| 337 |
positive, _, _ := strings.Cut(pattern, ";") |
| 338 |
result := strings.Replace(positive, "¤", symbol, 1) |
| 339 |
numPattern := strings.TrimSpace(strings.Replace(positive, "¤", "", 1)) |
| 340 |
result = strings.Replace(result, numPattern, formatted, 1) |
| 341 |
return result |
| 342 |
} |
| 343 |
|
| 344 |
func (t *translatorImpl) FormatNumber(num float64, p int) string { |
| 345 |
negative := num < 0 |
| 346 |
if negative { |
| 347 |
num = -num |
| 348 |
} |
| 349 |
|
| 350 |
decimal := _strings[t.data.decimal] |
| 351 |
group := _strings[t.data.group] |
| 352 |
minus := _strings[t.data.minus] |
| 353 |
|
| 354 |
// Round to the requested precision. |
| 355 |
if p > 0 { |
| 356 |
shift := math.Pow10(p) |
| 357 |
num = math.Round(num*shift) / shift |
| 358 |
} else { |
| 359 |
num = math.Round(num) |
| 360 |
} |
| 361 |
s := strconv.FormatFloat(num, 'f', p, 64) |
| 362 |
|
| 363 |
// Split into integer and fractional parts. |
| 364 |
intPart, fracPart, hasFrac := strings.Cut(s, ".") |
| 365 |
|
| 366 |
// Add grouping separators to the integer part (groups of 3 from the right). |
| 367 |
if group != "" && len(intPart) > 3 { |
| 368 |
var buf strings.Builder |
| 369 |
start := len(intPart) % 3 |
| 370 |
if start == 0 { |
| 371 |
start = 3 |
| 372 |
} |
| 373 |
buf.WriteString(intPart[:start]) |
| 374 |
for i := start; i < len(intPart); i += 3 { |
| 375 |
buf.WriteString(group) |
| 376 |
buf.WriteString(intPart[i : i+3]) |
| 377 |
} |
| 378 |
intPart = buf.String() |
| 379 |
} |
| 380 |
|
| 381 |
var result string |
| 382 |
if hasFrac { |
| 383 |
result = intPart + decimal + fracPart |
| 384 |
} else { |
| 385 |
result = intPart |
| 386 |
} |
| 387 |
|
| 388 |
if negative { |
| 389 |
result = minus + result |
| 390 |
} |
| 391 |
return result |
| 392 |
} |
| 393 |
|
| 394 |
// kvLookup does a binary search on a sorted slice of kv pairs. |
| 395 |
func kvLookup(pairs []kv, key string) (string, bool) { |
| 396 |
i, ok := slices.BinarySearchFunc(pairs, key, func(p kv, target string) int { |
| 397 |
return cmp.Compare(p.k, target) |
| 398 |
}) |
| 399 |
if ok { |
| 400 |
return pairs[i].v, true |
| 401 |
} |
| 402 |
return "", false |
| 403 |
} |