-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTypes.cs
More file actions
3985 lines (3325 loc) · 113 KB
/
Types.cs
File metadata and controls
3985 lines (3325 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2017 Stanislav Muhametsin. All rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using CBAM.Abstractions;
using CBAM.SQL.PostgreSQL;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UtilPack;
// TODO document these later.
// TODO when (if?) we will have extension properties ( https://www.infoq.com/news/2017/08/CSharp-8 , under "extension everything" ), most of the properties of these types can be refactored into extension properties.
// Writing them now as extension methods would not be feasible in terms of user experience.
#pragma warning disable 1591
namespace CBAM.SQL.PostgreSQL
{
// TODO implement IPgTypeWithBackendTextFormat
public struct PgSQLInterval : IComparable, IComparable<PgSQLInterval>, IEquatable<PgSQLInterval>
{
//// Getting decimal digits from System.Decimal: http://stackoverflow.com/questions/13477689/find-number-of-decimal-places-in-decimal-value-regardless-of-culture
//private delegate Int32 GetDigitsDelegate( ref Decimal value );
//private static class DecimalHelper
//{
// public static readonly GetDigitsDelegate GetDigits;
// static DecimalHelper()
// {
// var value = Expression.Parameter( typeof( Decimal ).MakeByRefType(), "value" );
// //return (value.flags & ~Int32.MinValue) >> 16
// var digits = Expression.RightShift(
// Expression.And( Expression.Field( value, "flags" ), Expression.Constant( ~Int32.MinValue, typeof( Int32 ) ) ),
// Expression.Constant( 16, typeof( Int32 ) ) );
// GetDigits = Expression.Lambda<GetDigitsDelegate>( digits, value ).Compile();
// }
//}
#region Consts
private const Int32 DAYS_PER_MONTH = 30;
private const Int32 MONTHS_PER_YEAR = 12;
private const Int64 TICKS_PER_MONTH = TimeSpan.TicksPerDay * DAYS_PER_MONTH;
internal const Int64 TICKS_PER_MICROSECOND = TimeSpan.TicksPerMillisecond / 1000;
internal const Int64 MICROSECONDS_PER_SECOND = 1000000;
internal const Int64 MILLISECONDS_PER_SECOND = 1000;
internal const Int64 SECONDS_PER_MINUTE = 60;
internal const Int64 MINUTES_PER_HOUR = 60;
#endregion
#region Static
public static PgSQLInterval MinValue = new PgSQLInterval( Int64.MinValue );
public static PgSQLInterval MaxValue = new PgSQLInterval( Int64.MaxValue );
public static PgSQLInterval Zero = new PgSQLInterval( 0 );
internal static void AppendTimeInformation( StringBuilder sb, Int64 ticks )
{
sb.Append( Math.Abs( CalcHours( ticks ) ).ToString( "D2" ) ) // Hours
.Append( ':' )
.Append( Math.Abs( CalcMinutes( ticks ) ).ToString( "D2" ) ) // Minutes
.Append( ':' )
// Calculate seconds part (total seconds minus whole minutes in seconds)
.Append( Math.Abs( ticks / (Decimal) TimeSpan.TicksPerSecond - ( ticks / TimeSpan.TicksPerMinute ) * 60 ).ToString( "0#.######", System.Globalization.CultureInfo.InvariantCulture.NumberFormat ) ); // Seconds
}
internal static Int32 CalcMicroseconds( Int64 ticks )
{
return (Int32) ( ( ticks / TICKS_PER_MICROSECOND ) % MICROSECONDS_PER_SECOND );
}
internal static Int32 CalcMilliseconds( Int64 ticks )
{
return (Int32) ( ( ticks / TimeSpan.TicksPerMillisecond ) % MILLISECONDS_PER_SECOND );
}
internal static Int32 CalcSeconds( Int64 ticks )
{
return (Int32) ( ( ticks / TimeSpan.TicksPerSecond ) % SECONDS_PER_MINUTE );
}
internal static Int32 CalcMinutes( Int64 ticks )
{
return (Int32) ( ( ticks / TimeSpan.TicksPerMinute ) % MINUTES_PER_HOUR );
}
internal static Int32 CalcHours( Int64 ticks )
{
return (Int32) ( ticks / TimeSpan.TicksPerHour );
}
#endregion
#region Fields
private readonly Int32 _months;
private readonly Int32 _days;
private readonly Int64 _ticks;
#endregion
#region Constructors
public PgSQLInterval( Int64 ticks )
: this( 0, 0, ticks )
{
}
public PgSQLInterval( TimeSpan span )
: this( span.Ticks )
{
}
public PgSQLInterval( Int32 months, Int32 days, Int64 ticks )
{
this._months = months;
this._days = days;
this._ticks = ticks;
}
public PgSQLInterval( Int32 days, Int32 hours, Int32 minutes, Int32 seconds )
: this( 0, days, new TimeSpan( hours, minutes, seconds ).Ticks )
{
}
public PgSQLInterval( Int32 days, Int32 hours, Int32 minutes, Int32 seconds, Int32 milliseconds )
: this( 0, days, new TimeSpan( 0, hours, minutes, seconds, milliseconds ).Ticks )
{
}
public PgSQLInterval( Int32 months, Int32 days, Int32 hours, Int32 minutes, Int32 seconds, Int32 milliseconds )
: this( months, days, new TimeSpan( 0, hours, minutes, seconds, milliseconds ).Ticks )
{
}
public PgSQLInterval( Int32 years, Int32 months, Int32 days, Int32 hours, Int32 minutes, Int32 seconds, Int32 milliseconds )
: this( years * 12 + months, days, new TimeSpan( 0, hours, minutes, seconds, milliseconds ).Ticks )
{
}
#endregion
#region Whole parts
public Int64 Ticks
{
get
{
return this._ticks;
}
}
public Int32 Microseconds
{
get
{
return CalcMicroseconds( this._ticks );
}
}
public Int32 Milliseconds
{
get
{
return CalcMilliseconds( this._ticks );
}
}
public Int32 Seconds
{
get
{
return CalcSeconds( this._ticks );
}
}
public Int32 Minutes
{
get
{
return CalcMinutes( this._ticks );
}
}
public Int32 Hours
{
get
{
return CalcHours( this._ticks );
}
}
public Int32 Days
{
get
{
return this._days;
}
}
public Int32 Months
{
get
{
return this._months;
}
}
#endregion
#region Total parts
public Int64 TotalTicks
{
get
{
return this._ticks + this._days * TimeSpan.TicksPerDay + this._months * TICKS_PER_MONTH;
}
}
public Double TotalMicroseconds
{
get
{
return this.TotalTicks / ( (Double) TICKS_PER_MICROSECOND );
}
}
public Double TotalMilliseconds
{
get
{
return this.TotalTicks / ( (Double) TimeSpan.TicksPerMillisecond );
}
}
public Double TotalSeconds
{
get
{
return this.TotalTicks / ( (Double) TimeSpan.TicksPerSecond );
}
}
public Double TotalMinutes
{
get
{
return this.TotalTicks / ( (Double) TimeSpan.TicksPerMinute );
}
}
public Double TotalHours
{
get
{
return this.TotalTicks / ( (Double) TimeSpan.TicksPerHour );
}
}
public Double TotalDays
{
get
{
return this.TotalTicks / ( (Double) TimeSpan.TicksPerDay );
}
}
public Double TotalMonths
{
get
{
return this.TotalTicks / ( (Double) TICKS_PER_MONTH );
}
}
#endregion
#region Justification
public PgSQLInterval JustifyDays()
{
return new PgSQLInterval( this._months, this._days + (Int32) ( this._ticks / TimeSpan.TicksPerDay ), this._ticks % TimeSpan.TicksPerDay );
}
public PgSQLInterval UnjustifyDays()
{
return new PgSQLInterval( this._months, 0, this._ticks + this._days * TimeSpan.TicksPerDay );
}
public PgSQLInterval JustifyMonths()
{
return new PgSQLInterval( this._months + this._days / DAYS_PER_MONTH, this._days % DAYS_PER_MONTH, this._ticks );
}
public PgSQLInterval UnjustifyMonths()
{
return new PgSQLInterval( 0, this._days + this._months * DAYS_PER_MONTH, this._ticks );
}
public PgSQLInterval JustifyInterval()
{
return this.JustifyMonths().JustifyDays();
}
public PgSQLInterval UnjustifyInterval()
{
return new PgSQLInterval( 0, 0, this._ticks + this._days * TimeSpan.TicksPerDay + this._months * TICKS_PER_MONTH );
}
public PgSQLInterval Canonicalize()
{
return new PgSQLInterval( 0, this._days + this._months * DAYS_PER_MONTH + (Int32) ( this._ticks / TimeSpan.TicksPerDay ), this._ticks % TimeSpan.TicksPerDay );
}
#endregion
#region Arithmetic
public PgSQLInterval Add( PgSQLInterval another )
{
return new PgSQLInterval( this._months + another._months, this._days + another._days, this._ticks + another._ticks );
}
public PgSQLInterval Subtract( PgSQLInterval another )
{
return new PgSQLInterval( this._months - another._months, this._days - another._days, this._ticks - another._ticks );
}
public PgSQLInterval Negate()
{
return new PgSQLInterval( -this._months, -this._days, -this._ticks );
}
public PgSQLInterval Duration()
{
return this.UnjustifyInterval().Ticks < 0 ? this.Negate() : this;
}
#endregion
#region Comparison
public Int32 CompareTo( PgSQLInterval other )
{
return this.UnjustifyInterval().Ticks.CompareTo( other.UnjustifyInterval().Ticks );
}
Int32 IComparable.CompareTo( Object obj )
{
if ( obj == null )
{
// This is always 'greater' than null
return 1;
}
else if ( obj is PgSQLInterval )
{
return this.CompareTo( (PgSQLInterval) obj );
}
else
{
throw new ArgumentException( "Given object must be of type " + this.GetType() + " or null." );
}
}
public Boolean Equals( PgSQLInterval other )
{
return this._ticks == other._ticks && this._days == other._days && this._months == other._months;
}
public override Boolean Equals( Object obj )
{
return obj != null && obj is PgSQLInterval && this.Equals( (PgSQLInterval) obj );
}
public override Int32 GetHashCode()
{
return this.UnjustifyInterval().Ticks.GetHashCode();
}
#endregion
#region Casts
public static implicit operator TimeSpan( PgSQLInterval x )
{
return new TimeSpan( x._ticks + x._days * TimeSpan.TicksPerDay + x._months * TICKS_PER_MONTH );
}
public static implicit operator PgSQLInterval( TimeSpan x )
{
return new PgSQLInterval( x ).Canonicalize();
}
#endregion
#region Creation from parts
public static PgSQLInterval FromTicks( Int64 ticks )
{
return new PgSQLInterval( ticks ).Canonicalize();
}
public static PgSQLInterval FromMicroseconds( Double microseconds )
{
return FromTicks( (Int64) ( microseconds * ( TimeSpan.TicksPerMillisecond / 1000 ) ) );
}
public static PgSQLInterval FromMilliseconds( Double milliseconds )
{
return FromTicks( (Int64) ( milliseconds * TimeSpan.TicksPerMillisecond ) );
}
public static PgSQLInterval FromSeconds( Double seconds )
{
return FromTicks( (Int64) ( seconds * TimeSpan.TicksPerSecond ) );
}
public static PgSQLInterval FromMinutes( Double minutes )
{
return FromTicks( (Int64) ( minutes * TimeSpan.TicksPerMinute ) );
}
public static PgSQLInterval FromHours( Double hours )
{
return FromTicks( (Int64) ( hours * TimeSpan.TicksPerHour ) );
}
public static PgSQLInterval FromDays( Double days )
{
return FromTicks( (Int64) ( days * TimeSpan.TicksPerDay ) );
}
public static PgSQLInterval FromMonths( Double months )
{
return FromTicks( (Int64) ( months * TICKS_PER_MONTH ) );
}
#endregion
#region Operators
public static PgSQLInterval operator +( PgSQLInterval x, PgSQLInterval y )
{
return x.Add( y );
}
public static PgSQLInterval operator -( PgSQLInterval x, PgSQLInterval y )
{
return x.Subtract( y );
}
public static Boolean operator ==( PgSQLInterval x, PgSQLInterval y )
{
return x.Equals( y );
}
public static Boolean operator !=( PgSQLInterval x, PgSQLInterval y )
{
return !( x == y );
}
public static Boolean operator <( PgSQLInterval x, PgSQLInterval y )
{
return x.UnjustifyInterval().Ticks < y.UnjustifyInterval().Ticks;
}
public static Boolean operator <=( PgSQLInterval x, PgSQLInterval y )
{
return x.UnjustifyInterval().Ticks <= y.UnjustifyInterval().Ticks;
}
public static Boolean operator >( PgSQLInterval x, PgSQLInterval y )
{
return !( x <= y );
}
public static Boolean operator >=( PgSQLInterval x, PgSQLInterval y )
{
return !( x < y );
}
public static PgSQLInterval operator +( PgSQLInterval x )
{
return x;
}
public static PgSQLInterval operator -( PgSQLInterval x )
{
return x.Negate();
}
#endregion
#region To and from string
public override String ToString()
{
var sb = new StringBuilder();
// Months
if ( this._months != 0 )
{
sb.Append( this._months ).Append( Math.Abs( this._months ) == 1 ? " mon " : " mons " );
}
// Days
if ( this._days != 0 )
{
if ( this._months < 0 && this._days > 0 )
{
sb.Append( '+' );
}
sb.Append( this._days ).Append( Math.Abs( this._days ) == 1 ? " day " : " days " );
}
// The rest
if ( this._ticks != 0 || sb.Length == 0 )
{
// The sign
if ( this._ticks < 0 )
{
sb.Append( '-' );
}
else if ( this._days < 0 || ( this._days == 0 && this._months < 0 ) )
{
sb.Append( '+' );
}
AppendTimeInformation( sb, this._ticks );
}
return sb.ToString( 0, sb[sb.Length - 1] == ' ' ? ( sb.Length - 1 ) : sb.Length );
}
public static PgSQLInterval Parse( String str )
{
PgSQLInterval result; Exception error;
TryParse( str, out result, out error );
if ( error != null )
{
throw error;
}
return result;
}
public static Boolean TryParse( String str, out PgSQLInterval result )
{
Exception error;
TryParse( str, out result, out error );
return error == null;
}
private static void TryParse( String str, out PgSQLInterval result, out Exception error )
{
if ( str == null )
{
result = default( PgSQLInterval );
error = new ArgumentNullException( "String" );
}
else
{
// Easymode for plurals
str = str.Replace( 's', ' ' );
error = null;
// Initialize variables
var years = 0;
var months = 0;
var days = 0;
var ticks = 0L;
// Years
var idx = str.IndexOf( "year" );
var start = 0;
if ( idx > 0 && !Int32.TryParse( str.Substring( start, idx - start ), out years ) )
{
error = new FormatException( "Years were in invalid format." );
}
UpdateStartIndex( str, idx, ref start, 5 );
// Months
if ( error == null )
{
idx = str.IndexOf( "mon", start );
if ( idx > 0 && !Int32.TryParse( str.Substring( start, idx - start ), out months ) )
{
error = new FormatException( "Months were in invalid format." );
}
UpdateStartIndex( str, idx, ref start, 4 );
}
// Days
if ( error == null )
{
idx = str.IndexOf( "day", start );
if ( idx > 0 && !Int32.TryParse( str.Substring( start, idx - start ), out days ) )
{
error = new FormatException( "Days were in invalid format." );
}
UpdateStartIndex( str, idx, ref start, 4 );
}
// Time
if ( error == null )
{
Int32 hours, minutes; Decimal seconds; Boolean isNegative;
ParseTime( str, start, out hours, out minutes, out seconds, out isNegative, ref error, false );
if ( error == null )
{
try
{
ticks = hours * TimeSpan.TicksPerHour + minutes * TimeSpan.TicksPerMinute + (Int64) ( seconds * TimeSpan.TicksPerSecond );
}
catch ( Exception exc )
{
// E.g. overflow exception
error = new FormatException( "Error when calculating ticks, ", exc );
}
}
}
result = error == null ?
new PgSQLInterval( years * MONTHS_PER_YEAR + months, days, ticks ) :
default( PgSQLInterval );
}
}
private static void UpdateStartIndex( String str, Int32 idx, ref Int32 startIdx, Int32 addition )
{
if ( idx >= 0 )
{
startIdx = ( idx + addition ) >= str.Length ? str.Length : ( idx + addition );
}
}
internal static void ParseTime( String str, Int32 start, out Int32 hours, out Int32 minutes, out Decimal seconds, out Boolean isNegative, ref Exception error, Boolean timeIsMandatory )
{
hours = 0;
minutes = 0;
seconds = 0m;
var seenOtherThanWhitespace = false;
isNegative = false;
var curState = 0; // 0 - hours, 1 - minutes, 2 - seconds
var idx = start;
var len = str.Length;
while ( idx < len && error == null )
{
var c = str[idx];
if ( !Char.IsWhiteSpace( c ) )
{
if ( c == '-' )
{
if ( seenOtherThanWhitespace || isNegative )
{
error = new FormatException( "Unexpected minus sign." );
}
else
{
isNegative = true;
}
}
else if ( c == ':' || idx == len - 1 )
{
var timeStr = str.Substring( start, idx - start + ( c == ':' ? 0 : 1 ) );
switch ( curState )
{
case 0: // Hours
if ( !Int32.TryParse( timeStr, out hours ) )
{
error = new FormatException( "Malformed hours." );
}
break;
case 1: // Minutes
if ( !Int32.TryParse( timeStr, out minutes ) )
{
error = new FormatException( "Malformed minutes." );
}
break;
case 2: // Seconds
if ( !Decimal.TryParse( timeStr, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out seconds ) )
{
error = new FormatException( "Malformed seconds." );
}
break;
}
++curState;
start = idx + 1;
}
seenOtherThanWhitespace = true;
}
++idx;
}
if ( curState == 0 && timeIsMandatory )
{
error = new FormatException( "Missing time information." );
}
if ( isNegative )
{
minutes = -minutes;
seconds = -seconds;
}
}
#endregion
}
//public interface IPgSQLDate
//{
// #region Properties
// Int32 DayOfYear { get; }
// Int32 Year { get; }
// Int32 Month { get; }
// Int32 Day { get; }
// DayOfWeek DayOfWeek { get; }
// Int32 DaysSinceEra { get; }
// Boolean IsLeapYear { get; }
// #endregion
//}
public struct PgSQLDate : IEquatable<PgSQLDate>, IComparable, IComparable<PgSQLDate>//, IPgSQLDate
{
#region Consts
public const Int32 MAX_YEAR = 5874897; // As per PostgreSQL documentation
public const Int32 MIN_YEAR = -4714; // As per PostgreSQL documentation
private const Int32 DAYS_IN_YEAR = 365; //Common years
private const Int32 DAYS_IN_4YEARS = 4 * DAYS_IN_YEAR + 1; //Leap year every 4 years.
private const Int32 DAYS_IN_CENTURY = 25 * DAYS_IN_4YEARS - 1; //Except no leap year every 100.
private const Int32 DAYS_IN_4CENTURIES = 4 * DAYS_IN_CENTURY + 1; //Except leap year every 400.
internal const String INFINITY = "infinity";
internal const String MINUS_INFINITY = "-" + INFINITY;
#endregion
#region Static
// Cumulative days in non-leap years
private static readonly Int32[] CommonYearDays = new Int32[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
// Cumulative days in leap years
private static readonly Int32[] LeapYearDays = new Int32[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
// Amount of days in non-leap year months
private static readonly Int32[] CommonYearMaxes = new Int32[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// Amount of days in leap year months
private static readonly Int32[] LeapYearMaxes = new Int32[] { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
private static Boolean IsLeap( Int32 year )
{
//Every 4 years is a leap year
//Except every 100 years isn't a leap year.
//Except every 400 years is.
// Also: http://support.microsoft.com/kb/214019 (doesn't cover 0 and negative years)
if ( year < 1 )
{
++year;
}
return ( year % 4 == 0 ) && ( ( year % 100 != 0 ) || ( year % 400 == 0 ) );
}
private static Int32 DaysForYears( Int32 years )
{
//Number of years after 1CE (0 for 1CE, -1 for 1BCE, 1 for 2CE).
if ( years >= 1 )
{
--years;
}
return years / 400 * DAYS_IN_4CENTURIES //Blocks of 400 years with their leap and common years
+ years % 400 / 100 * DAYS_IN_CENTURY //Remaining blocks of 100 years with their leap and common years
+ years % 100 / 4 * DAYS_IN_4YEARS //Remaining blocks of 4 years with their leap and common years
+ years % 4 * DAYS_IN_YEAR //Remaining years, all common
+ ( years < 0 ? -1 : 0 ); //And 1BCE is leap.
}
private static Int32 ComponentsToDays( Int32 year, Int32 month, Int32 day )
{
if ( year == 0 || year < MIN_YEAR || year > MAX_YEAR )
{
throw new ArgumentOutOfRangeException( "Year" );
}
else if ( month < 1 || month > 12 )
{
throw new ArgumentOutOfRangeException( "Month" );
}
else
{
var isLeap = IsLeap( year );
if ( day < 1 || day > ( isLeap ? 366 : 365 ) )
{
throw new ArgumentOutOfRangeException( "Day" );
}
else
{
return DaysForYears( year ) + ( isLeap ? LeapYearDays : CommonYearDays )[month - 1] + day - 1;
}
}
}
public static readonly PgSQLDate Epoch = new PgSQLDate( 1970, 1, 1 );
public static readonly PgSQLDate MaxValue = new PgSQLDate( MAX_YEAR, 12, 31 );
public static readonly PgSQLDate MinValue = new PgSQLDate( MIN_YEAR, 11, 24 );
public static readonly PgSQLDate Era = new PgSQLDate( 0 );
public static readonly PgSQLDate Infinity = new PgSQLDate( DateTime.MaxValue );
public static readonly PgSQLDate MinusInfinity = new PgSQLDate( DateTime.MinValue );
public static PgSQLDate Now
{
get
{
return new PgSQLDate( DateTime.Now );
}
}
public static PgSQLDate Today
{
get
{
return Now;
}
}
public static PgSQLDate Yesterday
{
get
{
return Now.AddDays( -1 );
}
}
public static PgSQLDate Tomorrow
{
get
{
return Now.AddDays( 1 );
}
}
#endregion
#region Fields
private readonly Int32 _days;
#endregion
#region Constructors
public PgSQLDate( Int32 daysSinceEra )
{
this._days = daysSinceEra;
}
public PgSQLDate( PgSQLDate other )
: this( other._days )
{
}
public PgSQLDate( DateTime datetime )
: this( (Int32) ( datetime.Ticks / TimeSpan.TicksPerDay ) )
{
}
public PgSQLDate( Int32 year, Int32 month, Int32 day )
: this( ComponentsToDays( year, month, day ) )
{
}
#endregion
#region Properties
public Int32 DayOfYear
{
get
{
return this._days - DaysForYears( this.Year ) + 1;
}
}
public Int32 Year
{
get
{
var start = ( (Int32) Math.Round( this._days / 365.2425 ) ) - 1;
while ( DaysForYears( ++start ) <= this._days ) ;
return start - 1;
}
}
public Int32 Month
{
get
{
var max = this.DayOfYear;
var array = this.IsLeapYear ? LeapYearDays : CommonYearDays;
var i = 1;
while ( max > array[i] )
{
++i;
}
return i;
}
}
public Int32 Day
{
get
{
return this.DayOfYear - ( this.IsLeapYear ? LeapYearDays : CommonYearDays )[this.Month - 1];
}
}
public DayOfWeek DayOfWeek
{
get
{
return (DayOfWeek) ( ( this._days + 1 ) % 7 );
}
}
public Int32 DaysSinceEra
{
get
{
return this._days;
}
}
public Boolean IsLeapYear
{
get
{
return IsLeap( this.Year );
}
}
#endregion
#region Arithmetics
public PgSQLDate AddDays( Int32 days )
{
return new PgSQLDate( this._days + days );
}
public PgSQLDate AddMonths( Int32 months )
{
var newYear = this.Year;
var newMonth = this.Month + months;
while ( newMonth > 12 )
{
newMonth -= 12;
++newYear;
if ( newYear == 0 )
{
++newYear; // No 'zero'eth year.