1#!/bin/sh
2#
3# Copyright (c) 2016 Ingo Schwarze <schwarze@openbsd.org>
4#
5# Permission to use, copy, modify, and distribute this software for any
6# purpose with or without fee is hereby granted, provided that the above
7# copyright notice and this permission notice appear in all copies.
8#
9# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
17unset LC_ALL
18
19test_wc()
20{
21	stdin=$1
22	expected=$2
23	export LC_CTYPE=en_US.UTF-8
24	result=`echo -n "$stdin" | wc -lwm`
25	if [ "$result" != "${expected}" ]; then
26		echo "echo -n \"$stdin\" | wc -lwm"
27		echo -n "$stdin" | hexdump -C
28		echo "expected: \"$expected\""
29		echo "result: \"$result\""
30		exit 1;
31	fi
32
33	if [ -n "$3" ]; then
34		expected=$3
35	fi
36	result=`echo -n "$stdin" | wc`
37	if [ "$result" != "${expected}" ]; then
38		echo "echo -n \"$stdin\" | wc"
39		echo -n "$stdin" | hexdump -C
40		echo "expected: \"$expected\""
41		echo "result: \"$result\""
42		exit 1;
43	fi
44
45	export LC_CTYPE=C
46	result=`echo -n "$stdin" | wc -lwm`
47	if [ "$result" != "${expected}" ]; then
48		echo "[C] echo -n \"$stdin\" | wc -lwm"
49		echo -n "$stdin" | hexdump -C
50		echo "expected: \"$expected\""
51		echo "result: \"$result\""
52		exit 1;
53	fi
54}
55
56# single byte characters
57test_wc "two lines\nand five words\n" "       2       5      25"
58
59# non-printable characters
60test_wc "a\033b\000c\n" "       1       1       6"
61
62# multibyte characters
63test_wc "ax\0314\0200b\n" "       1       1       5" "       1       1       6"
64test_wc "a\0354\0277\0277b\n" "       1       1       4" \
65	"       1       1       6"
66
67# invalid bytes
68test_wc "a\0377\0277c\n" "       1       1       5"
69
70# edge cases
71test_wc "" "       0       0       0"
72test_wc " " "       0       0       1"
73test_wc "x" "       0       1       1"
74test_wc "\0303\0244" "       0       1       1" "       0       1       2"
75
76exit 0
77