1/*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include <stdbool.h>
17#include "endian_internal.h"
18
19#define B_L_SWAP16(A)  ((((uint16_t)(A) & 0xff00) >> 8) | (((uint16_t)(A) & 0x00ff) << 8))
20#define B_L_SWAP32(A)  ((((uint32_t)(A) & 0xff000000) >> 24) | (((uint32_t)(A) & 0x00ff0000) >> 8) | \
21    (((uint32_t)(A) & 0x0000ff00) << 8) | (((uint32_t)(A) & 0x000000ff) << 24))
22
23static bool CheckEndian(void);
24
25static bool CheckEndian(void)
26{
27    union {
28        int32_t i;
29        uint8_t s[4];
30    } c;
31    c.i = 0x12345678;
32
33    return (c.s[0] == 0x12);
34}
35
36uint32_t HtonlInter(uint32_t h)
37{
38    return CheckEndian() ? h : B_L_SWAP32(h);
39}
40
41uint32_t NtohlInter(uint32_t n)
42{
43    return CheckEndian() ? n : B_L_SWAP32(n);
44}
45
46uint16_t HtonsInter(uint16_t h)
47{
48    return CheckEndian() ? h : B_L_SWAP16(h);
49}
50
51uint16_t NtohsInter(uint16_t n)
52{
53    return CheckEndian() ? n : B_L_SWAP16(n);
54}