#include "config.h"
#include "TimeRanges.h"
#include <math.h>
using namespace WebCore;
TimeRanges::TimeRanges(float start, float end)
{
add(start, end);
}
PassRefPtr<TimeRanges> TimeRanges::copy()
{
RefPtr<TimeRanges> newSession = TimeRanges::create();
unsigned size = m_ranges.size();
for (unsigned i = 0; i < size; i++)
newSession->add(m_ranges[i].m_start, m_ranges[i].m_end);
return newSession.release();
}
float TimeRanges::start(unsigned index, ExceptionCode& ec) const
{
if (index >= length()) {
ec = INDEX_SIZE_ERR;
return 0;
}
return m_ranges[index].m_start;
}
float TimeRanges::end(unsigned index, ExceptionCode& ec) const
{
if (index >= length()) {
ec = INDEX_SIZE_ERR;
return 0;
}
return m_ranges[index].m_end;
}
void TimeRanges::add(float start, float end)
{
ASSERT(start <= end);
unsigned int overlappingArcIndex;
Range addedRange(start, end);
for (overlappingArcIndex = 0; overlappingArcIndex < m_ranges.size(); overlappingArcIndex++) {
if (addedRange.isOverlappingRange(m_ranges[overlappingArcIndex])
|| addedRange.isContiguousWithRange(m_ranges[overlappingArcIndex])) {
addedRange = addedRange.unionWithOverlappingOrContiguousRange(m_ranges[overlappingArcIndex]);
m_ranges.remove(overlappingArcIndex);
overlappingArcIndex--;
} else {
if (!overlappingArcIndex) {
if (addedRange.isBeforeRange(m_ranges[0])) {
break;
}
} else {
if (m_ranges[overlappingArcIndex - 1].isBeforeRange(addedRange)
&& addedRange.isBeforeRange(m_ranges[overlappingArcIndex])) {
break;
}
}
}
}
m_ranges.insert(overlappingArcIndex, addedRange);
}
bool TimeRanges::contain(float time) const
{
ExceptionCode unused;
for (unsigned n = 0; n < length(); n++) {
if (time >= start(n, unused) && time <= end(n, unused))
return true;
}
return false;
}
float TimeRanges::nearest(float time) const
{
ExceptionCode unused;
float closest = 0;
unsigned count = length();
for (unsigned ndx = 0; ndx < count; ndx++) {
float startTime = start(ndx, unused);
float endTime = end(ndx, unused);
if (time >= startTime && time <= endTime)
return time;
if (fabs(startTime - time) < closest)
closest = fabsf(startTime - time);
else if (fabs(endTime - time) < closest)
closest = fabsf(endTime - time);
}
return closest;
}