package com.datastax.oss.driver.internal.core.os;
import java.util.Locale;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GraalLibc implements Libc {
private static final Logger LOG = LoggerFactory.getLogger(GraalLibc.class);
private static final Locale LOCALE = Locale.ENGLISH;
private static final String MAC_PLATFORM_STR = "mac".toLowerCase(LOCALE);
private static final String DARWIN_PLATFORM_STR = "darwin".toLowerCase(LOCALE);
private static final String LINUX_PLATFORM_STR = "linux".toLowerCase(LOCALE);
private final boolean available = checkAvailability();
private boolean checkPlatform() {
String osName = System.getProperty("os.name").split(" ", -1)[0];
String compareStr = osName.toLowerCase(Locale.ENGLISH);
return compareStr.startsWith(MAC_PLATFORM_STR)
|| compareStr.startsWith(DARWIN_PLATFORM_STR)
|| compareStr.startsWith(LINUX_PLATFORM_STR);
}
private boolean checkAvailability() {
if (!checkPlatform()) {
return false;
}
try {
getpidRaw();
} catch (Throwable t) {
LOG.debug("Error calling getpid()", t);
return false;
}
try {
gettimeofdayRaw();
} catch (Throwable t) {
LOG.debug("Error calling gettimeofday()", t);
return false;
}
return true;
}
@Override
public boolean available() {
return this.available;
}
@Override
public Optional<Long> gettimeofday() {
return this.available ? Optional.of(gettimeofdayRaw()) : Optional.empty();
}
private long gettimeofdayRaw() {
return Math.round(System.nanoTime() / 1_000d);
}
@Override
public Optional<Integer> getpid() {
return this.available ? Optional.of(getpidRaw()) : Optional.empty();
}
private int getpidRaw() {
return GraalGetpid.getpid();
}
}