/*
 * (C) Copyright IBM Corp. 2002
 */
//$Id: Conversions.java,v 1.3 2004/01/28 22:08:29 pmcgache Exp $

package s3.core.services.memory.JMTk;

import ovm.core.services.memory.VM_Address;
import ovm.core.services.memory.VM_Word;
import s3.core.services.memory.vmInterface.Constants;
import s3.core.services.memory.vmInterface.VM_Interface;
public class Conversions implements Constants, VM_Uninterruptible {

  public static VM_Word roundDownMB (VM_Word bytes) {
    // ovm.core.execution.Native.print_string("\nRounding down ");
    //ovm.core.execution.Native.print_int(bytes.asInt());
    VM_Word mask = VM_Word.fromInt(1).shiftL(LOG_BYTES_IN_MBYTE).sub(VM_Word.fromInt(1)).invert();
    //ovm.core.execution.Native.print_string(". result: ");
    //ovm.core.execution.Native.print_int(bytes.and(mask).asInt());
    return bytes.and(mask);
  }

  // Round up (if necessary)
  //
  public static int MBToPages(int megs) {
    if (VMResource.LOG_BYTES_IN_PAGE <= LOG_BYTES_IN_MBYTE)
      return (megs << (LOG_BYTES_IN_MBYTE - VMResource.LOG_BYTES_IN_PAGE));
    else
      return (megs + ((VMResource.BYTES_IN_PAGE >>> LOG_BYTES_IN_MBYTE) - 1)) >>> (VMResource.LOG_BYTES_IN_PAGE - LOG_BYTES_IN_MBYTE);
  }

  public static int bytesToMmapChunksUp(int bytes) {
    return (bytes + (LazyMmapper.MMAP_CHUNK_SIZE - 1)) >>> LazyMmapper.LOG_MMAP_CHUNK_SIZE;
  }

  public static int pagesToMmapChunksUp(int pages) {
    return bytesToMmapChunksUp(pagesToBytes(pages));
  }

  public static int addressToMmapChunksDown (VM_Address addr) {
    VM_Word chunk = addr.asWord().logicalShiftR(LazyMmapper.LOG_MMAP_CHUNK_SIZE);
    return chunk.asInt();
  }

  public static int addressToPagesDown (VM_Address addr) {
    VM_Word chunk = addr.asWord().logicalShiftR(LOG_BYTES_IN_PAGE);
    return chunk.asInt();
  }

  public static int addressToPages (VM_Address addr) {
    int page = addressToPagesDown(addr);
    if (VM_Interface.VerifyAssertions) VM_Interface._assert(pagesToAddress(page).EQ(addr));
    return page;
  }

  public static VM_Address pagesToAddress (int pages) {
    return VM_Word.fromInt         (pages).shiftL(LOG_BYTES_IN_PAGE).asAddress();
  }

  public static int addressToMmapChunksUp (VM_Address addr) {
    return ((addr.asInt()) + (LazyMmapper.MMAP_CHUNK_SIZE - 1)) >>> LazyMmapper.LOG_MMAP_CHUNK_SIZE;
  }

  public static int pagesToBytes(int pages) {
    return pages << LOG_BYTES_IN_PAGE;
  }

  public static int bytesToPagesUp (int bytes) {
    return (bytes + BYTES_IN_PAGE - 1) >>> LOG_BYTES_IN_PAGE;
  }

  public static int bytesToPages (int bytes) {
    int pages = bytesToPagesUp(bytes);
    if (VM_Interface.VerifyAssertions) VM_Interface._assert(pagesToBytes(pages) == bytes);
    return pages;
  }

  public static VM_Address mmapChunksToAddress(int chunk) {
    return VM_Word.fromInt(chunk).shiftL(LazyMmapper.LOG_MMAP_CHUNK_SIZE).asAddress();
  }



}

