github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/data/queue/file.go (about)

     1  package queue
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  )
     7  
     8  // queueType defines the type of queue data structure used.
     9  type queueType uint8
    10  
    11  // The possible queue types, used to determine compatibility when
    12  // one stored type is trying to be opened by a different type.
    13  const (
    14  	queueStack queueType = iota
    15  	queueQueue
    16  	queuePriorityQueue
    17  	queuePrefixQueue
    18  )
    19  
    20  // checkQueueType checks if the type of queue data structure
    21  // trying to be opened is compatible with the opener type.
    22  //
    23  // A file named 'queue' within the data directory used by
    24  // the structure stores the structure type, using the constants
    25  // declared above.
    26  //
    27  // Stacks and Queues are 100% compatible with each other, while
    28  // a PriorityQueue is incompatible with both.
    29  //
    30  // Returns true if types are compatible and false if incompatible.
    31  func checkQueueType(dataDir string, gt queueType) (bool, error) {
    32  	// SetHeader the path to 'queue' file.
    33  	path := filepath.Join(dataDir, "queue")
    34  
    35  	// Read 'queue' file for this directory.
    36  	f, err := os.OpenFile(path, os.O_RDONLY, 0)
    37  	if os.IsNotExist(err) {
    38  		f, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0644)
    39  		if err != nil {
    40  			return false, err
    41  		}
    42  		defer f.Close()
    43  
    44  		// Create byte slice of queueType.
    45  		gtb := make([]byte, 1)
    46  		gtb[0] = byte(gt)
    47  
    48  		_, err = f.Write(gtb)
    49  		if err != nil {
    50  			return false, err
    51  		}
    52  
    53  		return true, nil
    54  	}
    55  	if err != nil {
    56  		return false, err
    57  	}
    58  	defer f.Close()
    59  
    60  	// GetHeader the saved type from the file.
    61  	fb := make([]byte, 1)
    62  	_, err = f.Read(fb)
    63  	if err != nil {
    64  		return false, err
    65  	}
    66  
    67  	// Convert the file byte to its queueType.
    68  	filegt := queueType(fb[0])
    69  
    70  	// Compare the types.
    71  	if filegt == gt {
    72  		return true, nil
    73  	} else if filegt == queueStack && gt == queueQueue {
    74  		return true, nil
    75  	} else if filegt == queueQueue && gt == queueStack {
    76  		return true, nil
    77  	}
    78  
    79  	return false, nil
    80  }