1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#endif
internal import _FoundationICU
typealias ICUNumberFormatterSkeleton = String
/// For testing purposes, remove all caches from below formatters.
internal func resetAllNumberFormatterCaches() {
ICUNumberFormatter.cache.removeAllObjects()
ICUCurrencyNumberFormatter.cache.removeAllObjects()
ICUPercentNumberFormatter.cache.removeAllObjects()
ICUMeasurementNumberFormatter.cache.removeAllObjects()
}
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
internal class ICUNumberFormatterBase : @unchecked Sendable {
/// `Sendable` notes: ICU's `UNumberFormatter` itself is thread safe. The result type is not, but we create that each time we format.
internal let uformatter: OpaquePointer
/// Stored for testing purposes only
internal let skeleton: String
init?(skeleton: String, localeIdentifier: String, preferences: LocalePreferences?) {
self.skeleton = skeleton
let ustr = Array(skeleton.utf16)
var status = U_ZERO_ERROR
let formatter = unumf_openForSkeletonAndLocale(ustr, Int32(ustr.count), localeIdentifier, &status)
guard let formatter else {
return nil
}
guard status.isSuccess else {
unumf_close(formatter)
return nil
}
uformatter = formatter
}
deinit {
unumf_close(uformatter)
}
struct AttributePosition {
let field: UNumberFormatFields
let begin: Int
let end: Int
}
enum Value {
case integer(Int64)
case floatingPoint(Double)
case decimal(Decimal)
case numericStringRepresentation(String)
var fallbackDescription: String {
switch self {
case .integer(let i): return String(i)
case .floatingPoint(let d): return String(d)
case .decimal(let d): return d.description
case .numericStringRepresentation(let i): return i
}
}
}
func attributedStringFromPositions(_ positions: [ICUNumberFormatter.AttributePosition], string: String) -> AttributedString {
typealias NumberPartAttribute = AttributeScopes.FoundationAttributes.NumberFormatAttributes.NumberPartAttribute.NumberPart
typealias NumberSymbolAttribute = AttributeScopes.FoundationAttributes.NumberFormatAttributes.SymbolAttribute.Symbol
var attrstr = AttributedString(string)
for attr in positions {
let strRange = String.Index(utf16Offset: attr.begin, in: string) ..<
String.Index(utf16Offset: attr.end, in: string)
let range = Range<AttributedString.Index>(strRange, in: attrstr)!
let field = attr.field
var container = AttributeContainer()
if let part = NumberPartAttribute(unumberFormatField: field) {
container.numberPart = part
}
if let symbol = NumberSymbolAttribute(unumberFormatField: field) {
container.numberSymbol = symbol
}
attrstr[range].mergeAttributes(container)
}
return attrstr
}
func attributedFormatPositions(_ v: Value) -> (String, [AttributePosition])? {
var result: FormatResult?
switch v {
case .integer(let v):
result = try? FormatResult(formatter: uformatter, value: v)
case .floatingPoint(let v):
result = try? FormatResult(formatter: uformatter, value: v)
case .decimal(let v):
result = try? FormatResult(formatter: uformatter, value: v)
case .numericStringRepresentation(let v):
result = try? FormatResult(formatter: uformatter, value: v)
}
guard let result, let str = result.string else {
return nil
}
do {
let positer = try ICU.FieldPositer()
var status = U_ZERO_ERROR
unumf_resultGetAllFieldPositions(result.result, positer.positer, &status)
try status.checkSuccess()
let attributePositions = positer.fields.compactMap { next -> AttributePosition? in
return AttributePosition(field: UNumberFormatFields(CInt(next.field)), begin: next.begin, end: next.end)
}
return (str, attributePositions)
} catch {
return nil
}
}
func format(_ v: Int64) -> String? {
try? FormatResult(formatter: uformatter, value: v).string
}
func format(_ v: Double) -> String? {
try? FormatResult(formatter: uformatter, value: v).string
}
func format(_ v: Decimal) -> String? {
try? FormatResult(formatter: uformatter, value: v).string
}
func format(_ v: String) -> String? {
try? FormatResult(formatter: uformatter, value: v).string
}
// MARK: -
class FormatResult {
var result: OpaquePointer
init(formatter: OpaquePointer, value: Int64) throws {
var status = U_ZERO_ERROR
result = unumf_openResult(&status)
try status.checkSuccess()
unumf_formatInt(formatter, value, result, &status)
try status.checkSuccess()
}
init(formatter: OpaquePointer, value: Double) throws {
var status = U_ZERO_ERROR
result = unumf_openResult(&status)
try status.checkSuccess()
unumf_formatDouble(formatter, value, result, &status)
try status.checkSuccess()
}
init(formatter: OpaquePointer, value: Decimal) throws {
var status = U_ZERO_ERROR
result = unumf_openResult(&status)
try status.checkSuccess()
#if FOUNDATION_FRAMEWORK // TODO: Remove this when Decimal is moved
var v = value
var str = NSDecimalString(&v, nil)
#else
var str = value.description
#endif // FOUNDATION_FRAMEWORK
str.withUTF8 {
unumf_formatDecimal(formatter, $0.baseAddress, Int32($0.count), result, &status)
}
try status.checkSuccess()
}
init(formatter: OpaquePointer, value: String) throws {
var status = U_ZERO_ERROR
result = unumf_openResult(&status)
try status.checkSuccess()
var value = value
value.withUTF8 {
unumf_formatDecimal(formatter, $0.baseAddress, Int32($0.count), result, &status)
}
try status.checkSuccess()
}
deinit {
unumf_closeResult(result)
}
var string: String? {
return _withResizingUCharBuffer { buffer, size, status in
unumf_resultToString(result, buffer, size, &status)
}
}
}
}
// MARK: - Integer
final class ICUNumberFormatter : ICUNumberFormatterBase, @unchecked Sendable {
fileprivate struct Signature : Hashable {
let collection: NumberFormatStyleConfiguration.Collection
let localeIdentifier: String
let localePreferences: LocalePreferences?
}
fileprivate static let cache = FormatterCache<Signature, ICUNumberFormatter?>()
private static func _create(with signature: Signature) -> ICUNumberFormatter? {
Self.cache.formatter(for: signature) {
.init(skeleton: signature.collection.skeleton, localeIdentifier: signature.localeIdentifier, preferences: signature.localePreferences)
}
}
static func create<T: BinaryInteger>(for style: IntegerFormatStyle<T>) -> ICUNumberFormatter? {
_create(with: .init(collection: style.collection, localeIdentifier: style.locale.identifierCapturingPreferences, localePreferences: style.locale.prefs))
}
static func create(for style: Decimal.FormatStyle) -> ICUNumberFormatter? {
_create(with: .init(collection: style.collection, localeIdentifier: style.locale.identifierCapturingPreferences, localePreferences: style.locale.prefs))
}
static func create<T: BinaryFloatingPoint>(for style: FloatingPointFormatStyle<T>) -> ICUNumberFormatter? {
_create(with: .init(collection: style.collection, localeIdentifier: style.locale.identifierCapturingPreferences, localePreferences: style.locale.prefs))
}
func attributedFormat(_ v: Value) -> AttributedString {
guard let (str, attributes) = attributedFormatPositions(v) else {
return AttributedString(v.fallbackDescription)
}
return attributedStringFromPositions(attributes, string: str)
}
}
// MARK: - Currency
final class ICUCurrencyNumberFormatter : ICUNumberFormatterBase, @unchecked Sendable {
fileprivate struct Signature : Hashable {
let collection: CurrencyFormatStyleConfiguration.Collection
let currencyCode: String
let localeIdentifier: String
let localePreferences: LocalePreferences?
}
private static func skeleton(for signature: Signature) -> String {
var s = "currency/\(signature.currencyCode)"
let stem = signature.collection.skeleton
if stem.count > 0 {
s += " " + stem
}
return s
}
fileprivate static let cache = FormatterCache<Signature, ICUCurrencyNumberFormatter?>()
static private func _create(with signature: Signature) -> ICUCurrencyNumberFormatter? {
return Self.cache.formatter(for: signature) {
.init(skeleton: Self.skeleton(for: signature), localeIdentifier: signature.localeIdentifier, preferences: signature.localePreferences)
}
}
static func create<T: BinaryInteger>(for style: IntegerFormatStyle<T>.Currency) -> ICUCurrencyNumberFormatter? {
_create(with: .init(collection: style.collection, currencyCode: style.currencyCode, localeIdentifier: style.locale.identifierCapturingPreferences, localePreferences: style.locale.prefs))
}
static func create(for style: Decimal.FormatStyle.Currency) -> ICUCurrencyNumberFormatter? {
_create(with: .init(collection: style.collection, currencyCode: style.currencyCode, localeIdentifier: style.locale.identifierCapturingPreferences, localePreferences: style.locale.prefs))
}
static func create<T: BinaryFloatingPoint>(for style: FloatingPointFormatStyle<T>.Currency) -> ICUCurrencyNumberFormatter? {
_create(with: .init(collection: style.collection, currencyCode: style.currencyCode, localeIdentifier: style.locale.identifierCapturingPreferences, localePreferences: style.locale.prefs))
}
func attributedFormat(_ v: Value) -> AttributedString {
guard let (str, attributes) = attributedFormatPositions(v) else {
return AttributedString(v.fallbackDescription)
}
return attributedStringFromPositions(attributes, string: str)
}
}
// MARK: - Integer Percent
final class ICUPercentNumberFormatter : ICUNumberFormatterBase, @unchecked Sendable {
fileprivate struct Signature : Hashable {
let collection: NumberFormatStyleConfiguration.Collection
let localeIdentifier: String
let localePreferences: LocalePreferences?
}
private static func skeleton(for signature: Signature) -> String {
var s = "percent"
let stem = signature.collection.skeleton
if stem.count > 0 {
s += " " + stem
}
return s
}
fileprivate static let cache = FormatterCache<Signature, ICUPercentNumberFormatter?>()
private static func _create(with signature: Signature) -> ICUPercentNumberFormatter? {
return Self.cache.formatter(for: signature) {
.init(skeleton: Self.skeleton(for: signature), localeIdentifier: signature.localeIdentifier, preferences: signature.localePreferences)
}
}
static func create<T: BinaryInteger>(for style: IntegerFormatStyle<T>.Percent) -> ICUPercentNumberFormatter? {
_create(with: .init(collection: style.collection, localeIdentifier: style.locale.identifierCapturingPreferences, localePreferences: style.locale.prefs))
}
static func create(for style: Decimal.FormatStyle.Percent) -> ICUPercentNumberFormatter? {
_create(with: .init(collection: style.collection, localeIdentifier: style.locale.identifierCapturingPreferences, localePreferences: style.locale.prefs))
}
static func create<T: BinaryFloatingPoint>(for style: FloatingPointFormatStyle<T>.Percent) -> ICUPercentNumberFormatter? {
_create(with: .init(collection: style.collection, localeIdentifier: style.locale.identifierCapturingPreferences, localePreferences: style.locale.prefs))
}
func attributedFormat(_ v: Value) -> AttributedString {
guard let (str, attributes) = attributedFormatPositions(v) else {
return AttributedString(v.fallbackDescription)
}
return attributedStringFromPositions(attributes, string: str)
}
}
// MARK: - Byte Count
final class ICUByteCountNumberFormatter : ICUNumberFormatterBase, @unchecked Sendable {
fileprivate struct Signature : Hashable {
let skeleton: String
let localeIdentifier: String
let localePreferences: LocalePreferences?
}
fileprivate static let cache = FormatterCache<Signature, ICUByteCountNumberFormatter?>()
static func create(for skeleton: String, locale: Locale) -> ICUByteCountNumberFormatter? {
let signature = Signature(skeleton: skeleton, localeIdentifier: locale.identifierCapturingPreferences, localePreferences: locale.prefs)
return Self.cache.formatter(for: signature) {
.init(skeleton: skeleton, localeIdentifier: locale.identifierCapturingPreferences, preferences: locale.prefs)
}
}
func attributedFormat(_ v: Value, unit: ByteCountFormatStyle.Unit) -> AttributedString {
guard let (str, attributes) = attributedFormatPositions(v) else {
return AttributedString(v.fallbackDescription)
}
return attributedStringFromPositions(attributes, string: str, unit: unit)
}
private func attributedStringFromPositions(_ positions: [ICUNumberFormatter.AttributePosition], string: String, unit: ByteCountFormatStyle.Unit) -> AttributedString {
typealias NumberPartAttribute = AttributeScopes.FoundationAttributes.NumberFormatAttributes.NumberPartAttribute.NumberPart
typealias NumberSymbolAttribute = AttributeScopes.FoundationAttributes.NumberFormatAttributes.SymbolAttribute.Symbol
typealias ByteCountAttribute = AttributeScopes.FoundationAttributes.ByteCountAttribute.Component
var attrstr = AttributedString(string)
for attr in positions {
let strRange = String.Index(utf16Offset: attr.begin, in: string) ..<
String.Index(utf16Offset: attr.end, in: string)
let range = Range<AttributedString.Index>(strRange, in: attrstr)!
let field = attr.field
var container = AttributeContainer()
if let part = NumberPartAttribute(unumberFormatField: field) {
container.numberPart = part
}
if let symbol = NumberSymbolAttribute(unumberFormatField: field) {
container.numberSymbol = symbol
}
if let comp = ByteCountAttribute(unumberFormatField: field, unit: unit) {
container.byteCount = comp
}
attrstr[range].mergeAttributes(container)
}
return attrstr
}
}
// MARK: - Measurement
final class ICUMeasurementNumberFormatter : ICUNumberFormatterBase, @unchecked Sendable {
fileprivate struct Signature : Hashable {
let skeleton: String
let localeIdentifier: String
let localePreferences: LocalePreferences?
}
fileprivate static let cache = FormatterCache<Signature, ICUMeasurementNumberFormatter?>()
static func create(for skeleton: String, locale: Locale) -> ICUMeasurementNumberFormatter? {
let signature = Signature(skeleton: skeleton, localeIdentifier: locale.identifierCapturingPreferences, localePreferences: locale.prefs)
return Self.cache.formatter(for: signature) {
.init(skeleton: skeleton, localeIdentifier: locale.identifierCapturingPreferences, preferences: locale.prefs)
}
}
func attributedFormat(_ v: Value) -> AttributedString {
guard let (str, attributes) = attributedFormatPositions(v) else {
return AttributedString(v.fallbackDescription)
}
return attributedStringFromPositions(attributes, string: str)
}
/// Overrides superclass implementation to add the `MeasurementAttribute` property.
override func attributedStringFromPositions(_ positions: [ICUNumberFormatter.AttributePosition], string: String) -> AttributedString {
typealias NumberPartAttribute = AttributeScopes.FoundationAttributes.NumberFormatAttributes.NumberPartAttribute.NumberPart
typealias NumberSymbolAttribute = AttributeScopes.FoundationAttributes.NumberFormatAttributes.SymbolAttribute.Symbol
typealias MeasurementAttribute = AttributeScopes.FoundationAttributes.MeasurementAttribute.Component
var attrstr = AttributedString(string)
for attr in positions {
let strRange = String.Index(utf16Offset: attr.begin, in: string) ..<
String.Index(utf16Offset: attr.end, in: string)
let range = Range<AttributedString.Index>(strRange, in: attrstr)!
let field = attr.field
var container = AttributeContainer()
if let part = NumberPartAttribute(unumberFormatField: field) {
container.numberPart = part
}
if let symbol = NumberSymbolAttribute(unumberFormatField: field) {
container.numberSymbol = symbol
}
if let comp = MeasurementAttribute(unumberFormatField: field) {
container.measurement = comp
}
attrstr[range].mergeAttributes(container)
}
return attrstr
}
// The raw values are for use with ICU's API. They should match CLDR's declaration at https://github.com/unicode-org/cldr/blob/master/common/supplemental/units.xml
internal enum Usage: String {
// common
case general = "default"
case person
// energy
case food
// length
case personHeight = "person-height"
case road
case focalLength = "focal-length"
case rainfall
case snowfall
case visibility = "visiblty"
// pressure
case barometric = "baromtrc"
// speed
case wind
// temperature
case weather
// volume
case fluid
// Foundation's flag: Do not convert to preferred unit
case asProvided
}
enum UnitWidth: String, Codable {
case wide = "unit-width-full-name"
case abbreviated = "unit-width-short"
case narrow = "unit-width-narrow"
init(_ width: Duration.UnitsFormatStyle.UnitWidth) {
switch width.width.option {
case .wide:
self = .wide
case .abbreviated:
self = .abbreviated
case .narrow:
self = .narrow
}
}
}
static func skeleton(_ unitSkeleton: String?, width: UnitWidth, usage: Usage?, numberFormatStyle: FloatingPointFormatStyle<Double>?) -> String {
var stem = ""
if let unitSkeleton = unitSkeleton {
stem += unitSkeleton + " " + width.rawValue
if let usage {
// ICU handles the conversion when using the `usage` skeleton.
stem += " usage/" + usage.rawValue
}
}
if let numberFormatSkeleton = numberFormatStyle?.collection.skeleton {
if stem.count > 0 {
stem += " "
}
stem += numberFormatSkeleton
}
return stem
}
}
|