1 /* 2 * Some simple utility functions. 3 * 4 * Copyright (C) 2018 Paul Boddie <paul@boddie.org.uk> 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License as published by 8 * the Free Software Foundation, either version 3 of the License, or 9 * (at your option) any later version. 10 * 11 * This program is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU General Public License for more details. 15 * 16 * You should have received a copy of the GNU General Public License 17 * along with this program. If not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 #include "utils.h" 21 22 23 24 /* A simple busy wait involving a register-based counter. */ 25 26 void wait(uint32_t delay) 27 { 28 uint32_t counter = delay; 29 30 if (!delay) return; 31 while (counter--) __asm__(""); /* retain loop */ 32 } 33 34 /* Wrap a pointer within the given limits. */ 35 36 uint8_t *wrap_pointer(uint8_t *ptr, uint8_t *lower, uint8_t *upper) 37 { 38 uint32_t size = upper - lower; 39 40 if (ptr < lower) 41 return upper - (lower - ptr) % size; 42 else if (ptr >= upper) 43 return lower + (ptr - upper) % size; 44 else 45 return ptr; 46 } 47 48 /* Wrap a value within the bounds [0, limit). */ 49 50 int wrap_value(int value, int limit) 51 { 52 if (value < 0) 53 return limit - (-value % limit); 54 else if (value >= limit) 55 return (value - limit) % limit; 56 else 57 return value; 58 }