memset.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. ** Copyright 2005, Michael Noisternig. All rights reserved.
  3. ** Copyright 2001, Travis Geiselbrecht. All rights reserved.
  4. ** Distributed under the terms of the NewOS License.
  5. */
  6. /*
  7. * Copyright (c) 2008 Travis Geiselbrecht
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining
  10. * a copy of this software and associated documentation files
  11. * (the "Software"), to deal in the Software without restriction,
  12. * including without limitation the rights to use, copy, modify, merge,
  13. * publish, distribute, sublicense, and/or sell copies of the Software,
  14. * and to permit persons to whom the Software is furnished to do so,
  15. * subject to the following conditions:
  16. *
  17. * The above copyright notice and this permission notice shall be
  18. * included in all copies or substantial portions of the Software.
  19. *
  20. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  23. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  24. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  25. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  26. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. */
  28. #include <string.h>
  29. #include <sys/types.h>
  30. void *
  31. memset(void *s, int c, size_t count)
  32. {
  33. char *xs = (char *) s;
  34. size_t len = (-(size_t)s) & (sizeof(size_t)-1);
  35. int cc = c & 0xff;
  36. if ( count > len ) {
  37. count -= len;
  38. cc |= cc << 8;
  39. cc |= cc << 16;
  40. // write to non-aligned memory byte-wise
  41. for ( ; len > 0; len-- )
  42. *xs++ = c;
  43. // write to aligned memory dword-wise
  44. for ( len = count/sizeof(size_t); len > 0; len-- ) {
  45. *((size_t *)xs) = cc;
  46. xs += sizeof(size_t);
  47. }
  48. count &= sizeof(size_t)-1;
  49. }
  50. // write remaining bytes
  51. for ( ; count > 0; count-- )
  52. *xs++ = c;
  53. return s;
  54. }