reldatefmt.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /*
  4. ******************************************************************************
  5. * Copyright (C) 2014-2016, International Business Machines Corporation and
  6. * others. All Rights Reserved.
  7. ******************************************************************************
  8. *
  9. * File reldatefmt.cpp
  10. ******************************************************************************
  11. */
  12. #include "unicode/reldatefmt.h"
  13. #if !UCONFIG_NO_FORMATTING && !UCONFIG_NO_BREAK_ITERATION
  14. #include <cmath>
  15. #include <functional>
  16. #include "unicode/calendar.h"
  17. #include "unicode/datefmt.h"
  18. #include "unicode/dtfmtsym.h"
  19. #include "unicode/ucasemap.h"
  20. #include "unicode/ureldatefmt.h"
  21. #include "unicode/udisplaycontext.h"
  22. #include "unicode/unum.h"
  23. #include "unicode/localpointer.h"
  24. #include "unicode/plurrule.h"
  25. #include "unicode/simpleformatter.h"
  26. #include "unicode/decimfmt.h"
  27. #include "unicode/numfmt.h"
  28. #include "unicode/brkiter.h"
  29. #include "unicode/simpleformatter.h"
  30. #include "uresimp.h"
  31. #include "unicode/ures.h"
  32. #include "cstring.h"
  33. #include "ucln_in.h"
  34. #include "mutex.h"
  35. #include "charstr.h"
  36. #include "uassert.h"
  37. #include "quantityformatter.h"
  38. #include "resource.h"
  39. #include "sharedbreakiterator.h"
  40. #include "sharedpluralrules.h"
  41. #include "sharednumberformat.h"
  42. #include "standardplural.h"
  43. #include "unifiedcache.h"
  44. #include "util.h"
  45. #include "formatted_string_builder.h"
  46. #include "number_utypes.h"
  47. #include "number_modifiers.h"
  48. #include "formattedval_impl.h"
  49. #include "number_utils.h"
  50. // Copied from uscript_props.cpp
  51. U_NAMESPACE_BEGIN
  52. // RelativeDateTimeFormatter specific data for a single locale
  53. class RelativeDateTimeCacheData: public SharedObject {
  54. public:
  55. RelativeDateTimeCacheData() : combinedDateAndTime(nullptr) {
  56. // Initialize the cache arrays
  57. for (int32_t style = 0; style < UDAT_STYLE_COUNT; ++style) {
  58. for (int32_t relUnit = 0; relUnit < UDAT_REL_UNIT_COUNT; ++relUnit) {
  59. for (int32_t pl = 0; pl < StandardPlural::COUNT; ++pl) {
  60. relativeUnitsFormatters[style][relUnit][0][pl] = nullptr;
  61. relativeUnitsFormatters[style][relUnit][1][pl] = nullptr;
  62. }
  63. }
  64. }
  65. for (int32_t i = 0; i < UDAT_STYLE_COUNT; ++i) {
  66. fallBackCache[i] = -1;
  67. }
  68. }
  69. virtual ~RelativeDateTimeCacheData();
  70. // no numbers: e.g Next Tuesday; Yesterday; etc.
  71. UnicodeString absoluteUnits[UDAT_STYLE_COUNT][UDAT_ABSOLUTE_UNIT_COUNT][UDAT_DIRECTION_COUNT];
  72. // SimpleFormatter pointers for relative unit format,
  73. // e.g., Next Tuesday; Yesterday; etc. For third index, 0
  74. // means past, e.g., 5 days ago; 1 means future, e.g., in 5 days.
  75. SimpleFormatter *relativeUnitsFormatters[UDAT_STYLE_COUNT]
  76. [UDAT_REL_UNIT_COUNT][2][StandardPlural::COUNT];
  77. const UnicodeString& getAbsoluteUnitString(int32_t fStyle,
  78. UDateAbsoluteUnit unit,
  79. UDateDirection direction) const;
  80. const SimpleFormatter* getRelativeUnitFormatter(int32_t fStyle,
  81. UDateRelativeUnit unit,
  82. int32_t pastFutureIndex,
  83. int32_t pluralUnit) const;
  84. const SimpleFormatter* getRelativeDateTimeUnitFormatter(int32_t fStyle,
  85. URelativeDateTimeUnit unit,
  86. int32_t pastFutureIndex,
  87. int32_t pluralUnit) const;
  88. const UnicodeString emptyString;
  89. // Mapping from source to target styles for alias fallback.
  90. int32_t fallBackCache[UDAT_STYLE_COUNT];
  91. void adoptCombinedDateAndTime(SimpleFormatter *fmtToAdopt) {
  92. delete combinedDateAndTime;
  93. combinedDateAndTime = fmtToAdopt;
  94. }
  95. const SimpleFormatter *getCombinedDateAndTime() const {
  96. return combinedDateAndTime;
  97. }
  98. private:
  99. SimpleFormatter *combinedDateAndTime;
  100. RelativeDateTimeCacheData(const RelativeDateTimeCacheData &other);
  101. RelativeDateTimeCacheData& operator=(
  102. const RelativeDateTimeCacheData &other);
  103. };
  104. RelativeDateTimeCacheData::~RelativeDateTimeCacheData() {
  105. // clear out the cache arrays
  106. for (int32_t style = 0; style < UDAT_STYLE_COUNT; ++style) {
  107. for (int32_t relUnit = 0; relUnit < UDAT_REL_UNIT_COUNT; ++relUnit) {
  108. for (int32_t pl = 0; pl < StandardPlural::COUNT; ++pl) {
  109. delete relativeUnitsFormatters[style][relUnit][0][pl];
  110. delete relativeUnitsFormatters[style][relUnit][1][pl];
  111. }
  112. }
  113. }
  114. delete combinedDateAndTime;
  115. }
  116. // Use fallback cache for absolute units.
  117. const UnicodeString& RelativeDateTimeCacheData::getAbsoluteUnitString(
  118. int32_t fStyle, UDateAbsoluteUnit unit, UDateDirection direction) const {
  119. int32_t style = fStyle;
  120. do {
  121. if (!absoluteUnits[style][unit][direction].isEmpty()) {
  122. return absoluteUnits[style][unit][direction];
  123. }
  124. style = fallBackCache[style];
  125. } while (style != -1);
  126. return emptyString;
  127. }
  128. const SimpleFormatter* RelativeDateTimeCacheData::getRelativeUnitFormatter(
  129. int32_t fStyle,
  130. UDateRelativeUnit unit,
  131. int32_t pastFutureIndex,
  132. int32_t pluralUnit) const {
  133. URelativeDateTimeUnit rdtunit = UDAT_REL_UNIT_COUNT;
  134. switch (unit) {
  135. case UDAT_RELATIVE_YEARS: rdtunit = UDAT_REL_UNIT_YEAR; break;
  136. case UDAT_RELATIVE_MONTHS: rdtunit = UDAT_REL_UNIT_MONTH; break;
  137. case UDAT_RELATIVE_WEEKS: rdtunit = UDAT_REL_UNIT_WEEK; break;
  138. case UDAT_RELATIVE_DAYS: rdtunit = UDAT_REL_UNIT_DAY; break;
  139. case UDAT_RELATIVE_HOURS: rdtunit = UDAT_REL_UNIT_HOUR; break;
  140. case UDAT_RELATIVE_MINUTES: rdtunit = UDAT_REL_UNIT_MINUTE; break;
  141. case UDAT_RELATIVE_SECONDS: rdtunit = UDAT_REL_UNIT_SECOND; break;
  142. default: // a unit that the above method does not handle
  143. return nullptr;
  144. }
  145. return getRelativeDateTimeUnitFormatter(fStyle, rdtunit, pastFutureIndex, pluralUnit);
  146. }
  147. // Use fallback cache for SimpleFormatter relativeUnits.
  148. const SimpleFormatter* RelativeDateTimeCacheData::getRelativeDateTimeUnitFormatter(
  149. int32_t fStyle,
  150. URelativeDateTimeUnit unit,
  151. int32_t pastFutureIndex,
  152. int32_t pluralUnit) const {
  153. while (true) {
  154. int32_t style = fStyle;
  155. do {
  156. if (relativeUnitsFormatters[style][unit][pastFutureIndex][pluralUnit] != nullptr) {
  157. return relativeUnitsFormatters[style][unit][pastFutureIndex][pluralUnit];
  158. }
  159. style = fallBackCache[style];
  160. } while (style != -1);
  161. if (pluralUnit == StandardPlural::OTHER) {
  162. break;
  163. }
  164. pluralUnit = StandardPlural::OTHER;
  165. }
  166. return nullptr; // No formatter found.
  167. }
  168. static UBool getStringByIndex(
  169. const UResourceBundle *resource,
  170. int32_t idx,
  171. UnicodeString &result,
  172. UErrorCode &status) {
  173. int32_t len = 0;
  174. const char16_t *resStr = ures_getStringByIndex(
  175. resource, idx, &len, &status);
  176. if (U_FAILURE(status)) {
  177. return false;
  178. }
  179. result.setTo(true, resStr, len);
  180. return true;
  181. }
  182. namespace {
  183. /**
  184. * Sink for enumerating all of the measurement unit display names.
  185. *
  186. * More specific bundles (en_GB) are enumerated before their parents (en_001, en, root):
  187. * Only store a value if it is still missing, that is, it has not been overridden.
  188. */
  189. struct RelDateTimeFmtDataSink : public ResourceSink {
  190. /**
  191. * Sink for patterns for relative dates and times. For example,
  192. * fields/relative/...
  193. */
  194. // Generic unit enum for storing Unit info.
  195. typedef enum RelAbsUnit {
  196. INVALID_UNIT = -1,
  197. SECOND,
  198. MINUTE,
  199. HOUR,
  200. DAY,
  201. WEEK,
  202. MONTH,
  203. QUARTER,
  204. YEAR,
  205. SUNDAY,
  206. MONDAY,
  207. TUESDAY,
  208. WEDNESDAY,
  209. THURSDAY,
  210. FRIDAY,
  211. SATURDAY
  212. } RelAbsUnit;
  213. static int32_t relUnitFromGeneric(RelAbsUnit genUnit) {
  214. // Converts the generic units to UDAT_RELATIVE version.
  215. switch (genUnit) {
  216. case SECOND:
  217. return UDAT_REL_UNIT_SECOND;
  218. case MINUTE:
  219. return UDAT_REL_UNIT_MINUTE;
  220. case HOUR:
  221. return UDAT_REL_UNIT_HOUR;
  222. case DAY:
  223. return UDAT_REL_UNIT_DAY;
  224. case WEEK:
  225. return UDAT_REL_UNIT_WEEK;
  226. case MONTH:
  227. return UDAT_REL_UNIT_MONTH;
  228. case QUARTER:
  229. return UDAT_REL_UNIT_QUARTER;
  230. case YEAR:
  231. return UDAT_REL_UNIT_YEAR;
  232. case SUNDAY:
  233. return UDAT_REL_UNIT_SUNDAY;
  234. case MONDAY:
  235. return UDAT_REL_UNIT_MONDAY;
  236. case TUESDAY:
  237. return UDAT_REL_UNIT_TUESDAY;
  238. case WEDNESDAY:
  239. return UDAT_REL_UNIT_WEDNESDAY;
  240. case THURSDAY:
  241. return UDAT_REL_UNIT_THURSDAY;
  242. case FRIDAY:
  243. return UDAT_REL_UNIT_FRIDAY;
  244. case SATURDAY:
  245. return UDAT_REL_UNIT_SATURDAY;
  246. default:
  247. return -1;
  248. }
  249. }
  250. static int32_t absUnitFromGeneric(RelAbsUnit genUnit) {
  251. // Converts the generic units to UDAT_RELATIVE version.
  252. switch (genUnit) {
  253. case DAY:
  254. return UDAT_ABSOLUTE_DAY;
  255. case WEEK:
  256. return UDAT_ABSOLUTE_WEEK;
  257. case MONTH:
  258. return UDAT_ABSOLUTE_MONTH;
  259. case QUARTER:
  260. return UDAT_ABSOLUTE_QUARTER;
  261. case YEAR:
  262. return UDAT_ABSOLUTE_YEAR;
  263. case SUNDAY:
  264. return UDAT_ABSOLUTE_SUNDAY;
  265. case MONDAY:
  266. return UDAT_ABSOLUTE_MONDAY;
  267. case TUESDAY:
  268. return UDAT_ABSOLUTE_TUESDAY;
  269. case WEDNESDAY:
  270. return UDAT_ABSOLUTE_WEDNESDAY;
  271. case THURSDAY:
  272. return UDAT_ABSOLUTE_THURSDAY;
  273. case FRIDAY:
  274. return UDAT_ABSOLUTE_FRIDAY;
  275. case SATURDAY:
  276. return UDAT_ABSOLUTE_SATURDAY;
  277. case HOUR:
  278. return UDAT_ABSOLUTE_HOUR;
  279. case MINUTE:
  280. return UDAT_ABSOLUTE_MINUTE;
  281. default:
  282. return -1;
  283. }
  284. }
  285. static int32_t keyToDirection(const char* key) {
  286. if (uprv_strcmp(key, "-2") == 0) {
  287. return UDAT_DIRECTION_LAST_2;
  288. }
  289. if (uprv_strcmp(key, "-1") == 0) {
  290. return UDAT_DIRECTION_LAST;
  291. }
  292. if (uprv_strcmp(key, "0") == 0) {
  293. return UDAT_DIRECTION_THIS;
  294. }
  295. if (uprv_strcmp(key, "1") == 0) {
  296. return UDAT_DIRECTION_NEXT;
  297. }
  298. if (uprv_strcmp(key, "2") == 0) {
  299. return UDAT_DIRECTION_NEXT_2;
  300. }
  301. return -1;
  302. }
  303. // Values kept between levels of parsing the CLDR data.
  304. int32_t pastFutureIndex; // 0 == past or 1 == future
  305. UDateRelativeDateTimeFormatterStyle style; // {LONG, SHORT, NARROW}
  306. RelAbsUnit genericUnit;
  307. RelativeDateTimeCacheData &outputData;
  308. // Constructor
  309. RelDateTimeFmtDataSink(RelativeDateTimeCacheData& cacheData)
  310. : outputData(cacheData) {
  311. // Clear cacheData.fallBackCache
  312. cacheData.fallBackCache[UDAT_STYLE_LONG] = -1;
  313. cacheData.fallBackCache[UDAT_STYLE_SHORT] = -1;
  314. cacheData.fallBackCache[UDAT_STYLE_NARROW] = -1;
  315. }
  316. ~RelDateTimeFmtDataSink();
  317. // Utility functions
  318. static UDateRelativeDateTimeFormatterStyle styleFromString(const char *s) {
  319. int32_t len = static_cast<int32_t>(uprv_strlen(s));
  320. if (len >= 7 && uprv_strcmp(s + len - 7, "-narrow") == 0) {
  321. return UDAT_STYLE_NARROW;
  322. }
  323. if (len >= 6 && uprv_strcmp(s + len - 6, "-short") == 0) {
  324. return UDAT_STYLE_SHORT;
  325. }
  326. return UDAT_STYLE_LONG;
  327. }
  328. static int32_t styleSuffixLength(UDateRelativeDateTimeFormatterStyle style) {
  329. switch (style) {
  330. case UDAT_STYLE_NARROW:
  331. return 7;
  332. case UDAT_STYLE_SHORT:
  333. return 6;
  334. default:
  335. return 0;
  336. }
  337. }
  338. // Utility functions
  339. static UDateRelativeDateTimeFormatterStyle styleFromAliasUnicodeString(UnicodeString s) {
  340. static const char16_t narrow[7] = {0x002D, 0x006E, 0x0061, 0x0072, 0x0072, 0x006F, 0x0077};
  341. static const char16_t sshort[6] = {0x002D, 0x0073, 0x0068, 0x006F, 0x0072, 0x0074,};
  342. if (s.endsWith(narrow, 7)) {
  343. return UDAT_STYLE_NARROW;
  344. }
  345. if (s.endsWith(sshort, 6)) {
  346. return UDAT_STYLE_SHORT;
  347. }
  348. return UDAT_STYLE_LONG;
  349. }
  350. static RelAbsUnit unitOrNegativeFromString(const char* keyword, int32_t length) {
  351. // Quick check from string to enum.
  352. switch (length) {
  353. case 3:
  354. if (uprv_strncmp(keyword, "day", length) == 0) {
  355. return DAY;
  356. } else if (uprv_strncmp(keyword, "sun", length) == 0) {
  357. return SUNDAY;
  358. } else if (uprv_strncmp(keyword, "mon", length) == 0) {
  359. return MONDAY;
  360. } else if (uprv_strncmp(keyword, "tue", length) == 0) {
  361. return TUESDAY;
  362. } else if (uprv_strncmp(keyword, "wed", length) == 0) {
  363. return WEDNESDAY;
  364. } else if (uprv_strncmp(keyword, "thu", length) == 0) {
  365. return THURSDAY;
  366. } else if (uprv_strncmp(keyword, "fri", length) == 0) {
  367. return FRIDAY;
  368. } else if (uprv_strncmp(keyword, "sat", length) == 0) {
  369. return SATURDAY;
  370. }
  371. break;
  372. case 4:
  373. if (uprv_strncmp(keyword, "hour", length) == 0) {
  374. return HOUR;
  375. } else if (uprv_strncmp(keyword, "week", length) == 0) {
  376. return WEEK;
  377. } else if (uprv_strncmp(keyword, "year", length) == 0) {
  378. return YEAR;
  379. }
  380. break;
  381. case 5:
  382. if (uprv_strncmp(keyword, "month", length) == 0) {
  383. return MONTH;
  384. }
  385. break;
  386. case 6:
  387. if (uprv_strncmp(keyword, "minute", length) == 0) {
  388. return MINUTE;
  389. } else if (uprv_strncmp(keyword, "second", length) == 0) {
  390. return SECOND;
  391. }
  392. break;
  393. case 7:
  394. if (uprv_strncmp(keyword, "quarter", length) == 0) {
  395. return QUARTER; // TODO: Check @provisional
  396. }
  397. break;
  398. default:
  399. break;
  400. }
  401. return INVALID_UNIT;
  402. }
  403. void handlePlainDirection(ResourceValue &value, UErrorCode &errorCode) {
  404. // Handle Display Name for PLAIN direction for some units.
  405. if (U_FAILURE(errorCode)) { return; }
  406. int32_t absUnit = absUnitFromGeneric(genericUnit);
  407. if (absUnit < 0) {
  408. return; // Not interesting.
  409. }
  410. // Store displayname if not set.
  411. if (outputData.absoluteUnits[style]
  412. [absUnit][UDAT_DIRECTION_PLAIN].isEmpty()) {
  413. outputData.absoluteUnits[style]
  414. [absUnit][UDAT_DIRECTION_PLAIN].fastCopyFrom(value.getUnicodeString(errorCode));
  415. return;
  416. }
  417. }
  418. void consumeTableRelative(const char *key, ResourceValue &value, UErrorCode &errorCode) {
  419. ResourceTable unitTypesTable = value.getTable(errorCode);
  420. if (U_FAILURE(errorCode)) { return; }
  421. for (int32_t i = 0; unitTypesTable.getKeyAndValue(i, key, value); ++i) {
  422. if (value.getType() == URES_STRING) {
  423. int32_t direction = keyToDirection(key);
  424. if (direction < 0) {
  425. continue;
  426. }
  427. int32_t relUnitIndex = relUnitFromGeneric(genericUnit);
  428. if (relUnitIndex == UDAT_REL_UNIT_SECOND && uprv_strcmp(key, "0") == 0 &&
  429. outputData.absoluteUnits[style][UDAT_ABSOLUTE_NOW][UDAT_DIRECTION_PLAIN].isEmpty()) {
  430. // Handle "NOW"
  431. outputData.absoluteUnits[style][UDAT_ABSOLUTE_NOW]
  432. [UDAT_DIRECTION_PLAIN].fastCopyFrom(value.getUnicodeString(errorCode));
  433. }
  434. int32_t absUnitIndex = absUnitFromGeneric(genericUnit);
  435. if (absUnitIndex < 0) {
  436. continue;
  437. }
  438. // Only reset if slot is empty.
  439. if (outputData.absoluteUnits[style][absUnitIndex][direction].isEmpty()) {
  440. outputData.absoluteUnits[style][absUnitIndex]
  441. [direction].fastCopyFrom(value.getUnicodeString(errorCode));
  442. }
  443. }
  444. }
  445. }
  446. void consumeTimeDetail(int32_t relUnitIndex,
  447. const char *key, ResourceValue &value, UErrorCode &errorCode) {
  448. ResourceTable unitTypesTable = value.getTable(errorCode);
  449. if (U_FAILURE(errorCode)) { return; }
  450. for (int32_t i = 0; unitTypesTable.getKeyAndValue(i, key, value); ++i) {
  451. if (value.getType() == URES_STRING) {
  452. int32_t pluralIndex = StandardPlural::indexOrNegativeFromString(key);
  453. if (pluralIndex >= 0) {
  454. SimpleFormatter **patterns =
  455. outputData.relativeUnitsFormatters[style][relUnitIndex]
  456. [pastFutureIndex];
  457. // Only set if not already established.
  458. if (patterns[pluralIndex] == nullptr) {
  459. patterns[pluralIndex] = new SimpleFormatter(
  460. value.getUnicodeString(errorCode), 0, 1, errorCode);
  461. if (patterns[pluralIndex] == nullptr) {
  462. errorCode = U_MEMORY_ALLOCATION_ERROR;
  463. }
  464. }
  465. }
  466. }
  467. }
  468. }
  469. void consumeTableRelativeTime(const char *key, ResourceValue &value, UErrorCode &errorCode) {
  470. ResourceTable relativeTimeTable = value.getTable(errorCode);
  471. if (U_FAILURE(errorCode)) { return; }
  472. int32_t relUnitIndex = relUnitFromGeneric(genericUnit);
  473. if (relUnitIndex < 0) {
  474. return;
  475. }
  476. for (int32_t i = 0; relativeTimeTable.getKeyAndValue(i, key, value); ++i) {
  477. if (uprv_strcmp(key, "past") == 0) {
  478. pastFutureIndex = 0;
  479. } else if (uprv_strcmp(key, "future") == 0) {
  480. pastFutureIndex = 1;
  481. } else {
  482. // Unknown key.
  483. continue;
  484. }
  485. consumeTimeDetail(relUnitIndex, key, value, errorCode);
  486. }
  487. }
  488. void consumeAlias(const char *key, const ResourceValue &value, UErrorCode &errorCode) {
  489. UDateRelativeDateTimeFormatterStyle sourceStyle = styleFromString(key);
  490. const UnicodeString valueStr = value.getAliasUnicodeString(errorCode);
  491. if (U_FAILURE(errorCode)) { return; }
  492. UDateRelativeDateTimeFormatterStyle targetStyle =
  493. styleFromAliasUnicodeString(valueStr);
  494. if (sourceStyle == targetStyle) {
  495. errorCode = U_INVALID_FORMAT_ERROR;
  496. return;
  497. }
  498. if (outputData.fallBackCache[sourceStyle] != -1 &&
  499. outputData.fallBackCache[sourceStyle] != targetStyle) {
  500. errorCode = U_INVALID_FORMAT_ERROR;
  501. return;
  502. }
  503. outputData.fallBackCache[sourceStyle] = targetStyle;
  504. }
  505. void consumeTimeUnit(const char *key, ResourceValue &value, UErrorCode &errorCode) {
  506. ResourceTable unitTypesTable = value.getTable(errorCode);
  507. if (U_FAILURE(errorCode)) { return; }
  508. for (int32_t i = 0; unitTypesTable.getKeyAndValue(i, key, value); ++i) {
  509. // Handle display name.
  510. if (uprv_strcmp(key, "dn") == 0 && value.getType() == URES_STRING) {
  511. handlePlainDirection(value, errorCode);
  512. }
  513. if (value.getType() == URES_TABLE) {
  514. if (uprv_strcmp(key, "relative") == 0) {
  515. consumeTableRelative(key, value, errorCode);
  516. } else if (uprv_strcmp(key, "relativeTime") == 0) {
  517. consumeTableRelativeTime(key, value, errorCode);
  518. }
  519. }
  520. }
  521. }
  522. virtual void put(const char *key, ResourceValue &value,
  523. UBool /*noFallback*/, UErrorCode &errorCode) override {
  524. // Main entry point to sink
  525. ResourceTable table = value.getTable(errorCode);
  526. if (U_FAILURE(errorCode)) { return; }
  527. for (int32_t i = 0; table.getKeyAndValue(i, key, value); ++i) {
  528. if (value.getType() == URES_ALIAS) {
  529. consumeAlias(key, value, errorCode);
  530. } else {
  531. style = styleFromString(key);
  532. int32_t unitSize = static_cast<int32_t>(uprv_strlen(key)) - styleSuffixLength(style);
  533. genericUnit = unitOrNegativeFromString(key, unitSize);
  534. if (style >= 0 && genericUnit != INVALID_UNIT) {
  535. consumeTimeUnit(key, value, errorCode);
  536. }
  537. }
  538. }
  539. }
  540. };
  541. // Virtual destructors must be defined out of line.
  542. RelDateTimeFmtDataSink::~RelDateTimeFmtDataSink() {}
  543. } // namespace
  544. static const DateFormatSymbols::DtWidthType styleToDateFormatSymbolWidth[UDAT_STYLE_COUNT] = {
  545. DateFormatSymbols::WIDE, DateFormatSymbols::SHORT, DateFormatSymbols::NARROW
  546. };
  547. // Get days of weeks from the DateFormatSymbols class.
  548. static void loadWeekdayNames(UnicodeString absoluteUnits[UDAT_STYLE_COUNT]
  549. [UDAT_ABSOLUTE_UNIT_COUNT][UDAT_DIRECTION_COUNT],
  550. const char* localeId,
  551. UErrorCode& status) {
  552. if (U_FAILURE(status)) {
  553. return;
  554. }
  555. Locale locale(localeId);
  556. DateFormatSymbols dfSym(locale, status);
  557. if (U_FAILURE(status)) {
  558. return;
  559. }
  560. for (int32_t style = 0; style < UDAT_STYLE_COUNT; ++style) {
  561. DateFormatSymbols::DtWidthType dtfmtWidth = styleToDateFormatSymbolWidth[style];
  562. int32_t count;
  563. const UnicodeString* weekdayNames =
  564. dfSym.getWeekdays(count, DateFormatSymbols::STANDALONE, dtfmtWidth);
  565. for (int32_t dayIndex = UDAT_ABSOLUTE_SUNDAY;
  566. dayIndex <= UDAT_ABSOLUTE_SATURDAY; ++ dayIndex) {
  567. int32_t dateSymbolIndex = (dayIndex - UDAT_ABSOLUTE_SUNDAY) + UCAL_SUNDAY;
  568. absoluteUnits[style][dayIndex][UDAT_DIRECTION_PLAIN].fastCopyFrom(
  569. weekdayNames[dateSymbolIndex]);
  570. }
  571. }
  572. }
  573. static UBool loadUnitData(
  574. const UResourceBundle *resource,
  575. RelativeDateTimeCacheData &cacheData,
  576. const char* localeId,
  577. UErrorCode &status) {
  578. RelDateTimeFmtDataSink sink(cacheData);
  579. ures_getAllItemsWithFallback(resource, "fields", sink, status);
  580. if (U_FAILURE(status)) {
  581. return false;
  582. }
  583. // Get the weekday names from DateFormatSymbols.
  584. loadWeekdayNames(cacheData.absoluteUnits, localeId, status);
  585. return U_SUCCESS(status);
  586. }
  587. static const int32_t cTypeBufMax = 32;
  588. static UBool getDateTimePattern(
  589. Locale locale,
  590. const UResourceBundle *resource,
  591. UnicodeString &result,
  592. UErrorCode &status) {
  593. if (U_FAILURE(status)) {
  594. return false;
  595. }
  596. char cType[cTypeBufMax + 1];
  597. Calendar::getCalendarTypeFromLocale(locale, cType, cTypeBufMax, status);
  598. cType[cTypeBufMax] = 0;
  599. if (U_FAILURE(status) || cType[0] == 0) {
  600. status = U_ZERO_ERROR;
  601. uprv_strcpy(cType, "gregorian");
  602. }
  603. LocalUResourceBundlePointer topLevel;
  604. int32_t dateTimeFormatOffset = DateFormat::kMedium;
  605. CharString pathBuffer;
  606. // Currently, for compatibility with pre-CLDR-42 data, we default to the "atTime"
  607. // combining patterns. Depending on guidance in CLDR 42 spec and on DisplayOptions,
  608. // we may change this.
  609. pathBuffer.append("calendar/", status)
  610. .append(cType, status)
  611. .append("/DateTimePatterns%atTime", status);
  612. topLevel.adoptInstead(
  613. ures_getByKeyWithFallback(
  614. resource, pathBuffer.data(), nullptr, &status));
  615. if (U_FAILURE(status) || ures_getSize(topLevel.getAlias()) < 4) {
  616. // Fall back to standard combining patterns
  617. status = U_ZERO_ERROR;
  618. dateTimeFormatOffset = DateFormat::kDateTime;
  619. pathBuffer.clear();
  620. pathBuffer.append("calendar/", status)
  621. .append(cType, status)
  622. .append("/DateTimePatterns", status);
  623. topLevel.adoptInstead(
  624. ures_getByKeyWithFallback(
  625. resource, pathBuffer.data(), nullptr, &status));
  626. }
  627. if (U_FAILURE(status)) {
  628. return false;
  629. }
  630. if (dateTimeFormatOffset == DateFormat::kDateTime && ures_getSize(topLevel.getAlias()) <= DateFormat::kDateTime) {
  631. // Oops, size is too small to access the index that we want, fallback
  632. // to a hard-coded value.
  633. result = UNICODE_STRING_SIMPLE("{1} {0}");
  634. return true;
  635. }
  636. return getStringByIndex(topLevel.getAlias(), dateTimeFormatOffset, result, status);
  637. }
  638. template<>
  639. const RelativeDateTimeCacheData *LocaleCacheKey<RelativeDateTimeCacheData>::createObject(const void * /*unused*/, UErrorCode &status) const {
  640. const char *localeId = fLoc.getName();
  641. LocalUResourceBundlePointer topLevel(ures_open(nullptr, localeId, &status));
  642. if (U_FAILURE(status)) {
  643. return nullptr;
  644. }
  645. LocalPointer<RelativeDateTimeCacheData> result(
  646. new RelativeDateTimeCacheData());
  647. if (result.isNull()) {
  648. status = U_MEMORY_ALLOCATION_ERROR;
  649. return nullptr;
  650. }
  651. if (!loadUnitData(
  652. topLevel.getAlias(),
  653. *result,
  654. localeId,
  655. status)) {
  656. return nullptr;
  657. }
  658. UnicodeString dateTimePattern;
  659. if (!getDateTimePattern(fLoc, topLevel.getAlias(), dateTimePattern, status)) {
  660. return nullptr;
  661. }
  662. result->adoptCombinedDateAndTime(
  663. new SimpleFormatter(dateTimePattern, 2, 2, status));
  664. if (U_FAILURE(status)) {
  665. return nullptr;
  666. }
  667. result->addRef();
  668. return result.orphan();
  669. }
  670. static constexpr FormattedStringBuilder::Field kRDTNumericField
  671. = {UFIELD_CATEGORY_RELATIVE_DATETIME, UDAT_REL_NUMERIC_FIELD};
  672. static constexpr FormattedStringBuilder::Field kRDTLiteralField
  673. = {UFIELD_CATEGORY_RELATIVE_DATETIME, UDAT_REL_LITERAL_FIELD};
  674. class FormattedRelativeDateTimeData : public FormattedValueStringBuilderImpl {
  675. public:
  676. FormattedRelativeDateTimeData() : FormattedValueStringBuilderImpl(kRDTNumericField) {}
  677. virtual ~FormattedRelativeDateTimeData();
  678. };
  679. FormattedRelativeDateTimeData::~FormattedRelativeDateTimeData() = default;
  680. UPRV_FORMATTED_VALUE_SUBCLASS_AUTO_IMPL(FormattedRelativeDateTime)
  681. RelativeDateTimeFormatter::RelativeDateTimeFormatter(UErrorCode& status) :
  682. fCache(nullptr),
  683. fNumberFormat(nullptr),
  684. fPluralRules(nullptr),
  685. fStyle(UDAT_STYLE_LONG),
  686. fContext(UDISPCTX_CAPITALIZATION_NONE),
  687. fOptBreakIterator(nullptr) {
  688. init(nullptr, nullptr, status);
  689. }
  690. RelativeDateTimeFormatter::RelativeDateTimeFormatter(
  691. const Locale& locale, UErrorCode& status) :
  692. fCache(nullptr),
  693. fNumberFormat(nullptr),
  694. fPluralRules(nullptr),
  695. fStyle(UDAT_STYLE_LONG),
  696. fContext(UDISPCTX_CAPITALIZATION_NONE),
  697. fOptBreakIterator(nullptr),
  698. fLocale(locale) {
  699. init(nullptr, nullptr, status);
  700. }
  701. RelativeDateTimeFormatter::RelativeDateTimeFormatter(
  702. const Locale& locale, NumberFormat *nfToAdopt, UErrorCode& status) :
  703. fCache(nullptr),
  704. fNumberFormat(nullptr),
  705. fPluralRules(nullptr),
  706. fStyle(UDAT_STYLE_LONG),
  707. fContext(UDISPCTX_CAPITALIZATION_NONE),
  708. fOptBreakIterator(nullptr),
  709. fLocale(locale) {
  710. init(nfToAdopt, nullptr, status);
  711. }
  712. RelativeDateTimeFormatter::RelativeDateTimeFormatter(
  713. const Locale& locale,
  714. NumberFormat *nfToAdopt,
  715. UDateRelativeDateTimeFormatterStyle styl,
  716. UDisplayContext capitalizationContext,
  717. UErrorCode& status) :
  718. fCache(nullptr),
  719. fNumberFormat(nullptr),
  720. fPluralRules(nullptr),
  721. fStyle(styl),
  722. fContext(capitalizationContext),
  723. fOptBreakIterator(nullptr),
  724. fLocale(locale) {
  725. if (U_FAILURE(status)) {
  726. return;
  727. }
  728. if ((capitalizationContext >> 8) != UDISPCTX_TYPE_CAPITALIZATION) {
  729. status = U_ILLEGAL_ARGUMENT_ERROR;
  730. return;
  731. }
  732. if (capitalizationContext == UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE) {
  733. BreakIterator *bi = BreakIterator::createSentenceInstance(locale, status);
  734. if (U_FAILURE(status)) {
  735. return;
  736. }
  737. init(nfToAdopt, bi, status);
  738. } else {
  739. init(nfToAdopt, nullptr, status);
  740. }
  741. }
  742. RelativeDateTimeFormatter::RelativeDateTimeFormatter(
  743. const RelativeDateTimeFormatter& other)
  744. : UObject(other),
  745. fCache(other.fCache),
  746. fNumberFormat(other.fNumberFormat),
  747. fPluralRules(other.fPluralRules),
  748. fStyle(other.fStyle),
  749. fContext(other.fContext),
  750. fOptBreakIterator(other.fOptBreakIterator),
  751. fLocale(other.fLocale) {
  752. fCache->addRef();
  753. fNumberFormat->addRef();
  754. fPluralRules->addRef();
  755. if (fOptBreakIterator != nullptr) {
  756. fOptBreakIterator->addRef();
  757. }
  758. }
  759. RelativeDateTimeFormatter& RelativeDateTimeFormatter::operator=(
  760. const RelativeDateTimeFormatter& other) {
  761. if (this != &other) {
  762. SharedObject::copyPtr(other.fCache, fCache);
  763. SharedObject::copyPtr(other.fNumberFormat, fNumberFormat);
  764. SharedObject::copyPtr(other.fPluralRules, fPluralRules);
  765. SharedObject::copyPtr(other.fOptBreakIterator, fOptBreakIterator);
  766. fStyle = other.fStyle;
  767. fContext = other.fContext;
  768. fLocale = other.fLocale;
  769. }
  770. return *this;
  771. }
  772. RelativeDateTimeFormatter::~RelativeDateTimeFormatter() {
  773. if (fCache != nullptr) {
  774. fCache->removeRef();
  775. }
  776. if (fNumberFormat != nullptr) {
  777. fNumberFormat->removeRef();
  778. }
  779. if (fPluralRules != nullptr) {
  780. fPluralRules->removeRef();
  781. }
  782. if (fOptBreakIterator != nullptr) {
  783. fOptBreakIterator->removeRef();
  784. }
  785. }
  786. const NumberFormat& RelativeDateTimeFormatter::getNumberFormat() const {
  787. return **fNumberFormat;
  788. }
  789. UDisplayContext RelativeDateTimeFormatter::getCapitalizationContext() const {
  790. return fContext;
  791. }
  792. UDateRelativeDateTimeFormatterStyle RelativeDateTimeFormatter::getFormatStyle() const {
  793. return fStyle;
  794. }
  795. // To reduce boilerplate code, we use a helper function that forwards variadic
  796. // arguments to the formatImpl function.
  797. template<typename F, typename... Args>
  798. UnicodeString& RelativeDateTimeFormatter::doFormat(
  799. F callback,
  800. UnicodeString& appendTo,
  801. UErrorCode& status,
  802. Args... args) const {
  803. FormattedRelativeDateTimeData output;
  804. (this->*callback)(std::forward<Args>(args)..., output, status);
  805. if (U_FAILURE(status)) {
  806. return appendTo;
  807. }
  808. UnicodeString result = output.getStringRef().toUnicodeString();
  809. return appendTo.append(adjustForContext(result));
  810. }
  811. template<typename F, typename... Args>
  812. FormattedRelativeDateTime RelativeDateTimeFormatter::doFormatToValue(
  813. F callback,
  814. UErrorCode& status,
  815. Args... args) const {
  816. if (!checkNoAdjustForContext(status)) {
  817. return FormattedRelativeDateTime(status);
  818. }
  819. LocalPointer<FormattedRelativeDateTimeData> output(
  820. new FormattedRelativeDateTimeData(), status);
  821. if (U_FAILURE(status)) {
  822. return FormattedRelativeDateTime(status);
  823. }
  824. (this->*callback)(std::forward<Args>(args)..., *output, status);
  825. output->getStringRef().writeTerminator(status);
  826. return FormattedRelativeDateTime(output.orphan());
  827. }
  828. UnicodeString& RelativeDateTimeFormatter::format(
  829. double quantity,
  830. UDateDirection direction,
  831. UDateRelativeUnit unit,
  832. UnicodeString& appendTo,
  833. UErrorCode& status) const {
  834. return doFormat(
  835. &RelativeDateTimeFormatter::formatImpl,
  836. appendTo,
  837. status,
  838. quantity,
  839. direction,
  840. unit);
  841. }
  842. FormattedRelativeDateTime RelativeDateTimeFormatter::formatToValue(
  843. double quantity,
  844. UDateDirection direction,
  845. UDateRelativeUnit unit,
  846. UErrorCode& status) const {
  847. return doFormatToValue(
  848. &RelativeDateTimeFormatter::formatImpl,
  849. status,
  850. quantity,
  851. direction,
  852. unit);
  853. }
  854. void RelativeDateTimeFormatter::formatImpl(
  855. double quantity,
  856. UDateDirection direction,
  857. UDateRelativeUnit unit,
  858. FormattedRelativeDateTimeData& output,
  859. UErrorCode& status) const {
  860. if (U_FAILURE(status)) {
  861. return;
  862. }
  863. if (direction != UDAT_DIRECTION_LAST && direction != UDAT_DIRECTION_NEXT) {
  864. status = U_ILLEGAL_ARGUMENT_ERROR;
  865. return;
  866. }
  867. int32_t bFuture = direction == UDAT_DIRECTION_NEXT ? 1 : 0;
  868. StandardPlural::Form pluralForm;
  869. QuantityFormatter::formatAndSelect(
  870. quantity,
  871. **fNumberFormat,
  872. **fPluralRules,
  873. output.getStringRef(),
  874. pluralForm,
  875. status);
  876. if (U_FAILURE(status)) {
  877. return;
  878. }
  879. const SimpleFormatter* formatter =
  880. fCache->getRelativeUnitFormatter(fStyle, unit, bFuture, pluralForm);
  881. if (formatter == nullptr) {
  882. // TODO: WARN - look at quantity formatter's action with an error.
  883. status = U_INVALID_FORMAT_ERROR;
  884. return;
  885. }
  886. number::impl::SimpleModifier modifier(*formatter, kRDTLiteralField, false);
  887. modifier.formatAsPrefixSuffix(
  888. output.getStringRef(), 0, output.getStringRef().length(), status);
  889. }
  890. UnicodeString& RelativeDateTimeFormatter::formatNumeric(
  891. double offset,
  892. URelativeDateTimeUnit unit,
  893. UnicodeString& appendTo,
  894. UErrorCode& status) const {
  895. return doFormat(
  896. &RelativeDateTimeFormatter::formatNumericImpl,
  897. appendTo,
  898. status,
  899. offset,
  900. unit);
  901. }
  902. FormattedRelativeDateTime RelativeDateTimeFormatter::formatNumericToValue(
  903. double offset,
  904. URelativeDateTimeUnit unit,
  905. UErrorCode& status) const {
  906. return doFormatToValue(
  907. &RelativeDateTimeFormatter::formatNumericImpl,
  908. status,
  909. offset,
  910. unit);
  911. }
  912. void RelativeDateTimeFormatter::formatNumericImpl(
  913. double offset,
  914. URelativeDateTimeUnit unit,
  915. FormattedRelativeDateTimeData& output,
  916. UErrorCode& status) const {
  917. if (U_FAILURE(status)) {
  918. return;
  919. }
  920. UDateDirection direction = UDAT_DIRECTION_NEXT;
  921. if (std::signbit(offset)) { // needed to handle -0.0
  922. direction = UDAT_DIRECTION_LAST;
  923. offset = -offset;
  924. }
  925. if (direction != UDAT_DIRECTION_LAST && direction != UDAT_DIRECTION_NEXT) {
  926. status = U_ILLEGAL_ARGUMENT_ERROR;
  927. return;
  928. }
  929. int32_t bFuture = direction == UDAT_DIRECTION_NEXT ? 1 : 0;
  930. StandardPlural::Form pluralForm;
  931. QuantityFormatter::formatAndSelect(
  932. offset,
  933. **fNumberFormat,
  934. **fPluralRules,
  935. output.getStringRef(),
  936. pluralForm,
  937. status);
  938. if (U_FAILURE(status)) {
  939. return;
  940. }
  941. const SimpleFormatter* formatter =
  942. fCache->getRelativeDateTimeUnitFormatter(fStyle, unit, bFuture, pluralForm);
  943. if (formatter == nullptr) {
  944. // TODO: WARN - look at quantity formatter's action with an error.
  945. status = U_INVALID_FORMAT_ERROR;
  946. return;
  947. }
  948. number::impl::SimpleModifier modifier(*formatter, kRDTLiteralField, false);
  949. modifier.formatAsPrefixSuffix(
  950. output.getStringRef(), 0, output.getStringRef().length(), status);
  951. }
  952. UnicodeString& RelativeDateTimeFormatter::format(
  953. UDateDirection direction,
  954. UDateAbsoluteUnit unit,
  955. UnicodeString& appendTo,
  956. UErrorCode& status) const {
  957. return doFormat(
  958. &RelativeDateTimeFormatter::formatAbsoluteImpl,
  959. appendTo,
  960. status,
  961. direction,
  962. unit);
  963. }
  964. FormattedRelativeDateTime RelativeDateTimeFormatter::formatToValue(
  965. UDateDirection direction,
  966. UDateAbsoluteUnit unit,
  967. UErrorCode& status) const {
  968. return doFormatToValue(
  969. &RelativeDateTimeFormatter::formatAbsoluteImpl,
  970. status,
  971. direction,
  972. unit);
  973. }
  974. void RelativeDateTimeFormatter::formatAbsoluteImpl(
  975. UDateDirection direction,
  976. UDateAbsoluteUnit unit,
  977. FormattedRelativeDateTimeData& output,
  978. UErrorCode& status) const {
  979. if (U_FAILURE(status)) {
  980. return;
  981. }
  982. if (unit == UDAT_ABSOLUTE_NOW && direction != UDAT_DIRECTION_PLAIN) {
  983. status = U_ILLEGAL_ARGUMENT_ERROR;
  984. return;
  985. }
  986. // Get string using fallback.
  987. output.getStringRef().append(
  988. fCache->getAbsoluteUnitString(fStyle, unit, direction),
  989. kRDTLiteralField,
  990. status);
  991. }
  992. UnicodeString& RelativeDateTimeFormatter::format(
  993. double offset,
  994. URelativeDateTimeUnit unit,
  995. UnicodeString& appendTo,
  996. UErrorCode& status) const {
  997. return doFormat(
  998. &RelativeDateTimeFormatter::formatRelativeImpl,
  999. appendTo,
  1000. status,
  1001. offset,
  1002. unit);
  1003. }
  1004. FormattedRelativeDateTime RelativeDateTimeFormatter::formatToValue(
  1005. double offset,
  1006. URelativeDateTimeUnit unit,
  1007. UErrorCode& status) const {
  1008. return doFormatToValue(
  1009. &RelativeDateTimeFormatter::formatRelativeImpl,
  1010. status,
  1011. offset,
  1012. unit);
  1013. }
  1014. void RelativeDateTimeFormatter::formatRelativeImpl(
  1015. double offset,
  1016. URelativeDateTimeUnit unit,
  1017. FormattedRelativeDateTimeData& output,
  1018. UErrorCode& status) const {
  1019. if (U_FAILURE(status)) {
  1020. return;
  1021. }
  1022. // TODO:
  1023. // The full implementation of this depends on CLDR data that is not yet available,
  1024. // see: http://unicode.org/cldr/trac/ticket/9165 Add more relative field data.
  1025. // In the meantime do a quick bring-up by calling the old format method; this
  1026. // leaves some holes (even for data that is currently available, such as quarter).
  1027. // When the new CLDR data is available, update the data storage accordingly,
  1028. // rewrite this to use it directly, and rewrite the old format method to call this
  1029. // new one; that is covered by https://unicode-org.atlassian.net/browse/ICU-12171.
  1030. UDateDirection direction = UDAT_DIRECTION_COUNT;
  1031. if (offset > -2.1 && offset < 2.1) {
  1032. // Allow a 1% epsilon, so offsets in -1.01..-0.99 map to LAST
  1033. double offsetx100 = offset * 100.0;
  1034. int32_t intoffset = (offsetx100 < 0)? (int32_t)(offsetx100-0.5) : (int32_t)(offsetx100+0.5);
  1035. switch (intoffset) {
  1036. case -200/*-2*/: direction = UDAT_DIRECTION_LAST_2; break;
  1037. case -100/*-1*/: direction = UDAT_DIRECTION_LAST; break;
  1038. case 0/* 0*/: direction = UDAT_DIRECTION_THIS; break;
  1039. case 100/* 1*/: direction = UDAT_DIRECTION_NEXT; break;
  1040. case 200/* 2*/: direction = UDAT_DIRECTION_NEXT_2; break;
  1041. default: break;
  1042. }
  1043. }
  1044. UDateAbsoluteUnit absunit = UDAT_ABSOLUTE_UNIT_COUNT;
  1045. switch (unit) {
  1046. case UDAT_REL_UNIT_YEAR: absunit = UDAT_ABSOLUTE_YEAR; break;
  1047. case UDAT_REL_UNIT_QUARTER: absunit = UDAT_ABSOLUTE_QUARTER; break;
  1048. case UDAT_REL_UNIT_MONTH: absunit = UDAT_ABSOLUTE_MONTH; break;
  1049. case UDAT_REL_UNIT_WEEK: absunit = UDAT_ABSOLUTE_WEEK; break;
  1050. case UDAT_REL_UNIT_DAY: absunit = UDAT_ABSOLUTE_DAY; break;
  1051. case UDAT_REL_UNIT_SECOND:
  1052. if (direction == UDAT_DIRECTION_THIS) {
  1053. absunit = UDAT_ABSOLUTE_NOW;
  1054. direction = UDAT_DIRECTION_PLAIN;
  1055. }
  1056. break;
  1057. case UDAT_REL_UNIT_SUNDAY: absunit = UDAT_ABSOLUTE_SUNDAY; break;
  1058. case UDAT_REL_UNIT_MONDAY: absunit = UDAT_ABSOLUTE_MONDAY; break;
  1059. case UDAT_REL_UNIT_TUESDAY: absunit = UDAT_ABSOLUTE_TUESDAY; break;
  1060. case UDAT_REL_UNIT_WEDNESDAY: absunit = UDAT_ABSOLUTE_WEDNESDAY; break;
  1061. case UDAT_REL_UNIT_THURSDAY: absunit = UDAT_ABSOLUTE_THURSDAY; break;
  1062. case UDAT_REL_UNIT_FRIDAY: absunit = UDAT_ABSOLUTE_FRIDAY; break;
  1063. case UDAT_REL_UNIT_SATURDAY: absunit = UDAT_ABSOLUTE_SATURDAY; break;
  1064. case UDAT_REL_UNIT_HOUR: absunit = UDAT_ABSOLUTE_HOUR; break;
  1065. case UDAT_REL_UNIT_MINUTE: absunit = UDAT_ABSOLUTE_MINUTE; break;
  1066. default: break;
  1067. }
  1068. if (direction != UDAT_DIRECTION_COUNT && absunit != UDAT_ABSOLUTE_UNIT_COUNT) {
  1069. formatAbsoluteImpl(direction, absunit, output, status);
  1070. if (output.getStringRef().length() != 0) {
  1071. return;
  1072. }
  1073. }
  1074. // otherwise fallback to formatNumeric
  1075. formatNumericImpl(offset, unit, output, status);
  1076. }
  1077. UnicodeString& RelativeDateTimeFormatter::combineDateAndTime(
  1078. const UnicodeString& relativeDateString, const UnicodeString& timeString,
  1079. UnicodeString& appendTo, UErrorCode& status) const {
  1080. return fCache->getCombinedDateAndTime()->format(
  1081. timeString, relativeDateString, appendTo, status);
  1082. }
  1083. UnicodeString& RelativeDateTimeFormatter::adjustForContext(UnicodeString &str) const {
  1084. if (fOptBreakIterator == nullptr
  1085. || str.length() == 0 || !u_islower(str.char32At(0))) {
  1086. return str;
  1087. }
  1088. // Must guarantee that one thread at a time accesses the shared break
  1089. // iterator.
  1090. static UMutex gBrkIterMutex;
  1091. Mutex lock(&gBrkIterMutex);
  1092. str.toTitle(
  1093. fOptBreakIterator->get(),
  1094. fLocale,
  1095. U_TITLECASE_NO_LOWERCASE | U_TITLECASE_NO_BREAK_ADJUSTMENT);
  1096. return str;
  1097. }
  1098. UBool RelativeDateTimeFormatter::checkNoAdjustForContext(UErrorCode& status) const {
  1099. // This is unsupported because it's hard to keep fields in sync with title
  1100. // casing. The code could be written and tested if there is demand.
  1101. if (fOptBreakIterator != nullptr) {
  1102. status = U_UNSUPPORTED_ERROR;
  1103. return false;
  1104. }
  1105. return true;
  1106. }
  1107. void RelativeDateTimeFormatter::init(
  1108. NumberFormat *nfToAdopt,
  1109. BreakIterator *biToAdopt,
  1110. UErrorCode &status) {
  1111. LocalPointer<NumberFormat> nf(nfToAdopt);
  1112. LocalPointer<BreakIterator> bi(biToAdopt);
  1113. UnifiedCache::getByLocale(fLocale, fCache, status);
  1114. if (U_FAILURE(status)) {
  1115. return;
  1116. }
  1117. const SharedPluralRules *pr = PluralRules::createSharedInstance(
  1118. fLocale, UPLURAL_TYPE_CARDINAL, status);
  1119. if (U_FAILURE(status)) {
  1120. return;
  1121. }
  1122. SharedObject::copyPtr(pr, fPluralRules);
  1123. pr->removeRef();
  1124. if (nf.isNull()) {
  1125. const SharedNumberFormat *shared = NumberFormat::createSharedInstance(
  1126. fLocale, UNUM_DECIMAL, status);
  1127. if (U_FAILURE(status)) {
  1128. return;
  1129. }
  1130. SharedObject::copyPtr(shared, fNumberFormat);
  1131. shared->removeRef();
  1132. } else {
  1133. SharedNumberFormat *shared = new SharedNumberFormat(nf.getAlias());
  1134. if (shared == nullptr) {
  1135. status = U_MEMORY_ALLOCATION_ERROR;
  1136. return;
  1137. }
  1138. nf.orphan();
  1139. SharedObject::copyPtr(shared, fNumberFormat);
  1140. }
  1141. if (bi.isNull()) {
  1142. SharedObject::clearPtr(fOptBreakIterator);
  1143. } else {
  1144. SharedBreakIterator *shared = new SharedBreakIterator(bi.getAlias());
  1145. if (shared == nullptr) {
  1146. status = U_MEMORY_ALLOCATION_ERROR;
  1147. return;
  1148. }
  1149. bi.orphan();
  1150. SharedObject::copyPtr(shared, fOptBreakIterator);
  1151. }
  1152. }
  1153. U_NAMESPACE_END
  1154. // Plain C API
  1155. U_NAMESPACE_USE
  1156. // Magic number: "FRDT" (FormattedRelativeDateTime) in ASCII
  1157. UPRV_FORMATTED_VALUE_CAPI_AUTO_IMPL(
  1158. FormattedRelativeDateTime,
  1159. UFormattedRelativeDateTime,
  1160. UFormattedRelativeDateTimeImpl,
  1161. UFormattedRelativeDateTimeApiHelper,
  1162. ureldatefmt,
  1163. 0x46524454)
  1164. U_CAPI URelativeDateTimeFormatter* U_EXPORT2
  1165. ureldatefmt_open( const char* locale,
  1166. UNumberFormat* nfToAdopt,
  1167. UDateRelativeDateTimeFormatterStyle width,
  1168. UDisplayContext capitalizationContext,
  1169. UErrorCode* status )
  1170. {
  1171. if (U_FAILURE(*status)) {
  1172. return nullptr;
  1173. }
  1174. LocalPointer<RelativeDateTimeFormatter> formatter(new RelativeDateTimeFormatter(Locale(locale),
  1175. (NumberFormat*)nfToAdopt, width,
  1176. capitalizationContext, *status), *status);
  1177. if (U_FAILURE(*status)) {
  1178. return nullptr;
  1179. }
  1180. return (URelativeDateTimeFormatter*)formatter.orphan();
  1181. }
  1182. U_CAPI void U_EXPORT2
  1183. ureldatefmt_close(URelativeDateTimeFormatter *reldatefmt)
  1184. {
  1185. delete (RelativeDateTimeFormatter*)reldatefmt;
  1186. }
  1187. U_CAPI int32_t U_EXPORT2
  1188. ureldatefmt_formatNumeric( const URelativeDateTimeFormatter* reldatefmt,
  1189. double offset,
  1190. URelativeDateTimeUnit unit,
  1191. char16_t* result,
  1192. int32_t resultCapacity,
  1193. UErrorCode* status)
  1194. {
  1195. if (U_FAILURE(*status)) {
  1196. return 0;
  1197. }
  1198. if (result == nullptr ? resultCapacity != 0 : resultCapacity < 0) {
  1199. *status = U_ILLEGAL_ARGUMENT_ERROR;
  1200. return 0;
  1201. }
  1202. UnicodeString res;
  1203. if (result != nullptr) {
  1204. // nullptr destination for pure preflighting: empty dummy string
  1205. // otherwise, alias the destination buffer (copied from udat_format)
  1206. res.setTo(result, 0, resultCapacity);
  1207. }
  1208. ((RelativeDateTimeFormatter*)reldatefmt)->formatNumeric(offset, unit, res, *status);
  1209. if (U_FAILURE(*status)) {
  1210. return 0;
  1211. }
  1212. return res.extract(result, resultCapacity, *status);
  1213. }
  1214. U_CAPI void U_EXPORT2
  1215. ureldatefmt_formatNumericToResult(
  1216. const URelativeDateTimeFormatter* reldatefmt,
  1217. double offset,
  1218. URelativeDateTimeUnit unit,
  1219. UFormattedRelativeDateTime* result,
  1220. UErrorCode* status) {
  1221. if (U_FAILURE(*status)) {
  1222. return;
  1223. }
  1224. auto* fmt = reinterpret_cast<const RelativeDateTimeFormatter*>(reldatefmt);
  1225. auto* resultImpl = UFormattedRelativeDateTimeApiHelper::validate(result, *status);
  1226. resultImpl->fImpl = fmt->formatNumericToValue(offset, unit, *status);
  1227. }
  1228. U_CAPI int32_t U_EXPORT2
  1229. ureldatefmt_format( const URelativeDateTimeFormatter* reldatefmt,
  1230. double offset,
  1231. URelativeDateTimeUnit unit,
  1232. char16_t* result,
  1233. int32_t resultCapacity,
  1234. UErrorCode* status)
  1235. {
  1236. if (U_FAILURE(*status)) {
  1237. return 0;
  1238. }
  1239. if (result == nullptr ? resultCapacity != 0 : resultCapacity < 0) {
  1240. *status = U_ILLEGAL_ARGUMENT_ERROR;
  1241. return 0;
  1242. }
  1243. UnicodeString res;
  1244. if (result != nullptr) {
  1245. // nullptr destination for pure preflighting: empty dummy string
  1246. // otherwise, alias the destination buffer (copied from udat_format)
  1247. res.setTo(result, 0, resultCapacity);
  1248. }
  1249. ((RelativeDateTimeFormatter*)reldatefmt)->format(offset, unit, res, *status);
  1250. if (U_FAILURE(*status)) {
  1251. return 0;
  1252. }
  1253. return res.extract(result, resultCapacity, *status);
  1254. }
  1255. U_CAPI void U_EXPORT2
  1256. ureldatefmt_formatToResult(
  1257. const URelativeDateTimeFormatter* reldatefmt,
  1258. double offset,
  1259. URelativeDateTimeUnit unit,
  1260. UFormattedRelativeDateTime* result,
  1261. UErrorCode* status) {
  1262. if (U_FAILURE(*status)) {
  1263. return;
  1264. }
  1265. auto* fmt = reinterpret_cast<const RelativeDateTimeFormatter*>(reldatefmt);
  1266. auto* resultImpl = UFormattedRelativeDateTimeApiHelper::validate(result, *status);
  1267. resultImpl->fImpl = fmt->formatToValue(offset, unit, *status);
  1268. }
  1269. U_CAPI int32_t U_EXPORT2
  1270. ureldatefmt_combineDateAndTime( const URelativeDateTimeFormatter* reldatefmt,
  1271. const char16_t * relativeDateString,
  1272. int32_t relativeDateStringLen,
  1273. const char16_t * timeString,
  1274. int32_t timeStringLen,
  1275. char16_t* result,
  1276. int32_t resultCapacity,
  1277. UErrorCode* status )
  1278. {
  1279. if (U_FAILURE(*status)) {
  1280. return 0;
  1281. }
  1282. if (result == nullptr ? resultCapacity != 0 : resultCapacity < 0 ||
  1283. (relativeDateString == nullptr ? relativeDateStringLen != 0 : relativeDateStringLen < -1) ||
  1284. (timeString == nullptr ? timeStringLen != 0 : timeStringLen < -1)) {
  1285. *status = U_ILLEGAL_ARGUMENT_ERROR;
  1286. return 0;
  1287. }
  1288. UnicodeString relDateStr((UBool)(relativeDateStringLen == -1), relativeDateString, relativeDateStringLen);
  1289. UnicodeString timeStr((UBool)(timeStringLen == -1), timeString, timeStringLen);
  1290. UnicodeString res(result, 0, resultCapacity);
  1291. ((RelativeDateTimeFormatter*)reldatefmt)->combineDateAndTime(relDateStr, timeStr, res, *status);
  1292. if (U_FAILURE(*status)) {
  1293. return 0;
  1294. }
  1295. return res.extract(result, resultCapacity, *status);
  1296. }
  1297. #endif /* !UCONFIG_NO_FORMATTING */