1
- // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
1
+ // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2
2
// file at the top-level directory of this distribution and at
3
3
// http://rust-lang.org/COPYRIGHT.
4
4
//
@@ -90,6 +90,30 @@ impl Timespec {
90
90
}
91
91
}
92
92
93
+ impl Add < Timespec , Timespec > for Timespec {
94
+ fn add ( & self , other : & Timespec ) -> Timespec {
95
+ let mut sec = self . sec + other. sec ;
96
+ let mut nsec = self . nsec + other. nsec ;
97
+ if nsec >= NSEC_PER_SEC {
98
+ nsec -= NSEC_PER_SEC ;
99
+ sec += 1 ;
100
+ }
101
+ Timespec :: new ( sec, nsec)
102
+ }
103
+ }
104
+
105
+ impl Sub < Timespec , Timespec > for Timespec {
106
+ fn sub ( & self , other : & Timespec ) -> Timespec {
107
+ let mut sec = self . sec - other. sec ;
108
+ let mut nsec = self . nsec - other. nsec ;
109
+ if nsec < 0 {
110
+ nsec += NSEC_PER_SEC ;
111
+ sec -= 1 ;
112
+ }
113
+ Timespec :: new ( sec, nsec)
114
+ }
115
+ }
116
+
93
117
/**
94
118
* Returns the current time as a `timespec` containing the seconds and
95
119
* nanoseconds since 1970-01-01T00:00:00Z.
@@ -1489,6 +1513,46 @@ mod tests {
1489
1513
assert ! ( d. gt( c) ) ;
1490
1514
}
1491
1515
1516
+ fn test_timespec_add ( ) {
1517
+ let a = Timespec :: new ( 1 , 2 ) ;
1518
+ let b = Timespec :: new ( 2 , 3 ) ;
1519
+ let c = a + b;
1520
+ assert_eq ! ( c. sec, 3 ) ;
1521
+ assert_eq ! ( c. nsec, 5 ) ;
1522
+
1523
+ let p = Timespec :: new ( 1 , super :: NSEC_PER_SEC - 2 ) ;
1524
+ let q = Timespec :: new ( 2 , 2 ) ;
1525
+ let r = p + q;
1526
+ assert_eq ! ( r. sec, 4 ) ;
1527
+ assert_eq ! ( r. nsec, 0 ) ;
1528
+
1529
+ let u = Timespec :: new ( 1 , super :: NSEC_PER_SEC - 2 ) ;
1530
+ let v = Timespec :: new ( 2 , 3 ) ;
1531
+ let w = u + v;
1532
+ assert_eq ! ( w. sec, 4 ) ;
1533
+ assert_eq ! ( w. nsec, 1 ) ;
1534
+ }
1535
+
1536
+ fn test_timespec_sub ( ) {
1537
+ let a = Timespec :: new ( 2 , 3 ) ;
1538
+ let b = Timespec :: new ( 1 , 2 ) ;
1539
+ let c = a - b;
1540
+ assert_eq ! ( c. sec, 1 ) ;
1541
+ assert_eq ! ( c. nsec, 1 ) ;
1542
+
1543
+ let p = Timespec :: new ( 2 , 0 ) ;
1544
+ let q = Timespec :: new ( 1 , 2 ) ;
1545
+ let r = p - q;
1546
+ assert_eq ! ( r. sec, 0 ) ;
1547
+ assert_eq ! ( r. nsec, super :: NSEC_PER_SEC - 2 ) ;
1548
+
1549
+ let u = Timespec :: new ( 1 , 2 ) ;
1550
+ let v = Timespec :: new ( 2 , 3 ) ;
1551
+ let w = u - v;
1552
+ assert_eq ! ( w. sec, -2 ) ;
1553
+ assert_eq ! ( w. nsec, super :: NSEC_PER_SEC - 1 ) ;
1554
+ }
1555
+
1492
1556
#[ test]
1493
1557
#[ ignore( cfg( target_os = "android" ) ) ] // FIXME #10958
1494
1558
fn run_tests ( ) {
@@ -1505,6 +1569,8 @@ mod tests {
1505
1569
test_ctime ( ) ;
1506
1570
test_strftime ( ) ;
1507
1571
test_timespec_eq_ord ( ) ;
1572
+ test_timespec_add ( ) ;
1573
+ test_timespec_sub ( ) ;
1508
1574
}
1509
1575
1510
1576
#[ bench]
0 commit comments