aboutsummaryrefslogtreecommitdiff
path: root/libxsde/xsde/cxx/string-search.cxx
blob: b7ca311054bb8ee2c861e7667d1ef130cb0611af (plain)
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
// file      : xsde/cxx/string-search.cxx
// copyright : Copyright (c) 2005-2011 Code Synthesis Tools CC
// license   : GNU GPL v2 + exceptions; see accompanying LICENSE file

#include <string.h> // strcmp
#include <xsde/cxx/string-search.hxx>

namespace xsde
{
  namespace cxx
  {
    size_t
    search (const char* const* array, size_t size, const char* s)
    {
      if (size == 0)
        return 0;

      int r = 1;
      size_t m = 0;
      size_t l = 0;
      size_t h = size - 1;

      while (l <= h)
      {
        m = l + (h - l) / 2;

        r = strcmp (array[m], s);

        if (r == 0 || l == h)
          break;

        if (r < 0)
          l = m + 1;
        else
          h = (m == 0 ? 0 : m - 1);
      }

      return r == 0 ? m : size;
    }
  }
}