1
2//===-- Unittests for swab ------------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#include "src/unistd/swab.h"
11
12#include "src/string/string_utils.h"
13#include "test/UnitTest/Test.h"
14
15TEST(LlvmLibcSwabTest, NegativeSizeIsNoOp) {
16 const char *from = "abc";
17 char to[4] = {'x', 'y', 'z', '\0'};
18 LIBC_NAMESPACE::swab(from, to, n: -1);
19 ASSERT_STREQ(to, "xyz");
20}
21
22TEST(LlvmLibcSwabTest, ZeroSizeIsNoOp) {
23 const char *from = "abc";
24 char to[4] = {'x', 'y', 'z', '\0'};
25 LIBC_NAMESPACE::swab(from, to, n: 0);
26 ASSERT_STREQ(to, "xyz");
27}
28
29TEST(LlvmLibcSwabTest, SingleByteIsNoOp) {
30 char from[] = {'a'};
31 char to[4] = {'x', 'y', 'z', '\0'};
32 LIBC_NAMESPACE::swab(from, to, n: sizeof(from));
33 ASSERT_STREQ(to, "xyz");
34}
35
36TEST(LlvmLibcSwabTest, NullPtrsAreNotDeRefedIfNIsLessThanTwo) {
37 // This test passes if a crash does not happen
38 LIBC_NAMESPACE::swab(from: nullptr, to: nullptr, n: -1);
39 LIBC_NAMESPACE::swab(from: nullptr, to: nullptr, n: 0);
40 LIBC_NAMESPACE::swab(from: nullptr, to: nullptr, n: 1);
41}
42
43TEST(LlvmLibcSwabTest, BytesAreSwappedWithEvenN) {
44 {
45 const char *from = "ab";
46 char to[3] = {};
47 LIBC_NAMESPACE::swab(from, to,
48 LIBC_NAMESPACE::internal::string_length(src: from));
49 ASSERT_STREQ(to, "ba");
50 }
51 {
52 const char *from = "abcd";
53 char to[5] = {};
54 LIBC_NAMESPACE::swab(from, to,
55 LIBC_NAMESPACE::internal::string_length(src: from));
56 ASSERT_STREQ(to, "badc");
57 }
58 {
59 const char *from = "aAaAaA";
60 char to[7] = {};
61 LIBC_NAMESPACE::swab(from, to,
62 LIBC_NAMESPACE::internal::string_length(src: from));
63 ASSERT_STREQ(to, "AaAaAa");
64 }
65}
66
67TEST(LlvmLibcSwabTest, LastByteIgnoredWithOddN) {
68 {
69 const char *from = "aba";
70 char to[3] = {};
71 LIBC_NAMESPACE::swab(from, to,
72 LIBC_NAMESPACE::internal::string_length(src: from));
73 ASSERT_STREQ(to, "ba");
74 }
75 {
76 const char *from = "abcde";
77 char to[5] = {};
78 LIBC_NAMESPACE::swab(from, to,
79 LIBC_NAMESPACE::internal::string_length(src: from));
80 ASSERT_STREQ(to, "badc");
81 }
82 {
83 const char *from = "aAaAaAx";
84 char to[7] = {};
85 LIBC_NAMESPACE::swab(from, to,
86 LIBC_NAMESPACE::internal::string_length(src: from));
87 ASSERT_STREQ(to, "AaAaAa");
88 }
89}
90

source code of libc/test/src/unistd/swab_test.cpp