File: NAComparator.h

package info (click to toggle)
rcpp 0.11.3-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 9,948 kB
  • ctags: 16,427
  • sloc: ansic: 42,692; cpp: 34,078; makefile: 32; sh: 21
file content (86 lines) | stat: -rw-r--r-- 2,426 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*-
/* :tabSize=4:indentSize=4:noTabs=false:folding=explicit:collapseFolds=1: */
//
// NAComparator.h: Rcpp R/C++ interface class library -- comparator
//
// Copyright (C) 2012-2014 Dirk Eddelbuettel, Romain Francois and Kevin Ushey
//
// This file is part of Rcpp.
//
// Rcpp is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Rcpp is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Rcpp.  If not, see <http://www.gnu.org/licenses/>.

#ifndef Rcpp__internal__NAComparator__h
#define Rcpp__internal__NAComparator__h

namespace Rcpp{

namespace internal {

inline int StrCmp(SEXP x, SEXP y) {
    if (x == NA_STRING) return (y == NA_STRING ? 0 : 1);
    if (y == NA_STRING) return -1;
    if (x == y) return 0;  // same string in cache
    return strcmp(char_nocheck(x), char_nocheck(y));
}

template <typename T>
struct NAComparator {
    inline bool operator()(T left, T right) const {
        return left < right;
    }
};

template <>
struct NAComparator<int> {
    inline bool operator()(int left, int right) const {
        if (left == NA_INTEGER) return false;
        if (right == NA_INTEGER) return true;
        return left < right;
    }
};

template <>
struct NAComparator<double> {
    inline bool operator()(double left, double right) const {

        bool leftNaN = (left != left);
        bool rightNaN = (right != right);

        // this branch inspired by data.table: see
        // https://github.com/arunsrinivasan/datatable/commit/1a3e476d3f746e18261662f484d2afa84ac7a146#commitcomment-4885242
        if (Rcpp_IsNaN(right) and Rcpp_IsNA(left))
            return true;

        if (leftNaN != rightNaN) {
            return leftNaN < rightNaN;
        } else {
            return left < right;
        }

      }

};

template <>
struct NAComparator<SEXP> {
    inline bool operator()(SEXP left, SEXP right) const {
        return StrCmp(left, right) < 0;
    }
};

}

}

#endif