TimeZone.cs 53 KB

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