File: reverse.c

package info (click to toggle)
ghc 9.10.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 168,924 kB
  • sloc: haskell: 713,548; ansic: 84,223; cpp: 30,255; javascript: 9,003; sh: 7,870; fortran: 3,527; python: 3,228; asm: 2,523; makefile: 2,326; yacc: 1,570; lisp: 532; xml: 196; perl: 111; csh: 2
file content (42 lines) | stat: -rw-r--r-- 1,021 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
 * Copyright (c) 2021 Andrew Lelechenko <andrew.lelechenko@gmail.com>
 */

#include <string.h>
#include <stdint.h>

/*
  _hs_text_reverse takes a UTF-8 encoded buffer, specified by (src0, off, len),
  and reverses it, writing output starting from dst0.

  The input buffer (src0, off, len) must be a valid UTF-8 sequence,
  this condition is not checked.
*/
void _hs_text_reverse(uint8_t *dst0, const uint8_t *src0, size_t off, size_t len)
{
  const uint8_t *src = src0 + off;
  const uint8_t *srcend = src + len;
  uint8_t *dst = dst0 + len - 1;

  while (src < srcend){
    uint8_t leadByte = *src++;
    if (leadByte < 0x80){
      *dst-- = leadByte;
    } else if (leadByte < 0xe0){
      *(dst-1) = leadByte;
      *dst     = *src++;
      dst-=2;
    } else if (leadByte < 0xf0){
      *(dst-2) = leadByte;
      *(dst-1) = *src++;
      *dst     = *src++;
      dst-=3;
    } else {
      *(dst-3) = leadByte;
      *(dst-2) = *src++;
      *(dst-1) = *src++;
      *dst     = *src++;
      dst-=4;
    }
  }
}