1 ///////////////////////////////////////////////////////////////////////////////////////////////
2 // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3 // Copyright (C) 2001-2026 the original author or authors.
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 ///////////////////////////////////////////////////////////////////////////////////////////////
19
20 package com.puppycrawl.tools.checkstyle.checks;
21
22 import java.nio.charset.StandardCharsets;
23 import java.util.Arrays;
24
25 /**
26 * Represents the options for line separator settings.
27 *
28 * @see NewlineAtEndOfFileCheck
29 */
30 public enum LineSeparatorOption {
31
32 /** Windows-style line separators. */
33 CRLF("\r\n"),
34
35 /** Mac-style line separators. */
36 CR("\r"),
37
38 /** Unix-style line separators. */
39 LF("\n"),
40
41 /**
42 * Matches CR, LF and CRLF line separators.
43 * Only the length is used - the actual value is ignored.
44 */
45 LF_CR_CRLF("#"),
46
47 /** System default line separators. */
48 SYSTEM(System.lineSeparator());
49
50 /** The line separator representation. */
51 private final String lineSeparator;
52
53 /**
54 * Creates a new {@code LineSeparatorOption} instance.
55 *
56 * @param sep the line separator, e.g. "\r\n"
57 */
58 LineSeparatorOption(String sep) {
59 lineSeparator = sep;
60 }
61
62 /**
63 * Checks that bytes is equal to the byte representation of this line separator.
64 *
65 * @param bytes a bytes array to check
66 * @return if bytes is equal to the byte representation of this line separator
67 */
68 public boolean matches(byte... bytes) {
69 final boolean result;
70 if (this == LF_CR_CRLF) {
71 // this silently assumes LF and CR are of length 1
72 // CRLF always matches LF, so CRLF isn't tested
73 result = LF.matches(bytes) || CR.matches(bytes);
74 }
75 else {
76 result = Arrays.equals(
77 bytes,
78 lineSeparator.getBytes(StandardCharsets.US_ASCII)
79 );
80 }
81 return result;
82 }
83
84 /**
85 * Returns length of file separator in bytes.
86 *
87 * @return the length of the file separator in bytes,
88 * e.g. 1 for CR, 2 for CRLF, ...
89 */
90 public int length() {
91 return lineSeparator.length();
92 }
93
94 }