#include <string.h> //This is where memcpy() hangs out. I know! I know!
///memcopyfill: Fills a block of memory with a specified pattern. from
///The thetarget addressblock starts at pToFill and extends for pToFillSize bytes.
///The source pattern starts at pFillWith and extends for pFillWithSize bytes.
///Will fill the whole buffer including a trailing partial pattern at the end (if necesssary).
///pFillWithSize must not be 0. pFillWith must not be NULL.
///If Either pToFill is NULL or pToFillSize is 0, does nothing and returns without error.
///The area to fill and pattern must not overlap or behaviour is undefined.
///Returns 0 on success and non-zero on error.
intvoid memcopyfill(void*const pToFill,const size_t pToFillSize,const void*const pFillWith,const size_t pFillWithSize){
if(pToFill==NULL||pToFillSize==0){
return 0; return;//Nothing to do.
}
if(pFillWith==NULL||pFillWithSize==0){
return 1; return;//ERROR! Something to fillCan anddo nothing to fill it with...
}
if(pToFillSize<=pFillWithSizepToFillSize<pFillWithSize){
memcpy(pToFill,pFillWith,pToFillSize);
return 0; return;//Short buffer.
}
//The to buffer is bigger so we start with a full copy of pattern.
memcpy(pToFill,pFillWith,pFillWithSize);
//Now we keep doubling the copies by copying and copying from the target onto itself.
char*lFillFrom=((char*)pToFill)+pFillWithSize;
size_t lFilledSoFar=pFillWithSize;
char*lFillEnd=((char*)pToFill)+pToFillSize;
while(lFilledSoFar<(lFillEnd-lFillFrom)){//Overflow safe.
memcpy(lFillFrom,pToFill,lFilledSoFar);
lFillFrom+=lFilledSoFar;
lFilledSoFar=lFilledSoFar<<1;//Doubling....
}
//No we can fill the endrestend of the buffer in one final step. Could be half the job.
memcpy(lFillFrom,pToFill,pToFillSize-lFilledSoFar);
return 0;
}
Can it be improvedbettered?
One use is to fill an array with a default structure. If
If that is the purpose you don't need the initial fannying about with the short buffer special case.
I half remember one where it was 0xFFF...FF and that was clever because the hardware could detect overflow easily and handle all sorts of wrap-around errors gracefully. I'm damned if I can remember what it was. It may have been a hypothetical example to show why standards should give implementers freedom.
Versioning: This is V1.1 19-Dec-2014 including improvements suggested by @Edward - See answer below.