memmove.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright Institute of Communication and Computer Systems (ICCS)
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. /**
  18. * @file memmove.c
  19. * @author Ioannis Koutras
  20. * @date October 2012
  21. * @brief memmove() implementation
  22. */
  23. #include "memmove.h"
  24. /** Copies n bytes from string s2 to string s1. The two strings may overlap; the
  25. * copy is always done in a non-destructive manner.
  26. *
  27. * Original code at:
  28. * http://discuss.joelonsoftware.com/default.asp?interview.11.437419.13
  29. */
  30. void * memmove(void *destination, void *source, size_t count) {
  31. size_t i = 0;
  32. char *src = (char *)source;
  33. char *dest = (char *)destination;
  34. void * ptr = dest;
  35. char * src_beg = src;
  36. char * src_end = src_beg + count;
  37. char * dest_beg = dest;
  38. char * dest_end = dest_beg + count;
  39. if(src == dest) {
  40. return ptr;
  41. }
  42. if((dest_beg >= src_beg && dest_beg <= src_end) || (dest_end >= src_beg && dest_end <= src_end)) {
  43. //Copy from higher addresses to lower addresses
  44. for( i = count ; i > 0 ; i--)
  45. {
  46. *(dest + i) = *(src + i);
  47. }
  48. return ptr;
  49. }
  50. //No overlap, copy from lower addresses to higher addresses
  51. for( i = 0 ; i < count ; i++)
  52. {
  53. *(dest + i) = *(src + i);
  54. }
  55. return ptr;
  56. }