Beispiel #1
0
PRMJ_ToExtendedTime(PRInt32 time)
{
    PRInt64 exttime;
    PRInt64 g1970GMTMicroSeconds;
    PRInt64 low;
    time_t diff;
    PRInt64  tmp;
    PRInt64  tmp1;

    diff = PRMJ_LocalGMTDifference();
    LL_UI2L(tmp, PRMJ_USEC_PER_SEC);
    LL_I2L(tmp1,diff);
    LL_MUL(tmp,tmp,tmp1);

    LL_UI2L(g1970GMTMicroSeconds,G1970GMTMICROHI);
    LL_UI2L(low,G1970GMTMICROLOW);
#ifndef HAVE_LONG_LONG
    LL_SHL(g1970GMTMicroSeconds,g1970GMTMicroSeconds,16);
    LL_SHL(g1970GMTMicroSeconds,g1970GMTMicroSeconds,16);
#else
    LL_SHL(g1970GMTMicroSeconds,g1970GMTMicroSeconds,32);
#endif
    LL_ADD(g1970GMTMicroSeconds,g1970GMTMicroSeconds,low);

    LL_I2L(exttime,time);
    LL_ADD(exttime,exttime,g1970GMTMicroSeconds);
    LL_SUB(exttime,exttime,tmp);
    return exttime;
}
Beispiel #2
0
int workqueue_init(workqueue_t *workqueue, int numWorkers) {
    int i;
    worker_t *worker;
    pthread_cond_t blank_cond = PTHREAD_COND_INITIALIZER;
    pthread_mutex_t blank_mutex = PTHREAD_MUTEX_INITIALIZER;

    if (numWorkers < 1) numWorkers = 1;
    memset(workqueue, 0, sizeof(*workqueue));
    memcpy(&workqueue->jobs_mutex, &blank_mutex,
           sizeof(workqueue->jobs_mutex));
    memcpy(&workqueue->jobs_cond, &blank_cond, sizeof(workqueue->jobs_cond));

    for (i = 0; i < numWorkers; i++) {
        if ((worker = (worker_t*)malloc(sizeof(worker_t))) == NULL) {
            perror("Failed to allocate all workers");
            return 1;
        }
        memset(worker, 0, sizeof(*worker));
        worker->workqueue = workqueue;
        if (pthread_create(&worker->thread, NULL, worker_function,
                           (void *)worker)) {
            perror("Failed to start all worker threads");
            free(worker);
            return 1;
        }
        LL_ADD(worker, worker->workqueue->workers);
    }

    return 0;
}
Beispiel #3
0
static void deadlines_update(iocpdesc_t *iocpd, pn_timestamp_t deadline)
{
  if (deadline == iocpd->deadline)
    return;

  iocpd->deadline = deadline;
  pn_selector_t *selector = iocpd->selector;
  if (!deadline) {
    deadlines_remove(selector, iocpd);
    pni_events_update(iocpd, iocpd->events & ~PN_EXPIRED);
  } else {
    if (iocpd->deadlines_prev || selector->deadlines_head == iocpd) {
      deadlines_remove(selector, iocpd);
      pni_events_update(iocpd, iocpd->events & ~PN_EXPIRED);
    }
    iocpdesc_t *dl_iocpd = LL_HEAD(selector, deadlines);
    while (dl_iocpd && dl_iocpd->deadline <= deadline)
      dl_iocpd = dl_iocpd->deadlines_next;
    if (dl_iocpd) {
      // insert
      iocpd->deadlines_prev = dl_iocpd->deadlines_prev;
      iocpd->deadlines_next = dl_iocpd;
      dl_iocpd->deadlines_prev = iocpd;
      if (selector->deadlines_head == dl_iocpd)
        selector->deadlines_head = iocpd;
    } else {
      LL_ADD(selector, deadlines, iocpd);  // append
    }
  }
}
Beispiel #4
0
void workqueue_add_job(workqueue_t *workqueue, job_t *job) {
    /* Add the job to the job queue, and notify a worker. */
    pthread_mutex_lock(&workqueue->jobs_mutex);
    LL_ADD(job, workqueue->waiting_jobs);
    pthread_cond_signal(&workqueue->jobs_cond);
    pthread_mutex_unlock(&workqueue->jobs_mutex);
}
Beispiel #5
0
PRTime
rdf_ParseDate(const nsACString &aTime)
{
    PRTime t;
    PR_ParseTimeString(PromiseFlatCString(aTime).get(), PR_TRUE, &t);

    PRInt32 usec = 0;

    nsACString::const_iterator begin, digit, end;
    aTime.BeginReading(begin);
    aTime.EndReading(end);

    // Walk backwards until we find a `+', run out of string, or a
    // non-numeric character.
    digit = end;
    while (--digit != begin && *digit != '+') {
        if (*digit < '0' || *digit > '9')
            break;
    }

    if (digit != begin && *digit == '+') {
        // There's a usec field specified (or, at least, something
        // that looks close enough. Parse it, and add it to the time.
        while (++digit != end) {
            usec *= 10;
            usec += *digit - '0';
        }

        PRTime temp;
        LL_I2L(temp, usec);
        LL_ADD(t, t, temp);
    }

    return t;
}
Beispiel #6
0
/*
 * PR_Now() on the Mac only gives us a resolution of seconds.  Using
 * PR_IntervalNow() gives us better resolution. with the drawback that 
 * the timeline is only good for about six hours.
 *
 * PR_IntervalNow() occasionally exhibits discontinuities on Windows,
 * so we only use it on the Mac.  Bleah!
 */
static PRTime Now(void)
{
    PRIntervalTime numTicks = PR_IntervalNow() - initInterval;
    PRTime now;
    LL_ADD(now, initTime, PR_IntervalToMilliseconds(numTicks) * 1000);
    return now;
}
Beispiel #7
0
void addVariance(VarianceState* inVariance, unsigned inValue)
/*
**  Add a value to a variance state.
*/
{
    PRUint64 squared;
    PRUint64 bigValue;
    
    LL_UI2L(bigValue, inValue);

    LL_ADD(inVariance->mSum, inVariance->mSum, bigValue);

    LL_MUL(squared, bigValue, bigValue);
    LL_ADD(inVariance->mSquaredSum, inVariance->mSquaredSum, squared);

    inVariance->mCount++;
}
Beispiel #8
0
void nsTimelineServiceTimer::stop(PRTime now)
{
    TIMER_CHECK_OWNER();
    mRunning--;
    if (mRunning == 0) {
        PRTime delta, accum;
        LL_SUB(delta, now, mStart);
        LL_ADD(accum, mAccum, delta);
        mAccum = accum;
    }
}
Beispiel #9
0
static PRUint64
RubyTo64BitInt(VALUE aRuby)
{
    VALUE bitMask = max_PRUint32;
    VALUE lo = rb_funcall(aRuby, id_and, 1, bitMask);
    VALUE hi = rb_funcall(aRuby, id_rshift, 1, INT2FIX(32));
    PRUint64 result, hi64, lo64;
    LL_UI2L(hi64, NUM2UINT(hi));
    LL_UI2L(lo64, NUM2UINT(lo));
    LL_SHL(result, hi64, 32);
    LL_ADD(result, result, lo64);
    return result;
}
PRInt64 StatsManagerUtil::getSeconds(PRInt64 time)
{
    PRInt64 temp = 0;
    PRInt64 dividend = 0;
    PRInt64 divisor = 0;

    LL_UI2L(temp, PR_USEC_PER_SEC/2);
    LL_ADD(dividend, time, temp);
    LL_UI2L(divisor, PR_USEC_PER_SEC);
    LL_DIV(temp, dividend, divisor);

    return temp;
}
Beispiel #11
0
PRMJ_ToBaseTime(PRInt64 time)
{
    PRInt64 g1970GMTMicroSeconds;
    PRInt64 g2037GMTMicroSeconds;
    PRInt64 low;
    PRInt32 result;

    LL_UI2L(g1970GMTMicroSeconds,G1970GMTMICROHI);
    LL_UI2L(low,G1970GMTMICROLOW);
#ifndef HAVE_LONG_LONG
    LL_SHL(g1970GMTMicroSeconds,g1970GMTMicroSeconds,16);
    LL_SHL(g1970GMTMicroSeconds,g1970GMTMicroSeconds,16);
#else
    LL_SHL(g1970GMTMicroSeconds,g1970GMTMicroSeconds,32);
#endif
    LL_ADD(g1970GMTMicroSeconds,g1970GMTMicroSeconds,low);

    LL_UI2L(g2037GMTMicroSeconds,G2037GMTMICROHI);
    LL_UI2L(low,G2037GMTMICROLOW);
#ifndef HAVE_LONG_LONG
    LL_SHL(g2037GMTMicroSeconds,g2037GMTMicroSeconds,16);
    LL_SHL(g2037GMTMicroSeconds,g2037GMTMicroSeconds,16);
#else
    LL_SHL(g2037GMTMicroSeconds,g2037GMTMicroSeconds,32);
#endif

    LL_ADD(g2037GMTMicroSeconds,g2037GMTMicroSeconds,low);


    if(LL_CMP(time, <, g1970GMTMicroSeconds) ||
       LL_CMP(time, >, g2037GMTMicroSeconds)){
	return -1;
    }

    LL_SUB(time,time,g1970GMTMicroSeconds);
    LL_L2I(result,time);
    return result;
}
Beispiel #12
0
PRTime nsTimelineServiceTimer::getAccum(PRTime now)
{
    TIMER_CHECK_OWNER();
    PRTime accum;

    if (!mRunning) {
        accum = mAccum;
    } else {
        PRTime delta;
        LL_SUB(delta, now, mStart);
        LL_ADD(accum, mAccum, delta);
    }
    return accum;
}
Beispiel #13
0
pni_entry_t *pni_store_put(pni_store_t *store, const char *address)
{
  assert(store);
  static pn_class_t clazz = PN_CLASS(pni_entry);

  if (!address) address = "";
  pni_stream_t *stream = pni_stream_put(store, address);
  if (!stream) return NULL;
  pni_entry_t *entry = (pni_entry_t *) pn_new(sizeof(pni_entry_t), &clazz);
  if (!entry) return NULL;
  entry->stream = stream;
  entry->free = false;
  entry->stream_next = NULL;
  entry->stream_prev = NULL;
  entry->store_next = NULL;
  entry->store_prev = NULL;
  entry->delivery = NULL;
  entry->bytes = pn_buffer(64);
  entry->status = PN_STATUS_UNKNOWN;
  LL_ADD(stream, stream, entry);
  LL_ADD(store, store, entry);
  store->size++;
  return entry;
}
Beispiel #14
0
PR_Now(void)
{
    PRInt64 s, ms, ms2us, s2us;
    struct timeb b;

    ftime(&b);
    LL_I2L(ms2us, PR_USEC_PER_MSEC);
    LL_I2L(s2us, PR_USEC_PER_SEC);
    LL_I2L(s, b.time);
    LL_I2L(ms, b.millitm);
    LL_MUL(ms, ms, ms2us);
    LL_MUL(s, s, s2us);
    LL_ADD(s, s, ms);
    return s;       
}
Beispiel #15
0
PRStatus TimelineInit(void)
{
    char *timeStr;
    char *fileName;
    PRInt32 secs, msecs;
    PRFileDesc *fd;
    PRInt64 tmp1, tmp2;

    PRStatus status = PR_NewThreadPrivateIndex( &gTLSIndex, ThreadDestruct );
    NS_WARN_IF_FALSE(status==0, "TimelineService could not allocate TLS storage.");

    timeStr = PR_GetEnv("NS_TIMELINE_INIT_TIME");
#ifdef XP_MAC    
    initInterval = PR_IntervalNow();
#endif
    // NS_TIMELINE_INIT_TIME only makes sense for the main thread, so if it
    // exists, set it there.  If not, let normal thread management code take
    // care of setting the init time.
    if (timeStr != NULL && 2 == PR_sscanf(timeStr, "%d.%d", &secs, &msecs)) {
        PRTime &initTime = GetThisThreadData()->initTime;
        LL_MUL(tmp1, (PRInt64)secs, 1000000);
        LL_MUL(tmp2, (PRInt64)msecs, 1000);
        LL_ADD(initTime, tmp1, tmp2);
#ifdef XP_MAC
        initInterval -= PR_MicrosecondsToInterval(
            (PRUint32)(PR_Now() - initTime));
#endif
    }
    // Get the log file.
#ifdef XP_MAC
    fileName = "timeline.txt";
#else
    fileName = PR_GetEnv("NS_TIMELINE_LOG_FILE");
#endif
    if (fileName != NULL
        && (fd = PR_Open(fileName, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
                         0666)) != NULL) {
        timelineFD = fd;
        PR_fprintf(fd,
                   "NOTE: due to asynchrony, the indentation that you see does"
                   " not necessarily correspond to nesting in the code.\n\n");
    }

    // Runtime disable of timeline
    if (PR_GetEnv("NS_TIMELINE_ENABLE"))
        gTimelineDisabled = PR_FALSE;
    return PR_SUCCESS;
}
Beispiel #16
0
// This should use NSPR but NSPR isn't exporting its PR_strtoll function
// Until then...
PRInt64 nsCRT::atoll(const char *str)
{
    if (!str)
        return LL_Zero();

    PRInt64 ll = LL_Zero(), digitll = LL_Zero();

    while (*str && *str >= '0' && *str <= '9') {
        LL_MUL(ll, ll, 10);
        LL_UI2L(digitll, (*str - '0'));
        LL_ADD(ll, ll, digitll);
        str++;
    }

    return ll;
}
Beispiel #17
0
/*
 * Determine if the token is logged in. We have to actually query the token,
 * because it's state can change without intervention from us.
 */
PRBool
PK11_IsLoggedIn(PK11SlotInfo *slot,void *wincx)
{
    CK_SESSION_INFO sessionInfo;
    int askpw = slot->askpw;
    int timeout = slot->timeout;
    CK_RV crv;
    PRIntervalTime curTime;
    static PRIntervalTime login_delay_time = 0;

    if (login_delay_time == 0) {
	login_delay_time = PR_SecondsToInterval(1);
    }

    /* If we don't have our own password default values, use the system
     * ones */
    if ((slot->defaultFlags & PK11_OWN_PW_DEFAULTS) == 0) {
	PK11SlotInfo *def_slot = PK11_GetInternalKeySlot();

	if (def_slot) {
	    askpw = def_slot->askpw;
	    timeout = def_slot->timeout;
	    PK11_FreeSlot(def_slot);
	}
    }

    if ((wincx != NULL) && (PK11_Global.isLoggedIn != NULL) &&
	(*PK11_Global.isLoggedIn)(slot, wincx) == PR_FALSE) { return PR_FALSE; }


    /* forget the password if we've been inactive too long */
    if (askpw == 1) {
	int64 currtime = PR_Now();
	int64 result;
	int64 mult;
	
	LL_I2L(result, timeout);
	LL_I2L(mult, 60*1000*1000);
	LL_MUL(result,result,mult);
	LL_ADD(result, result, slot->authTime);
	if (LL_CMP(result, <, currtime) ) {
	    PK11_EnterSlotMonitor(slot);
	    PK11_GETTAB(slot)->C_Logout(slot->session);
	    slot->lastLoginCheck = 0;
	    PK11_ExitSlotMonitor(slot);
	} else {
Beispiel #18
0
PR_IMPLEMENT(PRUint64) PR_htonll(PRUint64 n)
{
#ifdef IS_BIG_ENDIAN
    return n;
#else
    PRUint64 tmp;
    PRUint32 hi, lo;
    LL_L2UI(lo, n);
    LL_SHR(tmp, n, 32);
    LL_L2UI(hi, tmp);
    hi = htonl(hi);
    lo = htonl(lo);
    LL_UI2L(n, lo);
    LL_SHL(n, n, 32);
    LL_UI2L(tmp, hi);
    LL_ADD(n, n, tmp);
    return n;
#endif
}  /* htonll */
void nsNetscapeProfileMigratorBase::CopyNextFolder()
{
  if (mFileCopyTransactionIndex < mFileCopyTransactions.Length())
  {
    PRUint32 percentage = 0;
    fileTransactionEntry fileTransaction =
      mFileCopyTransactions.ElementAt(mFileCopyTransactionIndex++);

    // copy the file
    fileTransaction.srcFile->CopyTo(fileTransaction.destFile,
                                    fileTransaction.newName);

    // add to our current progress
    PRInt64 fileSize;
    fileTransaction.srcFile->GetFileSize(&fileSize);
    LL_ADD(mCurrentProgress, mCurrentProgress, fileSize);

    PRInt64 percentDone;
    LL_MUL(percentDone, mCurrentProgress, 100);

    LL_DIV(percentDone, percentDone, mMaxProgress);

    LL_L2UI(percentage, percentDone);

    nsAutoString index;
    index.AppendInt(percentage);

    NOTIFY_OBSERVERS(MIGRATION_PROGRESS, index.get());

    // fire a timer to handle the next one.
    mFileIOTimer = do_CreateInstance("@mozilla.org/timer;1");

    if (mFileIOTimer)
      mFileIOTimer->InitWithCallback(static_cast<nsITimerCallback *>(this), percentage == 100 ? 500 : 0, nsITimer::TYPE_ONE_SHOT);
  } else
    EndCopyFolders();

  return;
}
static int start_ssl_shutdown( pn_ssl_t *ssl )
{
  if (!ssl->ssl_shutdown) {
    _log(ssl, "Shutting down SSL connection...\n");
    if (ssl->session_id) {
      // save the negotiated credentials before we close the connection
      pn_ssl_session_t *ssn = (pn_ssl_session_t *)calloc( 1, sizeof(pn_ssl_session_t));
      if (ssn) {
        ssn->id = pn_strdup( ssl->session_id );
        ssn->session = SSL_get1_session( ssl->ssl );
        if (ssn->session) {
          _log( ssl, "Saving SSL session as %s\n", ssl->session_id );
          LL_ADD( ssl->domain, ssn_cache, ssn );
        } else {
          ssl_session_free( ssn );
        }
      }
    }
    ssl->ssl_shutdown = true;
    BIO_ssl_shutdown( ssl->bio_ssl );
  }
  return 0;
}
Beispiel #21
0
NS_IMETHODIMP
InvokeTestTarget::AddTwoLLs(PRInt64 p1, PRInt64 p2, PRInt64* retval)
{
    LL_ADD(*retval, p1, p2);
    return NS_OK;
}
Beispiel #22
0
// Set rcvDate to true to get the Received: date instead of the Date: date.
nsresult nsMsgGroupView::GetAgeBucketValue(nsIMsgDBHdr *aMsgHdr, PRUint32 * aAgeBucket, bool rcvDate)
{
  NS_ENSURE_ARG_POINTER(aMsgHdr);
  NS_ENSURE_ARG_POINTER(aAgeBucket);

  PRTime dateOfMsg;
  nsresult rv;
  if (!rcvDate)
    rv = aMsgHdr->GetDate(&dateOfMsg);
  else
  {
    PRUint32 rcvDateSecs;
    rv = aMsgHdr->GetUint32Property("dateReceived", &rcvDateSecs);
    Seconds2PRTime(rcvDateSecs, &dateOfMsg);
  }
  NS_ENSURE_SUCCESS(rv, rv);

  PRTime currentTime = PR_Now();
  PRExplodedTime currentExplodedTime;
  PR_ExplodeTime(currentTime, PR_LocalTimeParameters, &currentExplodedTime);
  PRExplodedTime explodedMsgTime;
  PR_ExplodeTime(dateOfMsg, PR_LocalTimeParameters, &explodedMsgTime);

  if (m_lastCurExplodedTime.tm_mday &&
     m_lastCurExplodedTime.tm_mday != currentExplodedTime.tm_mday)
    m_dayChanged = true; // this will cause us to rebuild the view.

  m_lastCurExplodedTime = currentExplodedTime;
  if (currentExplodedTime.tm_year == explodedMsgTime.tm_year &&
      currentExplodedTime.tm_month == explodedMsgTime.tm_month &&
      currentExplodedTime.tm_mday == explodedMsgTime.tm_mday)
  {
    // same day...
    *aAgeBucket = 1;
  }
  // figure out how many days ago this msg arrived
  else if (LL_CMP(currentTime, >, dateOfMsg))
  {
    // some constants for calculation
    static PRInt64 microSecondsPerSecond;
    static PRInt64 microSecondsPerDay;
    static PRInt64 secondsPerDay;
    static PRInt64 microSecondsPer6Days;
    static PRInt64 microSecondsPer13Days;

    static bool bGotConstants = false;
    if ( !bGotConstants )
    {
      // seeds
      LL_I2L  ( microSecondsPerSecond,  PR_USEC_PER_SEC );
      LL_UI2L ( secondsPerDay,          60 * 60 * 24 );

      // derivees
      LL_MUL( microSecondsPerDay,   secondsPerDay,      microSecondsPerSecond );
      LL_MUL( microSecondsPer6Days, microSecondsPerDay, 6 );
      LL_MUL( microSecondsPer13Days, microSecondsPerDay, 13 );
      bGotConstants = true;
    }

    // setting the time variables to local time
    PRInt64 GMTLocalTimeShift;
    LL_ADD( GMTLocalTimeShift, currentExplodedTime.tm_params.tp_gmt_offset, currentExplodedTime.tm_params.tp_dst_offset );
    LL_MUL( GMTLocalTimeShift, GMTLocalTimeShift, microSecondsPerSecond );
    LL_ADD( currentTime, currentTime, GMTLocalTimeShift );
    LL_ADD( dateOfMsg, dateOfMsg, GMTLocalTimeShift );

    // the most recent midnight, counting from current time
    PRInt64 todaysMicroSeconds, mostRecentMidnight;
    LL_MOD( todaysMicroSeconds, currentTime, microSecondsPerDay );
    LL_SUB( mostRecentMidnight, currentTime, todaysMicroSeconds );
    PRInt64 yesterday;
    LL_SUB( yesterday, mostRecentMidnight, microSecondsPerDay );
    // most recent midnight minus 6 days
    PRInt64 mostRecentWeek;
    LL_SUB( mostRecentWeek, mostRecentMidnight, microSecondsPer6Days );

    // was the message sent yesterday?
    if ( LL_CMP( dateOfMsg, >=, yesterday ) ) // yes ....
      *aAgeBucket = 2;
    else if ( LL_CMP(dateOfMsg, >=, mostRecentWeek) )
      *aAgeBucket = 3;
    else
    {
nsresult nsMsgSearchAdapter::EncodeImapTerm (nsIMsgSearchTerm *term, bool reallyDredd, const PRUnichar *srcCharset, const PRUnichar *destCharset, char **ppOutTerm)
{
  NS_ENSURE_ARG_POINTER(term);
  NS_ENSURE_ARG_POINTER(ppOutTerm);

  nsresult err = NS_OK;
  bool useNot = false;
  bool useQuotes = false;
  bool ignoreValue = false;
  nsCAutoString arbitraryHeader;
  const char *whichMnemonic = nsnull;
  const char *orHeaderMnemonic = nsnull;

  *ppOutTerm = nsnull;

  nsCOMPtr <nsIMsgSearchValue> searchValue;
  nsresult rv = term->GetValue(getter_AddRefs(searchValue));

  NS_ENSURE_SUCCESS(rv,rv);

  nsMsgSearchOpValue op;
  term->GetOp(&op);

  if (op == nsMsgSearchOp::DoesntContain || op == nsMsgSearchOp::Isnt)
    useNot = true;

  nsMsgSearchAttribValue attrib;
  term->GetAttrib(&attrib);

  switch (attrib)
  {
  case nsMsgSearchAttrib::ToOrCC:
    orHeaderMnemonic = m_kImapCC;
    // fall through to case nsMsgSearchAttrib::To:
  case nsMsgSearchAttrib::To:
    whichMnemonic = m_kImapTo;
    break;
  case nsMsgSearchAttrib::CC:
    whichMnemonic = m_kImapCC;
    break;
  case nsMsgSearchAttrib::Sender:
    whichMnemonic = m_kImapFrom;
    break;
  case nsMsgSearchAttrib::Subject:
    whichMnemonic = m_kImapSubject;
    break;
  case nsMsgSearchAttrib::Body:
    whichMnemonic = m_kImapBody;
    break;
  case nsMsgSearchAttrib::AgeInDays:  // added for searching online for age in days...
    // for AgeInDays, we are actually going to perform a search by date, so convert the operations for age
    // to the IMAP mnemonics that we would use for date!
    {
      // If we have a future date, the > and < are reversed.
      // e.g. ageInDays > 2 means more than 2 days old ("date before X") whereas
      //      ageInDays > -2 should be more than 2 days in the future ("date after X")
      PRInt32 ageInDays;
      searchValue->GetAge(&ageInDays);
      bool dateInFuture = (ageInDays < 0);
      switch (op)
      {
      case nsMsgSearchOp::IsGreaterThan:
        whichMnemonic = (!dateInFuture) ? m_kImapBefore : m_kImapSince;
        break;
      case nsMsgSearchOp::IsLessThan:
        whichMnemonic = (!dateInFuture) ? m_kImapSince : m_kImapBefore;
        break;
      case nsMsgSearchOp::Is:
        whichMnemonic = m_kImapSentOn;
        break;
      default:
        NS_ASSERTION(false, "invalid search operator");
        return NS_ERROR_INVALID_ARG;
      }
    }
    break;
  case nsMsgSearchAttrib::Size:
    switch (op)
    {
    case nsMsgSearchOp::IsGreaterThan:
      whichMnemonic = m_kImapSizeLarger;
      break;
    case nsMsgSearchOp::IsLessThan:
      whichMnemonic = m_kImapSizeSmaller;
      break;
    default:
      NS_ASSERTION(false, "invalid search operator");
      return NS_ERROR_INVALID_ARG;
    }
    break;
    case nsMsgSearchAttrib::Date:
      switch (op)
      {
      case nsMsgSearchOp::IsBefore:
        whichMnemonic = m_kImapBefore;
        break;
      case nsMsgSearchOp::IsAfter:
        whichMnemonic = m_kImapSince;
        break;
      case nsMsgSearchOp::Isnt:  /* we've already added the "Not" so just process it like it was a date is search */
      case nsMsgSearchOp::Is:
        whichMnemonic = m_kImapSentOn;
        break;
      default:
        NS_ASSERTION(false, "invalid search operator");
        return NS_ERROR_INVALID_ARG;
      }
      break;
    case nsMsgSearchAttrib::AnyText:
      whichMnemonic = m_kImapAnyText;
      break;
    case nsMsgSearchAttrib::Keywords:
      whichMnemonic = m_kImapKeyword;
      break;
    case nsMsgSearchAttrib::MsgStatus:
      useNot = false; // bizarrely, NOT SEEN is wrong, but UNSEEN is right.
      ignoreValue = true; // the mnemonic is all we need
      PRUint32 status;
      searchValue->GetStatus(&status);

      switch (status)
      {
      case nsMsgMessageFlags::Read:
        whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapSeen : m_kImapNotSeen;
        break;
      case nsMsgMessageFlags::Replied:
        whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapAnswered : m_kImapNotAnswered;
        break;
      case nsMsgMessageFlags::New:
        whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapNew : m_kImapNotNew;
        break;
      case nsMsgMessageFlags::Marked:
        whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapFlagged : m_kImapNotFlagged;
        break;
      default:
        NS_ASSERTION(false, "invalid search operator");
        return NS_ERROR_INVALID_ARG;
      }
      break;
    default:
      if ( attrib > nsMsgSearchAttrib::OtherHeader && attrib < nsMsgSearchAttrib::kNumMsgSearchAttributes)
      {
        nsCString arbitraryHeaderTerm;
        term->GetArbitraryHeader(arbitraryHeaderTerm);
        if (!arbitraryHeaderTerm.IsEmpty())
        {
          arbitraryHeader.AssignLiteral(" \"");
          arbitraryHeader.Append(arbitraryHeaderTerm);
          arbitraryHeader.AppendLiteral("\" ");
          whichMnemonic = arbitraryHeader.get();
        }
        else
          return NS_ERROR_FAILURE;
      }
      else
      {
        NS_ASSERTION(false, "invalid search operator");
        return NS_ERROR_INVALID_ARG;
      }
    }

    char *value = nsnull;
    char dateBuf[100];
    dateBuf[0] = '\0';

    bool valueWasAllocated = false;
    if (attrib == nsMsgSearchAttrib::Date)
    {
      // note that there used to be code here that encoded an RFC822 date for imap searches.
      // The IMAP RFC 2060 is misleading to the point that it looks like it requires an RFC822
      // date but really it expects dd-mmm-yyyy, like dredd, and refers to the RFC822 date only in that the
      // dd-mmm-yyyy date will match the RFC822 date within the message.

      PRTime adjustedDate;
      searchValue->GetDate(&adjustedDate);
      if (whichMnemonic == m_kImapSince)
      {
        // it looks like the IMAP server searches on Since includes the date in question...
        // our UI presents Is, IsGreater and IsLessThan. For the IsGreater case (m_kImapSince)
        // we need to adjust the date so we get greater than and not greater than or equal to which
        // is what the IMAP server wants to search on
        // won't work on Mac.
        // ack, is this right? is PRTime seconds or microseconds?
        PRInt64 microSecondsPerSecond, secondsInDay, microSecondsInDay;

        LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC);
        LL_UI2L(secondsInDay, 60 * 60 * 24);
        LL_MUL(microSecondsInDay, secondsInDay, microSecondsPerSecond);
        LL_ADD(adjustedDate, adjustedDate, microSecondsInDay); // bump up to the day after this one...
      }

      PRExplodedTime exploded;
      PR_ExplodeTime(adjustedDate, PR_LocalTimeParameters, &exploded);
      PR_FormatTimeUSEnglish(dateBuf, sizeof(dateBuf), "%d-%b-%Y", &exploded);
      //    strftime (dateBuf, sizeof(dateBuf), "%d-%b-%Y", localtime (/* &term->m_value.u.date */ &adjustedDate));
      value = dateBuf;
    }
    else
    {
      if (attrib == nsMsgSearchAttrib::AgeInDays)
      {
        // okay, take the current date, subtract off the age in days, then do an appropriate Date search on
        // the resulting day.
        PRInt32 ageInDays;

        searchValue->GetAge(&ageInDays);

        PRTime now = PR_Now();
        PRTime matchDay;

        PRInt64 microSecondsPerSecond, secondsInDays, microSecondsInDay;

        LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC);
        LL_I2L(secondsInDays, 60 * 60 * 24 * ageInDays);
        LL_MUL(microSecondsInDay, secondsInDays, microSecondsPerSecond);

        LL_SUB(matchDay, now, microSecondsInDay); // = now - term->m_value.u.age * 60 * 60 * 24;
        PRExplodedTime exploded;
        PR_ExplodeTime(matchDay, PR_LocalTimeParameters, &exploded);
        PR_FormatTimeUSEnglish(dateBuf, sizeof(dateBuf), "%d-%b-%Y", &exploded);
        //      strftime (dateBuf, sizeof(dateBuf), "%d-%b-%Y", localtime (&matchDay));
        value = dateBuf;
      }
      else if (attrib == nsMsgSearchAttrib::Size)
      {
        PRUint32 sizeValue;
        nsCAutoString searchTermValue;
        searchValue->GetSize(&sizeValue);

        // Multiply by 1024 to get into kb resolution
        sizeValue *= 1024;

        // Ensure that greater than is really greater than
        // in kb resolution.
        if (op == nsMsgSearchOp::IsGreaterThan)
          sizeValue += 1024;

        searchTermValue.AppendInt(sizeValue);

        value = ToNewCString(searchTermValue);
        valueWasAllocated = true;
      }
      else

      if (IS_STRING_ATTRIBUTE(attrib))
      {
        PRUnichar *convertedValue; // = reallyDredd ? MSG_EscapeSearchUrl (term->m_value.u.string) : msg_EscapeImapSearchProtocol(term->m_value.u.string);
        nsString searchTermValue;
        searchValue->GetStr(searchTermValue);
        // Ugly switch for Korean mail/news charsets.
        // We want to do this here because here is where
        // we know what charset we want to use.
#ifdef DOING_CHARSET
        if (reallyDredd)
          dest_csid = INTL_DefaultNewsCharSetID(dest_csid);
        else
          dest_csid = INTL_DefaultMailCharSetID(dest_csid);
#endif

        // do all sorts of crazy escaping
        convertedValue = reallyDredd ? EscapeSearchUrl (searchTermValue.get()) :
        EscapeImapSearchProtocol(searchTermValue.get());
        useQuotes = ((!reallyDredd ||
                    (nsDependentString(convertedValue).FindChar(PRUnichar(' ')) != -1)) &&
           (attrib != nsMsgSearchAttrib::Keywords));
        // now convert to char* and escape quoted_specials
        nsCAutoString valueStr;
        nsresult rv = ConvertFromUnicode(NS_LossyConvertUTF16toASCII(destCharset).get(),
          nsDependentString(convertedValue), valueStr);
        if (NS_SUCCEEDED(rv))
        {
          const char *vptr = valueStr.get();
          // max escaped length is one extra character for every character in the cmd.
          nsAutoArrayPtr<char> newValue(new char[2*strlen(vptr) + 1]);
          if (newValue)
          {
            char *p = newValue;
            while (1)
            {
              char ch = *vptr++;
              if (!ch)
                break;
              if ((useQuotes ? ch == '"' : 0) || ch == '\\')
                *p++ = '\\';
              *p++ = ch;
            }
            *p = '\0';
            value = strdup(newValue); // realloc down to smaller size
          }
        }
        else
          value = strdup("");
        NS_Free(convertedValue);
        valueWasAllocated = true;

      }
    }

    // this should be rewritten to use nsCString
    int subLen =
      (value ? strlen(value) : 0) +
      (useNot ? strlen(m_kImapNot) : 0) +
      strlen(m_kImapHeader);
    int len = strlen(whichMnemonic) + subLen + (useQuotes ? 2 : 0) +
      (orHeaderMnemonic
       ? (subLen + strlen(m_kImapOr) + strlen(orHeaderMnemonic) + 2 /*""*/)
       : 0) +
      10; // add slough for imap string literals
    char *encoding = new char[len];
    if (encoding)
    {
      encoding[0] = '\0';
      // Remember: if ToOrCC and useNot then the expression becomes NOT To AND Not CC as opposed to (NOT TO) || (NOT CC)
      if (orHeaderMnemonic && !useNot)
        PL_strcat(encoding, m_kImapOr);
      if (useNot)
        PL_strcat (encoding, m_kImapNot);
      if (!arbitraryHeader.IsEmpty())
        PL_strcat (encoding, m_kImapHeader);
      PL_strcat (encoding, whichMnemonic);
      if (!ignoreValue)
        err = EncodeImapValue(encoding, value, useQuotes, reallyDredd);

      if (orHeaderMnemonic)
      {
        if (useNot)
          PL_strcat(encoding, m_kImapNot);

        PL_strcat (encoding, m_kImapHeader);

        PL_strcat (encoding, orHeaderMnemonic);
        if (!ignoreValue)
          err = EncodeImapValue(encoding, value, useQuotes, reallyDredd);
      }

      // kmcentee, don't let the encoding end with whitespace,
      // this throws off later url STRCMP
      if (*encoding && *(encoding + strlen(encoding) - 1) == ' ')
        *(encoding + strlen(encoding) - 1) = '\0';
    }

    if (value && valueWasAllocated)
      NS_Free (value);

    *ppOutTerm = encoding;

    return err;
}
Beispiel #24
0
/*
 * get the difference in seconds between this time zone and UTC (GMT)
 */
PR_IMPLEMENT(time_t) PRMJ_LocalGMTDifference()
{
#if defined(XP_UNIX) || defined(XP_PC)
    struct tm ltime;
    /* get the difference between this time zone and GMT */
    memset((char *)&ltime,0,sizeof(ltime));
    ltime.tm_mday = 2;
    ltime.tm_year = 70;
#ifdef SUNOS4
    ltime.tm_zone = 0;
    ltime.tm_gmtoff = 0;
    return timelocal(&ltime) - (24 * 3600);
#else
    return mktime(&ltime) - (24L * 3600L);
#endif
#endif
#if defined(XP_MAC)
    static time_t    zone = -1L;
    MachineLocation  machineLocation;
    PRUint64	     gmtOffsetSeconds;
    PRUint64	     gmtDelta;
    PRUint64	     dlsOffset;
    PRInt32	     offset;

    /* difference has been set no need to recalculate */
    if(zone != -1)
	return zone;

    /* Get the information about the local machine, including
     * its GMT offset and its daylight savings time info.
     * Convert each into wides that we can add to
     * startupTimeMicroSeconds.
     */

    MyReadLocation(&machineLocation);

    /* Mask off top eight bits of gmtDelta, sign extend lower three. */

    if ((machineLocation.u.gmtDelta & 0x00800000) != 0) {
	gmtOffsetSeconds.lo = (machineLocation.u.gmtDelta & 0x00FFFFFF) | 0xFF000000;
	gmtOffsetSeconds.hi = 0xFFFFFFFF;
	LL_UI2L(gmtDelta,0);
    }
    else {

	gmtOffsetSeconds.lo = (machineLocation.u.gmtDelta & 0x00FFFFFF);
	gmtOffsetSeconds.hi = 0;
	LL_UI2L(gmtDelta,PRMJ_DAY_SECONDS);
    }
    /* normalize time to be positive if you are behind GMT. gmtDelta will always
     * be positive.
     */
    LL_SUB(gmtDelta,gmtDelta,gmtOffsetSeconds);

    /* Is Daylight Savings On?  If so, we need to add an hour to the offset. */
    if (machineLocation.u.dlsDelta != 0) {
	LL_UI2L(dlsOffset, PRMJ_HOUR_SECONDS);
    }
    else
	LL_I2L(dlsOffset, 0);

    LL_ADD(gmtDelta,gmtDelta, dlsOffset);
    LL_L2I(offset,gmtDelta);

    zone = offset;
    return (time_t)offset;
#endif
}
Beispiel #25
0
PRMJ_Now(void)
{
#ifdef XP_PC
    PRInt64 s, us, ms2us, s2us;
    struct timeb b;
#endif /* XP_PC */
#ifdef XP_UNIX
    struct timeval tv;
    PRInt64 s, us, s2us;
#endif /* XP_UNIX */
#ifdef XP_MAC
    UnsignedWide upTime;
    PRInt64	 localTime;
    PRInt64       gmtOffset;
    PRInt64    dstOffset;
    time_t       gmtDiff;
    PRInt64	 s2us;
#endif /* XP_MAC */

#ifdef XP_PC
    ftime(&b);
    LL_UI2L(ms2us, PRMJ_USEC_PER_MSEC);
    LL_UI2L(s2us, PRMJ_USEC_PER_SEC);
    LL_UI2L(s, b.time);
    LL_UI2L(us, b.millitm);
    LL_MUL(us, us, ms2us);
    LL_MUL(s, s, s2us);
    LL_ADD(s, s, us);
    return s;
#endif

#ifdef XP_UNIX
#if defined(SOLARIS)
    gettimeofday(&tv);
#else
    gettimeofday(&tv, 0);
#endif /* SOLARIS */
    LL_UI2L(s2us, PRMJ_USEC_PER_SEC);
    LL_UI2L(s, tv.tv_sec);
    LL_UI2L(us, tv.tv_usec);
    LL_MUL(s, s, s2us);
    LL_ADD(s, s, us);
    return s;
#endif /* XP_UNIX */
#ifdef XP_MAC
    LL_UI2L(localTime,0);
    gmtDiff = PRMJ_LocalGMTDifference();
    LL_I2L(gmtOffset,gmtDiff);
    LL_UI2L(s2us, PRMJ_USEC_PER_SEC);
    LL_MUL(gmtOffset,gmtOffset,s2us);
    LL_UI2L(dstOffset,0);
    dstOffset = PRMJ_DSTOffset(dstOffset);
    LL_SUB(gmtOffset,gmtOffset,dstOffset);
    /* don't adjust for DST since it sets ctime and gmtime off on the MAC */
    Microseconds(&upTime);
    LL_ADD(localTime,localTime,gmtOffset);
    LL_ADD(localTime,localTime, *((PRUint64 *)&dstLocalBaseMicroseconds));
    LL_ADD(localTime,localTime, *((PRUint64 *)&upTime));

    return *((PRUint64 *)&localTime);
#endif /* XP_MAC */
}
Beispiel #26
0
int main(int argc, char** argv)
{
	/* The command line argument: -d is used to determine if the test is being run
	in debug mode. The regress tool requires only one line output:PASS or FAIL.
	All of the printfs associated with this test has been handled with a if (debug_mode)
	test.
	Usage: test_name -d
	*/
	PLOptStatus os;
	PLOptState *opt;
    
    PR_STDIO_INIT();
	opt = PL_CreateOptState(argc, argv, "d");
	while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
		if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'd':  /* debug mode */
			debug_mode = PR_TRUE;
            break;
         default:
            break;
        }
    }
	PL_DestroyOptState(opt);

 /* main test */
	
    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);

#ifdef XP_MAC
	SetupMacPrintfLog("timetest.log");
	debug_mode = PR_TRUE;
#endif
    /* Testing zero PRTime (the epoch) */
    {
	PRTime t;
	PRExplodedTime et;

	LL_I2L(t, 0);
	if (debug_mode) printf("The NSPR epoch is:\n");
        PR_ExplodeTime(t, PR_LocalTimeParameters, &et);
	printExplodedTime(&et);
	if (debug_mode) printf("\n");
	PR_ExplodeTime(t, PR_GMTParameters, &et);
	printExplodedTime(&et);
	if (debug_mode) printf("\n\n");
	testParseTimeString(t);
    }

    /*
     *************************************************************
     **
     **  Testing PR_Now(), PR_ExplodeTime, and PR_ImplodeTime
     **  on the current time
     **
     *************************************************************
     */

    {
	PRTime t1, t2;
	PRExplodedTime et;

	if (debug_mode) {
	printf("*********************************************\n");
	printf("**                                         **\n");
    printf("** Testing PR_Now(), PR_ExplodeTime, and   **\n");
	printf("** PR_ImplodeTime on the current time      **\n");
	printf("**                                         **\n");
	printf("*********************************************\n\n");
	}
	t1 = PR_Now();

        /* First try converting to UTC */

        PR_ExplodeTime(t1, PR_GMTParameters, &et);
        if (et.tm_params.tp_gmt_offset || et.tm_params.tp_dst_offset) {
	    if (debug_mode) printf("ERROR: UTC has nonzero gmt or dst offset.\n");
		else failed_already=1;
	    return 1;
        }
        if (debug_mode) printf("Current UTC is ");
	printExplodedTime(&et);
	if (debug_mode) printf("\n");

        t2 = PR_ImplodeTime(&et);
        if (LL_NE(t1, t2)) {
	    if (debug_mode) printf("ERROR: Explode and implode are NOT inverse.\n");
		else printf("FAIL\n");
	    return 1;
        }

        /* Next, try converting to local (US Pacific) time */

        PR_ExplodeTime(t1, PR_LocalTimeParameters, &et);
        if (debug_mode) printf("Current local time is ");
	printExplodedTime(&et);
	if (debug_mode) printf("\n");
	if (debug_mode) printf("GMT offset is %ld, DST offset is %ld\n",
		et.tm_params.tp_gmt_offset, et.tm_params.tp_dst_offset);
        t2 = PR_ImplodeTime(&et);
        if (LL_NE(t1, t2)) {
	    if (debug_mode) printf("ERROR: Explode and implode are NOT inverse.\n");
	    return 1;
	}

	if (debug_mode) printf("Please examine the results\n");
	testParseTimeString(t1);
    }


    /*
     *******************************************
     **
     ** Testing PR_NormalizeTime()
     **
     *******************************************
     */

    /* July 4, 2001 is Wednesday */
    {
	PRExplodedTime et;

	if (debug_mode)  {
	printf("\n");
	printf("**********************************\n");
	printf("**                              **\n");
	printf("** Testing PR_NormalizeTime()   **\n");
	printf("**                              **\n");
	printf("**********************************\n\n");
	}
        et.tm_year    = 2001;
        et.tm_month   = 7 - 1;
        et.tm_mday    = 4;
        et.tm_hour    = 0;
        et.tm_min     = 0;
        et.tm_sec     = 0;
	et.tm_usec    = 0;
        et.tm_params  = PR_GMTParameters(&et);

	PR_NormalizeTime(&et, PR_GMTParameters);

	if (debug_mode) printf("July 4, 2001 is %s.\n", dayOfWeek[et.tm_wday]);
	if (et.tm_wday == 3) {
	    if (debug_mode) printf("PASS\n");
        } else {
            if (debug_mode) printf("ERROR: It should be Wednesday\n");
			else failed_already=1;
	    return 1;
	}
	testParseTimeString(PR_ImplodeTime(&et));

        /* June 12, 1997 23:00 PST == June 13, 1997 00:00 PDT */
        et.tm_year    = 1997;
        et.tm_month   = 6 - 1;
        et.tm_mday    = 12;
        et.tm_hour    = 23;
        et.tm_min     = 0;
        et.tm_sec     = 0;
	et.tm_usec    = 0;
        et.tm_params.tp_gmt_offset = -8 * 3600;
	et.tm_params.tp_dst_offset = 0;

	PR_NormalizeTime(&et, PR_USPacificTimeParameters);

	if (debug_mode) {
	    printf("Thu Jun 12, 1997 23:00:00 PST is ");
	}
	printExplodedTime(&et);
	if (debug_mode) printf(".\n");
	if (et.tm_wday == 5) {
	    if (debug_mode) printf("PASS\n");
        } else {
            if (debug_mode) printf("ERROR: It should be Friday\n");
			else failed_already=1;
	    return 1;
	}
	testParseTimeString(PR_ImplodeTime(&et));

        /* Feb 14, 1997 00:00:00 PDT == Feb 13, 1997 23:00:00 PST */
        et.tm_year    = 1997;
        et.tm_month   = 2 - 1;
        et.tm_mday    = 14;
        et.tm_hour    = 0;
        et.tm_min     = 0;
        et.tm_sec     = 0;
	et.tm_usec    = 0;
        et.tm_params.tp_gmt_offset = -8 * 3600;
	et.tm_params.tp_dst_offset = 3600;

	PR_NormalizeTime(&et, PR_USPacificTimeParameters);

	if (debug_mode) {
	    printf("Fri Feb 14, 1997 00:00:00 PDT is ");
	}
	printExplodedTime(&et);
	if (debug_mode) printf(".\n");
	if (et.tm_wday == 4) {
	    if (debug_mode) printf("PASS\n");
        } else {
            if (debug_mode) printf("ERROR: It should be Thursday\n");
			else failed_already=1;
	    return 1;
	}
	testParseTimeString(PR_ImplodeTime(&et));

        /* What time is Nov. 7, 1996, 18:29:23 PDT? */
        et.tm_year    = 1996;
        et.tm_month   = 11 - 1;
        et.tm_mday    = 7;
        et.tm_hour    = 18;
        et.tm_min     = 29;
        et.tm_sec     = 23;
	et.tm_usec    = 0;
        et.tm_params.tp_gmt_offset = -8 * 3600;  /* PDT */
	et.tm_params.tp_dst_offset = 3600; 

	PR_NormalizeTime(&et, PR_LocalTimeParameters);
        if (debug_mode) printf("Nov 7 18:29:23 PDT 1996 is ");
	printExplodedTime(&et);
	if (debug_mode) printf(".\n");
	testParseTimeString(PR_ImplodeTime(&et));

        /* What time is Oct. 7, 1995, 18:29:23 PST? */
        et.tm_year    = 1995;
        et.tm_month   = 10 - 1;
        et.tm_mday    = 7;
        et.tm_hour    = 18;
        et.tm_min     = 29;
        et.tm_sec     = 23;
        et.tm_params.tp_gmt_offset = -8 * 3600;  /* PST */
	et.tm_params.tp_dst_offset = 0;

	PR_NormalizeTime(&et, PR_LocalTimeParameters);
        if (debug_mode) printf("Oct 7 18:29:23 PST 1995 is ");
	printExplodedTime(&et);
	if (debug_mode) printf(".\n");
	testParseTimeString(PR_ImplodeTime(&et));

	if (debug_mode) printf("Please examine the results\n");
    }

    /*
     **************************************************************
     **
     ** Testing range of years
     **
     **************************************************************
     */

    {
	PRExplodedTime et1, et2;
    PRTime  ttt;
	PRTime secs;

	if (debug_mode) {
	printf("\n");
	printf("***************************************\n");
	printf("**                                   **\n");
	printf("**  Testing range of years           **\n");
	printf("**                                   **\n");
	printf("***************************************\n\n");
	}
	/* April 4, 1917 GMT */
	et1.tm_usec = 0;
	et1.tm_sec = 0;
	et1.tm_min = 0;
	et1.tm_hour = 0;
	et1.tm_mday = 4;
	et1.tm_month = 4 - 1;
	et1.tm_year = 1917;
	et1.tm_params = PR_GMTParameters(&et1);
	PR_NormalizeTime(&et1, PR_LocalTimeParameters);
	secs = PR_ImplodeTime(&et1);
	if (LL_GE_ZERO(secs)) {
	    if (debug_mode)
		printf("ERROR: April 4, 1917 GMT returns a nonnegative second count\n");
		failed_already = 1;
	    return 1;
        }
	PR_ExplodeTime(secs, PR_LocalTimeParameters, &et2);
	if (!explodedTimeIsEqual(&et1, &et2)) {
		if (debug_mode)
		printf("ERROR: PR_ImplodeTime and PR_ExplodeTime are not inverse for April 4, 1917 GMT\n");
		failed_already=1;
	    return 1;
        }
    ttt = PR_ImplodeTime(&et1);
	testParseTimeString( ttt );

	if (debug_mode) printf("Test passed for April 4, 1917\n");

	/* July 4, 2050 */
	et1.tm_usec = 0;
	et1.tm_sec = 0;
	et1.tm_min = 0;
	et1.tm_hour = 0;
	et1.tm_mday = 4;
	et1.tm_month = 7 - 1;
	et1.tm_year = 2050;
	et1.tm_params = PR_GMTParameters(&et1);
	PR_NormalizeTime(&et1, PR_LocalTimeParameters);
	secs = PR_ImplodeTime(&et1);
	if (!LL_GE_ZERO(secs)) {
	    if (debug_mode)
			printf("ERROR: July 4, 2050 GMT returns a negative second count\n");
		failed_already = 1;
	    return 1;
        }
	PR_ExplodeTime(secs, PR_LocalTimeParameters, &et2);
	if (!explodedTimeIsEqual(&et1, &et2)) {
	    if (debug_mode)
		printf("ERROR: PR_ImplodeTime and PR_ExplodeTime are not inverse for July 4, 2050 GMT\n");
		failed_already=1;
	    return 1;
        }
	testParseTimeString(PR_ImplodeTime(&et1));

	if (debug_mode) printf("Test passed for July 4, 2050\n");

    }

    /*
     **************************************************************
     **
     **  Stress test
     *
     **      Go through four years, starting from
     **      00:00:00 PST Jan. 1, 1993, incrementing
     **      every 10 minutes.
     **
     **************************************************************
     */

    {
	PRExplodedTime et, et1, et2;
	PRInt64 usecPer10Min;
	int day, hour, min;
	PRTime usecs;
	int dstInEffect = 0;

	if (debug_mode) {
	printf("\n");
	printf("*******************************************************\n");
	printf("**                                                   **\n");
	printf("**                 Stress test                       **\n");
	printf("**  Starting from midnight Jan. 1, 1993 PST,         **\n");
	printf("**  going through four years in 10-minute increment  **\n");
	printf("**                                                   **\n");
	printf("*******************************************************\n\n");
	}
	LL_I2L(usecPer10Min, 600000000L);

	/* 00:00:00 PST Jan. 1, 1993 */
	et.tm_usec = 0;
	et.tm_sec = 0;
	et.tm_min = 0;
	et.tm_hour = 0;
	et.tm_mday = 1;
	et.tm_month = 0;
	et.tm_year = 1993;
	et.tm_params.tp_gmt_offset = -8 * 3600;
	et.tm_params.tp_dst_offset = 0;
	usecs = PR_ImplodeTime(&et);

        for (day = 0; day < 4 * 365 + 1; day++) {
	    for (hour = 0; hour < 24; hour++) {
		for (min = 0; min < 60; min += 10) {
	            LL_ADD(usecs, usecs, usecPer10Min);
		    PR_ExplodeTime(usecs, PR_USPacificTimeParameters, &et1);

		    et2 = et;
		    et2.tm_usec += 600000000L;
		    PR_NormalizeTime(&et2, PR_USPacificTimeParameters);

		    if (!explodedTimeIsEqual(&et1, &et2)) {
		        if (debug_mode) printf("ERROR: componentwise comparison failed\n");
			printExplodedTime(&et1);
			if (debug_mode) printf("\n");
			printExplodedTime(&et2);
			if (debug_mode) printf("\n");
			failed_already=1;
		        return 1;
		    }

		    if (LL_NE(usecs, PR_ImplodeTime(&et1))) { 
                        if (debug_mode)
					printf("ERROR: PR_ExplodeTime and PR_ImplodeTime are not inverse\n");
			printExplodedTime(&et1);
			if (debug_mode) printf("\n");
			failed_already=1;
		        return 1;
		    }
		    testParseTimeString(usecs);

		    if (!dstInEffect && et1.tm_params.tp_dst_offset) {
		        dstInEffect = 1;
		        if (debug_mode) printf("DST changeover from ");
			printExplodedTime(&et);
			if (debug_mode) printf(" to ");
			printExplodedTime(&et1);
			if (debug_mode) printf(".\n");
                    } else if (dstInEffect && !et1.tm_params.tp_dst_offset) {
		        dstInEffect = 0;
			if (debug_mode) printf("DST changeover from ");
			printExplodedTime(&et);
			if (debug_mode) printf(" to ");
			printExplodedTime(&et1);
			if (debug_mode) printf(".\n");
                    }

		    et = et1;
		}
	    }
        }
	if (debug_mode) printf("Test passed\n");
    }


    /* Same stress test, but with PR_LocalTimeParameters */

    {
	PRExplodedTime et, et1, et2;
	PRInt64 usecPer10Min;
	int day, hour, min;
	PRTime usecs;
	int dstInEffect = 0;

	if (debug_mode) {
	printf("\n");
	printf("*******************************************************\n");
	printf("**                                                   **\n");
	printf("**                 Stress test                       **\n");
	printf("**  Starting from midnight Jan. 1, 1993 PST,         **\n");
	printf("**  going through four years in 10-minute increment  **\n");
	printf("**                                                   **\n");
	printf("*******************************************************\n\n");
	}
	
	LL_I2L(usecPer10Min, 600000000L);

	/* 00:00:00 PST Jan. 1, 1993 */
	et.tm_usec = 0;
	et.tm_sec = 0;
	et.tm_min = 0;
	et.tm_hour = 0;
	et.tm_mday = 1;
	et.tm_month = 0;
	et.tm_year = 1993;
	et.tm_params.tp_gmt_offset = -8 * 3600;
	et.tm_params.tp_dst_offset = 0;
	usecs = PR_ImplodeTime(&et);

        for (day = 0; day < 4 * 365 + 1; day++) {
	    for (hour = 0; hour < 24; hour++) {
		for (min = 0; min < 60; min += 10) {
	            LL_ADD(usecs, usecs, usecPer10Min);
		    PR_ExplodeTime(usecs, PR_LocalTimeParameters, &et1);

		    et2 = et;
		    et2.tm_usec += 600000000L;
		    PR_NormalizeTime(&et2, PR_LocalTimeParameters);

		    if (!explodedTimeIsEqual(&et1, &et2)) {
		        if (debug_mode) printf("ERROR: componentwise comparison failed\n");
			printExplodedTime(&et1);
			if (debug_mode) printf("\n");
			printExplodedTime(&et2);
			if (debug_mode) printf("\n");
		        return 1;
		    }

		    if (LL_NE(usecs, PR_ImplodeTime(&et1))) {
                        printf("ERROR: PR_ExplodeTime and PR_ImplodeTime are not inverse\n");
			printExplodedTime(&et1);
			if (debug_mode) printf("\n");
			failed_already=1;
		        return 1;
		    }
		    testParseTimeString(usecs);

		    if (!dstInEffect && et1.tm_params.tp_dst_offset) {
		        dstInEffect = 1;
		        if (debug_mode) printf("DST changeover from ");
			printExplodedTime(&et);
			if (debug_mode) printf(" to ");
			printExplodedTime(&et1);
			if (debug_mode) printf(".\n");
                    } else if (dstInEffect && !et1.tm_params.tp_dst_offset) {
		        dstInEffect = 0;
			if (debug_mode) printf("DST changeover from ");
			printExplodedTime(&et);
			if (debug_mode) printf(" to ");
			printExplodedTime(&et1);
			if (debug_mode) printf(".\n");
                    }

		    et = et1;
		}
	    }
        }
	if (debug_mode) printf("Test passed\n");
    }

    /* Same stress test, but with PR_LocalTimeParameters and going backward */

    {
	PRExplodedTime et, et1, et2;
	PRInt64 usecPer10Min;
	int day, hour, min;
	PRTime usecs;
	int dstInEffect = 0;

	if (debug_mode) {
	printf("\n");
	printf("*******************************************************\n");
	printf("**                                                   **\n");
	printf("**                 Stress test                       **\n");
	printf("**  Starting from midnight Jan. 1, 1997 PST,         **\n");
	printf("**  going back four years in 10-minute increment     **\n");
	printf("**                                                   **\n");
	printf("*******************************************************\n\n");
	}

	LL_I2L(usecPer10Min, 600000000L);

	/* 00:00:00 PST Jan. 1, 1997 */
	et.tm_usec = 0;
	et.tm_sec = 0;
	et.tm_min = 0;
	et.tm_hour = 0;
	et.tm_mday = 1;
	et.tm_month = 0;
	et.tm_year = 1997;
	et.tm_params.tp_gmt_offset = -8 * 3600;
	et.tm_params.tp_dst_offset = 0;
	usecs = PR_ImplodeTime(&et);

        for (day = 0; day < 4 * 365 + 1; day++) {
	    for (hour = 0; hour < 24; hour++) {
		for (min = 0; min < 60; min += 10) {
	            LL_SUB(usecs, usecs, usecPer10Min);
		    PR_ExplodeTime(usecs, PR_LocalTimeParameters, &et1);

		    et2 = et;
		    et2.tm_usec -= 600000000L;
		    PR_NormalizeTime(&et2, PR_LocalTimeParameters);

		    if (!explodedTimeIsEqual(&et1, &et2)) {
		        if (debug_mode) printf("ERROR: componentwise comparison failed\n");
			printExplodedTime(&et1);
			if (debug_mode) printf("\n");
			printExplodedTime(&et2);
			if (debug_mode) printf("\n");
		        return 1;
		    }

		    if (LL_NE(usecs, PR_ImplodeTime(&et1))) {
                   if (debug_mode)
					printf("ERROR: PR_ExplodeTime and PR_ImplodeTime are not inverse\n");
			printExplodedTime(&et1);
			if (debug_mode) printf("\n");
			failed_already=1;
		        return 1;
		    }
		    testParseTimeString(usecs);

		    if (!dstInEffect && et1.tm_params.tp_dst_offset) {
		        dstInEffect = 1;
		        if (debug_mode) printf("DST changeover from ");
			printExplodedTime(&et);
			if (debug_mode) printf(" to ");
			printExplodedTime(&et1);
			if (debug_mode) printf(".\n");
                    } else if (dstInEffect && !et1.tm_params.tp_dst_offset) {
		        dstInEffect = 0;
			if (debug_mode) printf("DST changeover from ");
			printExplodedTime(&et);
			if (debug_mode) printf(" to ");
			printExplodedTime(&et1);
			if (debug_mode) printf(".\n");
                    }

		    et = et1;
		}
	    }
        }
    }

	if (failed_already) return 1;
	else return 0;

}
Beispiel #27
0
static PRUint64
_pr_strtoull(const char *str, char **endptr, int base)
{
    static const int BASE_MAX = 16;
    static const char digits[] = "0123456789abcdef";
    char *digitPtr;
    PRUint64 x;    /* return value */
    PRInt64 base64;
    const char *cPtr;
    PRBool negative;
    const char *digitStart;

    PR_ASSERT(base == 0 || base == 8 || base == 10 || base == 16);
    if (base < 0 || base == 1 || base > BASE_MAX) {
        if (endptr) {
            *endptr = (char *) str;
            return LL_ZERO;
        }
    }

    cPtr = str;
    while (isspace(*cPtr)) {
        ++cPtr;
    }

    negative = PR_FALSE;
    if (*cPtr == '-') {
        negative = PR_TRUE;
        cPtr++;
    } else if (*cPtr == '+') {
        cPtr++;
    }

    if (base == 16) {
        if (*cPtr == '0' && (cPtr[1] == 'x' || cPtr[1] == 'X')) {
            cPtr += 2;
        }
    } else if (base == 0) {
        if (*cPtr != '0') {
            base = 10;
        } else if (cPtr[1] == 'x' || cPtr[1] == 'X') {
            base = 16;
            cPtr += 2;
        } else {
            base = 8;
        } 
    }
    PR_ASSERT(base != 0);
    LL_I2L(base64, base);
    digitStart = cPtr;

    /* Skip leading zeros */
    while (*cPtr == '0') {
        cPtr++;
    }

    LL_I2L(x, 0);
    while ((digitPtr = (char*)memchr(digits, tolower(*cPtr), base)) != NULL) {
        PRUint64 d;

        LL_I2L(d, (digitPtr - digits));
        LL_MUL(x, x, base64);
        LL_ADD(x, x, d);
        cPtr++;
    }

    if (cPtr == digitStart) {
        if (endptr) {
            *endptr = (char *) str;
        }
        return LL_ZERO;
    }

    if (negative) {
#ifdef HAVE_LONG_LONG
        /* The cast to a signed type is to avoid a compiler warning */
        x = -(PRInt64)x;
#else
        LL_NEG(x, x);
#endif
    }

    if (endptr) {
        *endptr = (char *) cPtr;
    }
    return x;
}
Beispiel #28
0
static void triggered_list_add(pn_selector_t *selector, iocpdesc_t *iocpd)
{
  if (iocpd->triggered_list_prev || selector->triggered_list_head == iocpd)
    return; // already in list
  LL_ADD(selector, triggered_list, iocpd);
}