Reactos
at master 80 lines 2.4 kB view raw
1// 2// lfind.cpp 3// 4// Copyright (c) Microsoft Corporation. All rights reserved. 5// 6// Defines _lfind(), which performs a linear search over an array. 7// 8#include <corecrt_internal.h> 9#include <search.h> 10 11#ifdef _M_CEE 12 #define __fileDECL __clrcall 13#else 14 #define __fileDECL __cdecl 15#endif 16 17 18 19#ifdef __USE_CONTEXT 20 #define __COMPARE(context, p1, p2) (*compare)(context, p1, p2) 21#else 22 #define __COMPARE(context, p1, p2) (*compare)(p1, p2) 23#endif 24 25// Performs a linear search over the array, looking for the value 'key' in an 26// array of 'num' elements of 'width' bytes in size. Returns a pointer to the 27// matching element if found. Otherwise, returns nullptr. 28// 29// Parameters: 30// * key: The key for which to search 31// * base: A pointer to the initial element of the array to be searched 32// * num: The number of elements in the array. 33// * width: The size of each element, in bytes. 34// * comp: Pointer to a function returning analog of strcmp for strings, but 35// supplied by the caller for comparing the array elements. It 36// accepts two pointers to elements; returns negative if 1 < 2; 37// zero if 1 == 2, and positive if 1 > 2. 38#ifndef _M_CEE 39extern "C" 40#endif 41#ifdef __USE_CONTEXT 42void* __fileDECL _lfind_s( 43 void const* const key, 44 void const* const base, 45 unsigned int* const num, 46 size_t const width, 47 int (__fileDECL* const compare)(void*, void const*, void const*), 48 void* const context 49 ) 50#else // __USE_CONTEXT 51void* __fileDECL _lfind( 52 void const* const key, 53 void const* const base, 54 unsigned int* const num, 55 unsigned int const width, 56 int (__fileDECL* const compare)(void const*, void const*) 57 ) 58#endif // __USE_CONTEXT 59{ 60 _VALIDATE_RETURN(key != nullptr, EINVAL, nullptr); 61 _VALIDATE_RETURN(num != nullptr, EINVAL, nullptr); 62 _VALIDATE_RETURN(base != nullptr || *num == 0, EINVAL, nullptr); 63 _VALIDATE_RETURN(width > 0, EINVAL, nullptr); 64 _VALIDATE_RETURN(compare != nullptr, EINVAL, nullptr); 65 66 char const* const first = static_cast<char const*>(base); 67 char const* const last = first + *num * width; 68 69 for (char const* p = first; p != last; p += width) 70 { 71 if (__COMPARE(context, key, const_cast<char*>(p)) == 0) 72 { 73 return const_cast<char*>(p); 74 } 75 } 76 77 return nullptr; 78} 79 80#undef __COMPARE