1 //////////////////////////////////////////////////////////////////////////////// 2 // checkstyle: Checks Java source code for adherence to a set of rules. 3 // Copyright (C) 2001-2019 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.getProperty("line.separator")); 49 50 /** The line separator representation. */ 51 private final byte[] lineSeparator; 52 53 /** 54 * Creates a new {@code LineSeparatorOption} instance. 55 * @param sep the line separator, e.g. "\r\n" 56 */ 57 LineSeparatorOption(String sep) { 58 lineSeparator = sep.getBytes(StandardCharsets.US_ASCII); 59 } 60 61 /** 62 * Checks that bytes is equal to the byte representation of this line separator. 63 * @param bytes a bytes array to check 64 * @return if bytes is equal to the byte representation 65 * of this line separator 66 */ 67 public boolean matches(byte... bytes) { 68 final boolean result; 69 if (this == LF_CR_CRLF) { 70 // this silently assumes LF and CR are of length 1 71 // CRLF always matches LF, so CRLF isn't tested 72 result = LF.matches(Arrays.copyOfRange(bytes, 1, 2)) 73 || CR.matches(Arrays.copyOfRange(bytes, 1, 2)); 74 } 75 else { 76 result = Arrays.equals(bytes, lineSeparator); 77 } 78 return result; 79 } 80 81 /** 82 * Returns length of file separator in bytes. 83 * @return the length of the file separator in bytes, 84 * e.g. 1 for CR, 2 for CRLF, ... 85 */ 86 public int length() { 87 return lineSeparator.length; 88 } 89 90 }