+func (obj *OTS_TimeSeries) AddDataPoint (timestamp, rate float64) int {
+ if math.IsNaN (timestamp) || (timestamp < 0.0) {
+ return -1
+ }
+
+ /* Handle the usual case first. */
+ if (timestamp > obj.TimestampLast ()) || (obj.DataPoints == nil) {
+ obj.DataPoints = append (obj.DataPoints, OTS_DataPoint{timestamp, rate})
+ return 0
+ }
+
+ /* Find the first index where the timestamp is greater than or equal to the
+ * new timestamp. This is an O(log n) operation. */
+ index := sort.Search (len (obj.DataPoints), func (i int) bool {
+ if obj.DataPoints[i].TimeStamp >= timestamp {
+ return true
+ }
+ return false
+ })
+
+ /* Check for a duplicate time. */
+ if obj.DataPoints[index].TimeStamp == timestamp {
+ obj.DataPoints[index].Rate = rate
+ return 0
+ }
+
+ /* Insert the new datapoint at "index". Currently, this is a O(n) operation.
+ * First, add the new datapoint at the end. */
+ obj.DataPoints = append (obj.DataPoints, OTS_DataPoint{timestamp, rate})
+ /* Now move the datapoint to the position "index". */
+ for i := len (obj.DataPoints) - 2; i >= index; i-- {
+ /* TODO: Is there a faster way to manipulate arrays in Go than to move
+ * elements in bubblesort fashion? */
+ obj.Swap (i, i + 1)
+ }
+
+ return 0
+}
+