/*
 * Copyright (C) 2019 Collabora, Ltd.
 * SPDX-License-Identifier: MIT
 */

#include "pan_util.h"
#include <stdio.h>

/* Translate a PIPE swizzle quad to a 12-bit Mali swizzle code. PIPE
 * swizzles line up with Mali swizzles for the XYZW01, but PIPE swizzles have
 * an additional "NONE" field that we have to mask out to zero. Additionally,
 * PIPE swizzles are sparse but Mali swizzles are packed */

unsigned
pan_translate_swizzle_4(const unsigned char swizzle[4])
{
   unsigned out = 0;

   for (unsigned i = 0; i < 4; ++i) {
      assert(swizzle[i] <= PIPE_SWIZZLE_1);
      out |= (swizzle[i] << (3 * i));
   }

   return out;
}

void
pan_invert_swizzle(const unsigned char *in, unsigned char *out)
{
   /* First, default to all zeroes, both to prevent uninitialized junk
      and to provide a known baseline so we can tell when components
      have been modified
    */

   for (unsigned c = 0; c < 4; ++c)
      out[c] = PIPE_SWIZZLE_0;

   /* Now "do" what the swizzle says */

   for (unsigned c = 0; c < 4; ++c) {
      unsigned char i = in[c];

      /* Who cares? */
      assert(PIPE_SWIZZLE_X == 0);
      if (i > PIPE_SWIZZLE_W)
         continue;

      /* Invert (only if we haven't already applied) */
      unsigned idx = i - PIPE_SWIZZLE_X;
      if (out[idx] == PIPE_SWIZZLE_0)
         out[idx] = PIPE_SWIZZLE_X + c;
   }
}
