TimeZone.cs 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737
  1. using Ryujinx.Common;
  2. using Ryujinx.HLE.Utilities;
  3. using System;
  4. using System.IO;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using static Ryujinx.HLE.HOS.Services.Time.TimeZone.TimeZoneRule;
  8. namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
  9. {
  10. public class TimeZone
  11. {
  12. private const int TimeTypeSize = 8;
  13. private const int EpochYear = 1970;
  14. private const int YearBase = 1900;
  15. private const int EpochWeekDay = 4;
  16. private const int SecondsPerMinute = 60;
  17. private const int MinutesPerHour = 60;
  18. private const int HoursPerDays = 24;
  19. private const int DaysPerWekk = 7;
  20. private const int DaysPerNYear = 365;
  21. private const int DaysPerLYear = 366;
  22. private const int MonthsPerYear = 12;
  23. private const int SecondsPerHour = SecondsPerMinute * MinutesPerHour;
  24. private const int SecondsPerDay = SecondsPerHour * HoursPerDays;
  25. private const int YearsPerRepeat = 400;
  26. private const long AverageSecondsPerYear = 31556952;
  27. private const long SecondsPerRepeat = YearsPerRepeat * AverageSecondsPerYear;
  28. private static readonly int[] YearLengths = { DaysPerNYear, DaysPerLYear };
  29. private static readonly int[][] MonthsLengths = new int[][]
  30. {
  31. new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
  32. new int[] { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
  33. };
  34. private const string TimeZoneDefaultRule = ",M4.1.0,M10.5.0";
  35. [StructLayout(LayoutKind.Sequential, Pack = 0x4, Size = 0x10)]
  36. private struct CalendarTimeInternal
  37. {
  38. // NOTE: On the IPC side this is supposed to be a 16 bits value but internally this need to be a 64 bits value for ToPosixTime.
  39. public long Year;
  40. public sbyte Month;
  41. public sbyte Day;
  42. public sbyte Hour;
  43. public sbyte Minute;
  44. public sbyte Second;
  45. public int CompareTo(CalendarTimeInternal other)
  46. {
  47. if (Year != other.Year)
  48. {
  49. if (Year < other.Year)
  50. {
  51. return -1;
  52. }
  53. return 1;
  54. }
  55. if (Month != other.Month)
  56. {
  57. return Month - other.Month;
  58. }
  59. if (Day != other.Day)
  60. {
  61. return Day - other.Day;
  62. }
  63. if (Hour != other.Hour)
  64. {
  65. return Hour - other.Hour;
  66. }
  67. if (Minute != other.Minute)
  68. {
  69. return Minute - other.Minute;
  70. }
  71. if (Second != other.Second)
  72. {
  73. return Second - other.Second;
  74. }
  75. return 0;
  76. }
  77. }
  78. private enum RuleType
  79. {
  80. JulianDay,
  81. DayOfYear,
  82. MonthNthDayOfWeek
  83. }
  84. private struct Rule
  85. {
  86. public RuleType Type;
  87. public int Day;
  88. public int Week;
  89. public int Month;
  90. public int TransitionTime;
  91. }
  92. private static int Detzcode32(byte[] bytes)
  93. {
  94. if (BitConverter.IsLittleEndian)
  95. {
  96. Array.Reverse(bytes, 0, bytes.Length);
  97. }
  98. return BitConverter.ToInt32(bytes, 0);
  99. }
  100. private static unsafe int Detzcode32(int* data)
  101. {
  102. int result = *data;
  103. if (BitConverter.IsLittleEndian)
  104. {
  105. byte[] bytes = BitConverter.GetBytes(result);
  106. Array.Reverse(bytes, 0, bytes.Length);
  107. result = BitConverter.ToInt32(bytes, 0);
  108. }
  109. return result;
  110. }
  111. private static unsafe long Detzcode64(long* data)
  112. {
  113. long result = *data;
  114. if (BitConverter.IsLittleEndian)
  115. {
  116. byte[] bytes = BitConverter.GetBytes(result);
  117. Array.Reverse(bytes, 0, bytes.Length);
  118. result = BitConverter.ToInt64(bytes, 0);
  119. }
  120. return result;
  121. }
  122. private static bool DifferByRepeat(long t1, long t0)
  123. {
  124. return (t1 - t0) == SecondsPerRepeat;
  125. }
  126. private static unsafe bool TimeTypeEquals(TimeZoneRule outRules, byte aIndex, byte bIndex)
  127. {
  128. if (aIndex < 0 || aIndex >= outRules.TypeCount || bIndex < 0 || bIndex >= outRules.TypeCount)
  129. {
  130. return false;
  131. }
  132. TimeTypeInfo a = outRules.Ttis[aIndex];
  133. TimeTypeInfo b = outRules.Ttis[bIndex];
  134. fixed (char* chars = outRules.Chars)
  135. {
  136. return a.GmtOffset == b.GmtOffset &&
  137. a.IsDaySavingTime == b.IsDaySavingTime &&
  138. a.IsStandardTimeDaylight == b.IsStandardTimeDaylight &&
  139. a.IsGMT == b.IsGMT &&
  140. StringUtils.CompareCStr(chars + a.AbbreviationListIndex, chars + b.AbbreviationListIndex) == 0;
  141. }
  142. }
  143. private static int GetQZName(char[] name, int namePosition, char delimiter)
  144. {
  145. int i = namePosition;
  146. while (name[i] != '\0' && name[i] != delimiter)
  147. {
  148. i++;
  149. }
  150. return i;
  151. }
  152. private static int GetTZName(char[] name, int namePosition)
  153. {
  154. int i = namePosition;
  155. char c = name[i];
  156. while (c != '\0' && !char.IsDigit(c) && c != ',' && c != '-' && c != '+')
  157. {
  158. c = name[i];
  159. i++;
  160. }
  161. return i;
  162. }
  163. private static bool GetNum(char[] name, ref int namePosition, out int num, int min, int max)
  164. {
  165. num = 0;
  166. if (namePosition >= name.Length)
  167. {
  168. return false;
  169. }
  170. char c = name[namePosition];
  171. if (!char.IsDigit(c))
  172. {
  173. return false;
  174. }
  175. do
  176. {
  177. num = num * 10 + (c - '0');
  178. if (num > max)
  179. {
  180. return false;
  181. }
  182. if (++namePosition >= name.Length)
  183. {
  184. return false;
  185. }
  186. c = name[namePosition];
  187. }
  188. while (char.IsDigit(c));
  189. if (num < min)
  190. {
  191. return false;
  192. }
  193. return true;
  194. }
  195. private static bool GetSeconds(char[] name, ref int namePosition, out int seconds)
  196. {
  197. seconds = 0;
  198. bool isValid = GetNum(name, ref namePosition, out int num, 0, HoursPerDays * DaysPerWekk - 1);
  199. if (!isValid)
  200. {
  201. return false;
  202. }
  203. seconds = num * SecondsPerHour;
  204. if (namePosition >= name.Length)
  205. {
  206. return false;
  207. }
  208. if (name[namePosition] == ':')
  209. {
  210. namePosition++;
  211. isValid = GetNum(name, ref namePosition, out num, 0, MinutesPerHour - 1);
  212. if (!isValid)
  213. {
  214. return false;
  215. }
  216. seconds += num * SecondsPerMinute;
  217. if (namePosition >= name.Length)
  218. {
  219. return false;
  220. }
  221. if (name[namePosition] == ':')
  222. {
  223. namePosition++;
  224. isValid = GetNum(name, ref namePosition, out num, 0, SecondsPerMinute);
  225. if (!isValid)
  226. {
  227. return false;
  228. }
  229. seconds += num;
  230. }
  231. }
  232. return true;
  233. }
  234. private static bool GetOffset(char[] name, ref int namePosition, ref int offset)
  235. {
  236. bool isNegative = false;
  237. if (namePosition >= name.Length)
  238. {
  239. return false;
  240. }
  241. if (name[namePosition] == '-')
  242. {
  243. isNegative = true;
  244. namePosition++;
  245. }
  246. else if (name[namePosition] == '+')
  247. {
  248. namePosition++;
  249. }
  250. if (namePosition >= name.Length)
  251. {
  252. return false;
  253. }
  254. bool isValid = GetSeconds(name, ref namePosition, out offset);
  255. if (!isValid)
  256. {
  257. return false;
  258. }
  259. if (isNegative)
  260. {
  261. offset = -offset;
  262. }
  263. return true;
  264. }
  265. private static bool GetRule(char[] name, ref int namePosition, out Rule rule)
  266. {
  267. rule = new Rule();
  268. bool isValid = false;
  269. if (name[namePosition] == 'J')
  270. {
  271. namePosition++;
  272. rule.Type = RuleType.JulianDay;
  273. isValid = GetNum(name, ref namePosition, out rule.Day, 1, DaysPerNYear);
  274. }
  275. else if (name[namePosition] == 'M')
  276. {
  277. namePosition++;
  278. rule.Type = RuleType.MonthNthDayOfWeek;
  279. isValid = GetNum(name, ref namePosition, out rule.Month, 1, MonthsPerYear);
  280. if (!isValid)
  281. {
  282. return false;
  283. }
  284. if (name[namePosition++] != '.')
  285. {
  286. return false;
  287. }
  288. isValid = GetNum(name, ref namePosition, out rule.Week, 1, 5);
  289. if (!isValid)
  290. {
  291. return false;
  292. }
  293. if (name[namePosition++] != '.')
  294. {
  295. return false;
  296. }
  297. isValid = GetNum(name, ref namePosition, out rule.Day, 0, DaysPerWekk - 1);
  298. }
  299. else if (char.IsDigit(name[namePosition]))
  300. {
  301. rule.Type = RuleType.DayOfYear;
  302. isValid = GetNum(name, ref namePosition, out rule.Day, 0, DaysPerLYear - 1);
  303. }
  304. else
  305. {
  306. return false;
  307. }
  308. if (!isValid)
  309. {
  310. return false;
  311. }
  312. if (name[namePosition] == '/')
  313. {
  314. namePosition++;
  315. return GetOffset(name, ref namePosition, ref rule.TransitionTime);
  316. }
  317. else
  318. {
  319. rule.TransitionTime = 2 * SecondsPerHour;
  320. }
  321. return true;
  322. }
  323. private static int IsLeap(int year)
  324. {
  325. if (((year) % 4) == 0 && (((year) % 100) != 0 || ((year) % 400) == 0))
  326. {
  327. return 1;
  328. }
  329. return 0;
  330. }
  331. private static bool ParsePosixName(Span<char> name, out TimeZoneRule outRules, bool lastDitch)
  332. {
  333. outRules = new TimeZoneRule
  334. {
  335. Ats = new long[TzMaxTimes],
  336. Types = new byte[TzMaxTimes],
  337. Ttis = new TimeTypeInfo[TzMaxTypes],
  338. Chars = new char[TzCharsArraySize]
  339. };
  340. int stdLen;
  341. Span<char> stdName = name;
  342. int namePosition = 0;
  343. int stdOffset = 0;
  344. if (lastDitch)
  345. {
  346. stdLen = 3;
  347. namePosition += stdLen;
  348. }
  349. else
  350. {
  351. if (name[namePosition] == '<')
  352. {
  353. namePosition++;
  354. stdName = name.Slice(namePosition);
  355. int stdNamePosition = namePosition;
  356. namePosition = GetQZName(name.ToArray(), namePosition, '>');
  357. if (name[namePosition] != '>')
  358. {
  359. return false;
  360. }
  361. stdLen = namePosition - stdNamePosition;
  362. namePosition++;
  363. }
  364. else
  365. {
  366. namePosition = GetTZName(name.ToArray(), namePosition);
  367. stdLen = namePosition;
  368. }
  369. if (stdLen == 0)
  370. {
  371. return false;
  372. }
  373. bool isValid = GetOffset(name.ToArray(), ref namePosition, ref stdOffset);
  374. if (!isValid)
  375. {
  376. return false;
  377. }
  378. }
  379. int charCount = stdLen + 1;
  380. int destLen = 0;
  381. int dstOffset = 0;
  382. Span<char> destName = name.Slice(namePosition);
  383. if (TzCharsArraySize < charCount)
  384. {
  385. return false;
  386. }
  387. if (name[namePosition] != '\0')
  388. {
  389. if (name[namePosition] == '<')
  390. {
  391. destName = name.Slice(++namePosition);
  392. int destNamePosition = namePosition;
  393. namePosition = GetQZName(name.ToArray(), namePosition, '>');
  394. if (name[namePosition] != '>')
  395. {
  396. return false;
  397. }
  398. destLen = namePosition - destNamePosition;
  399. namePosition++;
  400. }
  401. else
  402. {
  403. destName = name.Slice(namePosition);
  404. namePosition = GetTZName(name.ToArray(), namePosition);
  405. destLen = namePosition;
  406. }
  407. if (destLen == 0)
  408. {
  409. return false;
  410. }
  411. charCount += destLen + 1;
  412. if (TzCharsArraySize < charCount)
  413. {
  414. return false;
  415. }
  416. if (name[namePosition] != '\0' && name[namePosition] != ',' && name[namePosition] != ';')
  417. {
  418. bool isValid = GetOffset(name.ToArray(), ref namePosition, ref dstOffset);
  419. if (!isValid)
  420. {
  421. return false;
  422. }
  423. }
  424. else
  425. {
  426. dstOffset = stdOffset - SecondsPerHour;
  427. }
  428. if (name[namePosition] == '\0')
  429. {
  430. name = TimeZoneDefaultRule.ToCharArray();
  431. namePosition = 0;
  432. }
  433. if (name[namePosition] == ',' || name[namePosition] == ';')
  434. {
  435. namePosition++;
  436. bool IsRuleValid = GetRule(name.ToArray(), ref namePosition, out Rule start);
  437. if (!IsRuleValid)
  438. {
  439. return false;
  440. }
  441. if (name[namePosition++] != ',')
  442. {
  443. return false;
  444. }
  445. IsRuleValid = GetRule(name.ToArray(), ref namePosition, out Rule end);
  446. if (!IsRuleValid)
  447. {
  448. return false;
  449. }
  450. if (name[namePosition] != '\0')
  451. {
  452. return false;
  453. }
  454. outRules.TypeCount = 2;
  455. outRules.Ttis[0] = new TimeTypeInfo
  456. {
  457. GmtOffset = -dstOffset,
  458. IsDaySavingTime = true,
  459. AbbreviationListIndex = stdLen + 1
  460. };
  461. outRules.Ttis[1] = new TimeTypeInfo
  462. {
  463. GmtOffset = -stdOffset,
  464. IsDaySavingTime = false,
  465. AbbreviationListIndex = 0
  466. };
  467. outRules.DefaultType = 0;
  468. int timeCount = 0;
  469. long janFirst = 0;
  470. int janOffset = 0;
  471. int yearBegining = EpochYear;
  472. do
  473. {
  474. int yearSeconds = YearLengths[IsLeap(yearBegining - 1)] * SecondsPerDay;
  475. yearBegining--;
  476. if (IncrementOverflow64(ref janFirst, -yearSeconds))
  477. {
  478. janOffset = -yearSeconds;
  479. break;
  480. }
  481. }
  482. while (EpochYear - YearsPerRepeat / 2 < yearBegining);
  483. int yearLimit = yearBegining + YearsPerRepeat + 1;
  484. int year;
  485. for (year = yearBegining; year < yearLimit; year++)
  486. {
  487. int startTime = TransitionTime(year, start, stdOffset);
  488. int endTime = TransitionTime(year, end, dstOffset);
  489. int yearSeconds = YearLengths[IsLeap(year)] * SecondsPerDay;
  490. bool isReversed = endTime < startTime;
  491. if (isReversed)
  492. {
  493. int swap = startTime;
  494. startTime = endTime;
  495. endTime = swap;
  496. }
  497. if (isReversed || (startTime < endTime && (endTime - startTime < (yearSeconds + (stdOffset - dstOffset)))))
  498. {
  499. if (TzMaxTimes - 2 < timeCount)
  500. {
  501. break;
  502. }
  503. outRules.Ats[timeCount] = janFirst;
  504. if (!IncrementOverflow64(ref outRules.Ats[timeCount], janOffset + startTime))
  505. {
  506. outRules.Types[timeCount++] = isReversed ? (byte)1 : (byte)0;
  507. }
  508. else if (janOffset != 0)
  509. {
  510. outRules.DefaultType = isReversed ? 1 : 0;
  511. }
  512. outRules.Ats[timeCount] = janFirst;
  513. if (!IncrementOverflow64(ref outRules.Ats[timeCount], janOffset + endTime))
  514. {
  515. outRules.Types[timeCount++] = isReversed ? (byte)0 : (byte)1;
  516. yearLimit = year + YearsPerRepeat + 1;
  517. }
  518. else if (janOffset != 0)
  519. {
  520. outRules.DefaultType = isReversed ? 0 : 1;
  521. }
  522. }
  523. if (IncrementOverflow64(ref janFirst, janOffset + yearSeconds))
  524. {
  525. break;
  526. }
  527. janOffset = 0;
  528. }
  529. outRules.TimeCount = timeCount;
  530. // There is no time variation, this is then a perpetual DST rule
  531. if (timeCount == 0)
  532. {
  533. outRules.TypeCount = 1;
  534. }
  535. else if (YearsPerRepeat < year - yearBegining)
  536. {
  537. outRules.GoBack = true;
  538. outRules.GoAhead = true;
  539. }
  540. }
  541. else
  542. {
  543. if (name[namePosition] == '\0')
  544. {
  545. return false;
  546. }
  547. long theirStdOffset = 0;
  548. for (int i = 0; i < outRules.TimeCount; i++)
  549. {
  550. int j = outRules.Types[i];
  551. if (outRules.Ttis[j].IsStandardTimeDaylight)
  552. {
  553. theirStdOffset = -outRules.Ttis[j].GmtOffset;
  554. }
  555. }
  556. long theirDstOffset = 0;
  557. for (int i = 0; i < outRules.TimeCount; i++)
  558. {
  559. int j = outRules.Types[i];
  560. if (outRules.Ttis[j].IsDaySavingTime)
  561. {
  562. theirDstOffset = -outRules.Ttis[j].GmtOffset;
  563. }
  564. }
  565. bool isDaySavingTime = false;
  566. long theirOffset = theirStdOffset;
  567. for (int i = 0; i < outRules.TimeCount; i++)
  568. {
  569. int j = outRules.Types[i];
  570. outRules.Types[i] = outRules.Ttis[j].IsDaySavingTime ? (byte)1 : (byte)0;
  571. if (!outRules.Ttis[j].IsGMT)
  572. {
  573. if (isDaySavingTime && !outRules.Ttis[j].IsStandardTimeDaylight)
  574. {
  575. outRules.Ats[i] += dstOffset - theirStdOffset;
  576. }
  577. else
  578. {
  579. outRules.Ats[i] += stdOffset - theirStdOffset;
  580. }
  581. }
  582. theirOffset = -outRules.Ttis[j].GmtOffset;
  583. if (outRules.Ttis[j].IsDaySavingTime)
  584. {
  585. theirDstOffset = theirOffset;
  586. }
  587. else
  588. {
  589. theirStdOffset = theirOffset;
  590. }
  591. }
  592. outRules.Ttis[0] = new TimeTypeInfo
  593. {
  594. GmtOffset = -stdOffset,
  595. IsDaySavingTime = false,
  596. AbbreviationListIndex = 0
  597. };
  598. outRules.Ttis[1] = new TimeTypeInfo
  599. {
  600. GmtOffset = -dstOffset,
  601. IsDaySavingTime = true,
  602. AbbreviationListIndex = stdLen + 1
  603. };
  604. outRules.TypeCount = 2;
  605. outRules.DefaultType = 0;
  606. }
  607. }
  608. else
  609. {
  610. // default is perpetual standard time
  611. outRules.TypeCount = 1;
  612. outRules.TimeCount = 0;
  613. outRules.DefaultType = 0;
  614. outRules.Ttis[0] = new TimeTypeInfo
  615. {
  616. GmtOffset = -stdOffset,
  617. IsDaySavingTime = false,
  618. AbbreviationListIndex = 0
  619. };
  620. }
  621. outRules.CharCount = charCount;
  622. int charsPosition = 0;
  623. for (int i = 0; i < stdLen; i++)
  624. {
  625. outRules.Chars[i] = stdName[i];
  626. }
  627. charsPosition += stdLen;
  628. outRules.Chars[charsPosition++] = '\0';
  629. if (destLen != 0)
  630. {
  631. for (int i = 0; i < destLen; i++)
  632. {
  633. outRules.Chars[charsPosition + i] = destName[i];
  634. }
  635. outRules.Chars[charsPosition + destLen] = '\0';
  636. }
  637. return true;
  638. }
  639. private static int TransitionTime(int year, Rule rule, int offset)
  640. {
  641. int leapYear = IsLeap(year);
  642. int value;
  643. switch (rule.Type)
  644. {
  645. case RuleType.JulianDay:
  646. value = (rule.Day - 1) * SecondsPerDay;
  647. if (leapYear == 1 && rule.Day >= 60)
  648. {
  649. value += SecondsPerDay;
  650. }
  651. break;
  652. case RuleType.DayOfYear:
  653. value = rule.Day * SecondsPerDay;
  654. break;
  655. case RuleType.MonthNthDayOfWeek:
  656. // Here we use Zeller's Congruence to get the day of week of the first month.
  657. int m1 = (rule.Month + 9) % 12 + 1;
  658. int yy0 = (rule.Month <= 2) ? (year - 1) : year;
  659. int yy1 = yy0 / 100;
  660. int yy2 = yy0 % 100;
  661. int dayOfWeek = ((26 * m1 - 2) / 10 + 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
  662. if (dayOfWeek < 0)
  663. {
  664. dayOfWeek += DaysPerWekk;
  665. }
  666. // Get the zero origin
  667. int d = rule.Day - dayOfWeek;
  668. if (d < 0)
  669. {
  670. d += DaysPerWekk;
  671. }
  672. for (int i = 1; i < rule.Week; i++)
  673. {
  674. if (d + DaysPerWekk >= MonthsLengths[leapYear][rule.Month - 1])
  675. {
  676. break;
  677. }
  678. d += DaysPerWekk;
  679. }
  680. value = d * SecondsPerDay;
  681. for (int i = 0; i < rule.Month - 1; i++)
  682. {
  683. value += MonthsLengths[leapYear][i] * SecondsPerDay;
  684. }
  685. break;
  686. default:
  687. throw new NotImplementedException("Unknown time transition!");
  688. }
  689. return value + rule.TransitionTime + offset;
  690. }
  691. private static bool NormalizeOverflow32(ref int ip, ref int unit, int baseValue)
  692. {
  693. int delta;
  694. if (unit >= 0)
  695. {
  696. delta = unit / baseValue;
  697. }
  698. else
  699. {
  700. delta = -1 - (-1 - unit) / baseValue;
  701. }
  702. unit -= delta * baseValue;
  703. return IncrementOverflow32(ref ip, delta);
  704. }
  705. private static bool NormalizeOverflow64(ref long ip, ref long unit, long baseValue)
  706. {
  707. long delta;
  708. if (unit >= 0)
  709. {
  710. delta = unit / baseValue;
  711. }
  712. else
  713. {
  714. delta = -1 - (-1 - unit) / baseValue;
  715. }
  716. unit -= delta * baseValue;
  717. return IncrementOverflow64(ref ip, delta);
  718. }
  719. private static bool IncrementOverflow32(ref int time, int j)
  720. {
  721. try
  722. {
  723. time = checked(time + j);
  724. return false;
  725. }
  726. catch (OverflowException)
  727. {
  728. return true;
  729. }
  730. }
  731. private static bool IncrementOverflow64(ref long time, long j)
  732. {
  733. try
  734. {
  735. time = checked(time + j);
  736. return false;
  737. }
  738. catch (OverflowException)
  739. {
  740. return true;
  741. }
  742. }
  743. internal static bool ParsePosixName(string name, out TimeZoneRule outRules)
  744. {
  745. return ParsePosixName(name.ToCharArray(), out outRules, false);
  746. }
  747. internal static unsafe bool ParseTimeZoneBinary(out TimeZoneRule outRules, Stream inputData)
  748. {
  749. outRules = new TimeZoneRule
  750. {
  751. Ats = new long[TzMaxTimes],
  752. Types = new byte[TzMaxTimes],
  753. Ttis = new TimeTypeInfo[TzMaxTypes],
  754. Chars = new char[TzCharsArraySize]
  755. };
  756. BinaryReader reader = new BinaryReader(inputData);
  757. long streamLength = reader.BaseStream.Length;
  758. if (streamLength < Marshal.SizeOf<TzifHeader>())
  759. {
  760. return false;
  761. }
  762. TzifHeader header = reader.ReadStruct<TzifHeader>();
  763. streamLength -= Marshal.SizeOf<TzifHeader>();
  764. int ttisGMTCount = Detzcode32(header.TtisGMTCount);
  765. int ttisSTDCount = Detzcode32(header.TtisSTDCount);
  766. int leapCount = Detzcode32(header.LeapCount);
  767. int timeCount = Detzcode32(header.TimeCount);
  768. int typeCount = Detzcode32(header.TypeCount);
  769. int charCount = Detzcode32(header.CharCount);
  770. if (!(0 <= leapCount
  771. && leapCount < TzMaxLeaps
  772. && 0 < typeCount
  773. && typeCount < TzMaxTypes
  774. && 0 <= timeCount
  775. && timeCount < TzMaxTimes
  776. && 0 <= charCount
  777. && charCount < TzMaxChars
  778. && (ttisSTDCount == typeCount || ttisSTDCount == 0)
  779. && (ttisGMTCount == typeCount || ttisGMTCount == 0)))
  780. {
  781. return false;
  782. }
  783. if (streamLength < (timeCount * TimeTypeSize
  784. + timeCount
  785. + typeCount * 6
  786. + charCount
  787. + leapCount * (TimeTypeSize + 4)
  788. + ttisSTDCount
  789. + ttisGMTCount))
  790. {
  791. return false;
  792. }
  793. outRules.TimeCount = timeCount;
  794. outRules.TypeCount = typeCount;
  795. outRules.CharCount = charCount;
  796. byte[] workBuffer = StreamUtils.StreamToBytes(inputData);
  797. timeCount = 0;
  798. fixed (byte* workBufferPtrStart = workBuffer)
  799. {
  800. byte* p = workBufferPtrStart;
  801. for (int i = 0; i < outRules.TimeCount; i++)
  802. {
  803. long at = Detzcode64((long*)p);
  804. outRules.Types[i] = 1;
  805. if (timeCount != 0 && at <= outRules.Ats[timeCount - 1])
  806. {
  807. if (at < outRules.Ats[timeCount - 1])
  808. {
  809. return false;
  810. }
  811. outRules.Types[i - 1] = 0;
  812. timeCount--;
  813. }
  814. outRules.Ats[timeCount++] = at;
  815. p += TimeTypeSize;
  816. }
  817. timeCount = 0;
  818. for (int i = 0; i < outRules.TimeCount; i++)
  819. {
  820. byte type = *p++;
  821. if (outRules.TypeCount <= type)
  822. {
  823. return false;
  824. }
  825. if (outRules.Types[i] != 0)
  826. {
  827. outRules.Types[timeCount++] = type;
  828. }
  829. }
  830. outRules.TimeCount = timeCount;
  831. for (int i = 0; i < outRules.TypeCount; i++)
  832. {
  833. TimeTypeInfo ttis = outRules.Ttis[i];
  834. ttis.GmtOffset = Detzcode32((int*)p);
  835. p += 4;
  836. if (*p >= 2)
  837. {
  838. return false;
  839. }
  840. ttis.IsDaySavingTime = *p != 0;
  841. p++;
  842. int abbreviationListIndex = *p++;
  843. if (abbreviationListIndex >= outRules.CharCount)
  844. {
  845. return false;
  846. }
  847. ttis.AbbreviationListIndex = abbreviationListIndex;
  848. outRules.Ttis[i] = ttis;
  849. }
  850. fixed (char* chars = outRules.Chars)
  851. {
  852. Encoding.ASCII.GetChars(p, outRules.CharCount, chars, outRules.CharCount);
  853. }
  854. p += outRules.CharCount;
  855. outRules.Chars[outRules.CharCount] = '\0';
  856. for (int i = 0; i < outRules.TypeCount; i++)
  857. {
  858. if (ttisSTDCount == 0)
  859. {
  860. outRules.Ttis[i].IsStandardTimeDaylight = false;
  861. }
  862. else
  863. {
  864. if (*p >= 2)
  865. {
  866. return false;
  867. }
  868. outRules.Ttis[i].IsStandardTimeDaylight = *p++ != 0;
  869. }
  870. }
  871. for (int i = 0; i < outRules.TypeCount; i++)
  872. {
  873. if (ttisSTDCount == 0)
  874. {
  875. outRules.Ttis[i].IsGMT = false;
  876. }
  877. else
  878. {
  879. if (*p >= 2)
  880. {
  881. return false;
  882. }
  883. outRules.Ttis[i].IsGMT = *p++ != 0;
  884. }
  885. }
  886. long position = (p - workBufferPtrStart);
  887. long nRead = streamLength - position;
  888. if (nRead < 0)
  889. {
  890. return false;
  891. }
  892. // Nintendo abort in case of a TzIf file with a POSIX TZ Name too long to fit inside a TimeZoneRule.
  893. // As it's impossible in normal usage to achive this, we also force a crash.
  894. if (nRead > (TzNameMax + 1))
  895. {
  896. throw new InvalidOperationException();
  897. }
  898. char[] tempName = new char[TzNameMax + 1];
  899. Array.Copy(workBuffer, position, tempName, 0, nRead);
  900. if (nRead > 2 && tempName[0] == '\n' && tempName[nRead - 1] == '\n' && outRules.TypeCount + 2 <= TzMaxTypes)
  901. {
  902. tempName[nRead - 1] = '\0';
  903. char[] name = new char[TzNameMax];
  904. Array.Copy(tempName, 1, name, 0, nRead - 1);
  905. if (ParsePosixName(name, out TimeZoneRule tempRules, false))
  906. {
  907. int abbreviationCount = 0;
  908. charCount = outRules.CharCount;
  909. fixed (char* chars = outRules.Chars)
  910. {
  911. for (int i = 0; i < tempRules.TypeCount; i++)
  912. {
  913. fixed (char* tempChars = tempRules.Chars)
  914. {
  915. char* tempAbbreviation = tempChars + tempRules.Ttis[i].AbbreviationListIndex;
  916. int j;
  917. for (j = 0; j < charCount; j++)
  918. {
  919. if (StringUtils.CompareCStr(chars + j, tempAbbreviation) == 0)
  920. {
  921. tempRules.Ttis[i].AbbreviationListIndex = j;
  922. abbreviationCount++;
  923. break;
  924. }
  925. }
  926. if (j >= charCount)
  927. {
  928. int abbreviationLength = StringUtils.LengthCstr(tempAbbreviation);
  929. if (j + abbreviationLength < TzMaxChars)
  930. {
  931. for (int x = 0; x < abbreviationLength; x++)
  932. {
  933. chars[j + x] = tempAbbreviation[x];
  934. }
  935. charCount = j + abbreviationLength + 1;
  936. tempRules.Ttis[i].AbbreviationListIndex = j;
  937. abbreviationCount++;
  938. }
  939. }
  940. }
  941. }
  942. if (abbreviationCount == tempRules.TypeCount)
  943. {
  944. outRules.CharCount = charCount;
  945. // Remove trailing
  946. while (1 < outRules.TimeCount && (outRules.Types[outRules.TimeCount - 1] == outRules.Types[outRules.TimeCount - 2]))
  947. {
  948. outRules.TimeCount--;
  949. }
  950. int i;
  951. for (i = 0; i < tempRules.TimeCount; i++)
  952. {
  953. if (outRules.TimeCount == 0 || outRules.Ats[outRules.TimeCount - 1] < tempRules.Ats[i])
  954. {
  955. break;
  956. }
  957. }
  958. while (i < tempRules.TimeCount && outRules.TimeCount < TzMaxTimes)
  959. {
  960. outRules.Ats[outRules.TimeCount] = tempRules.Ats[i];
  961. outRules.Types[outRules.TimeCount] = (byte)(outRules.TypeCount + (byte)tempRules.Types[i]);
  962. outRules.TimeCount++;
  963. i++;
  964. }
  965. for (i = 0; i < tempRules.TypeCount; i++)
  966. {
  967. outRules.Ttis[outRules.TypeCount++] = tempRules.Ttis[i];
  968. }
  969. }
  970. }
  971. }
  972. }
  973. if (outRules.TypeCount == 0)
  974. {
  975. return false;
  976. }
  977. if (outRules.TimeCount > 1)
  978. {
  979. for (int i = 1; i < outRules.TimeCount; i++)
  980. {
  981. if (TimeTypeEquals(outRules, outRules.Types[i], outRules.Types[0]) && DifferByRepeat(outRules.Ats[i], outRules.Ats[0]))
  982. {
  983. outRules.GoBack = true;
  984. break;
  985. }
  986. }
  987. for (int i = outRules.TimeCount - 2; i >= 0; i--)
  988. {
  989. if (TimeTypeEquals(outRules, outRules.Types[outRules.TimeCount - 1], outRules.Types[i]) && DifferByRepeat(outRules.Ats[outRules.TimeCount - 1], outRules.Ats[i]))
  990. {
  991. outRules.GoAhead = true;
  992. break;
  993. }
  994. }
  995. }
  996. int defaultType;
  997. for (defaultType = 0; defaultType < outRules.TimeCount; defaultType++)
  998. {
  999. if (outRules.Types[defaultType] == 0)
  1000. {
  1001. break;
  1002. }
  1003. }
  1004. defaultType = defaultType < outRules.TimeCount ? -1 : 0;
  1005. if (defaultType < 0 && outRules.TimeCount > 0 && outRules.Ttis[outRules.Types[0]].IsDaySavingTime)
  1006. {
  1007. defaultType = outRules.Types[0];
  1008. while (--defaultType >= 0)
  1009. {
  1010. if (!outRules.Ttis[defaultType].IsDaySavingTime)
  1011. {
  1012. break;
  1013. }
  1014. }
  1015. }
  1016. if (defaultType < 0)
  1017. {
  1018. defaultType = 0;
  1019. while (outRules.Ttis[defaultType].IsDaySavingTime)
  1020. {
  1021. if (++defaultType >= outRules.TypeCount)
  1022. {
  1023. defaultType = 0;
  1024. break;
  1025. }
  1026. }
  1027. }
  1028. outRules.DefaultType = defaultType;
  1029. }
  1030. return true;
  1031. }
  1032. private static long GetLeapDaysNotNeg(long year)
  1033. {
  1034. return year / 4 - year / 100 + year / 400;
  1035. }
  1036. private static long GetLeapDays(long year)
  1037. {
  1038. if (year < 0)
  1039. {
  1040. return -1 - GetLeapDaysNotNeg(-1 - year);
  1041. }
  1042. else
  1043. {
  1044. return GetLeapDaysNotNeg(year);
  1045. }
  1046. }
  1047. private static ResultCode CreateCalendarTime(long time, int gmtOffset, out CalendarTimeInternal calendarTime, out CalendarAdditionalInfo calendarAdditionalInfo)
  1048. {
  1049. long year = EpochYear;
  1050. long timeDays = time / SecondsPerDay;
  1051. long remainingSeconds = time % SecondsPerDay;
  1052. calendarTime = new CalendarTimeInternal();
  1053. calendarAdditionalInfo = new CalendarAdditionalInfo()
  1054. {
  1055. TimezoneName = new char[8]
  1056. };
  1057. while (timeDays < 0 || timeDays >= YearLengths[IsLeap((int)year)])
  1058. {
  1059. long timeDelta = timeDays / DaysPerLYear;
  1060. long delta = timeDelta;
  1061. if (delta == 0)
  1062. {
  1063. delta = timeDays < 0 ? -1 : 1;
  1064. }
  1065. long newYear = year;
  1066. if (IncrementOverflow64(ref newYear, delta))
  1067. {
  1068. return ResultCode.OutOfRange;
  1069. }
  1070. long leapDays = GetLeapDays(newYear - 1) - GetLeapDays(year - 1);
  1071. timeDays -= (newYear - year) * DaysPerNYear;
  1072. timeDays -= leapDays;
  1073. year = newYear;
  1074. }
  1075. long dayOfYear = timeDays;
  1076. remainingSeconds += gmtOffset;
  1077. while (remainingSeconds < 0)
  1078. {
  1079. remainingSeconds += SecondsPerDay;
  1080. dayOfYear -= 1;
  1081. }
  1082. while (remainingSeconds >= SecondsPerDay)
  1083. {
  1084. remainingSeconds -= SecondsPerDay;
  1085. dayOfYear += 1;
  1086. }
  1087. while (dayOfYear < 0)
  1088. {
  1089. if (IncrementOverflow64(ref year, -1))
  1090. {
  1091. return ResultCode.OutOfRange;
  1092. }
  1093. dayOfYear += YearLengths[IsLeap((int)year)];
  1094. }
  1095. while (dayOfYear >= YearLengths[IsLeap((int)year)])
  1096. {
  1097. dayOfYear -= YearLengths[IsLeap((int)year)];
  1098. if (IncrementOverflow64(ref year, 1))
  1099. {
  1100. return ResultCode.OutOfRange;
  1101. }
  1102. }
  1103. calendarTime.Year = year;
  1104. calendarAdditionalInfo.DayOfYear = (uint)dayOfYear;
  1105. long dayOfWeek = (EpochWeekDay + ((year - EpochYear) % DaysPerWekk) * (DaysPerNYear % DaysPerWekk) + GetLeapDays(year - 1) - GetLeapDays(EpochYear - 1) + dayOfYear) % DaysPerWekk;
  1106. if (dayOfWeek < 0)
  1107. {
  1108. dayOfWeek += DaysPerWekk;
  1109. }
  1110. calendarAdditionalInfo.DayOfWeek = (uint)dayOfWeek;
  1111. calendarTime.Hour = (sbyte)((remainingSeconds / SecondsPerHour) % SecondsPerHour);
  1112. remainingSeconds %= SecondsPerHour;
  1113. calendarTime.Minute = (sbyte)(remainingSeconds / SecondsPerMinute);
  1114. calendarTime.Second = (sbyte)(remainingSeconds % SecondsPerMinute);
  1115. int[] ip = MonthsLengths[IsLeap((int)year)];
  1116. for (calendarTime.Month = 0; dayOfYear >= ip[calendarTime.Month]; ++calendarTime.Month)
  1117. {
  1118. dayOfYear -= ip[calendarTime.Month];
  1119. }
  1120. calendarTime.Day = (sbyte)(dayOfYear + 1);
  1121. calendarAdditionalInfo.IsDaySavingTime = false;
  1122. calendarAdditionalInfo.GmtOffset = gmtOffset;
  1123. return 0;
  1124. }
  1125. private static ResultCode ToCalendarTimeInternal(TimeZoneRule rules, long time, out CalendarTimeInternal calendarTime, out CalendarAdditionalInfo calendarAdditionalInfo)
  1126. {
  1127. calendarTime = new CalendarTimeInternal();
  1128. calendarAdditionalInfo = new CalendarAdditionalInfo()
  1129. {
  1130. TimezoneName = new char[8]
  1131. };
  1132. ResultCode result;
  1133. if ((rules.GoAhead && time < rules.Ats[0]) || (rules.GoBack && time > rules.Ats[rules.TimeCount - 1]))
  1134. {
  1135. long newTime = time;
  1136. long seconds;
  1137. long years;
  1138. if (time < rules.Ats[0])
  1139. {
  1140. seconds = rules.Ats[0] - time;
  1141. }
  1142. else
  1143. {
  1144. seconds = time - rules.Ats[rules.TimeCount - 1];
  1145. }
  1146. seconds -= 1;
  1147. years = (seconds / SecondsPerRepeat + 1) * YearsPerRepeat;
  1148. seconds = years * AverageSecondsPerYear;
  1149. if (time < rules.Ats[0])
  1150. {
  1151. newTime += seconds;
  1152. }
  1153. else
  1154. {
  1155. newTime -= seconds;
  1156. }
  1157. if (newTime < rules.Ats[0] && newTime > rules.Ats[rules.TimeCount - 1])
  1158. {
  1159. return ResultCode.TimeNotFound;
  1160. }
  1161. result = ToCalendarTimeInternal(rules, newTime, out calendarTime, out calendarAdditionalInfo);
  1162. if (result != 0)
  1163. {
  1164. return result;
  1165. }
  1166. if (time < rules.Ats[0])
  1167. {
  1168. calendarTime.Year -= years;
  1169. }
  1170. else
  1171. {
  1172. calendarTime.Year += years;
  1173. }
  1174. return ResultCode.Success;
  1175. }
  1176. int ttiIndex;
  1177. if (rules.TimeCount == 0 || time < rules.Ats[0])
  1178. {
  1179. ttiIndex = rules.DefaultType;
  1180. }
  1181. else
  1182. {
  1183. int low = 1;
  1184. int high = rules.TimeCount;
  1185. while (low < high)
  1186. {
  1187. int mid = (low + high) >> 1;
  1188. if (time < rules.Ats[mid])
  1189. {
  1190. high = mid;
  1191. }
  1192. else
  1193. {
  1194. low = mid + 1;
  1195. }
  1196. }
  1197. ttiIndex = rules.Types[low - 1];
  1198. }
  1199. result = CreateCalendarTime(time, rules.Ttis[ttiIndex].GmtOffset, out calendarTime, out calendarAdditionalInfo);
  1200. if (result == 0)
  1201. {
  1202. calendarAdditionalInfo.IsDaySavingTime = rules.Ttis[ttiIndex].IsDaySavingTime;
  1203. unsafe
  1204. {
  1205. fixed (char* timeZoneAbbreviation = &rules.Chars[rules.Ttis[ttiIndex].AbbreviationListIndex])
  1206. {
  1207. int timeZoneSize = Math.Min(StringUtils.LengthCstr(timeZoneAbbreviation), 8);
  1208. for (int i = 0; i < timeZoneSize; i++)
  1209. {
  1210. calendarAdditionalInfo.TimezoneName[i] = timeZoneAbbreviation[i];
  1211. }
  1212. }
  1213. }
  1214. }
  1215. return result;
  1216. }
  1217. private static ResultCode ToPosixTimeInternal(TimeZoneRule rules, CalendarTimeInternal calendarTime, out long posixTime)
  1218. {
  1219. posixTime = 0;
  1220. int hour = calendarTime.Hour;
  1221. int minute = calendarTime.Minute;
  1222. if (NormalizeOverflow32(ref hour, ref minute, MinutesPerHour))
  1223. {
  1224. return ResultCode.Overflow;
  1225. }
  1226. calendarTime.Minute = (sbyte)minute;
  1227. int day = calendarTime.Day;
  1228. if (NormalizeOverflow32(ref day, ref hour, HoursPerDays))
  1229. {
  1230. return ResultCode.Overflow;
  1231. }
  1232. calendarTime.Day = (sbyte)day;
  1233. calendarTime.Hour = (sbyte)hour;
  1234. long year = calendarTime.Year;
  1235. long month = calendarTime.Month;
  1236. if (NormalizeOverflow64(ref year, ref month, MonthsPerYear))
  1237. {
  1238. return ResultCode.Overflow;
  1239. }
  1240. calendarTime.Month = (sbyte)month;
  1241. if (IncrementOverflow64(ref year, YearBase))
  1242. {
  1243. return ResultCode.Overflow;
  1244. }
  1245. while (day <= 0)
  1246. {
  1247. if (IncrementOverflow64(ref year, -1))
  1248. {
  1249. return ResultCode.Overflow;
  1250. }
  1251. long li = year;
  1252. if (1 < calendarTime.Month)
  1253. {
  1254. li++;
  1255. }
  1256. day += YearLengths[IsLeap((int)li)];
  1257. }
  1258. while (day > DaysPerLYear)
  1259. {
  1260. long li = year;
  1261. if (1 < calendarTime.Month)
  1262. {
  1263. li++;
  1264. }
  1265. day -= YearLengths[IsLeap((int)li)];
  1266. if (IncrementOverflow64(ref year, 1))
  1267. {
  1268. return ResultCode.Overflow;
  1269. }
  1270. }
  1271. while (true)
  1272. {
  1273. int i = MonthsLengths[IsLeap((int)year)][calendarTime.Month];
  1274. if (day <= i)
  1275. {
  1276. break;
  1277. }
  1278. day -= i;
  1279. calendarTime.Month += 1;
  1280. if (calendarTime.Month >= MonthsPerYear)
  1281. {
  1282. calendarTime.Month = 0;
  1283. if (IncrementOverflow64(ref year, 1))
  1284. {
  1285. return ResultCode.Overflow;
  1286. }
  1287. }
  1288. }
  1289. calendarTime.Day = (sbyte)day;
  1290. if (IncrementOverflow64(ref year, -YearBase))
  1291. {
  1292. return ResultCode.Overflow;
  1293. }
  1294. calendarTime.Year = year;
  1295. int savedSeconds;
  1296. if (calendarTime.Second >= 0 && calendarTime.Second < SecondsPerMinute)
  1297. {
  1298. savedSeconds = 0;
  1299. }
  1300. else if (year + YearBase < EpochYear)
  1301. {
  1302. int second = calendarTime.Second;
  1303. if (IncrementOverflow32(ref second, 1 - SecondsPerMinute))
  1304. {
  1305. return ResultCode.Overflow;
  1306. }
  1307. savedSeconds = second;
  1308. calendarTime.Second = 1 - SecondsPerMinute;
  1309. }
  1310. else
  1311. {
  1312. savedSeconds = calendarTime.Second;
  1313. calendarTime.Second = 0;
  1314. }
  1315. long low = long.MinValue;
  1316. long high = long.MaxValue;
  1317. while (true)
  1318. {
  1319. long pivot = low / 2 + high / 2;
  1320. if (pivot < low)
  1321. {
  1322. pivot = low;
  1323. }
  1324. else if (pivot > high)
  1325. {
  1326. pivot = high;
  1327. }
  1328. int direction;
  1329. ResultCode result = ToCalendarTimeInternal(rules, pivot, out CalendarTimeInternal candidateCalendarTime, out _);
  1330. if (result != 0)
  1331. {
  1332. if (pivot > 0)
  1333. {
  1334. direction = 1;
  1335. }
  1336. else
  1337. {
  1338. direction = -1;
  1339. }
  1340. }
  1341. else
  1342. {
  1343. direction = candidateCalendarTime.CompareTo(calendarTime);
  1344. }
  1345. if (direction == 0)
  1346. {
  1347. long timeResult = pivot + savedSeconds;
  1348. if ((timeResult < pivot) != (savedSeconds < 0))
  1349. {
  1350. return ResultCode.Overflow;
  1351. }
  1352. posixTime = timeResult;
  1353. break;
  1354. }
  1355. else
  1356. {
  1357. if (pivot == low)
  1358. {
  1359. if (pivot == long.MaxValue)
  1360. {
  1361. return ResultCode.TimeNotFound;
  1362. }
  1363. pivot += 1;
  1364. low += 1;
  1365. }
  1366. else if (pivot == high)
  1367. {
  1368. if (pivot == long.MinValue)
  1369. {
  1370. return ResultCode.TimeNotFound;
  1371. }
  1372. pivot -= 1;
  1373. high -= 1;
  1374. }
  1375. if (low > high)
  1376. {
  1377. return ResultCode.TimeNotFound;
  1378. }
  1379. if (direction > 0)
  1380. {
  1381. high = pivot;
  1382. }
  1383. else
  1384. {
  1385. low = pivot;
  1386. }
  1387. }
  1388. }
  1389. return ResultCode.Success;
  1390. }
  1391. internal static ResultCode ToCalendarTime(TimeZoneRule rules, long time, out CalendarInfo calendar)
  1392. {
  1393. ResultCode result = ToCalendarTimeInternal(rules, time, out CalendarTimeInternal calendarTime, out CalendarAdditionalInfo calendarAdditionalInfo);
  1394. calendar = new CalendarInfo()
  1395. {
  1396. Time = new CalendarTime()
  1397. {
  1398. Year = (short)calendarTime.Year,
  1399. Month = calendarTime.Month,
  1400. Day = calendarTime.Day,
  1401. Hour = calendarTime.Hour,
  1402. Minute = calendarTime.Minute,
  1403. Second = calendarTime.Second
  1404. },
  1405. AdditionalInfo = calendarAdditionalInfo
  1406. };
  1407. return result;
  1408. }
  1409. internal static ResultCode ToPosixTime(TimeZoneRule rules, CalendarTime calendarTime, out long posixTime)
  1410. {
  1411. CalendarTimeInternal calendarTimeInternal = new CalendarTimeInternal()
  1412. {
  1413. Year = calendarTime.Year,
  1414. Month = calendarTime.Month,
  1415. Day = calendarTime.Day,
  1416. Hour = calendarTime.Hour,
  1417. Minute = calendarTime.Minute,
  1418. Second = calendarTime.Second
  1419. };
  1420. return ToPosixTimeInternal(rules, calendarTimeInternal, out posixTime);
  1421. }
  1422. }
  1423. }