TimeZone.cs 54 KB

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