TimeZone.cs 54 KB

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