dt_status_t dt_offset_between()

in src/dt.c [141:183]


dt_status_t dt_offset_between(const dt_timestamp_t *lhs, const dt_timestamp_t *rhs, dt_offset_t *result)
{
    dt_compare_result_t cr = DT_EQUALS;
    const dt_timestamp_t *lower_timestamp = NULL;
    const dt_timestamp_t *higher_timestamp = NULL;
    dt_bool_t is_forward = DT_FALSE;
    unsigned long seconds = 0;
    long nano_seconds = 0;
    dt_status_t s = DT_UNKNOWN_ERROR;


    if (dt_validate_timestamp(lhs) != DT_TRUE || dt_validate_timestamp(rhs) != DT_TRUE || !result) {
        return DT_INVALID_ARGUMENT;
    }

    s = dt_compare_timestamps(lhs, rhs, &cr);
    if (s != DT_OK) {
        return s;
    }
    lower_timestamp = cr < 0 ? lhs : rhs;
    higher_timestamp = cr < 0 ? rhs : lhs;
    seconds = higher_timestamp->second - lower_timestamp->second;
    nano_seconds = (long) higher_timestamp->nano_second - (long) lower_timestamp->nano_second;
    is_forward = cr < 0 ? DT_TRUE : DT_FALSE;


    if (cr == DT_EQUALS) {
        // Equal timestamps case
        result->duration.seconds = 0L;
        result->duration.nano_seconds = 0L;
        result->is_forward = DT_TRUE;
        return DT_OK;
    }

    if (nano_seconds < 0L) {
        seconds -= 1L;
        nano_seconds += 1000000000UL;
    }
    result->duration.seconds = seconds;
    result->duration.nano_seconds = nano_seconds;
    result->is_forward = is_forward;
    return DT_OK;
}