View Javadoc
1   /*
2    * Copyright (c) 2002-2025 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://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  package org.htmlunit.util;
16  
17  import java.nio.ByteBuffer;
18  import java.nio.CharBuffer;
19  import java.nio.charset.Charset;
20  import java.nio.charset.CharsetDecoder;
21  import java.nio.charset.CharsetEncoder;
22  import java.nio.charset.CoderResult;
23  import java.nio.charset.StandardCharsets;
24  
25  /**
26   * Simple implementation of the 'x-user-defined' {@link Charset}.
27   * @author Ronald Brill
28   *
29   */
30  public final class XUserDefinedCharset extends Charset {
31  
32      /** The single instance. */
33      public static final String NAME = "x-user-defined";
34  
35      /** The single instance. */
36      public static final XUserDefinedCharset INSTANCE = new XUserDefinedCharset();
37  
38      private XUserDefinedCharset() {
39          super(NAME, new String[0]);
40      }
41  
42      @Override
43      public boolean contains(final Charset charset) {
44          return StandardCharsets.US_ASCII.equals(charset);
45      }
46  
47      @Override
48      public CharsetDecoder newDecoder() {
49          return new XUserDefinedDecoder();
50      }
51  
52      @Override
53      public CharsetEncoder newEncoder() {
54          // not implemented for now
55          return null;
56      }
57  
58      private static final class XUserDefinedDecoder extends CharsetDecoder {
59          XUserDefinedDecoder() {
60              super(XUserDefinedCharset.INSTANCE, 1, 1);
61          }
62  
63          @Override
64          protected CoderResult decodeLoop(final ByteBuffer in, final CharBuffer out) {
65              while (true) {
66                  if (!in.hasRemaining()) {
67                      return CoderResult.UNDERFLOW;
68                  }
69                  if (!out.hasRemaining()) {
70                      return CoderResult.OVERFLOW;
71                  }
72                  final byte b = in.get();
73                  if (b >= 0) {
74                      out.append((char) b);
75                  }
76                  else {
77                      out.append((char) (0xF700 + (b & 0xFF)));
78                  }
79              }
80          }
81      }
82  }