// Copyright 2025 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.skyframe.serialization.analysis;

import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.io.OutputStream;

/**
 * A utility class to handle the magic bytes used to identify different versions of the wire format.
 *
 * <p>The magic byte sequence is {@code 0x8000}. This specific sequence is chosen because it can
 * never be produced by a CodedOutputStream when writing a valid varint integer. Varint encoding
 * uses the most significant bit (MSB) of a byte to indicate if more bytes follow. A byte of {@code
 * 0x80} has its MSB set, implying more bytes are coming. However, a following byte of {@code 0x00}
 * as the final byte of a varint is not a canonical representation and is not generated by
 * CodedOutputStream. This makes {@code 0x8000} a safe and unique marker.
 */
final class MagicBytes {
  /** The magic byte sequence (0x8000) used to identify the new wire format. */
  private static final byte[] magicBytes = new byte[] {(byte) 0x80, 0x00};

  private MagicBytes() {}

  /**
   * Writes the magic byte sequence to the given CodedOutputStream.
   *
   * @param stream the CodedOutputStream to write to.
   * @throws IOException if an I/O error occurs.
   */
  public static void writeMagicBytes(final OutputStream stream) throws IOException {
    stream.write(magicBytes);
  }

  /**
   * Checks if the beginning of the byte array contains the magic byte sequence.
   *
   * @param bytes the byte array to read from.
   * @return {@code true} if the array starts with the magic bytes, {@code false} otherwise.
   */
  public static boolean hasMagicBytes(byte[] bytes) {
    return bytes.length >= 2 && bytes[0] == magicBytes[0] && bytes[1] == magicBytes[1];
  }

  @VisibleForTesting
  public static byte[] magicBytes() {
    return magicBytes;
  }
}
