TimeZone.cs 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739
  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. // NOTE: Nintendo's month range is 1-12, internal range is 0-11.
  1400. Month = (sbyte)(calendarTime.Month + 1),
  1401. Day = calendarTime.Day,
  1402. Hour = calendarTime.Hour,
  1403. Minute = calendarTime.Minute,
  1404. Second = calendarTime.Second
  1405. },
  1406. AdditionalInfo = calendarAdditionalInfo
  1407. };
  1408. return result;
  1409. }
  1410. internal static ResultCode ToPosixTime(TimeZoneRule rules, CalendarTime calendarTime, out long posixTime)
  1411. {
  1412. CalendarTimeInternal calendarTimeInternal = new CalendarTimeInternal()
  1413. {
  1414. Year = calendarTime.Year,
  1415. // NOTE: Nintendo's month range is 1-12, internal range is 0-11.
  1416. Month = (sbyte)(calendarTime.Month - 1),
  1417. Day = calendarTime.Day,
  1418. Hour = calendarTime.Hour,
  1419. Minute = calendarTime.Minute,
  1420. Second = calendarTime.Second
  1421. };
  1422. return ToPosixTimeInternal(rules, calendarTimeInternal, out posixTime);
  1423. }
  1424. }
  1425. }