1 /* Count characters in UTF-8 string. 2 Copyright (C) 2007, 2009-2021 Free Software Foundation, Inc. 3 Written by Bruno Haible <bruno@clisp.org>, 2007. 4 5 This file is free software. 6 It is dual-licensed under "the GNU LGPLv3+ or the GNU GPLv2+". 7 You can redistribute it and/or modify it under either 8 - the terms of the GNU Lesser General Public License as published 9 by the Free Software Foundation; either version 3, or (at your 10 option) any later version, or 11 - the terms of the GNU General Public License as published by the 12 Free Software Foundation; either version 2, or (at your option) 13 any later version, or 14 - the same dual license "the GNU LGPLv3+ or the GNU GPLv2+". 15 16 This file is distributed in the hope that it will be useful, 17 but WITHOUT ANY WARRANTY; without even the implied warranty of 18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 19 Lesser General Public License and the GNU General Public License 20 for more details. 21 22 You should have received a copy of the GNU Lesser General Public 23 License and of the GNU General Public License along with this 24 program. If not, see <https://www.gnu.org/licenses/>. */ 25 26 #include <config.h> 27 28 /* Specification. */ 29 #include "unistr.h" 30 31 size_t 32 u8_mbsnlen (const uint8_t *s, size_t n) /* */ 33 { 34 size_t characters; 35 36 characters = 0; 37 while (n > 0) 38 { 39 ucs4_t uc; 40 int count = u8_mbtoucr (&uc, s, n); 41 characters++; 42 if (count == -2) 43 break; 44 if (count < 0) 45 count = u8_mbtouc (&uc, s, n); 46 else if (count == 0) 47 count = 1; 48 s += count; 49 n -= count; 50 } 51 return characters; 52 }