@pulsar-edit/fuzzy-native 1.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +78 -0
- package/binding.gyp +40 -0
- package/lib/main.js +1 -0
- package/lib/main.js.flow +45 -0
- package/package.json +30 -0
- package/src/MatcherBase.cpp +329 -0
- package/src/MatcherBase.h +93 -0
- package/src/binding.cpp +233 -0
- package/src/fuzzaldrin_score.cpp +112 -0
- package/src/fuzzaldrin_score.h +5 -0
- package/src/memrchr.h +179 -0
- package/src/score_match.cpp +278 -0
- package/src/score_match.h +32 -0
package/src/binding.cpp
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
#include <nan.h>
|
|
2
|
+
#include <vector>
|
|
3
|
+
#include <unordered_map>
|
|
4
|
+
#include <chrono>
|
|
5
|
+
|
|
6
|
+
#include "MatcherBase.h"
|
|
7
|
+
|
|
8
|
+
using namespace Nan;
|
|
9
|
+
|
|
10
|
+
#define CHECK(cond, msg) \
|
|
11
|
+
if (!(cond)) \
|
|
12
|
+
{ \
|
|
13
|
+
ThrowTypeError(msg); \
|
|
14
|
+
return; \
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
template <typename T>
|
|
18
|
+
T get_property(const v8::Local<v8::Object> &object, const char *name)
|
|
19
|
+
{
|
|
20
|
+
auto prop = Nan::Get(object, Nan::New(name).ToLocalChecked());
|
|
21
|
+
if (prop.IsEmpty())
|
|
22
|
+
{
|
|
23
|
+
return T();
|
|
24
|
+
}
|
|
25
|
+
Nan::Maybe<T> result = Nan::To<T>(prop.ToLocalChecked());
|
|
26
|
+
if (result.IsNothing())
|
|
27
|
+
{
|
|
28
|
+
return T();
|
|
29
|
+
}
|
|
30
|
+
return result.FromJust();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* This saves one string copy over using v8::String::Utf8Value.
|
|
35
|
+
*/
|
|
36
|
+
std::string to_std_string(const v8::Local<v8::String> &v8str)
|
|
37
|
+
{
|
|
38
|
+
v8::Isolate *isolate = v8::Isolate::GetCurrent();
|
|
39
|
+
std::string str(v8str->Utf8Length(isolate), ' ');
|
|
40
|
+
v8str->WriteUtf8(isolate, &str[0]);
|
|
41
|
+
return str;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
std::string get_string_property(const v8::Local<v8::Object> &object,
|
|
45
|
+
const char *name)
|
|
46
|
+
{
|
|
47
|
+
auto prop =
|
|
48
|
+
Nan::Get(object, Nan::New(name).ToLocalChecked());
|
|
49
|
+
if (!prop.IsEmpty())
|
|
50
|
+
{
|
|
51
|
+
auto propLocal = prop.ToLocalChecked();
|
|
52
|
+
if (propLocal->IsNull() || propLocal->IsUndefined())
|
|
53
|
+
{
|
|
54
|
+
return std::string("");
|
|
55
|
+
}
|
|
56
|
+
if (!propLocal->IsString())
|
|
57
|
+
{
|
|
58
|
+
std::string msg =
|
|
59
|
+
std::string("property ") +
|
|
60
|
+
name +
|
|
61
|
+
std::string(" must be a string");
|
|
62
|
+
ThrowTypeError(msg.c_str());
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return to_std_string(Nan::To<v8::String>(propLocal).ToLocalChecked());
|
|
66
|
+
}
|
|
67
|
+
return std::string("");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
Persistent<v8::Function> MatcherConstructor;
|
|
71
|
+
|
|
72
|
+
class Matcher : public ObjectWrap
|
|
73
|
+
{
|
|
74
|
+
public:
|
|
75
|
+
static void Init(v8::Local<v8::Object> exports)
|
|
76
|
+
{
|
|
77
|
+
// Prepare constructor template
|
|
78
|
+
v8::Local<v8::FunctionTemplate> tpl =
|
|
79
|
+
New<v8::FunctionTemplate>(Matcher::Create);
|
|
80
|
+
tpl->SetClassName(New("Matcher").ToLocalChecked());
|
|
81
|
+
tpl->InstanceTemplate()->SetInternalFieldCount(1);
|
|
82
|
+
|
|
83
|
+
// Prototype
|
|
84
|
+
SetPrototypeMethod(tpl, "match", Match);
|
|
85
|
+
SetPrototypeMethod(tpl, "addCandidates", AddCandidates);
|
|
86
|
+
SetPrototypeMethod(tpl, "removeCandidates", RemoveCandidates);
|
|
87
|
+
SetPrototypeMethod(tpl, "setCandidates", SetCandidates);
|
|
88
|
+
|
|
89
|
+
v8::Local<v8::Context> context = Nan::GetCurrentContext();
|
|
90
|
+
|
|
91
|
+
MatcherConstructor.Reset(tpl->GetFunction(context).ToLocalChecked());
|
|
92
|
+
Set(exports, Nan::New("Matcher").ToLocalChecked(), tpl->GetFunction(context).ToLocalChecked());
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
static void Create(const Nan::FunctionCallbackInfo<v8::Value> &info)
|
|
96
|
+
{
|
|
97
|
+
CHECK(info.IsConstructCall(), "Use 'new' to construct Matcher");
|
|
98
|
+
auto obj = new Matcher();
|
|
99
|
+
obj->Wrap(info.This());
|
|
100
|
+
AddCandidates(info);
|
|
101
|
+
info.GetReturnValue().Set(info.This());
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
static void Match(const FunctionCallbackInfo<v8::Value> &info)
|
|
105
|
+
{
|
|
106
|
+
if (info.Length() < 1)
|
|
107
|
+
{
|
|
108
|
+
Nan::ThrowTypeError("Wrong number of arguments");
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
CHECK(info[0]->IsString(), "First argument should be a query string");
|
|
113
|
+
std::string query(to_std_string(Nan::To<v8::String>(info[0]).ToLocalChecked()));
|
|
114
|
+
|
|
115
|
+
MatcherOptions options;
|
|
116
|
+
if (info.Length() > 1)
|
|
117
|
+
{
|
|
118
|
+
CHECK(info[1]->IsObject(), "Second argument should be an options object");
|
|
119
|
+
auto options_obj = Nan::To<v8::Object>(info[1]).ToLocalChecked();
|
|
120
|
+
options.case_sensitive = get_property<bool>(options_obj, "caseSensitive");
|
|
121
|
+
options.smart_case = get_property<bool>(options_obj, "smartCase");
|
|
122
|
+
options.num_threads = get_property<int>(options_obj, "numThreads");
|
|
123
|
+
options.max_results = get_property<int>(options_obj, "maxResults");
|
|
124
|
+
options.max_gap = get_property<int>(options_obj, "maxGap");
|
|
125
|
+
options.record_match_indexes =
|
|
126
|
+
get_property<bool>(options_obj, "recordMatchIndexes");
|
|
127
|
+
options.fuzzaldrin =
|
|
128
|
+
get_string_property(options_obj, "algorithm") == "fuzzaldrin";
|
|
129
|
+
options.root_path = get_string_property(options_obj, "rootPath");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
auto idKey = New("id").ToLocalChecked();
|
|
133
|
+
auto valueKey = New("value").ToLocalChecked();
|
|
134
|
+
auto scoreKey = New("score").ToLocalChecked();
|
|
135
|
+
auto matchIndexesKey = New("matchIndexes").ToLocalChecked();
|
|
136
|
+
|
|
137
|
+
auto matcher = Unwrap<Matcher>(info.This());
|
|
138
|
+
std::vector<MatchResult> matches =
|
|
139
|
+
matcher->impl_.findMatches(query, options);
|
|
140
|
+
auto result = New<v8::Array>();
|
|
141
|
+
size_t result_count = 0;
|
|
142
|
+
for (const auto &match : matches)
|
|
143
|
+
{
|
|
144
|
+
auto obj = New<v8::Object>();
|
|
145
|
+
Set(obj, idKey, New<v8::Uint32>(match.id));
|
|
146
|
+
Set(obj, scoreKey, New(match.score));
|
|
147
|
+
Set(obj, valueKey, New(*match.value).ToLocalChecked());
|
|
148
|
+
|
|
149
|
+
v8::Local<v8::Context> context = Nan::GetCurrentContext();
|
|
150
|
+
if (match.matchIndexes != nullptr)
|
|
151
|
+
{
|
|
152
|
+
auto array = New<v8::Array>(match.matchIndexes->size());
|
|
153
|
+
for (size_t i = 0; i < array->Length(); i++)
|
|
154
|
+
{
|
|
155
|
+
array->Set(context, i, New(match.matchIndexes->at(i)));
|
|
156
|
+
}
|
|
157
|
+
Set(obj, matchIndexesKey, array);
|
|
158
|
+
}
|
|
159
|
+
result->Set(context, result_count++, obj);
|
|
160
|
+
}
|
|
161
|
+
info.GetReturnValue().Set(result);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
static void AddCandidates(const FunctionCallbackInfo<v8::Value> &info)
|
|
165
|
+
{
|
|
166
|
+
auto matcher = Unwrap<Matcher>(info.This());
|
|
167
|
+
if (info.Length() > 0)
|
|
168
|
+
{
|
|
169
|
+
CHECK(info[0]->IsArray(), "Expected an array of unsigned 32-bit integer ids as the first argument");
|
|
170
|
+
CHECK(info[1]->IsArray(), "Expected an array of strings as the second argument");
|
|
171
|
+
|
|
172
|
+
auto ids = v8::Local<v8::Array>::Cast(info[0]);
|
|
173
|
+
auto values = v8::Local<v8::Array>::Cast(info[1]);
|
|
174
|
+
|
|
175
|
+
CHECK(ids->Length() == values->Length(), "Expected ids array and values array to have the same length");
|
|
176
|
+
|
|
177
|
+
// Create a random permutation so that candidates are shuffled.
|
|
178
|
+
std::vector<size_t> indexes(ids->Length());
|
|
179
|
+
for (size_t i = 0; i < indexes.size(); i++)
|
|
180
|
+
{
|
|
181
|
+
indexes[i] = i;
|
|
182
|
+
if (i > 0)
|
|
183
|
+
{
|
|
184
|
+
std::swap(indexes[rand() % i], indexes[i]);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
matcher->impl_.reserve(matcher->impl_.size() + ids->Length());
|
|
188
|
+
|
|
189
|
+
v8::Local<v8::Context> context = Nan::GetCurrentContext();
|
|
190
|
+
for (auto i : indexes)
|
|
191
|
+
{
|
|
192
|
+
auto id_value = ids->Get(context, i).ToLocalChecked();
|
|
193
|
+
CHECK(id_value->IsUint32(), "Expected first array to only contain unsigned 32-bit integer ids");
|
|
194
|
+
auto id = v8::Local<v8::Uint32>::Cast(id_value)->Value();
|
|
195
|
+
auto value = to_std_string(Nan::To<v8::String>(values->Get(context, i).ToLocalChecked()).ToLocalChecked());
|
|
196
|
+
matcher->impl_.addCandidate(id, value);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
static void RemoveCandidates(const FunctionCallbackInfo<v8::Value> &info)
|
|
202
|
+
{
|
|
203
|
+
auto matcher = Unwrap<Matcher>(info.This());
|
|
204
|
+
if (info.Length() > 0)
|
|
205
|
+
{
|
|
206
|
+
CHECK(info[0]->IsArray(), "Expected an array of unsigned 32-bit integer ids");
|
|
207
|
+
auto ids = v8::Local<v8::Array>::Cast(info[0]);
|
|
208
|
+
|
|
209
|
+
v8::Local<v8::Context> context = Nan::GetCurrentContext();
|
|
210
|
+
for (size_t i = 0; i < ids->Length(); i++)
|
|
211
|
+
{
|
|
212
|
+
auto id_value = ids->Get(context, i).ToLocalChecked();
|
|
213
|
+
CHECK(id_value->IsUint32(), "Expected array to only contain unsigned 32-bit integer ids");
|
|
214
|
+
auto id = v8::Local<v8::Uint32>::Cast(id_value)->Value();
|
|
215
|
+
matcher->impl_.removeCandidate(id);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
static void SetCandidates(const FunctionCallbackInfo<v8::Value> &info)
|
|
221
|
+
{
|
|
222
|
+
auto matcher = Unwrap<Matcher>(info.This());
|
|
223
|
+
matcher->impl_.clear();
|
|
224
|
+
AddCandidates(info);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private:
|
|
228
|
+
MatcherBase impl_;
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
void Init(v8::Local<v8::Object> exports) { Matcher::Init(exports); }
|
|
232
|
+
|
|
233
|
+
NAN_MODULE_WORKER_ENABLED(addon, Init)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Original ported from: string_score.js: String Scoring Algorithm 0.1.10
|
|
2
|
+
// https://github.com/joshaven/string_score
|
|
3
|
+
//
|
|
4
|
+
// Copyright (C) 2009-2011 Joshaven Potter <yourtech@gmail.com>
|
|
5
|
+
// Special thanks to all of the contributors listed here https://github.com/joshaven/string_score
|
|
6
|
+
// MIT license: http://www.opensource.org/licenses/mit-license.php
|
|
7
|
+
//
|
|
8
|
+
// Re-ported from Atom's Fuzzaldrin score.js file to C++
|
|
9
|
+
|
|
10
|
+
#include "fuzzaldrin_score.h"
|
|
11
|
+
|
|
12
|
+
const std::string PathSeparator = "/"; // Assuming Unix-like path separator
|
|
13
|
+
|
|
14
|
+
float fuzzaldrin_basename_score(const std::string& string, const std::string& query, float score) {
|
|
15
|
+
long index = string.length() - 1;
|
|
16
|
+
while (string[index] == PathSeparator[0]) { index--; } // Skip trailing slashes
|
|
17
|
+
std::size_t slashCount = 0;
|
|
18
|
+
const std::size_t lastCharacter = index;
|
|
19
|
+
std::string base;
|
|
20
|
+
|
|
21
|
+
while (index >= 0) {
|
|
22
|
+
if (string[index] == PathSeparator[0]) {
|
|
23
|
+
slashCount++;
|
|
24
|
+
if (base.empty()) {
|
|
25
|
+
base = string.substr(index + 1, lastCharacter - index);
|
|
26
|
+
}
|
|
27
|
+
} else if (index == 0) {
|
|
28
|
+
if (lastCharacter < (string.length() - 1)) {
|
|
29
|
+
if (base.empty()) {
|
|
30
|
+
base = string.substr(0, lastCharacter + 1);
|
|
31
|
+
}
|
|
32
|
+
} else {
|
|
33
|
+
if (base.empty()) {
|
|
34
|
+
base = string;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
index--;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Basename matches count for more.
|
|
42
|
+
if (base == string) {
|
|
43
|
+
score *= 2;
|
|
44
|
+
} else if (!base.empty()) {
|
|
45
|
+
score += fuzzaldrin_score(base, query);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Shallow files are scored higher
|
|
49
|
+
const std::size_t segmentCount = slashCount + 1;
|
|
50
|
+
const std::size_t depth = std::max<std::size_t>(1, 10 - segmentCount);
|
|
51
|
+
score *= depth * 0.01;
|
|
52
|
+
return score;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
bool queryIsLastPathSegment(const std::string& string, const std::string& query) {
|
|
56
|
+
auto res = string[string.length() - query.length() - 1] == PathSeparator[0];
|
|
57
|
+
|
|
58
|
+
if (string[string.length() - query.length() - 1] == PathSeparator[0]) {
|
|
59
|
+
auto res2 = string.rfind(query) == (string.length() - query.length());
|
|
60
|
+
return string.rfind(query) == (string.length() - query.length());
|
|
61
|
+
}
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
float fuzzaldrin_score(const std::string& candidate, const std::string& query) {
|
|
66
|
+
std::string string = candidate;
|
|
67
|
+
|
|
68
|
+
if (string == query) {
|
|
69
|
+
return 1.0;
|
|
70
|
+
}
|
|
71
|
+
if (queryIsLastPathSegment(string, query)) {
|
|
72
|
+
return 1.0;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
float totalCharacterScore = 0.0;
|
|
76
|
+
const std::size_t queryLength = query.length();
|
|
77
|
+
const std::size_t stringLength = string.length();
|
|
78
|
+
|
|
79
|
+
std::size_t indexInQuery = 0;
|
|
80
|
+
std::size_t indexInString = 0;
|
|
81
|
+
|
|
82
|
+
while (indexInQuery < queryLength) {
|
|
83
|
+
char character = query[indexInQuery++];
|
|
84
|
+
std::size_t lowerCaseIndex = string.find(std::tolower(character));
|
|
85
|
+
std::size_t upperCaseIndex = string.find(std::toupper(character));
|
|
86
|
+
std::size_t minIndex = std::min(lowerCaseIndex, upperCaseIndex);
|
|
87
|
+
if (minIndex == std::string::npos) { minIndex = std::max(lowerCaseIndex, upperCaseIndex); }
|
|
88
|
+
indexInString = minIndex;
|
|
89
|
+
if (indexInString == std::string::npos) { return 0.0; }
|
|
90
|
+
|
|
91
|
+
float characterScore = 0.1;
|
|
92
|
+
|
|
93
|
+
// Same case bonus.
|
|
94
|
+
if (string[indexInString] == character) { characterScore += 0.1; }
|
|
95
|
+
|
|
96
|
+
if ((indexInString == 0) || (string[indexInString - 1] == PathSeparator[0])) {
|
|
97
|
+
// Start of string bonus
|
|
98
|
+
characterScore += 0.8;
|
|
99
|
+
} else if (string[indexInString - 1] == '-' || string[indexInString - 1] == '_' || string[indexInString - 1] == ' ') {
|
|
100
|
+
// Start of word bonus
|
|
101
|
+
characterScore += 0.7;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Trim string to after the current abbreviation match
|
|
105
|
+
string = string.substr(indexInString + 1);
|
|
106
|
+
totalCharacterScore += characterScore;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const float queryScore = totalCharacterScore / queryLength;
|
|
110
|
+
auto div = (queryLength / (float) stringLength);
|
|
111
|
+
return ((queryScore * (queryLength / (float) stringLength)) + queryScore) / 2.0;
|
|
112
|
+
}
|
package/src/memrchr.h
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/* memrchr -- find the last occurrence of a byte in a memory block
|
|
2
|
+
Copyright (C) 1991, 93, 96, 97, 99, 2000, 2012 Free Software Foundation, Inc.
|
|
3
|
+
This file is part of the GNU C Library.
|
|
4
|
+
Based on strlen implementation by Torbjorn Granlund (tege@sics.se),
|
|
5
|
+
with help from Dan Sahlin (dan@sics.se) and
|
|
6
|
+
commentary by Jim Blandy (jimb@ai.mit.edu);
|
|
7
|
+
adaptation to memchr suggested by Dick Karpinski (dick@cca.ucsf.edu),
|
|
8
|
+
and implemented by Roland McGrath (roland@ai.mit.edu).
|
|
9
|
+
The GNU C Library is free software; you can redistribute it and/or
|
|
10
|
+
modify it under the terms of the GNU Lesser General Public
|
|
11
|
+
License as published by the Free Software Foundation; either
|
|
12
|
+
version 2.1 of the License, or (at your option) any later version.
|
|
13
|
+
The GNU C Library is distributed in the hope that it will be useful,
|
|
14
|
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
15
|
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
|
16
|
+
Lesser General Public License for more details.
|
|
17
|
+
You should have received a copy of the GNU Lesser General Public
|
|
18
|
+
License along with the GNU C Library; if not, see
|
|
19
|
+
<http://www.gnu.org/licenses/>. */
|
|
20
|
+
|
|
21
|
+
#include <stdlib.h>
|
|
22
|
+
|
|
23
|
+
#ifdef HAVE_CONFIG_H
|
|
24
|
+
# include <config.h>
|
|
25
|
+
#endif
|
|
26
|
+
|
|
27
|
+
#undef __ptr_t
|
|
28
|
+
#define __ptr_t void *
|
|
29
|
+
|
|
30
|
+
#if defined _LIBC
|
|
31
|
+
# include <string.h>
|
|
32
|
+
# include <memcopy.h>
|
|
33
|
+
#endif
|
|
34
|
+
|
|
35
|
+
#if defined HAVE_LIMITS_H || defined _LIBC
|
|
36
|
+
# include <limits.h>
|
|
37
|
+
#endif
|
|
38
|
+
|
|
39
|
+
#define LONG_MAX_32_BITS 2147483647
|
|
40
|
+
|
|
41
|
+
#ifndef LONG_MAX
|
|
42
|
+
# define LONG_MAX LONG_MAX_32_BITS
|
|
43
|
+
#endif
|
|
44
|
+
|
|
45
|
+
#include <sys/types.h>
|
|
46
|
+
|
|
47
|
+
/* Search no more than N bytes of S for C. */
|
|
48
|
+
inline __ptr_t memrchr(const __ptr_t s, int c_in, size_t n)
|
|
49
|
+
{
|
|
50
|
+
const unsigned char *char_ptr;
|
|
51
|
+
const unsigned long int *longword_ptr;
|
|
52
|
+
unsigned long int longword, magic_bits, charmask;
|
|
53
|
+
unsigned char c;
|
|
54
|
+
|
|
55
|
+
c = (unsigned char) c_in;
|
|
56
|
+
|
|
57
|
+
/* Handle the last few characters by reading one character at a time.
|
|
58
|
+
Do this until CHAR_PTR is aligned on a longword boundary. */
|
|
59
|
+
for (char_ptr = (const unsigned char *) s + n;
|
|
60
|
+
n > 0 && ((unsigned long int) char_ptr
|
|
61
|
+
& (sizeof (longword) - 1)) != 0;
|
|
62
|
+
--n)
|
|
63
|
+
if (*--char_ptr == c)
|
|
64
|
+
return (__ptr_t) char_ptr;
|
|
65
|
+
|
|
66
|
+
/* All these elucidatory comments refer to 4-byte longwords,
|
|
67
|
+
but the theory applies equally well to 8-byte longwords. */
|
|
68
|
+
|
|
69
|
+
longword_ptr = (const unsigned long int *) char_ptr;
|
|
70
|
+
|
|
71
|
+
/* Bits 31, 24, 16, and 8 of this number are zero. Call these bits
|
|
72
|
+
the "holes." Note that there is a hole just to the left of
|
|
73
|
+
each byte, with an extra at the end:
|
|
74
|
+
bits: 01111110 11111110 11111110 11111111
|
|
75
|
+
bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD
|
|
76
|
+
The 1-bits make sure that carries propagate to the next 0-bit.
|
|
77
|
+
The 0-bits provide holes for carries to fall into. */
|
|
78
|
+
|
|
79
|
+
if (sizeof (longword) != 4 && sizeof (longword) != 8)
|
|
80
|
+
abort ();
|
|
81
|
+
|
|
82
|
+
#if LONG_MAX <= LONG_MAX_32_BITS
|
|
83
|
+
magic_bits = 0x7efefeff;
|
|
84
|
+
#else
|
|
85
|
+
magic_bits = ((unsigned long int) 0x7efefefe << 32) | 0xfefefeff;
|
|
86
|
+
#endif
|
|
87
|
+
|
|
88
|
+
/* Set up a longword, each of whose bytes is C. */
|
|
89
|
+
charmask = c | (c << 8);
|
|
90
|
+
charmask |= charmask << 16;
|
|
91
|
+
#if LONG_MAX > LONG_MAX_32_BITS
|
|
92
|
+
charmask |= charmask << 32;
|
|
93
|
+
#endif
|
|
94
|
+
|
|
95
|
+
/* Instead of the traditional loop which tests each character,
|
|
96
|
+
we will test a longword at a time. The tricky part is testing
|
|
97
|
+
if *any of the four* bytes in the longword in question are zero. */
|
|
98
|
+
while (n >= sizeof (longword))
|
|
99
|
+
{
|
|
100
|
+
/* We tentatively exit the loop if adding MAGIC_BITS to
|
|
101
|
+
LONGWORD fails to change any of the hole bits of LONGWORD.
|
|
102
|
+
1) Is this safe? Will it catch all the zero bytes?
|
|
103
|
+
Suppose there is a byte with all zeros. Any carry bits
|
|
104
|
+
propagating from its left will fall into the hole at its
|
|
105
|
+
least significant bit and stop. Since there will be no
|
|
106
|
+
carry from its most significant bit, the LSB of the
|
|
107
|
+
byte to the left will be unchanged, and the zero will be
|
|
108
|
+
detected.
|
|
109
|
+
2) Is this worthwhile? Will it ignore everything except
|
|
110
|
+
zero bytes? Suppose every byte of LONGWORD has a bit set
|
|
111
|
+
somewhere. There will be a carry into bit 8. If bit 8
|
|
112
|
+
is set, this will carry into bit 16. If bit 8 is clear,
|
|
113
|
+
one of bits 9-15 must be set, so there will be a carry
|
|
114
|
+
into bit 16. Similarly, there will be a carry into bit
|
|
115
|
+
24. If one of bits 24-30 is set, there will be a carry
|
|
116
|
+
into bit 31, so all of the hole bits will be changed.
|
|
117
|
+
The one misfire occurs when bits 24-30 are clear and bit
|
|
118
|
+
31 is set; in this case, the hole at bit 31 is not
|
|
119
|
+
changed. If we had access to the processor carry flag,
|
|
120
|
+
we could close this loophole by putting the fourth hole
|
|
121
|
+
at bit 32!
|
|
122
|
+
So it ignores everything except 128's, when they're aligned
|
|
123
|
+
properly.
|
|
124
|
+
3) But wait! Aren't we looking for C, not zero?
|
|
125
|
+
Good point. So what we do is XOR LONGWORD with a longword,
|
|
126
|
+
each of whose bytes is C. This turns each byte that is C
|
|
127
|
+
into a zero. */
|
|
128
|
+
|
|
129
|
+
longword = *--longword_ptr ^ charmask;
|
|
130
|
+
|
|
131
|
+
/* Add MAGIC_BITS to LONGWORD. */
|
|
132
|
+
if ((((longword + magic_bits)
|
|
133
|
+
|
|
134
|
+
/* Set those bits that were unchanged by the addition. */
|
|
135
|
+
^ ~longword)
|
|
136
|
+
|
|
137
|
+
/* Look at only the hole bits. If any of the hole bits
|
|
138
|
+
are unchanged, most likely one of the bytes was a
|
|
139
|
+
zero. */
|
|
140
|
+
& ~magic_bits) != 0)
|
|
141
|
+
{
|
|
142
|
+
/* Which of the bytes was C? If none of them were, it was
|
|
143
|
+
a misfire; continue the search. */
|
|
144
|
+
|
|
145
|
+
const unsigned char *cp = (const unsigned char *) longword_ptr;
|
|
146
|
+
|
|
147
|
+
#if LONG_MAX > 2147483647
|
|
148
|
+
if (cp[7] == c)
|
|
149
|
+
return (__ptr_t) &cp[7];
|
|
150
|
+
if (cp[6] == c)
|
|
151
|
+
return (__ptr_t) &cp[6];
|
|
152
|
+
if (cp[5] == c)
|
|
153
|
+
return (__ptr_t) &cp[5];
|
|
154
|
+
if (cp[4] == c)
|
|
155
|
+
return (__ptr_t) &cp[4];
|
|
156
|
+
#endif
|
|
157
|
+
if (cp[3] == c)
|
|
158
|
+
return (__ptr_t) &cp[3];
|
|
159
|
+
if (cp[2] == c)
|
|
160
|
+
return (__ptr_t) &cp[2];
|
|
161
|
+
if (cp[1] == c)
|
|
162
|
+
return (__ptr_t) &cp[1];
|
|
163
|
+
if (cp[0] == c)
|
|
164
|
+
return (__ptr_t) cp;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
n -= sizeof (longword);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
char_ptr = (const unsigned char *) longword_ptr;
|
|
171
|
+
|
|
172
|
+
while (n-- > 0)
|
|
173
|
+
{
|
|
174
|
+
if (*--char_ptr == c)
|
|
175
|
+
return (__ptr_t) char_ptr;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return 0;
|
|
179
|
+
}
|