TimeZone.cs 53 KB

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